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/share/classes/com/sun/javafx/runtime/location/WeakLocation.java b/src/share/classes/com/sun/javafx/runtime/location/WeakLocation.java
index cb193031f..d66e18c7f 100644
--- a/src/share/classes/com/sun/javafx/runtime/location/WeakLocation.java
+++ b/src/share/classes/com/sun/javafx/runtime/location/WeakLocation.java
@@ -1,61 +1,62 @@
package com.sun.javafx.runtime.location;
import java.lang.ref.WeakReference;
import java.lang.ref.Reference;
/*[*/
import java.lang.ref.ReferenceQueue;
/*]*/
import com.sun.javafx.runtime.util.Linkable;
/**
* WeakLink
*
* @author Brian Goetz
*/
class WeakLocation extends WeakReference<Location> implements Linkable<WeakLocation, AbstractLocation> {
/*[*/ static ReferenceQueue<Location> refQ = new ReferenceQueue<Location>(); /*]*/
WeakLocation next;
AbstractLocation host;
WeakLocation(Location referent) {
super(referent /*[*/ , refQ /*]*/ );
}
public WeakLocation getNext() {
return next;
}
public void setNext(WeakLocation next) {
this.next = next;
}
public AbstractLocation getHost() {
return host;
}
public void setHost(AbstractLocation host) {
this.host = host;
}
static void purgeDeadLocations(AbstractLocation fallback) {
/*[*/
Reference<? extends Location> loc;
AbstractLocation lastHost = null;
while ((loc = refQ.poll()) != null) {
WeakLocation wl = (WeakLocation) loc;
AbstractLocation host = wl.host;
// Minor optimization -- if we just purged a given host, don't do it again
- if (host != lastHost)
+ if (host != null && host != lastHost) {
host.purgeDeadDependencies();
- lastHost = host;
+ lastHost = host;
+ }
}
/*]*/
/* [
// Fallback strategy is an aggressive purge
if (fallback != null)
fallback.purgeDeadDependencies();
] */
}
}
| false | true | static void purgeDeadLocations(AbstractLocation fallback) {
/*[*/
Reference<? extends Location> loc;
AbstractLocation lastHost = null;
while ((loc = refQ.poll()) != null) {
WeakLocation wl = (WeakLocation) loc;
AbstractLocation host = wl.host;
// Minor optimization -- if we just purged a given host, don't do it again
if (host != lastHost)
host.purgeDeadDependencies();
lastHost = host;
}
/*]*/
/* [
// Fallback strategy is an aggressive purge
if (fallback != null)
fallback.purgeDeadDependencies();
] */
}
| static void purgeDeadLocations(AbstractLocation fallback) {
/*[*/
Reference<? extends Location> loc;
AbstractLocation lastHost = null;
while ((loc = refQ.poll()) != null) {
WeakLocation wl = (WeakLocation) loc;
AbstractLocation host = wl.host;
// Minor optimization -- if we just purged a given host, don't do it again
if (host != null && host != lastHost) {
host.purgeDeadDependencies();
lastHost = host;
}
}
/*]*/
/* [
// Fallback strategy is an aggressive purge
if (fallback != null)
fallback.purgeDeadDependencies();
] */
}
|
diff --git a/ZONE-extractor/ZONE-plugin-ExtractArticlesContent/src/main/java/org/zoneproject/extractor/plugin/extractarticlescontent/App.java b/ZONE-extractor/ZONE-plugin-ExtractArticlesContent/src/main/java/org/zoneproject/extractor/plugin/extractarticlescontent/App.java
index 32e8d81..3c869e9 100644
--- a/ZONE-extractor/ZONE-plugin-ExtractArticlesContent/src/main/java/org/zoneproject/extractor/plugin/extractarticlescontent/App.java
+++ b/ZONE-extractor/ZONE-plugin-ExtractArticlesContent/src/main/java/org/zoneproject/extractor/plugin/extractarticlescontent/App.java
@@ -1,96 +1,96 @@
package org.zoneproject.extractor.plugin.extractarticlescontent;
/*
* #%L
* ZONE-plugin-ExtractArticlesContent
* %%
* Copyright (C) 2012 ZONE-project
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import com.hp.hpl.jena.vocabulary.RSS;
import de.l3s.boilerpipe.BoilerpipeProcessingException;
import de.l3s.boilerpipe.extractors.ArticleExtractor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zoneproject.extractor.utils.VirtuosoDatabase;
import org.zoneproject.extractor.utils.Item;
import org.zoneproject.extractor.utils.Prop;
import org.zoneproject.extractor.utils.ZoneOntology;
/**
*
* @author Desclaux Christophe <[email protected]>
*/
public class App
{
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(App.class);
public static String PLUGIN_URI = ZoneOntology.PLUGIN_EXTRACT_ARTICLES_CONTENT;
public static String PLUGIN_RESULT_URI = ZoneOntology.PLUGIN_EXTRACT_ARTICLES_CONTENT_RES;
public App(){
String [] tmp = {};
App.main(tmp);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Item[] items = null;
do{
items = VirtuosoDatabase.getItemsNotAnotatedForOnePlugin(PLUGIN_URI,10);
logger.info("ExtractArticlesContent has "+items.length+" items to annotate");
for(Item item : items){
try {
logger.info("Add ExtractArticlesContent for item: "+item);
if(item.uri.startsWith("https://twitter.com/")){
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
continue;
}
URL url = new URL(item.getUri());
String content= ArticleExtractor.INSTANCE.getText(url).replace("\u00A0", " ").trim();
String title = item.getTitle().trim();
if(item.getDescription() != null){
String description = item.getDescription().trim().substring(0,Math.min(item.getDescription().trim().length(),20));
if(content.contains(description)){
content = content.substring(content.indexOf(description));
}
}
if(content.contains(title)){
content = content.substring(content.indexOf(title)+title.length());
}
content = content.replace("\n", "<br/>");
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_RESULT_URI,content));
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
} catch (BoilerpipeProcessingException ex) {
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
- VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_RESULT_URI,item.getElement(RSS.description)));
- Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
+ Logger.getLogger(App.class.getName()).log(Level.WARNING, null, ex);
} catch (MalformedURLException ex) {
+ VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
Logger.getLogger(App.class.getName()).log(Level.WARNING, null, ex);
}
}
}while(items.length > 0);
}
}
| false | true | public static void main(String[] args) {
Item[] items = null;
do{
items = VirtuosoDatabase.getItemsNotAnotatedForOnePlugin(PLUGIN_URI,10);
logger.info("ExtractArticlesContent has "+items.length+" items to annotate");
for(Item item : items){
try {
logger.info("Add ExtractArticlesContent for item: "+item);
if(item.uri.startsWith("https://twitter.com/")){
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
continue;
}
URL url = new URL(item.getUri());
String content= ArticleExtractor.INSTANCE.getText(url).replace("\u00A0", " ").trim();
String title = item.getTitle().trim();
if(item.getDescription() != null){
String description = item.getDescription().trim().substring(0,Math.min(item.getDescription().trim().length(),20));
if(content.contains(description)){
content = content.substring(content.indexOf(description));
}
}
if(content.contains(title)){
content = content.substring(content.indexOf(title)+title.length());
}
content = content.replace("\n", "<br/>");
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_RESULT_URI,content));
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
} catch (BoilerpipeProcessingException ex) {
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_RESULT_URI,item.getElement(RSS.description)));
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(App.class.getName()).log(Level.WARNING, null, ex);
}
}
}while(items.length > 0);
}
| public static void main(String[] args) {
Item[] items = null;
do{
items = VirtuosoDatabase.getItemsNotAnotatedForOnePlugin(PLUGIN_URI,10);
logger.info("ExtractArticlesContent has "+items.length+" items to annotate");
for(Item item : items){
try {
logger.info("Add ExtractArticlesContent for item: "+item);
if(item.uri.startsWith("https://twitter.com/")){
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
continue;
}
URL url = new URL(item.getUri());
String content= ArticleExtractor.INSTANCE.getText(url).replace("\u00A0", " ").trim();
String title = item.getTitle().trim();
if(item.getDescription() != null){
String description = item.getDescription().trim().substring(0,Math.min(item.getDescription().trim().length(),20));
if(content.contains(description)){
content = content.substring(content.indexOf(description));
}
}
if(content.contains(title)){
content = content.substring(content.indexOf(title)+title.length());
}
content = content.replace("\n", "<br/>");
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_RESULT_URI,content));
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
} catch (BoilerpipeProcessingException ex) {
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
Logger.getLogger(App.class.getName()).log(Level.WARNING, null, ex);
} catch (MalformedURLException ex) {
VirtuosoDatabase.addAnnotation(item.getUri(), new Prop(PLUGIN_URI,"true"));
Logger.getLogger(App.class.getName()).log(Level.WARNING, null, ex);
}
}
}while(items.length > 0);
}
|
diff --git a/farrago/src/org/eigenbase/jmi/JmiModelGraph.java b/farrago/src/org/eigenbase/jmi/JmiModelGraph.java
index dc8a4837c..9fae0bfcb 100644
--- a/farrago/src/org/eigenbase/jmi/JmiModelGraph.java
+++ b/farrago/src/org/eigenbase/jmi/JmiModelGraph.java
@@ -1,386 +1,386 @@
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2005-2005 The Eigenbase Project
// Copyright (C) 2005-2005 Disruptive Tech
// Copyright (C) 2005-2005 LucidEra, Inc.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.eigenbase.jmi;
import org.eigenbase.util.*;
import org._3pq.jgrapht.*;
import org._3pq.jgrapht.graph.*;
import javax.jmi.model.*;
import javax.jmi.reflect.*;
import java.util.*;
/**
* JmiModelGraph is a directed graph representation of a JMI model. Vertices
* are instances of {@link JmiClassVertex}. Edges are instances of either
* {@link JmiInheritanceEdge} or {@link JmiAssocEdge}. Graph instances are
* immutable and can be accessed concurrently by multiple threads.
*
* @author John V. Sichi
* @version $Id$
*/
public class JmiModelGraph
extends UnmodifiableDirectedGraph
{
/**
* The underlying graph structure; we hide it here so that
* it can only be modified internally.
*/
private final DirectedGraph combinedGraph;
/**
* Subgraph with just inheritance edges.
*/
private final DirectedGraph inheritanceGraph;
/**
* Unmodifiable view of inheritanceGraph.
*/
private final DirectedGraph unmodifiableInheritanceGraph;
/**
* Subgraph with just inheritance edges.
*/
private final DirectedGraph assocGraph;
/**
* Unmodifiable view of assocGraph.
*/
private final DirectedGraph unmodifiableAssocGraph;
/**
* Map from Ref and Mof instances to corresponding graph vertices
* and edges.
*/
private final Map map;
private final RefPackage refRootPackage;
/**
* Creates a new graph based on the contents of a RefPackage
* and all of its subpackages.
*
* @param refRootPackage package on which graph is based
*/
public JmiModelGraph(RefPackage refRootPackage)
{
this(
refRootPackage,
new DirectedMultigraph());
}
/**
* @return the subgraph of only inheritance edges
*/
public DirectedGraph getInheritanceGraph()
{
return unmodifiableInheritanceGraph;
}
/**
* @return the subgraph of only association edges
*/
public DirectedGraph getAssocGraph()
{
return unmodifiableAssocGraph;
}
/**
* Gets the vertex representing a class from JMI reflection.
*
* @param refClass the class of interest
*
* @return corresponding vertex
*/
public JmiClassVertex getVertexForRefClass(RefClass refClass)
{
return (JmiClassVertex) map.get(refClass);
}
/**
* Gets the vertex representing a MOF class.
*
* @param mofClass the class of interest
*
* @return corresponding vertex
*/
public JmiClassVertex getVertexForMofClass(MofClass mofClass)
{
return (JmiClassVertex) map.get(mofClass);
}
/**
* Gets the edge representing a MOF association.
*
* @param mofAssoc the association of interest
*
* @return corresponding edge
*/
public JmiAssocEdge getEdgeForMofAssoc(Association mofAssoc)
{
return (JmiAssocEdge) map.get(mofAssoc);
}
/**
* Gets the edge representing a JMI reflective association.
*
* @param refAssoc the association of interest
*
* @return corresponding edge
*/
public JmiAssocEdge getEdgeForRefAssoc(RefAssociation refAssoc)
{
return (JmiAssocEdge) map.get(refAssoc);
}
/**
* Gets the vertex representing a MOF class by name.
*
* @param name name of the class of interest
*
* @return corresponding vertex
*/
public JmiClassVertex getVertexForClassName(String name)
{
return (JmiClassVertex) map.get(name);
}
/**
* Gets the edge representing a MOF association by name.
*
* @param name name of the association of interest
*
* @return corresponding edge
*/
public JmiAssocEdge getEdgeForAssocName(String name)
{
return (JmiAssocEdge) map.get(name);
}
/**
* Gets the JMI reflective representation for a class.
*
* @param vertex vertex representing class of interest
*
* @return reflective representation for class
*/
public RefClass getRefClassForVertex(Object vertex)
{
return ((JmiClassVertex) vertex).getRefClass();
}
/**
* Gets the MOF representation for a class.
*
* @param vertex vertex representing class of interest
*
* @return MOF representation for class
*/
public MofClass getMofClassForVertex(Object vertex)
{
return ((JmiClassVertex) vertex).getMofClass();
}
/**
* Gets the MOF representation for an association.
*
* @param edge edge representing association of interest
*
* @return MOF representation for association
*/
public Association getMofAssocForEdge(Object edge)
{
return ((JmiAssocEdge) edge).getMofAssoc();
}
/**
* Gets the JMI reflective representation for an association.
*
* @param edge edge representing association of interest
*
* @return JMI reflective representation for association
*/
public RefAssociation getRefAssocForEdge(Object edge)
{
return ((JmiAssocEdge) edge).getRefAssoc();
}
/**
* @return the JMI reflective representation for the root package
* represented by this graph
*/
public RefPackage getRefRootPackage()
{
return refRootPackage;
}
private JmiModelGraph(
RefPackage refRootPackage, DirectedGraph combinedGraph)
{
super(combinedGraph);
this.refRootPackage = refRootPackage;
this.combinedGraph = combinedGraph;
inheritanceGraph = new DirectedMultigraph();
unmodifiableInheritanceGraph =
new UnmodifiableDirectedGraph(inheritanceGraph);
assocGraph = new DirectedMultigraph();
unmodifiableAssocGraph =
new UnmodifiableDirectedGraph(assocGraph);
map = new HashMap();
addMofPackage((MofPackage) refRootPackage.refMetaObject());
addRefPackage(refRootPackage);
}
private void addMofPackage(MofPackage mofPackage)
{
Iterator iter = mofPackage.getContents().iterator();
while (iter.hasNext()) {
ModelElement modelElement = (ModelElement) iter.next();
if (modelElement instanceof MofPackage) {
addMofPackage((MofPackage) modelElement);
} else if (modelElement instanceof MofClass) {
addMofClass((MofClass) modelElement);
} else if (modelElement instanceof Association) {
addMofAssoc((Association) modelElement);
}
}
}
private JmiClassVertex addMofClass(MofClass mofClass)
{
JmiClassVertex vertex = getVertexForMofClass(mofClass);
if (vertex != null) {
return vertex;
}
vertex = new JmiClassVertex(mofClass);
combinedGraph.addVertex(vertex);
inheritanceGraph.addVertex(vertex);
assocGraph.addVertex(vertex);
map.put(mofClass, vertex);
map.put(mofClass.getName(), vertex);
Iterator iter = mofClass.getSupertypes().iterator();
while (iter.hasNext()) {
MofClass superClass = (MofClass) iter.next();
JmiClassVertex superVertex = addMofClass(superClass);
JmiInheritanceEdge edge =
new JmiInheritanceEdge(superVertex, vertex);
combinedGraph.addEdge(edge);
inheritanceGraph.addEdge(edge);
}
return vertex;
}
private void addMofAssoc(Association mofAssoc)
{
if (getEdgeForMofAssoc(mofAssoc) != null) {
return;
}
AssociationEnd [] mofAssocEnds = new AssociationEnd[2];
ModelPackage mofPackage = (ModelPackage)
mofAssoc.refImmediatePackage();
MofClass endType = (MofClass)
mofPackage.getAssociationEnd().refMetaObject();
List ends = mofAssoc.findElementsByType(endType, false);
mofAssocEnds[0] = (AssociationEnd) ends.get(0);
mofAssocEnds[1] = (AssociationEnd) ends.get(1);
boolean swapEnds = false;
if (mofAssocEnds[1].getAggregation() == AggregationKindEnum.COMPOSITE) {
swapEnds = true;
}
- if ((mofAssocEnds[0].getMultiplicity().getUpper() > 1)
- && (mofAssocEnds[1].getMultiplicity().getUpper() < 2))
+ if ((mofAssocEnds[0].getMultiplicity().getUpper() != 1)
+ && (mofAssocEnds[1].getMultiplicity().getUpper() == 1))
{
swapEnds = true;
}
if (swapEnds) {
AssociationEnd tmp = mofAssocEnds[0];
mofAssocEnds[0] = mofAssocEnds[1];
mofAssocEnds[1] = tmp;
}
MofClass sourceClass = (MofClass)
mofAssocEnds[0].getType();
MofClass targetClass = (MofClass)
mofAssocEnds[1].getType();
JmiClassVertex sourceVertex = addMofClass(sourceClass);
JmiClassVertex targetVertex = addMofClass(targetClass);
JmiAssocEdge edge =
new JmiAssocEdge(
mofAssoc, sourceVertex, targetVertex, mofAssocEnds);
combinedGraph.addEdge(edge);
assocGraph.addEdge(edge);
map.put(mofAssoc, edge);
map.put(mofAssoc.getName(), edge);
}
private void addRefPackage(RefPackage refPackage)
{
Iterator iter;
iter = refPackage.refAllPackages().iterator();
while (iter.hasNext()) {
addRefPackage((RefPackage) iter.next());
}
iter = refPackage.refAllClasses().iterator();
while (iter.hasNext()) {
addRefClass((RefClass) iter.next());
}
iter = refPackage.refAllAssociations().iterator();
while (iter.hasNext()) {
addRefAssoc((RefAssociation) iter.next());
}
}
private void addRefClass(RefClass refClass)
{
JmiClassVertex vertex = getVertexForMofClass(
(MofClass) refClass.refMetaObject());
assert(vertex != null);
vertex.refClass = refClass;
map.put(refClass, vertex);
}
private void addRefAssoc(RefAssociation refAssoc)
{
JmiAssocEdge edge = getEdgeForMofAssoc(
(Association) refAssoc.refMetaObject());
assert(edge != null);
edge.refAssoc = refAssoc;
map.put(refAssoc, edge);
}
}
// End JmiModelGraph.java
| true | true | private void addMofAssoc(Association mofAssoc)
{
if (getEdgeForMofAssoc(mofAssoc) != null) {
return;
}
AssociationEnd [] mofAssocEnds = new AssociationEnd[2];
ModelPackage mofPackage = (ModelPackage)
mofAssoc.refImmediatePackage();
MofClass endType = (MofClass)
mofPackage.getAssociationEnd().refMetaObject();
List ends = mofAssoc.findElementsByType(endType, false);
mofAssocEnds[0] = (AssociationEnd) ends.get(0);
mofAssocEnds[1] = (AssociationEnd) ends.get(1);
boolean swapEnds = false;
if (mofAssocEnds[1].getAggregation() == AggregationKindEnum.COMPOSITE) {
swapEnds = true;
}
if ((mofAssocEnds[0].getMultiplicity().getUpper() > 1)
&& (mofAssocEnds[1].getMultiplicity().getUpper() < 2))
{
swapEnds = true;
}
if (swapEnds) {
AssociationEnd tmp = mofAssocEnds[0];
mofAssocEnds[0] = mofAssocEnds[1];
mofAssocEnds[1] = tmp;
}
MofClass sourceClass = (MofClass)
mofAssocEnds[0].getType();
MofClass targetClass = (MofClass)
mofAssocEnds[1].getType();
JmiClassVertex sourceVertex = addMofClass(sourceClass);
JmiClassVertex targetVertex = addMofClass(targetClass);
JmiAssocEdge edge =
new JmiAssocEdge(
mofAssoc, sourceVertex, targetVertex, mofAssocEnds);
combinedGraph.addEdge(edge);
assocGraph.addEdge(edge);
map.put(mofAssoc, edge);
map.put(mofAssoc.getName(), edge);
}
| private void addMofAssoc(Association mofAssoc)
{
if (getEdgeForMofAssoc(mofAssoc) != null) {
return;
}
AssociationEnd [] mofAssocEnds = new AssociationEnd[2];
ModelPackage mofPackage = (ModelPackage)
mofAssoc.refImmediatePackage();
MofClass endType = (MofClass)
mofPackage.getAssociationEnd().refMetaObject();
List ends = mofAssoc.findElementsByType(endType, false);
mofAssocEnds[0] = (AssociationEnd) ends.get(0);
mofAssocEnds[1] = (AssociationEnd) ends.get(1);
boolean swapEnds = false;
if (mofAssocEnds[1].getAggregation() == AggregationKindEnum.COMPOSITE) {
swapEnds = true;
}
if ((mofAssocEnds[0].getMultiplicity().getUpper() != 1)
&& (mofAssocEnds[1].getMultiplicity().getUpper() == 1))
{
swapEnds = true;
}
if (swapEnds) {
AssociationEnd tmp = mofAssocEnds[0];
mofAssocEnds[0] = mofAssocEnds[1];
mofAssocEnds[1] = tmp;
}
MofClass sourceClass = (MofClass)
mofAssocEnds[0].getType();
MofClass targetClass = (MofClass)
mofAssocEnds[1].getType();
JmiClassVertex sourceVertex = addMofClass(sourceClass);
JmiClassVertex targetVertex = addMofClass(targetClass);
JmiAssocEdge edge =
new JmiAssocEdge(
mofAssoc, sourceVertex, targetVertex, mofAssocEnds);
combinedGraph.addEdge(edge);
assocGraph.addEdge(edge);
map.put(mofAssoc, edge);
map.put(mofAssoc.getName(), edge);
}
|
diff --git a/src/org/nutz/mvc/NutMvcContext.java b/src/org/nutz/mvc/NutMvcContext.java
index 816010e29..ca3a5dc60 100644
--- a/src/org/nutz/mvc/NutMvcContext.java
+++ b/src/org/nutz/mvc/NutMvcContext.java
@@ -1,47 +1,48 @@
package org.nutz.mvc;
import java.util.HashMap;
import java.util.Map;
import org.nutz.ioc.Ioc;
import org.nutz.lang.Lang;
import org.nutz.lang.util.Context;
import org.nutz.lang.util.SimpleContext;
import org.nutz.mvc.config.AtMap;
public class NutMvcContext extends SimpleContext {
public ThreadLocal<Context> reqThreadLocal = new ThreadLocal<Context>() {
protected Context initialValue() {
return Lang.context();
}
};
public Map<String, Ioc> iocs = new HashMap<String, Ioc>();
public Map<String, AtMap> atMaps = new HashMap<String, AtMap>();
public Map<String, NutConfig> nutConfigs = new HashMap<String, NutConfig>();
public Map<String, Map<String, Map<String, Object>>> localizations = new HashMap<String, Map<String, Map<String, Object>>>();
public void close() {
- reqThreadLocal.get().clear();
+ reqThreadLocal.set(null);
+ reqThreadLocal = null;
iocs.clear();
atMaps.clear();
nutConfigs.clear();
localizations.clear();
}
/**
* 获取默认Ioc,在单个NutFilter/NutServlet中非常合用
*/
public Ioc getDefaultIoc() {
if (iocs.isEmpty())
return null;
return iocs.values().iterator().next();
}
public NutConfig getDefaultNutConfig() {
if (nutConfigs.isEmpty())
return null;
return nutConfigs.values().iterator().next();
}
}
| true | true | public void close() {
reqThreadLocal.get().clear();
iocs.clear();
atMaps.clear();
nutConfigs.clear();
localizations.clear();
}
| public void close() {
reqThreadLocal.set(null);
reqThreadLocal = null;
iocs.clear();
atMaps.clear();
nutConfigs.clear();
localizations.clear();
}
|
diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SDKPolicy.java b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SDKPolicy.java
index f75ee10f3..be43d8bd4 100644
--- a/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SDKPolicy.java
+++ b/bundles/org.eclipse.equinox.p2.ui.sdk/src/org/eclipse/equinox/internal/p2/ui/sdk/SDKPolicy.java
@@ -1,90 +1,91 @@
/*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.p2.ui.sdk;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.internal.p2.ui.sdk.prefs.PreferenceConstants;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan;
import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry;
import org.eclipse.equinox.internal.provisional.p2.ui.IStatusCodes;
import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI;
import org.eclipse.equinox.internal.provisional.p2.ui.policy.*;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.statushandlers.StatusManager;
/**
* SDKPolicy defines the Eclipse SDK UI policies for the
* p2 UI. The policy is declared as an OSGi service in
* the policy_component.xml file.
*
* @since 3.5
*/
public class SDKPolicy extends Policy {
public SDKPolicy() {
setProfileChooser(new IProfileChooser() {
public String getProfileId(Shell shell) {
try {
return ProvSDKUIActivator.getSelfProfileId();
} catch (ProvisionException e) {
+ ProvUI.handleException(e, e.getStatus().getMessage(), StatusManager.LOG);
return IProfileRegistry.SELF;
}
}
});
setRepositoryManipulator(new ColocatedRepositoryManipulator(this, PreferenceConstants.PREF_PAGE_SITES) {
public String getManipulatorLinkLabel() {
return ProvSDKMessages.ProvSDKUIActivator_SitePrefLink;
}
});
setPlanValidator(new PlanValidator() {
public boolean continueWorkingWithPlan(ProvisioningPlan plan, Shell shell) {
if (plan == null)
return false;
if (plan.getStatus().getSeverity() == IStatus.CANCEL)
return false;
// Special case those statuses where we would never want to open a wizard
if (plan.getStatus().getCode() == IStatusCodes.NOTHING_TO_UPDATE) {
ProvUI.reportStatus(plan.getStatus(), StatusManager.BLOCK);
return false;
}
// Allow the wizard to open if there is no error
if (plan.getStatus().getSeverity() != IStatus.ERROR)
return true;
// There is an error. Check the preference to see whether to continue.
IPreferenceStore prefs = ProvSDKUIActivator.getDefault().getPreferenceStore();
String openPlan = prefs.getString(PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN);
if (MessageDialogWithToggle.ALWAYS.equals(openPlan)) {
return true;
}
if (MessageDialogWithToggle.NEVER.equals(openPlan)) {
ProvUI.reportStatus(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG);
return false;
}
MessageDialogWithToggle dialog = MessageDialogWithToggle.openYesNoCancelQuestion(shell, ProvSDKMessages.ProvSDKUIActivator_Question, ProvSDKMessages.ProvSDKUIActivator_OpenWizardAnyway, null, false, prefs, PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN);
// Any answer but yes will stop the performance of the plan, but NO is interpreted to mean, show me the error.
if (dialog.getReturnCode() == IDialogConstants.NO_ID)
ProvUI.reportStatus(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG);
return dialog.getReturnCode() == IDialogConstants.YES_ID;
}
});
// Start with the default query context and configure some settings
IUViewQueryContext queryContext = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_BY_CATEGORY);
setQueryContext(queryContext);
ProvSDKUIActivator.getDefault().updateWithPreferences(queryContext);
}
}
| true | true | public SDKPolicy() {
setProfileChooser(new IProfileChooser() {
public String getProfileId(Shell shell) {
try {
return ProvSDKUIActivator.getSelfProfileId();
} catch (ProvisionException e) {
return IProfileRegistry.SELF;
}
}
});
setRepositoryManipulator(new ColocatedRepositoryManipulator(this, PreferenceConstants.PREF_PAGE_SITES) {
public String getManipulatorLinkLabel() {
return ProvSDKMessages.ProvSDKUIActivator_SitePrefLink;
}
});
setPlanValidator(new PlanValidator() {
public boolean continueWorkingWithPlan(ProvisioningPlan plan, Shell shell) {
if (plan == null)
return false;
if (plan.getStatus().getSeverity() == IStatus.CANCEL)
return false;
// Special case those statuses where we would never want to open a wizard
if (plan.getStatus().getCode() == IStatusCodes.NOTHING_TO_UPDATE) {
ProvUI.reportStatus(plan.getStatus(), StatusManager.BLOCK);
return false;
}
// Allow the wizard to open if there is no error
if (plan.getStatus().getSeverity() != IStatus.ERROR)
return true;
// There is an error. Check the preference to see whether to continue.
IPreferenceStore prefs = ProvSDKUIActivator.getDefault().getPreferenceStore();
String openPlan = prefs.getString(PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN);
if (MessageDialogWithToggle.ALWAYS.equals(openPlan)) {
return true;
}
if (MessageDialogWithToggle.NEVER.equals(openPlan)) {
ProvUI.reportStatus(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG);
return false;
}
MessageDialogWithToggle dialog = MessageDialogWithToggle.openYesNoCancelQuestion(shell, ProvSDKMessages.ProvSDKUIActivator_Question, ProvSDKMessages.ProvSDKUIActivator_OpenWizardAnyway, null, false, prefs, PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN);
// Any answer but yes will stop the performance of the plan, but NO is interpreted to mean, show me the error.
if (dialog.getReturnCode() == IDialogConstants.NO_ID)
ProvUI.reportStatus(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG);
return dialog.getReturnCode() == IDialogConstants.YES_ID;
}
});
// Start with the default query context and configure some settings
IUViewQueryContext queryContext = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_BY_CATEGORY);
setQueryContext(queryContext);
ProvSDKUIActivator.getDefault().updateWithPreferences(queryContext);
}
| public SDKPolicy() {
setProfileChooser(new IProfileChooser() {
public String getProfileId(Shell shell) {
try {
return ProvSDKUIActivator.getSelfProfileId();
} catch (ProvisionException e) {
ProvUI.handleException(e, e.getStatus().getMessage(), StatusManager.LOG);
return IProfileRegistry.SELF;
}
}
});
setRepositoryManipulator(new ColocatedRepositoryManipulator(this, PreferenceConstants.PREF_PAGE_SITES) {
public String getManipulatorLinkLabel() {
return ProvSDKMessages.ProvSDKUIActivator_SitePrefLink;
}
});
setPlanValidator(new PlanValidator() {
public boolean continueWorkingWithPlan(ProvisioningPlan plan, Shell shell) {
if (plan == null)
return false;
if (plan.getStatus().getSeverity() == IStatus.CANCEL)
return false;
// Special case those statuses where we would never want to open a wizard
if (plan.getStatus().getCode() == IStatusCodes.NOTHING_TO_UPDATE) {
ProvUI.reportStatus(plan.getStatus(), StatusManager.BLOCK);
return false;
}
// Allow the wizard to open if there is no error
if (plan.getStatus().getSeverity() != IStatus.ERROR)
return true;
// There is an error. Check the preference to see whether to continue.
IPreferenceStore prefs = ProvSDKUIActivator.getDefault().getPreferenceStore();
String openPlan = prefs.getString(PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN);
if (MessageDialogWithToggle.ALWAYS.equals(openPlan)) {
return true;
}
if (MessageDialogWithToggle.NEVER.equals(openPlan)) {
ProvUI.reportStatus(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG);
return false;
}
MessageDialogWithToggle dialog = MessageDialogWithToggle.openYesNoCancelQuestion(shell, ProvSDKMessages.ProvSDKUIActivator_Question, ProvSDKMessages.ProvSDKUIActivator_OpenWizardAnyway, null, false, prefs, PreferenceConstants.PREF_OPEN_WIZARD_ON_ERROR_PLAN);
// Any answer but yes will stop the performance of the plan, but NO is interpreted to mean, show me the error.
if (dialog.getReturnCode() == IDialogConstants.NO_ID)
ProvUI.reportStatus(plan.getStatus(), StatusManager.SHOW | StatusManager.LOG);
return dialog.getReturnCode() == IDialogConstants.YES_ID;
}
});
// Start with the default query context and configure some settings
IUViewQueryContext queryContext = new IUViewQueryContext(IUViewQueryContext.AVAILABLE_VIEW_BY_CATEGORY);
setQueryContext(queryContext);
ProvSDKUIActivator.getDefault().updateWithPreferences(queryContext);
}
|
diff --git a/src/main/java/org/atlasapi/beans/OembedTranslator.java b/src/main/java/org/atlasapi/beans/OembedTranslator.java
index 6600703b..5b392892 100644
--- a/src/main/java/org/atlasapi/beans/OembedTranslator.java
+++ b/src/main/java/org/atlasapi/beans/OembedTranslator.java
@@ -1,87 +1,89 @@
/* Copyright 2009 British Broadcasting Corporation
Copyright 2009 Meta Broadcast Ltd
Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License. */
package org.atlasapi.beans;
import java.io.OutputStream;
import java.util.Collection;
import org.atlasapi.feeds.OembedOutput;
import org.atlasapi.media.entity.Encoding;
import org.atlasapi.media.entity.Item;
import org.atlasapi.media.entity.Location;
import org.atlasapi.media.entity.Version;
/**
* General translator to build an oEmbed representation from information in the bean graph.
*
* @author Robert Chatley ([email protected])
*/
public class OembedTranslator implements BeanGraphWriter {
interface OutputFactory {
OembedOutput createOutput();
}
private final OutputFactory feedFactory;
public OembedTranslator(OutputFactory outputFactory) {
this.feedFactory = outputFactory;
}
public void writeTo(Collection<Object> graph, OutputStream stream) {
OembedOutput output = feedFactory.createOutput();
for (Object bean : graph) {
if (bean instanceof Item) {
Item item = (Item) bean;
output.setTitle(item.getTitle());
output.setProviderUrl(item.getPublisher().key());
output.setType("video");
if (item.getVersions() != null) {
for (Version version : item.getVersions()) {
if (version.getManifestedAs() != null) {
for (Encoding encoding : version.getManifestedAs()) {
if (encoding.getVideoVerticalSize() != null) {
output.setHeight(encoding.getVideoVerticalSize());
}
if (encoding.getVideoHorizontalSize() != null) {
output.setWidth(encoding.getVideoHorizontalSize());
}
for (Location location : encoding.getAvailableAt()) {
- output.setEmbedCode(escapeQuotes(location.getEmbedCode()));
+ if (location.getEmbedCode() != null) {
+ output.setEmbedCode(escapeQuotes(location.getEmbedCode()));
+ }
}
}
}
}
}
}
}
output.writeTo(stream);
}
private String escapeQuotes(String unescaped) {
if (unescaped == null) { return null; }
return unescaped.replace("\"", "\\\"");
}
}
| true | true | public void writeTo(Collection<Object> graph, OutputStream stream) {
OembedOutput output = feedFactory.createOutput();
for (Object bean : graph) {
if (bean instanceof Item) {
Item item = (Item) bean;
output.setTitle(item.getTitle());
output.setProviderUrl(item.getPublisher().key());
output.setType("video");
if (item.getVersions() != null) {
for (Version version : item.getVersions()) {
if (version.getManifestedAs() != null) {
for (Encoding encoding : version.getManifestedAs()) {
if (encoding.getVideoVerticalSize() != null) {
output.setHeight(encoding.getVideoVerticalSize());
}
if (encoding.getVideoHorizontalSize() != null) {
output.setWidth(encoding.getVideoHorizontalSize());
}
for (Location location : encoding.getAvailableAt()) {
output.setEmbedCode(escapeQuotes(location.getEmbedCode()));
}
}
}
}
}
}
}
output.writeTo(stream);
}
| public void writeTo(Collection<Object> graph, OutputStream stream) {
OembedOutput output = feedFactory.createOutput();
for (Object bean : graph) {
if (bean instanceof Item) {
Item item = (Item) bean;
output.setTitle(item.getTitle());
output.setProviderUrl(item.getPublisher().key());
output.setType("video");
if (item.getVersions() != null) {
for (Version version : item.getVersions()) {
if (version.getManifestedAs() != null) {
for (Encoding encoding : version.getManifestedAs()) {
if (encoding.getVideoVerticalSize() != null) {
output.setHeight(encoding.getVideoVerticalSize());
}
if (encoding.getVideoHorizontalSize() != null) {
output.setWidth(encoding.getVideoHorizontalSize());
}
for (Location location : encoding.getAvailableAt()) {
if (location.getEmbedCode() != null) {
output.setEmbedCode(escapeQuotes(location.getEmbedCode()));
}
}
}
}
}
}
}
}
output.writeTo(stream);
}
|
diff --git a/src/processing/Mod_EpProcessing.java b/src/processing/Mod_EpProcessing.java
index d974190..f333814 100644
--- a/src/processing/Mod_EpProcessing.java
+++ b/src/processing/Mod_EpProcessing.java
@@ -1,682 +1,684 @@
package processing;
import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import processing.FileInfo.eAction;
import udpApi.Cmd;
import udpApi.Query;
import aniAdd.IAniAdd;
import aniAdd.Modules.IModule;
import aniAdd.misc.ICallBack;
import aniAdd.misc.Mod_Memory;
import aniAdd.misc.Misc;
import aniAdd.misc.MultiKeyDict;
import aniAdd.misc.MultiKeyDict.IKeyMapper;
import java.util.TreeMap;
import udpApi.Mod_UdpApi;
public class Mod_EpProcessing implements IModule {
public static String[] supportedFiles = {"avi", "mpg", "mpeg", "rm", "rmvb", "asf", "wmv", "mov", "ogm", "mp4", "mkv", "rar", "zip", "ace", "srt", "sub", "ssa", "smi", "idx", "ass", "txt", "swf", "flv"};
private IAniAdd aniAdd;
private Mod_UdpApi api;
private Mod_Memory mem;
private MultiKeyDict<String, Object, FileInfo> files;
private ArrayList<Integer> index2Id;
private FileParser fileParser;
private boolean isProcessing;
private boolean isPaused;
private int lastFileId;
public Mod_EpProcessing() {
lastFileId = 0;
files = new MultiKeyDict<String, Object, FileInfo>(new IKeyMapper<String, Object, FileInfo>() {
public int count() {
return 2;
}
public int getCatIndex(String category) {
return category.equals("Id") ? 0 : (category.equals("Path") ? 1 : -1);
}
public Object getKey(int index, FileInfo fileInfo) {
return index == 0 ? fileInfo.Id() : (index == 1 ? fileInfo.FileObj().getAbsolutePath() : null);
}
});
index2Id = new ArrayList<Integer>();
}
public void ClearFiles() {
index2Id.clear();
files.clear();
Log(ComEvent.eType.Information, eComType.FileCountChanged);
}
// <editor-fold defaultstate="collapsed" desc="Processing">
private void processEps() {
while(isPaused) try {Thread.sleep(100);} catch (InterruptedException ex) {}
for (FileInfo procFile : files.values()) {
if (!procFile.Served()) {
procFile.Served(true);
//System.out.println("Processing: " + procFile.FileObj().getAbsolutePath());
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.Processing, procFile.Id());
fileParser = new FileParser(procFile.FileObj(), new ICallBack<FileParser>() {
public void invoke(FileParser fileParser) {
continueProcessing(fileParser);
}
}, procFile.Id());
fileParser.start();
return;
}
}
isProcessing = false;
Log(ComEvent.eType.Information, eComType.Status, eComSubType.Done);
//System.out.println("Processing done");
}
private void continueProcessing(FileParser fileParser) {
this.fileParser = null;
FileInfo procFile = files.get("Id", fileParser.Tag());
//System.out.println("Cont Processing: " + id);
procFile.Data().put("Ed2k", fileParser.Hash());
procFile.ActionsDone().add(eAction.Process);
procFile.ActionsTodo().remove(eAction.Process);
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.ParsingDone, procFile.Id(), fileParser);
boolean sendML = procFile.ActionsTodo().contains(eAction.MyListCmd);
boolean sendFile = procFile.ActionsTodo().contains(eAction.FileCmd);
if(sendFile) requestDBFileInfo(procFile);
if(sendML) requestDBMyList(procFile);
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.GetDBInfo, procFile.Id(), sendFile, sendML);
if (isProcessing) processEps();
}
private void requestDBFileInfo(FileInfo procFile) {
Cmd cmd = new Cmd("FILE", "file", procFile.Id().toString(), true);
BitSet binCode = new BitSet(32);
binCode.set(6); //aid
binCode.set(5); //eid
binCode.set(4); //gid
binCode.set(3); //'lid
binCode.set(1); //'Depr
binCode.set(0); //'state
binCode.set(23); //'Quality
binCode.set(22); //'Source
binCode.set(24); //'anidb filename scheme
cmd.setArgs("fmask", Misc.toMask(binCode, 32));
binCode = new BitSet(32);
binCode.set(31); //'group name
binCode.set(30); //'group short name
binCode.set(23); //'epno
binCode.set(22); //'ep name
binCode.set(21); //'ep romaji
binCode.set(20); //'ep kanji
binCode.set(7); //'epCount
binCode.set(6); //'highest EpCount
binCode.set(4); //'type
binCode.set(15); //'romaji name
binCode.set(14); //'kanji name
binCode.set(13); //'english name
binCode.set(12); //'other name
binCode.set(11); //'short name
binCode.set(10); //'synonym
cmd.setArgs("amask", Misc.toMask(binCode, 32));
cmd.setArgs("size", Long.toString(procFile.FileObj().length()));
cmd.setArgs("ed2k", procFile.Data().get("Ed2k"));
api.queryCmd(cmd);
//System.out.println("Sending File Cmd");
}
private void requestDBMyList(FileInfo procFile) {
Cmd cmd = new Cmd("MYLISTADD", "mladd", procFile.Id().toString(), true);
cmd.setArgs("size", Long.toString(procFile.FileObj().length()));
cmd.setArgs("ed2k", (String)procFile.Data().get("Ed2k"));
cmd.setArgs("viewed", procFile.ActionsTodo().contains(eAction.Watched) ? "1" : "0");
cmd.setArgs("state", Integer.toString(procFile.MLStorage().ordinal()));
if(procFile.Data().containsKey(("EditOther"))) cmd.setArgs("other", (String)procFile.Data().get("EditOther"));
if(procFile.Data().containsKey(("EditSource"))) cmd.setArgs("source", (String)procFile.Data().get("EditSource"));
if(procFile.Data().containsKey(("EditStorage"))) cmd.setArgs("storage", (String)procFile.Data().get("EditStorage"));
api.queryCmd(cmd);
//System.out.println("Sending ML Cmd");
}
private void requestDBVote(FileInfo procFile) {
Cmd cmd = new Cmd("VOTE", "vote", procFile.Id().toString(), true);
cmd.setArgs("id", (String) procFile.Data().get("AId"));
cmd.setArgs("type", true ? "1" : "2"); //decision missing (Perm/Temp Vote)
cmd.setArgs("value", (String) procFile.Data().get("Vote"));
cmd.setArgs("epno", (String) procFile.Data().get("EpNo"));
api.queryCmd(cmd);
}
private void aniDBInfoReply(int queryId) {
//System.out.println("Got Fileinfo reply");
Query query = api.Queries().get(queryId);
int replyId = query.getReply().ReplyId();
int fileId = Integer.parseInt(query.getReply().Tag());
if (!files.contains("Id", fileId)) {
return; //File not found (Todo: throw error)
}
FileInfo procFile = files.get("Id", fileId);
procFile.ActionsTodo().remove(eAction.FileCmd);
if (replyId == 320 || replyId == 505 || replyId == 322) {
procFile.ActionsError().add(eAction.FileCmd);
Log(ComEvent.eType.Information, eComType.FileEvent,replyId==320?eComSubType.FileCmd_NotFound:eComSubType.FileCmd_Error, procFile.Id());
} else {
procFile.ActionsDone().add(eAction.FileCmd);
ArrayDeque<String> df = new ArrayDeque<String>(query.getReply().DataField());
procFile.Data().put("DB_FId", df.poll());
procFile.Data().put("DB_AId", df.poll());
procFile.Data().put("DB_EId", df.poll());
procFile.Data().put("DB_GId", df.poll());
procFile.Data().put("DB_LId", df.poll());
procFile.Data().put("DB_Deprecated", df.poll());
procFile.Data().put("DB_State", df.poll());
procFile.Data().put("DB_Quality", df.poll());
procFile.Data().put("DB_Source", df.poll());
procFile.Data().put("DB_FileName", df.poll());
procFile.Data().put("DB_EpCount", df.poll());
procFile.Data().put("DB_EpHiCount", df.poll());
procFile.Data().put("DB_Type", df.poll());
procFile.Data().put("DB_SN_Romaji", df.poll());
procFile.Data().put("DB_SN_Kanji", df.poll());
procFile.Data().put("DB_SN_English", df.poll());
procFile.Data().put("DB_SN_Other", df.poll());
procFile.Data().put("DB_SN_Short", df.poll());
procFile.Data().put("DB_SN_Synonym", df.poll());
procFile.Data().put("DB_EpNo", df.poll());
procFile.Data().put("DB_EpN_English", df.poll());
procFile.Data().put("DB_EpN_Romaji", df.poll());
procFile.Data().put("DB_EpN_Kanji", df.poll());
procFile.Data().put("DB_Group_Long", df.poll());
procFile.Data().put("DB_Group_Short", df.poll());
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.FileCmd_GotInfo, procFile.Id());
}
if (!procFile.IsFinal() && !(procFile.ActionsTodo().contains(eAction.FileCmd) || (procFile.ActionsTodo().contains(eAction.MyListCmd)))) {
finalProcessing(procFile);
}
}
private void aniDBMyListReply(int queryId) {
//System.out.println("Got ML Reply");
Query query = api.Queries().get(queryId);
int replyId = query.getReply().ReplyId();
int fileId = Integer.parseInt(query.getReply().Tag());
if (!files.contains("Id", fileId)) {
//System.out.println("MLCmd: Id not found");
return; //File not found (Todo: throw error)
}
FileInfo procFile = files.get("Id", fileId);
procFile.ActionsTodo().remove(eAction.MyListCmd);
if (replyId == 210 || replyId == 311) {
//File Added/Edited
procFile.ActionsDone().add(eAction.MyListCmd);
if(procFile.ActionsTodo().remove(eAction.Watched)){
procFile.ActionsDone().add(eAction.Watched);
}
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.MLCmd_FileAdded, procFile.Id());
} else if (replyId == 310) {
//File Already Added
procFile.ActionsTodo().add(eAction.MyListCmd);
Cmd cmd = new Cmd(query.getCmd(), true);
cmd.setArgs("edit", "1");
api.queryCmd(cmd);
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.MLCmd_AlreadyAdded, procFile.Id());
} else {
procFile.ActionsError().add(eAction.MyListCmd);
if(procFile.ActionsTodo().remove(eAction.Watched)){
procFile.ActionsError().add(eAction.Watched);
}
if (replyId == 320 || replyId == 330 || replyId == 350) {
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.MLCmd_NotFound, procFile.Id());
} else {
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.MLCmd_Error, procFile.Id());
}
}
if (!procFile.IsFinal() && !(procFile.ActionsTodo().contains(eAction.FileCmd) || (procFile.ActionsTodo().contains(eAction.MyListCmd)))) {
finalProcessing(procFile);
}
}
private void aniDBVoteReply(int queryId) {
Query query = api.Queries().get(queryId);
int replyId = query.getReply().ReplyId();
int fileId = Integer.parseInt(query.getReply().Tag());
if (!files.contains("Id", fileId)) {
return; //File not found (Todo: throw error)
}
FileInfo procFile = files.get("Id", fileId);
procFile.ActionsTodo().remove(eAction.MyListCmd);
if (replyId == 260 && replyId == 262) {
procFile.Data().put("Voted", "true"); //Voted
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.VoteCmd_EpVoted, procFile.Id());
} else if (replyId == 263) {
procFile.Data().put("Voted", "false");//Revoked
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.VoteCmd_EpVoteRevoked, procFile.Id());
} else if (replyId == 363) {
//PermVote Not Allowed
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.VoteCmd_Error, procFile.Id());
}
}
private void finalProcessing(FileInfo procFile) {
//System.out.println("Final processing");
procFile.IsFinal(true);
if (procFile.Data().get("Vote") != null) {
requestDBVote(procFile);
}
if (procFile.ActionsTodo().contains(eAction.Rename) && procFile.ActionsDone().contains(eAction.FileCmd)) {
procFile.ActionsTodo().remove(eAction.Rename);
if(renameFile(procFile)) {
procFile.ActionsDone().add(eAction.Rename);
} else {
procFile.ActionsError().add(eAction.Rename);
}
}
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.Done, procFile.Id());
}
private boolean renameFile(FileInfo procFile){
String folder="";
String filename="";
try {
TreeMap<String,String> ts = getPathFromTagSystem(procFile);
File folderObj = null;
- if((Boolean)mem.get("GUI_EnableFileMove")){
- if((Boolean)mem.get("GUI_MoveTypeUseFolder")){
+ if((Boolean)mem.get("GUI_EnableFileMove")) {
+ if((Boolean)mem.get("GUI_MoveTypeUseFolder")) {
folder = (String)mem.get("GUI_MoveToFolder");
- if((Boolean) mem.get("GUI_AppendAnimeTitle")){
+ if((Boolean) mem.get("GUI_AppendAnimeTitle")) {
int titleType = (Integer)mem.get("GUI_AppendAnimeTitleType");
folder += titleType==0?procFile.Data().get("DB_SN_English"):(titleType==1?procFile.Data().get("DB_SN_Romaji"):procFile.Data().get("DB_SN_Kanji")) + java.io.File.separatorChar;
}
} else {
folder = ts.get("PathName");
}
folder = folder.substring(0, 3) + folder.substring(3).replaceAll("[\":/*|<>?]", "");
if(folder.isEmpty()){
folder = procFile.FileObj().getParent() + java.io.File.separatorChar;
} else if(folder.length() > 240) {
throw new Exception("Pathname (Folder) too long");
}
folderObj = new File(folder);
if(!folderObj.isAbsolute()){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), "Folderpath needs to be absolute.");
return false;
}
folderObj.mkdir();
+ } else {
+ folderObj = new File(procFile.FileObj().getAbsolutePath());
}
String ext = procFile.FileObj().getName().substring(procFile.FileObj().getName().lastIndexOf("."));
if((Boolean)mem.get("GUI_RenameTypeAniDBFileName")){
filename = procFile.Data().get("DB_FileName");
} else {
filename = ts.get("FileName").replaceAll("[\\\\:\"/*|<>?]", "") + ext;
}
if(filename.length()+ folder.length() > 240) filename = filename.substring(0, 240-folder.length()-ext.length())+ext;
File renFile = (folderObj!=null)?(new File(folderObj, filename)):(new File(filename));
if(renFile.exists()){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), "Destination filename already exists.");
return false;
} else if(procFile.FileObj().renameTo(renFile)){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.FileRenamed, procFile.Id(), procFile.FileObj());
procFile.FileObj(renFile);
return true;
} else {
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj());
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), ex.getMessage());
return false;
}
}
private TreeMap<String,String> getPathFromTagSystem(FileInfo procFile) throws Exception {
TagSystem ts = new TagSystem();
TreeMap<String, String> tags = new TreeMap<String, String>();
tags.put("ATr", procFile.Data().get("DB_SN_Romaji"));
tags.put("ATe", procFile.Data().get("DB_SN_English"));
tags.put("ATk", procFile.Data().get("DB_SN_Kanji"));
tags.put("ATs", procFile.Data().get("DB_Synonym"));
tags.put("ATo", procFile.Data().get("DB_SN_Other"));
tags.put("ETr", procFile.Data().get("DB_EpN_Romaji"));
tags.put("ETe", procFile.Data().get("DB_EpN_English"));
tags.put("ETk", procFile.Data().get("DB_EpN_Kanji"));
tags.put("GTs", procFile.Data().get("DB_Group_Short"));
tags.put("GTl", procFile.Data().get("DB_Group_Long"));
tags.put("EpNo", procFile.Data().get("DB_EpNo"));
tags.put("EpHiNo", procFile.Data().get("DB_EpHiCount"));
tags.put("EpCount", procFile.Data().get("DB_EpCount"));
tags.put("Quality", procFile.Data().get("DB_Quality"));
tags.put("Source", procFile.Data().get("DB_Source"));
tags.put("Type", procFile.Data().get("DB_Type"));
tags.put("Watched", procFile.ActionsDone().contains(eAction.Watched) ? "1" : "");
tags.put("Depr", procFile.Data().get("DB_Deprecated").equals("1") ? "1" : "");
tags.put("Cen", ((Integer.valueOf(procFile.Data().get("DB_State")) & 8) != 0 ? "1" : ""));
tags.put("Ver", GetFileVersion(Integer.valueOf(procFile.Data().get("DB_State"))).toString());
//String path = "";
ts.parseAndTransform((String)mem.get("GUI_TagSystemCode"), tags);
return tags;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Public Methods">
public FileInfo id2FileInfo(int id) { return files.get("Id", id); }
public FileInfo index2FileInfo(int index) { return files.get("Id", index2Id.get(index));}
public int Index2Id(int index){ return index2Id.get(index); }
public int Id2Index(int id){ return Misc.binarySearch(index2Id, id); }
public int FileCount() { return files.size(); }
public void addFiles(Collection<File> newFiles) {
Integer storage = (Integer) mem.get("GUI_SetStorageType", 1);
boolean watched = (Boolean) mem.get("GUI_SetWatched", false);
boolean rename = (Boolean) mem.get("GUI_RenameFiles", false);
boolean addToMyList = (Boolean) mem.get("GUI_AddToMyList", false);
String otherStr="", sourceStr="", storageStr="";
if((Boolean)mem.get("GUI_ShowSrcStrOtEditBoxes", false)){
otherStr = (String)mem.get("GUI_OtherText","");
sourceStr = (String)mem.get("GUI_SourceText","");
storageStr = (String)mem.get("GUI_StorageText", "");
}
for (File cf : newFiles) {
if (files.contains("Path", cf.getAbsolutePath())) continue;
FileInfo fileInfo = new FileInfo(cf, lastFileId);
fileInfo.MLStorage(FileInfo.eMLStorageState.values()[storage]);
fileInfo.ActionsTodo().add(eAction.Process);
fileInfo.ActionsTodo().add(eAction.FileCmd);
if (addToMyList) fileInfo.ActionsTodo().add(eAction.MyListCmd);
if (watched) fileInfo.ActionsTodo().add(eAction.Watched);
if (rename) fileInfo.ActionsTodo().add(eAction.Rename);
if(!otherStr.isEmpty()) fileInfo.Data().put("EditOther", otherStr);
if(!sourceStr.isEmpty()) fileInfo.Data().put("EditSource", sourceStr);
if(!storageStr.isEmpty()) fileInfo.Data().put("EditStorage", storageStr);
index2Id.add(lastFileId++);
files.put(fileInfo);
}
Log(ComEvent.eType.Information, eComType.FileCountChanged);
}
public void addFile(File cf) {
ArrayList<File> lst = new ArrayList<File>();
lst.add(cf);
addFiles(lst);
}
public void delFile(int index) {
files.remove("Id", index2Id.get(index));
index2Id.remove(index);
Log(ComEvent.eType.Information, eComType.FileCountChanged);
}
public void processing(eProcess proc) {
switch (proc) {
case Start:
//System.out.println("Processing started");
Log(ComEvent.eType.Information, eComType.Status, eProcess.Start);
isProcessing = true;
isPaused = false;
processEps();
break;
case Pause:
//System.out.println("Processing paused");
Log(ComEvent.eType.Information, eComType.Status, eProcess.Pause);
isPaused = true;
if(fileParser!=null) fileParser.pause();
break;
case Resume:
//System.out.println("Processing resumed");
Log(ComEvent.eType.Information, eComType.Status, eProcess.Resume);
if(fileParser!=null) fileParser.resume();
isPaused = false;
break;
case Stop:
//System.out.println("Processing stopped");
Log(ComEvent.eType.Information, eComType.Status, eProcess.Stop);
//Not yet supported
isProcessing = false;
isPaused = false;
break;
}
}
public boolean isPaused() {return isPaused;}
public boolean isProcessing(){return isProcessing;}
public int processedFileCount(){
int count=0;
for (FileInfo fi : files.values()) {
if(fi.ActionsDone().contains(eAction.Process)) count++;
}
return count;
}
public long processedBytes(){
long count=0;
for (FileInfo fi : files.values()) {
if(fi.ActionsDone().contains(eAction.Process)) count += fi.FileObj().length();
}
//if(fileParser!=null) count += fileParser.getBytesRead();
return count;
}
public long processedBytesCurrentFile(){
long count=0;
if(fileParser!=null) count += fileParser.getBytesRead();
return count;
}
public long totalBytesCurrentFile() { return fileParser!=null?fileParser.getByteCount():0; }
public long totalBytes(){
long count=0;
for (FileInfo fi : files.values()) count += fi.FileObj().length();
return count;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="IModule">
protected String modName = "EpProcessing";
protected eModState modState = eModState.New;
public eModState ModState() { return modState; }
public String ModuleName() {return modName;}
public void Initialize(IAniAdd aniAdd) {
modState = eModState.Initializing;
this.aniAdd = aniAdd;
aniAdd.AddComListener(new AniAddEventHandler());
mem = (Mod_Memory)aniAdd.GetModule("Memory");
api = (Mod_UdpApi)aniAdd.GetModule("UdpApi");
api.registerEvent(new ICallBack<Integer>() {
public void invoke(Integer queryIndex) {
aniDBInfoReply(queryIndex);
}
}, "file");
api.registerEvent(new ICallBack<Integer>() {
public void invoke(Integer queryIndex) {
aniDBMyListReply(queryIndex);
}
}, "mladd", "mldel");
api.registerEvent(new ICallBack<Integer>() {
public void invoke(Integer queryIndex) {
}
}, "vote");
modState = eModState.Initialized;
}
public void Terminate() {
modState = eModState.Terminating;
isProcessing = false;
if(fileParser != null) fileParser.terminate();
modState = eModState.Terminated;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Com System">
private ArrayList<ComListener> listeners = new ArrayList<ComListener>();
protected void ComFire(ComEvent comEvent){
for (ComListener listener : listeners) {
listener.EventHandler(comEvent);
}
}
public void AddComListener(ComListener comListener){ listeners.add(comListener); }
public void RemoveComListener(ComListener comListener){ listeners.remove(comListener); }
class AniAddEventHandler implements ComListener{
public void EventHandler(ComEvent comEvent) {
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Misc">
protected void Log(ComEvent.eType type, Object... params){
ComFire(new ComEvent(this, type, params));
}
public enum eProcess {
Start, Pause, Resume, Stop
}
public enum eComType {
FileSettings,
FileCountChanged,
FileEvent,
Status
}
public enum eComSubType{
Processing,
NoWriteAccess,
GotFromHistory,
ParsingDone,
ParsingError,
GetDBInfo,
FileCmd_NotFound,
FileCmd_GotInfo,
FileCmd_Error,
MLCmd_FileAdded,
MLCmd_AlreadyAdded,
MLCmd_FileRemoved,
MLCmd_NotFound,
MLCmd_Error,
VoteCmd_EpVoted,
VoteCmd_EpVoteRevoked,
VoteCmd_Error,
RenamingFailed,
FileRenamed,
RenamingNotNeeded,
RelFilesRenamed,
RelFilesRenamingFailed,
Done
}
public static Integer GetFileVersion(int state){
int verFlag = (state & (4 + 8 + 16 + 32)) >> 2 ;
int version = 1;
while(verFlag != 0){
version++;
verFlag = verFlag>> 1 ;
}
return version;
}
// </editor-fold>
}
| false | true | private boolean renameFile(FileInfo procFile){
String folder="";
String filename="";
try {
TreeMap<String,String> ts = getPathFromTagSystem(procFile);
File folderObj = null;
if((Boolean)mem.get("GUI_EnableFileMove")){
if((Boolean)mem.get("GUI_MoveTypeUseFolder")){
folder = (String)mem.get("GUI_MoveToFolder");
if((Boolean) mem.get("GUI_AppendAnimeTitle")){
int titleType = (Integer)mem.get("GUI_AppendAnimeTitleType");
folder += titleType==0?procFile.Data().get("DB_SN_English"):(titleType==1?procFile.Data().get("DB_SN_Romaji"):procFile.Data().get("DB_SN_Kanji")) + java.io.File.separatorChar;
}
} else {
folder = ts.get("PathName");
}
folder = folder.substring(0, 3) + folder.substring(3).replaceAll("[\":/*|<>?]", "");
if(folder.isEmpty()){
folder = procFile.FileObj().getParent() + java.io.File.separatorChar;
} else if(folder.length() > 240) {
throw new Exception("Pathname (Folder) too long");
}
folderObj = new File(folder);
if(!folderObj.isAbsolute()){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), "Folderpath needs to be absolute.");
return false;
}
folderObj.mkdir();
}
String ext = procFile.FileObj().getName().substring(procFile.FileObj().getName().lastIndexOf("."));
if((Boolean)mem.get("GUI_RenameTypeAniDBFileName")){
filename = procFile.Data().get("DB_FileName");
} else {
filename = ts.get("FileName").replaceAll("[\\\\:\"/*|<>?]", "") + ext;
}
if(filename.length()+ folder.length() > 240) filename = filename.substring(0, 240-folder.length()-ext.length())+ext;
File renFile = (folderObj!=null)?(new File(folderObj, filename)):(new File(filename));
if(renFile.exists()){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), "Destination filename already exists.");
return false;
} else if(procFile.FileObj().renameTo(renFile)){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.FileRenamed, procFile.Id(), procFile.FileObj());
procFile.FileObj(renFile);
return true;
} else {
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj());
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), ex.getMessage());
return false;
}
}
| private boolean renameFile(FileInfo procFile){
String folder="";
String filename="";
try {
TreeMap<String,String> ts = getPathFromTagSystem(procFile);
File folderObj = null;
if((Boolean)mem.get("GUI_EnableFileMove")) {
if((Boolean)mem.get("GUI_MoveTypeUseFolder")) {
folder = (String)mem.get("GUI_MoveToFolder");
if((Boolean) mem.get("GUI_AppendAnimeTitle")) {
int titleType = (Integer)mem.get("GUI_AppendAnimeTitleType");
folder += titleType==0?procFile.Data().get("DB_SN_English"):(titleType==1?procFile.Data().get("DB_SN_Romaji"):procFile.Data().get("DB_SN_Kanji")) + java.io.File.separatorChar;
}
} else {
folder = ts.get("PathName");
}
folder = folder.substring(0, 3) + folder.substring(3).replaceAll("[\":/*|<>?]", "");
if(folder.isEmpty()){
folder = procFile.FileObj().getParent() + java.io.File.separatorChar;
} else if(folder.length() > 240) {
throw new Exception("Pathname (Folder) too long");
}
folderObj = new File(folder);
if(!folderObj.isAbsolute()){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), "Folderpath needs to be absolute.");
return false;
}
folderObj.mkdir();
} else {
folderObj = new File(procFile.FileObj().getAbsolutePath());
}
String ext = procFile.FileObj().getName().substring(procFile.FileObj().getName().lastIndexOf("."));
if((Boolean)mem.get("GUI_RenameTypeAniDBFileName")){
filename = procFile.Data().get("DB_FileName");
} else {
filename = ts.get("FileName").replaceAll("[\\\\:\"/*|<>?]", "") + ext;
}
if(filename.length()+ folder.length() > 240) filename = filename.substring(0, 240-folder.length()-ext.length())+ext;
File renFile = (folderObj!=null)?(new File(folderObj, filename)):(new File(filename));
if(renFile.exists()){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), "Destination filename already exists.");
return false;
} else if(procFile.FileObj().renameTo(renFile)){
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.FileRenamed, procFile.Id(), procFile.FileObj());
procFile.FileObj(renFile);
return true;
} else {
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj());
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
Log(ComEvent.eType.Information, eComType.FileEvent, eComSubType.RenamingFailed, procFile.Id(), procFile.FileObj(), ex.getMessage());
return false;
}
}
|
diff --git a/3rdPartyServices/EnterpriseServices/Calendar/org.societies.sharedCalendar/src/main/java/org/societies/rdPartyService/enterprise/sharedCalendar/commsServer/SharedCalendarCommServer.java b/3rdPartyServices/EnterpriseServices/Calendar/org.societies.sharedCalendar/src/main/java/org/societies/rdPartyService/enterprise/sharedCalendar/commsServer/SharedCalendarCommServer.java
index cc2f54bf..981229c1 100644
--- a/3rdPartyServices/EnterpriseServices/Calendar/org.societies.sharedCalendar/src/main/java/org/societies/rdPartyService/enterprise/sharedCalendar/commsServer/SharedCalendarCommServer.java
+++ b/3rdPartyServices/EnterpriseServices/Calendar/org.societies.sharedCalendar/src/main/java/org/societies/rdPartyService/enterprise/sharedCalendar/commsServer/SharedCalendarCommServer.java
@@ -1,191 +1,191 @@
/**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE 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 org.societies.rdPartyService.enterprise.sharedCalendar.commsServer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.societies.api.comm.xmpp.datatypes.Stanza;
import org.societies.api.comm.xmpp.exceptions.CommunicationException;
import org.societies.api.comm.xmpp.exceptions.XMPPError;
import org.societies.api.comm.xmpp.interfaces.ICommManager;
import org.societies.api.comm.xmpp.interfaces.IFeatureServer;
import org.societies.rdPartyService.enterprise.sharedCalendar.SharedCalendar;
import org.societies.rdpartyservice.enterprise.sharedcalendar.Calendar;
import org.societies.rdpartyservice.enterprise.sharedcalendar.Event;
import org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarResult;
/**
* This is the Shared Calendar Communication Manager that marshalls / unmarshalls XMPP messages
* and routes them to/from the correct Shared Calendar Server functionality.
*
* @author solutanet
*
*/
public class SharedCalendarCommServer implements IFeatureServer{
private ICommManager commManager;
private SharedCalendar sharedCalendarService;
private static final List<String> NAMESPACES = Collections.unmodifiableList(
Arrays.asList("http://societies.org/rdPartyService/enterprise/sharedCalendar"));
private static final List<String> PACKAGES = Collections.unmodifiableList(
Arrays.asList("org.societies.rdpartyservice.enterprise.sharedcalendar"));
//PROPERTIES
public ICommManager getCommManager() {
return commManager;
}
public void setCommManager(ICommManager commManager) {
this.commManager = commManager;
}
public SharedCalendar getSharedCalendarService() {
return sharedCalendarService;
}
public void setSharedCalendarService(SharedCalendar sharedCalendarService) {
this.sharedCalendarService = sharedCalendarService;
}
public void initService() {
// REGISTER OUR ServiceManager WITH THE XMPP Communication Manager
ICommManager cm = getCommManager();
try {
cm.register(this);
} catch (CommunicationException e) {
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see org.societies.api.comm.xmpp.interfaces.IFeatureServer#getXMLNamespaces()
*/
@Override
public List<String> getXMLNamespaces() {
// TODO Auto-generated method stub
return SharedCalendarCommServer.NAMESPACES;
}
/* (non-Javadoc)
* @see org.societies.api.comm.xmpp.interfaces.IFeatureServer#getJavaPackages()
*/
@Override
public List<String> getJavaPackages() {
// TODO Auto-generated method stub
return SharedCalendarCommServer.PACKAGES;
}
/* (non-Javadoc)
* @see org.societies.api.comm.xmpp.interfaces.IFeatureServer#receiveMessage(org.societies.api.comm.xmpp.datatypes.Stanza, java.lang.Object)
*/
@Override
public void receiveMessage(Stanza stanza, Object payload) {
// TODO Auto-generated method stub
System.out.println(stanza);
if (payload instanceof Calendar){
System.out.println((Calendar)payload);
}
}
/* (non-Javadoc)
* @see org.societies.api.comm.xmpp.interfaces.IFeatureServer#getQuery(org.societies.api.comm.xmpp.datatypes.Stanza, java.lang.Object)
*/
@Override
public Object getQuery(Stanza stanza, Object payload) throws XMPPError {
org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean bean = null;
SharedCalendarResult resultBean = new SharedCalendarResult();
if (payload instanceof org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean){
bean = (org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean) payload;
switch (bean.getMethod()) {
case DELETE_CIS_CALENDAR:
resultBean.setLastOperationSuccessful(this.sharedCalendarService.deleteCISCalendar(bean.getCISId()));
break;
case RETRIEVE_CIS_CALENDAR_LIST:
List<Calendar> retrievedCalendars = this.sharedCalendarService.retrieveCISCalendarList(bean.getCISId());
resultBean.setCalendarList(retrievedCalendars);
break;
- case RETRIEVE_CALENDAR_EVENTS:
+ case RETRIEVE_CIS_CALENDAR_EVENTS:
List<Event> retrievedEvents = this.sharedCalendarService.retrieveCalendarEvents(bean.getCalendarId());
resultBean.setEventList(retrievedEvents);
break;
case SUBSCRIBE_TO_EVENT:
resultBean.setSubscribingResult(this.sharedCalendarService.subscribeToEvent(bean.getCalendarId(),bean.getEventId(), bean.getSubscriberId()));
break;
case FIND_EVENTS:
List<Event> foundEvents = this.sharedCalendarService.findEvents(bean.getCalendarId(), bean.getKeyWord());
resultBean.setEventList(foundEvents);
break;
case UNSUBSCRIBE_FROM_EVENT:
resultBean.setSubscribingResult(this.sharedCalendarService.unsubscribeFromEvent(bean.getCalendarId(),bean.getEventId(), bean.getSubscriberId()));
break;
case CREATE_PRIVATE_CALENDAR:
resultBean.setLastOperationSuccessful(
this.sharedCalendarService.createPrivateCalendarUsingCSSId(stanza.getFrom().getJid(), bean.getCalendarSummary())
);
break;
case DELETE_PRIVATE_CALENDAR:
resultBean.setLastOperationSuccessful(this.sharedCalendarService.deletePrivateCalendar());
break;
case CREATE_EVENT_ON_PRIVATE_CALENDAR:
String calendarId = this.sharedCalendarService.retrievePrivateCalendarId(stanza.getFrom().getJid());
if (calendarId != null) {
String returnedEventId = this.sharedCalendarService.createEventOnPrivateCalendarUsingCSSId(calendarId, bean.getNewEvent());
resultBean.setEventId(returnedEventId);
}
break;
- case RETRIEVE_EVENTS_PRIVATE_CALENDAR:
+ case RETRIEVE_EVENTS_ON_PRIVATE_CALENDAR:
String calendarIdForAllEvents = this.sharedCalendarService.retrievePrivateCalendarId(stanza.getFrom().getJid());
if (calendarIdForAllEvents != null) {
List<Event> returnedPrivateCalendarEventList = this.sharedCalendarService.retrieveCalendarEvents(calendarIdForAllEvents);
resultBean.setEventList(returnedPrivateCalendarEventList);
}
break;
default:
resultBean = null;
break;
}
}
return resultBean;
}
/* (non-Javadoc)
* @see org.societies.api.comm.xmpp.interfaces.IFeatureServer#setQuery(org.societies.api.comm.xmpp.datatypes.Stanza, java.lang.Object)
*/
@Override
public Object setQuery(Stanza stanza, Object payload) throws XMPPError {
// TODO Auto-generated method stub
return null;
}
public SharedCalendarCommServer() {
super();
// TODO Auto-generated constructor stub
}
}
| false | true | public Object getQuery(Stanza stanza, Object payload) throws XMPPError {
org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean bean = null;
SharedCalendarResult resultBean = new SharedCalendarResult();
if (payload instanceof org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean){
bean = (org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean) payload;
switch (bean.getMethod()) {
case DELETE_CIS_CALENDAR:
resultBean.setLastOperationSuccessful(this.sharedCalendarService.deleteCISCalendar(bean.getCISId()));
break;
case RETRIEVE_CIS_CALENDAR_LIST:
List<Calendar> retrievedCalendars = this.sharedCalendarService.retrieveCISCalendarList(bean.getCISId());
resultBean.setCalendarList(retrievedCalendars);
break;
case RETRIEVE_CALENDAR_EVENTS:
List<Event> retrievedEvents = this.sharedCalendarService.retrieveCalendarEvents(bean.getCalendarId());
resultBean.setEventList(retrievedEvents);
break;
case SUBSCRIBE_TO_EVENT:
resultBean.setSubscribingResult(this.sharedCalendarService.subscribeToEvent(bean.getCalendarId(),bean.getEventId(), bean.getSubscriberId()));
break;
case FIND_EVENTS:
List<Event> foundEvents = this.sharedCalendarService.findEvents(bean.getCalendarId(), bean.getKeyWord());
resultBean.setEventList(foundEvents);
break;
case UNSUBSCRIBE_FROM_EVENT:
resultBean.setSubscribingResult(this.sharedCalendarService.unsubscribeFromEvent(bean.getCalendarId(),bean.getEventId(), bean.getSubscriberId()));
break;
case CREATE_PRIVATE_CALENDAR:
resultBean.setLastOperationSuccessful(
this.sharedCalendarService.createPrivateCalendarUsingCSSId(stanza.getFrom().getJid(), bean.getCalendarSummary())
);
break;
case DELETE_PRIVATE_CALENDAR:
resultBean.setLastOperationSuccessful(this.sharedCalendarService.deletePrivateCalendar());
break;
case CREATE_EVENT_ON_PRIVATE_CALENDAR:
String calendarId = this.sharedCalendarService.retrievePrivateCalendarId(stanza.getFrom().getJid());
if (calendarId != null) {
String returnedEventId = this.sharedCalendarService.createEventOnPrivateCalendarUsingCSSId(calendarId, bean.getNewEvent());
resultBean.setEventId(returnedEventId);
}
break;
case RETRIEVE_EVENTS_PRIVATE_CALENDAR:
String calendarIdForAllEvents = this.sharedCalendarService.retrievePrivateCalendarId(stanza.getFrom().getJid());
if (calendarIdForAllEvents != null) {
List<Event> returnedPrivateCalendarEventList = this.sharedCalendarService.retrieveCalendarEvents(calendarIdForAllEvents);
resultBean.setEventList(returnedPrivateCalendarEventList);
}
break;
default:
resultBean = null;
break;
}
}
return resultBean;
}
| public Object getQuery(Stanza stanza, Object payload) throws XMPPError {
org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean bean = null;
SharedCalendarResult resultBean = new SharedCalendarResult();
if (payload instanceof org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean){
bean = (org.societies.rdpartyservice.enterprise.sharedcalendar.SharedCalendarBean) payload;
switch (bean.getMethod()) {
case DELETE_CIS_CALENDAR:
resultBean.setLastOperationSuccessful(this.sharedCalendarService.deleteCISCalendar(bean.getCISId()));
break;
case RETRIEVE_CIS_CALENDAR_LIST:
List<Calendar> retrievedCalendars = this.sharedCalendarService.retrieveCISCalendarList(bean.getCISId());
resultBean.setCalendarList(retrievedCalendars);
break;
case RETRIEVE_CIS_CALENDAR_EVENTS:
List<Event> retrievedEvents = this.sharedCalendarService.retrieveCalendarEvents(bean.getCalendarId());
resultBean.setEventList(retrievedEvents);
break;
case SUBSCRIBE_TO_EVENT:
resultBean.setSubscribingResult(this.sharedCalendarService.subscribeToEvent(bean.getCalendarId(),bean.getEventId(), bean.getSubscriberId()));
break;
case FIND_EVENTS:
List<Event> foundEvents = this.sharedCalendarService.findEvents(bean.getCalendarId(), bean.getKeyWord());
resultBean.setEventList(foundEvents);
break;
case UNSUBSCRIBE_FROM_EVENT:
resultBean.setSubscribingResult(this.sharedCalendarService.unsubscribeFromEvent(bean.getCalendarId(),bean.getEventId(), bean.getSubscriberId()));
break;
case CREATE_PRIVATE_CALENDAR:
resultBean.setLastOperationSuccessful(
this.sharedCalendarService.createPrivateCalendarUsingCSSId(stanza.getFrom().getJid(), bean.getCalendarSummary())
);
break;
case DELETE_PRIVATE_CALENDAR:
resultBean.setLastOperationSuccessful(this.sharedCalendarService.deletePrivateCalendar());
break;
case CREATE_EVENT_ON_PRIVATE_CALENDAR:
String calendarId = this.sharedCalendarService.retrievePrivateCalendarId(stanza.getFrom().getJid());
if (calendarId != null) {
String returnedEventId = this.sharedCalendarService.createEventOnPrivateCalendarUsingCSSId(calendarId, bean.getNewEvent());
resultBean.setEventId(returnedEventId);
}
break;
case RETRIEVE_EVENTS_ON_PRIVATE_CALENDAR:
String calendarIdForAllEvents = this.sharedCalendarService.retrievePrivateCalendarId(stanza.getFrom().getJid());
if (calendarIdForAllEvents != null) {
List<Event> returnedPrivateCalendarEventList = this.sharedCalendarService.retrieveCalendarEvents(calendarIdForAllEvents);
resultBean.setEventList(returnedPrivateCalendarEventList);
}
break;
default:
resultBean = null;
break;
}
}
return resultBean;
}
|
diff --git a/printmodel/src/org/hanuna/gitalk/printmodel/layout/LayoutRowGenerator.java b/printmodel/src/org/hanuna/gitalk/printmodel/layout/LayoutRowGenerator.java
index e9188c8..54fd880 100644
--- a/printmodel/src/org/hanuna/gitalk/printmodel/layout/LayoutRowGenerator.java
+++ b/printmodel/src/org/hanuna/gitalk/printmodel/layout/LayoutRowGenerator.java
@@ -1,100 +1,103 @@
package org.hanuna.gitalk.printmodel.layout;
import org.hanuna.gitalk.common.compressedlist.generator.AbstractGenerator;
import org.hanuna.gitalk.graph.Graph;
import org.hanuna.gitalk.graph.elements.Edge;
import org.hanuna.gitalk.graph.elements.GraphElement;
import org.hanuna.gitalk.graph.elements.Node;
import org.hanuna.gitalk.graph.elements.NodeRow;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author erokhins
*/
class LayoutRowGenerator extends AbstractGenerator<MutableLayoutRow, LayoutRow> {
private final Graph graph;
public LayoutRowGenerator(@NotNull Graph graph) {
this.graph = graph;
}
@NotNull
@Override
protected MutableLayoutRow createMutable(@NotNull LayoutRow cellRow) {
return new MutableLayoutRow(cellRow);
}
@NotNull
private List<Edge> orderAddEdges(@NotNull List<Edge> edges) {
if (edges.size() <= 1) {
return edges;
} else {
List<Edge> sortEdges = new ArrayList<Edge>(edges);
Collections.sort(sortEdges, new Comparator<Edge>() {
@Override
public int compare(Edge o1, Edge o2) {
if (o1.getDownNode().getRowIndex() > o2.getDownNode().getRowIndex()) {
return -1;
} else {
return 1;
}
}
});
return sortEdges;
}
}
@NotNull
@Override
protected MutableLayoutRow oneStep(@NotNull MutableLayoutRow row) {
int newRowIndex = row.getGraphNodeRow().getRowIndex() + 1;
if (newRowIndex == graph.getNodeRows().size()) {
throw new NoSuchElementException();
}
List<GraphElement> layoutRow = row.getModifiableOrderedGraphElements();
+ Set<Node> addedNodeInNextRow = new HashSet<Node>();
for (ListIterator<GraphElement> iterator = layoutRow.listIterator(); iterator.hasNext(); ) {
GraphElement element = iterator.next();
Node node = element.getNode();
if (node != null) {
List<Edge> edges = node.getDownEdges();
if (edges.size() == 0) {
iterator.remove();
} else {
iterator.remove();
for (Edge edge : orderAddEdges(edges)) {
Node downNode = edge.getDownNode();
if (downNode.getRowIndex() == newRowIndex) {
- if (downNode.getBranch() == edge.getBranch()) {
+ if (!addedNodeInNextRow.contains(downNode)) {
iterator.add(downNode);
+ addedNodeInNextRow.add(downNode);
}
} else {
iterator.add(edge);
}
}
}
} else {
Edge edge = element.getEdge();
if (edge == null) {
throw new IllegalStateException("unexpected element class");
}
if (edge.getDownNode().getRowIndex() == newRowIndex) {
- if (edge.getBranch() == edge.getDownNode().getBranch()) {
+ if (!addedNodeInNextRow.contains(edge.getDownNode())) {
iterator.set(edge.getDownNode());
+ addedNodeInNextRow.add(edge.getDownNode());
} else {
iterator.remove();
}
}
}
}
NodeRow nextGraphRow = graph.getNodeRows().get(newRowIndex);
for (Node node : nextGraphRow.getNodes()) {
if (node.getUpEdges().isEmpty()) {
layoutRow.add(node);
}
}
row.setNodeRow(nextGraphRow);
return row;
}
}
| false | true | protected MutableLayoutRow oneStep(@NotNull MutableLayoutRow row) {
int newRowIndex = row.getGraphNodeRow().getRowIndex() + 1;
if (newRowIndex == graph.getNodeRows().size()) {
throw new NoSuchElementException();
}
List<GraphElement> layoutRow = row.getModifiableOrderedGraphElements();
for (ListIterator<GraphElement> iterator = layoutRow.listIterator(); iterator.hasNext(); ) {
GraphElement element = iterator.next();
Node node = element.getNode();
if (node != null) {
List<Edge> edges = node.getDownEdges();
if (edges.size() == 0) {
iterator.remove();
} else {
iterator.remove();
for (Edge edge : orderAddEdges(edges)) {
Node downNode = edge.getDownNode();
if (downNode.getRowIndex() == newRowIndex) {
if (downNode.getBranch() == edge.getBranch()) {
iterator.add(downNode);
}
} else {
iterator.add(edge);
}
}
}
} else {
Edge edge = element.getEdge();
if (edge == null) {
throw new IllegalStateException("unexpected element class");
}
if (edge.getDownNode().getRowIndex() == newRowIndex) {
if (edge.getBranch() == edge.getDownNode().getBranch()) {
iterator.set(edge.getDownNode());
} else {
iterator.remove();
}
}
}
}
NodeRow nextGraphRow = graph.getNodeRows().get(newRowIndex);
for (Node node : nextGraphRow.getNodes()) {
if (node.getUpEdges().isEmpty()) {
layoutRow.add(node);
}
}
row.setNodeRow(nextGraphRow);
return row;
}
| protected MutableLayoutRow oneStep(@NotNull MutableLayoutRow row) {
int newRowIndex = row.getGraphNodeRow().getRowIndex() + 1;
if (newRowIndex == graph.getNodeRows().size()) {
throw new NoSuchElementException();
}
List<GraphElement> layoutRow = row.getModifiableOrderedGraphElements();
Set<Node> addedNodeInNextRow = new HashSet<Node>();
for (ListIterator<GraphElement> iterator = layoutRow.listIterator(); iterator.hasNext(); ) {
GraphElement element = iterator.next();
Node node = element.getNode();
if (node != null) {
List<Edge> edges = node.getDownEdges();
if (edges.size() == 0) {
iterator.remove();
} else {
iterator.remove();
for (Edge edge : orderAddEdges(edges)) {
Node downNode = edge.getDownNode();
if (downNode.getRowIndex() == newRowIndex) {
if (!addedNodeInNextRow.contains(downNode)) {
iterator.add(downNode);
addedNodeInNextRow.add(downNode);
}
} else {
iterator.add(edge);
}
}
}
} else {
Edge edge = element.getEdge();
if (edge == null) {
throw new IllegalStateException("unexpected element class");
}
if (edge.getDownNode().getRowIndex() == newRowIndex) {
if (!addedNodeInNextRow.contains(edge.getDownNode())) {
iterator.set(edge.getDownNode());
addedNodeInNextRow.add(edge.getDownNode());
} else {
iterator.remove();
}
}
}
}
NodeRow nextGraphRow = graph.getNodeRows().get(newRowIndex);
for (Node node : nextGraphRow.getNodes()) {
if (node.getUpEdges().isEmpty()) {
layoutRow.add(node);
}
}
row.setNodeRow(nextGraphRow);
return row;
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/romanNumerals/RomanNumerals.java b/src/main/java/com/github/kpacha/jkata/romanNumerals/RomanNumerals.java
index c7c388b..80d255d 100644
--- a/src/main/java/com/github/kpacha/jkata/romanNumerals/RomanNumerals.java
+++ b/src/main/java/com/github/kpacha/jkata/romanNumerals/RomanNumerals.java
@@ -1,8 +1,11 @@
package com.github.kpacha.jkata.romanNumerals;
public class RomanNumerals {
public static String convert(int number) {
+ if (number == 2) {
+ return "II";
+ }
return "I";
}
}
| true | true | public static String convert(int number) {
return "I";
}
| public static String convert(int number) {
if (number == 2) {
return "II";
}
return "I";
}
|
diff --git a/src/haven/error/ErrorGui.java b/src/haven/error/ErrorGui.java
index 7f311d9..efdac15 100644
--- a/src/haven/error/ErrorGui.java
+++ b/src/haven/error/ErrorGui.java
@@ -1,144 +1,144 @@
package haven.error;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Dialog;
import javax.swing.*;
import java.awt.event.*;
public abstract class ErrorGui extends JDialog implements ErrorStatus {
private JLabel status;
private JPanel vp, dp;
private boolean verified, done;
- public ErrorGui(java.awt.Window parent) {
- super(parent, "Haven error!", Dialog.ModalityType.APPLICATION_MODAL);
+ public ErrorGui(java.awt.Frame parent) {
+ super(parent, "Haven error!", true);
setMinimumSize(new Dimension(300, 100));
setResizable(false);
setLayout(new BorderLayout());
add(status = new JLabel(""), BorderLayout.CENTER);
vp = new JPanel();
vp.setLayout(new FlowLayout());
JButton b;
vp.add(b = new JButton("Yes"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
verified = true;
done = true;
ErrorGui.this.notifyAll();
}
}
});
vp.add(b = new JButton("No"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
verified = false;
done = true;
ErrorGui.this.notifyAll();
}
}
});
dp = new JPanel();
dp.setLayout(new FlowLayout());
dp.add(b = new JButton("OK"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
done = true;
ErrorGui.this.notifyAll();
}
}
});
}
public boolean goterror(Throwable t) {
done = false;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
add(vp, BorderLayout.SOUTH);
status.setText("An error has occurred! Do you wish to report it?");
pack();
setVisible(true);
}
});
synchronized(this) {
try {
while(!done) {
wait();
}
} catch(InterruptedException e) {
throw(new Error(e));
}
}
remove(vp);
pack();
if(!verified)
errorsent();
return(verified);
}
public void connecting() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
status.setText("Connecting to server");
pack();
}
});
}
public void sending() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
status.setText("Sending error");
pack();
}
});
}
public void done() {
done = false;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
add(dp, BorderLayout.SOUTH);
status.setText("Done");
pack();
}
});
synchronized(this) {
try {
while(!done)
wait();
} catch(InterruptedException e) {
throw(new Error(e));
}
}
errorsent();
}
public void senderror(Exception e) {
e.printStackTrace();
done = false;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
add(dp, BorderLayout.SOUTH);
status.setText("An error occurred while sending!");
pack();
}
});
synchronized(this) {
try {
while(!done)
wait();
} catch(InterruptedException e2) {
throw(new Error(e2));
}
}
errorsent();
}
public abstract void errorsent();
}
| true | true | public ErrorGui(java.awt.Window parent) {
super(parent, "Haven error!", Dialog.ModalityType.APPLICATION_MODAL);
setMinimumSize(new Dimension(300, 100));
setResizable(false);
setLayout(new BorderLayout());
add(status = new JLabel(""), BorderLayout.CENTER);
vp = new JPanel();
vp.setLayout(new FlowLayout());
JButton b;
vp.add(b = new JButton("Yes"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
verified = true;
done = true;
ErrorGui.this.notifyAll();
}
}
});
vp.add(b = new JButton("No"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
verified = false;
done = true;
ErrorGui.this.notifyAll();
}
}
});
dp = new JPanel();
dp.setLayout(new FlowLayout());
dp.add(b = new JButton("OK"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
done = true;
ErrorGui.this.notifyAll();
}
}
});
}
| public ErrorGui(java.awt.Frame parent) {
super(parent, "Haven error!", true);
setMinimumSize(new Dimension(300, 100));
setResizable(false);
setLayout(new BorderLayout());
add(status = new JLabel(""), BorderLayout.CENTER);
vp = new JPanel();
vp.setLayout(new FlowLayout());
JButton b;
vp.add(b = new JButton("Yes"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
verified = true;
done = true;
ErrorGui.this.notifyAll();
}
}
});
vp.add(b = new JButton("No"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
verified = false;
done = true;
ErrorGui.this.notifyAll();
}
}
});
dp = new JPanel();
dp.setLayout(new FlowLayout());
dp.add(b = new JButton("OK"));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(ErrorGui.this) {
done = true;
ErrorGui.this.notifyAll();
}
}
});
}
|
diff --git a/src/nu/nerd/modreq/ModReq.java b/src/nu/nerd/modreq/ModReq.java
index c81e5e5..75b5b8d 100755
--- a/src/nu/nerd/modreq/ModReq.java
+++ b/src/nu/nerd/modreq/ModReq.java
@@ -1,496 +1,500 @@
package nu.nerd.modreq;
import com.avaje.ebean.CallableSql;
import com.avaje.ebean.SqlQuery;
import com.avaje.ebean.SqlUpdate;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import javax.persistence.PersistenceException;
import nu.nerd.modreq.database.Request;
import nu.nerd.modreq.database.Request.RequestStatus;
import nu.nerd.modreq.database.RequestTable;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permissible;
import org.bukkit.plugin.java.JavaPlugin;
public class ModReq extends JavaPlugin {
ModReqListener listener = new ModReqListener(this);
RequestTable reqTable;
@Override
public void onEnable() {
setupDatabase();
reqTable = new RequestTable(this);
getServer().getPluginManager().registerEvents(listener, this);
}
@Override
public void onDisable() {
// tear down
}
public boolean setupDatabase() {
try {
getDatabase().find(Request.class).findRowCount();
} catch (PersistenceException ex) {
getLogger().log(Level.INFO, "First run, initializing database.");
installDDL();
return true;
}
return false;
}
public void resetDatabase() {
List<Request> reqs = reqTable.getRequestPage(0, 1000, RequestStatus.OPEN, RequestStatus.CLAIMED);
removeDDL();
if (setupDatabase()) {
for (Request r : reqs) {
Request req = new Request();
req.setPlayerName(r.getPlayerName());
req.setRequest(r.getRequest());
req.setRequestTime(r.getRequestTime());
req.setRequestLocation(r.getRequestLocation());
req.setStatus(r.getStatus());
if (r.getStatus() == RequestStatus.CLAIMED) {
req.setAssignedMod(r.getAssignedMod());
}
req.setFlagForAdmin(r.isFlagForAdmin());
reqTable.save(req);
}
}
}
@Override
public ArrayList<Class<?>> getDatabaseClasses() {
ArrayList<Class<?>> list = new ArrayList<Class<?>>();
list.add(Request.class);
return list;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
String senderName = ChatColor.stripColor(sender.getName());
if (sender instanceof ConsoleCommandSender) {
senderName = "Console";
}
if (command.getName().equalsIgnoreCase("modreq")) {
if (args.length == 0) {
return false;
}
StringBuilder request = new StringBuilder(args[0]);
for (int i = 1; i < args.length; i++) {
request.append(" ").append(args[i]);
}
if (sender instanceof Player) {
Player player = (Player)sender;
if (reqTable.getNumRequestFromUser(senderName) < 5) {
Request req = new Request();
req.setPlayerName(senderName);
req.setRequest(request.toString());
req.setRequestTime(System.currentTimeMillis());
String location = String.format("%s,%f,%f,%f", player.getWorld().getName(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ());
req.setRequestLocation(location);
req.setStatus(RequestStatus.OPEN);
reqTable.save(req);
messageMods(ChatColor.GREEN + "New request. Type /check for more");
sender.sendMessage(ChatColor.GREEN + "Request has been filed. Please be patient for a moderator to complete your request.");
} else {
sender.sendMessage(ChatColor.RED + "You already have 5 open requests, please wait for them to be completed.");
}
}
}
else if (command.getName().equalsIgnoreCase("check")) {
int page = 1;
int requestId = 0;
int totalRequests = 0;
String limitName = null;
if (args.length > 0 && !args[0].startsWith("p:")) {
try {
requestId = Integer.parseInt(args[0]);
page = 0;
} catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "You must provide a number for requests.");
return true;
}
}
if (sender.hasPermission("modreq.check")) {
if (args.length == 0) {
page = 1;
}
else if (args[0].startsWith("p:")) {
try {
page = Integer.parseInt(args[0].substring(2));
} catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "You must provide a number for pages.");
return true;
}
}
}
else {
limitName = senderName;
}
List<Request> requests = new ArrayList<Request>();
if (page > 0) {
if (limitName != null) {
requests.addAll(reqTable.getUserRequests(limitName));
totalRequests = requests.size();
} else {
requests.addAll(reqTable.getRequestPage(page - 1, 5, RequestStatus.OPEN, RequestStatus.CLAIMED));
totalRequests = reqTable.getTotalRequest(RequestStatus.OPEN, RequestStatus.CLAIMED);
}
} else if (requestId > 0) {
Request req = reqTable.getRequest(requestId);
- totalRequests = 1;
- if (limitName != null && req.getPlayerName().equalsIgnoreCase(limitName)) {
- requests.add(req);
- } else if (limitName == null) {
- requests.add(req);
+ if (req != null) {
+ totalRequests = 1;
+ if (limitName != null && req.getPlayerName().equalsIgnoreCase(limitName)) {
+ requests.add(req);
+ } else if (limitName == null) {
+ requests.add(req);
+ } else {
+ totalRequests = 0;
+ }
} else {
totalRequests = 0;
}
}
if (totalRequests == 0) {
if (limitName != null) {
if (requestId > 0) {
sender.sendMessage(ChatColor.GREEN + "Either that request doesn't exist, or you do not have permission to view it.");
}
else {
sender.sendMessage(ChatColor.GREEN + "You don't have any outstanding mod requests.");
}
}
else {
sender.sendMessage(ChatColor.GREEN + "There are currently no open mod requests.");
}
} else if (totalRequests == 1 && requestId > 0) {
messageRequestToPlayer(sender, requests.get(0));
} else if (totalRequests > 0) {
if (page > 1 && requests.size() == 0) {
sender.sendMessage(ChatColor.RED + "There are no requests on that page.");
} else {
boolean showPage = true;
if (limitName != null) {
showPage = false;
}
messageRequestListToPlayer(sender, requests, page, totalRequests, showPage);
}
} else {
// there was an error.
}
}
else if (command.getName().equalsIgnoreCase("tp-id")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
player.sendMessage(ChatColor.GREEN + "[ModReq] Teleporting you to request " + requestId);
Location loc = stringToLocation(req.getRequestLocation());
player.teleport(loc);
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("claim")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if (req.getStatus() == RequestStatus.OPEN) {
req.setStatus(RequestStatus.CLAIMED);
req.setAssignedMod(senderName);
reqTable.save(req);
messageMods(String.format("%s%s is now handling request #%d", ChatColor.GREEN, senderName, requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("unclaim")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if (req.getAssignedMod().equalsIgnoreCase(senderName) && req.getStatus() == RequestStatus.CLAIMED) {
req.setStatus(RequestStatus.OPEN);
req.setAssignedMod(null);
reqTable.save(req);
messageMods(String.format("%s%s is no longer handling request #%d", ChatColor.GREEN, senderName, requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("done")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
String doneMessage = null;
if (args.length > 1) {
StringBuilder doneMessageBuilder = new StringBuilder(args[1]);
for (int i = 2; i < args.length; i++) {
doneMessageBuilder.append(" ").append(args[i]);
}
doneMessage = doneMessageBuilder.toString();
}
Request req = reqTable.getRequest(requestId);
if (req != null && req.getStatus() == RequestStatus.CLOSED) {
sender.sendMessage(ChatColor.RED + "Request Already Closed.");
}
else {
if (sender.hasPermission("modreq.done") && req != null) {
String msg = "";
msg = String.format("%sRequest #%d has been completed by %s", ChatColor.GREEN, requestId, senderName);
messageMods(msg);
if (doneMessage != null && doneMessage.length() != 0) {
msg = String.format("Close Message - %s%s", ChatColor.GRAY, doneMessage);
messageMods(msg);
}
}
else {
if (!req.getPlayerName().equalsIgnoreCase(senderName)) {
req = null;
sender.sendMessage(String.format("%s[ModReq] Error, you can only close your own requests.", ChatColor.RED));
}
}
if (req != null) {
req.setStatus(RequestStatus.CLOSED);
req.setCloseTime(System.currentTimeMillis());
req.setCloseMessage(doneMessage);
req.setAssignedMod(senderName);
Player requestCreator = getServer().getPlayerExact(req.getPlayerName());
if (requestCreator != null) {
if (!requestCreator.getName().equalsIgnoreCase(senderName)) {
String message = "";
if (doneMessage != null && doneMessage.length() != 0) {
message = String.format("%s completed your request - %s%s", senderName, ChatColor.GRAY, doneMessage);
} else {
message = String.format("%s completed your request", senderName);
}
requestCreator.sendMessage(ChatColor.GREEN + message);
}
else {
if (!sender.hasPermission("modreq.done")) {
messageMods(ChatColor.GREEN + String.format("Request #%d no longer needs to be handled", requestId));
sender.sendMessage(ChatColor.GREEN + String.format("Request #%d has been closed by you.", requestId));
}
}
req.setCloseSeenByUser(true);
}
reqTable.save(req);
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("reopen")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if ((req.getAssignedMod().equalsIgnoreCase(senderName) && req.getStatus() == RequestStatus.CLAIMED) || req.getStatus() == RequestStatus.CLOSED) {
req.setStatus(RequestStatus.OPEN);
req.setAssignedMod(null);
req.setCloseSeenByUser(false);
reqTable.save(req);
messageMods(ChatColor.GREEN + String.format("[ModReq] Request #%d is no longer claimed.", requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
} else if (command.getName().equalsIgnoreCase("elevate")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
Request req = reqTable.getRequest(requestId);
if (req.getStatus() == RequestStatus.OPEN) {
req.setFlagForAdmin(true);
messageMods(String.format("%s[ModReq] Request #%d has been flagged for admin.", ChatColor.GREEN, req.getId()));
reqTable.save(req);
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
} else if ( command.getName().equalsIgnoreCase("mr-reset")) {
try {
resetDatabase();
sender.sendMessage(ChatColor.GREEN + "[ModReq] Database has been reset.");
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Failed to reset database", ex);
}
}
return true;
}
private Location stringToLocation(String requestLocation) {
Location loc;
double x, y, z;
String world;
String[] split = requestLocation.split(",");
world = split[0];
x = Double.parseDouble(split[1]);
y = Double.parseDouble(split[2]);
z = Double.parseDouble(split[3]);
loc = new Location(getServer().getWorld(world), x, y, z);
return loc;
}
private String timestampToDateString(long timestamp) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
SimpleDateFormat format = new SimpleDateFormat("[email protected]");
return format.format(cal.getTime());
}
private void messageRequestToPlayer(CommandSender sender, Request req) {
List<String> messages = new ArrayList<String>();
ChatColor onlineStatus = ChatColor.RED;
if (getServer().getPlayerExact(req.getPlayerName()) != null) {
onlineStatus = ChatColor.GREEN;
}
Location loc = stringToLocation(req.getRequestLocation());
String location = String.format("%s, %d, %d, %d", loc.getWorld().getName(), Math.round(loc.getX()), Math.round(loc.getY()), Math.round(loc.getZ()));
messages.add(String.format("%sMod Request #%d - %s%s%s", ChatColor.AQUA, req.getId(), ChatColor.YELLOW, req.getStatus().toString(), ((req.getStatus() == RequestStatus.CLAIMED)?" by " + req.getAssignedMod():"")));
messages.add(String.format("%sFiled by %s%s%s at %s%s%s at %s%s", ChatColor.YELLOW, onlineStatus, req.getPlayerName(), ChatColor.YELLOW, ChatColor.GREEN, timestampToDateString(req.getRequestTime()), ChatColor.YELLOW, ChatColor.GREEN, location));
messages.add(String.format("%s%s", ChatColor.GRAY, req.getRequest()));
sender.sendMessage(messages.toArray(new String[1]));
}
private void messageRequestListToPlayer(CommandSender sender, List<Request> reqs, int page, int totalRequests, boolean showPage) {
List<String> messages = new ArrayList<String>();
messages.add(String.format("%s---- %d Mod Requests ----", ChatColor.AQUA, totalRequests));
for (Request r : reqs) {
ChatColor onlineStatus = ChatColor.RED;
String message = "";
if (r.getRequest().length() > 20) {
message = r.getRequest().substring(0, 17) + "...";
} else {
message = r.getRequest();
}
if (getServer().getPlayerExact(r.getPlayerName()) != null) {
onlineStatus = ChatColor.GREEN;
}
try {
messages.add(String.format("%s#%d.%s [%s%s%s] %s by %s%s%s - %s%s", ChatColor.GOLD, r.getId(), ((r.isFlagForAdmin())?(ChatColor.AQUA + " [ADMIN]" + ChatColor.GOLD):""), ChatColor.GREEN ,((r.getStatus() == RequestStatus.CLAIMED)?r.getAssignedMod():r.getStatus().toString()), ChatColor.GOLD, timestampToDateString(r.getRequestTime()), onlineStatus, r.getPlayerName(), ChatColor.GOLD, ChatColor.GRAY, message));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
if (showPage) {
messages.add(String.format("%s---- Page %d of %d ----", ChatColor.AQUA, page, (int)Math.ceil(totalRequests / 5.0)));
}
sender.sendMessage(messages.toArray(new String[1]));
}
public void messageMods(String message) {
String permission = "modreq.mod";
this.getServer().broadcast(message, permission);
Set<Permissible> subs = getServer().getPluginManager().getPermissionSubscriptions(permission);
for (Player player : getServer().getOnlinePlayers()) {
if (player.hasPermission(permission) && !subs.contains(player)) {
player.sendMessage(message);
}
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
String senderName = ChatColor.stripColor(sender.getName());
if (sender instanceof ConsoleCommandSender) {
senderName = "Console";
}
if (command.getName().equalsIgnoreCase("modreq")) {
if (args.length == 0) {
return false;
}
StringBuilder request = new StringBuilder(args[0]);
for (int i = 1; i < args.length; i++) {
request.append(" ").append(args[i]);
}
if (sender instanceof Player) {
Player player = (Player)sender;
if (reqTable.getNumRequestFromUser(senderName) < 5) {
Request req = new Request();
req.setPlayerName(senderName);
req.setRequest(request.toString());
req.setRequestTime(System.currentTimeMillis());
String location = String.format("%s,%f,%f,%f", player.getWorld().getName(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ());
req.setRequestLocation(location);
req.setStatus(RequestStatus.OPEN);
reqTable.save(req);
messageMods(ChatColor.GREEN + "New request. Type /check for more");
sender.sendMessage(ChatColor.GREEN + "Request has been filed. Please be patient for a moderator to complete your request.");
} else {
sender.sendMessage(ChatColor.RED + "You already have 5 open requests, please wait for them to be completed.");
}
}
}
else if (command.getName().equalsIgnoreCase("check")) {
int page = 1;
int requestId = 0;
int totalRequests = 0;
String limitName = null;
if (args.length > 0 && !args[0].startsWith("p:")) {
try {
requestId = Integer.parseInt(args[0]);
page = 0;
} catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "You must provide a number for requests.");
return true;
}
}
if (sender.hasPermission("modreq.check")) {
if (args.length == 0) {
page = 1;
}
else if (args[0].startsWith("p:")) {
try {
page = Integer.parseInt(args[0].substring(2));
} catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "You must provide a number for pages.");
return true;
}
}
}
else {
limitName = senderName;
}
List<Request> requests = new ArrayList<Request>();
if (page > 0) {
if (limitName != null) {
requests.addAll(reqTable.getUserRequests(limitName));
totalRequests = requests.size();
} else {
requests.addAll(reqTable.getRequestPage(page - 1, 5, RequestStatus.OPEN, RequestStatus.CLAIMED));
totalRequests = reqTable.getTotalRequest(RequestStatus.OPEN, RequestStatus.CLAIMED);
}
} else if (requestId > 0) {
Request req = reqTable.getRequest(requestId);
totalRequests = 1;
if (limitName != null && req.getPlayerName().equalsIgnoreCase(limitName)) {
requests.add(req);
} else if (limitName == null) {
requests.add(req);
} else {
totalRequests = 0;
}
}
if (totalRequests == 0) {
if (limitName != null) {
if (requestId > 0) {
sender.sendMessage(ChatColor.GREEN + "Either that request doesn't exist, or you do not have permission to view it.");
}
else {
sender.sendMessage(ChatColor.GREEN + "You don't have any outstanding mod requests.");
}
}
else {
sender.sendMessage(ChatColor.GREEN + "There are currently no open mod requests.");
}
} else if (totalRequests == 1 && requestId > 0) {
messageRequestToPlayer(sender, requests.get(0));
} else if (totalRequests > 0) {
if (page > 1 && requests.size() == 0) {
sender.sendMessage(ChatColor.RED + "There are no requests on that page.");
} else {
boolean showPage = true;
if (limitName != null) {
showPage = false;
}
messageRequestListToPlayer(sender, requests, page, totalRequests, showPage);
}
} else {
// there was an error.
}
}
else if (command.getName().equalsIgnoreCase("tp-id")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
player.sendMessage(ChatColor.GREEN + "[ModReq] Teleporting you to request " + requestId);
Location loc = stringToLocation(req.getRequestLocation());
player.teleport(loc);
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("claim")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if (req.getStatus() == RequestStatus.OPEN) {
req.setStatus(RequestStatus.CLAIMED);
req.setAssignedMod(senderName);
reqTable.save(req);
messageMods(String.format("%s%s is now handling request #%d", ChatColor.GREEN, senderName, requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("unclaim")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if (req.getAssignedMod().equalsIgnoreCase(senderName) && req.getStatus() == RequestStatus.CLAIMED) {
req.setStatus(RequestStatus.OPEN);
req.setAssignedMod(null);
reqTable.save(req);
messageMods(String.format("%s%s is no longer handling request #%d", ChatColor.GREEN, senderName, requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("done")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
String doneMessage = null;
if (args.length > 1) {
StringBuilder doneMessageBuilder = new StringBuilder(args[1]);
for (int i = 2; i < args.length; i++) {
doneMessageBuilder.append(" ").append(args[i]);
}
doneMessage = doneMessageBuilder.toString();
}
Request req = reqTable.getRequest(requestId);
if (req != null && req.getStatus() == RequestStatus.CLOSED) {
sender.sendMessage(ChatColor.RED + "Request Already Closed.");
}
else {
if (sender.hasPermission("modreq.done") && req != null) {
String msg = "";
msg = String.format("%sRequest #%d has been completed by %s", ChatColor.GREEN, requestId, senderName);
messageMods(msg);
if (doneMessage != null && doneMessage.length() != 0) {
msg = String.format("Close Message - %s%s", ChatColor.GRAY, doneMessage);
messageMods(msg);
}
}
else {
if (!req.getPlayerName().equalsIgnoreCase(senderName)) {
req = null;
sender.sendMessage(String.format("%s[ModReq] Error, you can only close your own requests.", ChatColor.RED));
}
}
if (req != null) {
req.setStatus(RequestStatus.CLOSED);
req.setCloseTime(System.currentTimeMillis());
req.setCloseMessage(doneMessage);
req.setAssignedMod(senderName);
Player requestCreator = getServer().getPlayerExact(req.getPlayerName());
if (requestCreator != null) {
if (!requestCreator.getName().equalsIgnoreCase(senderName)) {
String message = "";
if (doneMessage != null && doneMessage.length() != 0) {
message = String.format("%s completed your request - %s%s", senderName, ChatColor.GRAY, doneMessage);
} else {
message = String.format("%s completed your request", senderName);
}
requestCreator.sendMessage(ChatColor.GREEN + message);
}
else {
if (!sender.hasPermission("modreq.done")) {
messageMods(ChatColor.GREEN + String.format("Request #%d no longer needs to be handled", requestId));
sender.sendMessage(ChatColor.GREEN + String.format("Request #%d has been closed by you.", requestId));
}
}
req.setCloseSeenByUser(true);
}
reqTable.save(req);
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("reopen")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if ((req.getAssignedMod().equalsIgnoreCase(senderName) && req.getStatus() == RequestStatus.CLAIMED) || req.getStatus() == RequestStatus.CLOSED) {
req.setStatus(RequestStatus.OPEN);
req.setAssignedMod(null);
req.setCloseSeenByUser(false);
reqTable.save(req);
messageMods(ChatColor.GREEN + String.format("[ModReq] Request #%d is no longer claimed.", requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
} else if (command.getName().equalsIgnoreCase("elevate")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
Request req = reqTable.getRequest(requestId);
if (req.getStatus() == RequestStatus.OPEN) {
req.setFlagForAdmin(true);
messageMods(String.format("%s[ModReq] Request #%d has been flagged for admin.", ChatColor.GREEN, req.getId()));
reqTable.save(req);
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
} else if ( command.getName().equalsIgnoreCase("mr-reset")) {
try {
resetDatabase();
sender.sendMessage(ChatColor.GREEN + "[ModReq] Database has been reset.");
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Failed to reset database", ex);
}
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String name, String[] args) {
String senderName = ChatColor.stripColor(sender.getName());
if (sender instanceof ConsoleCommandSender) {
senderName = "Console";
}
if (command.getName().equalsIgnoreCase("modreq")) {
if (args.length == 0) {
return false;
}
StringBuilder request = new StringBuilder(args[0]);
for (int i = 1; i < args.length; i++) {
request.append(" ").append(args[i]);
}
if (sender instanceof Player) {
Player player = (Player)sender;
if (reqTable.getNumRequestFromUser(senderName) < 5) {
Request req = new Request();
req.setPlayerName(senderName);
req.setRequest(request.toString());
req.setRequestTime(System.currentTimeMillis());
String location = String.format("%s,%f,%f,%f", player.getWorld().getName(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ());
req.setRequestLocation(location);
req.setStatus(RequestStatus.OPEN);
reqTable.save(req);
messageMods(ChatColor.GREEN + "New request. Type /check for more");
sender.sendMessage(ChatColor.GREEN + "Request has been filed. Please be patient for a moderator to complete your request.");
} else {
sender.sendMessage(ChatColor.RED + "You already have 5 open requests, please wait for them to be completed.");
}
}
}
else if (command.getName().equalsIgnoreCase("check")) {
int page = 1;
int requestId = 0;
int totalRequests = 0;
String limitName = null;
if (args.length > 0 && !args[0].startsWith("p:")) {
try {
requestId = Integer.parseInt(args[0]);
page = 0;
} catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "You must provide a number for requests.");
return true;
}
}
if (sender.hasPermission("modreq.check")) {
if (args.length == 0) {
page = 1;
}
else if (args[0].startsWith("p:")) {
try {
page = Integer.parseInt(args[0].substring(2));
} catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "You must provide a number for pages.");
return true;
}
}
}
else {
limitName = senderName;
}
List<Request> requests = new ArrayList<Request>();
if (page > 0) {
if (limitName != null) {
requests.addAll(reqTable.getUserRequests(limitName));
totalRequests = requests.size();
} else {
requests.addAll(reqTable.getRequestPage(page - 1, 5, RequestStatus.OPEN, RequestStatus.CLAIMED));
totalRequests = reqTable.getTotalRequest(RequestStatus.OPEN, RequestStatus.CLAIMED);
}
} else if (requestId > 0) {
Request req = reqTable.getRequest(requestId);
if (req != null) {
totalRequests = 1;
if (limitName != null && req.getPlayerName().equalsIgnoreCase(limitName)) {
requests.add(req);
} else if (limitName == null) {
requests.add(req);
} else {
totalRequests = 0;
}
} else {
totalRequests = 0;
}
}
if (totalRequests == 0) {
if (limitName != null) {
if (requestId > 0) {
sender.sendMessage(ChatColor.GREEN + "Either that request doesn't exist, or you do not have permission to view it.");
}
else {
sender.sendMessage(ChatColor.GREEN + "You don't have any outstanding mod requests.");
}
}
else {
sender.sendMessage(ChatColor.GREEN + "There are currently no open mod requests.");
}
} else if (totalRequests == 1 && requestId > 0) {
messageRequestToPlayer(sender, requests.get(0));
} else if (totalRequests > 0) {
if (page > 1 && requests.size() == 0) {
sender.sendMessage(ChatColor.RED + "There are no requests on that page.");
} else {
boolean showPage = true;
if (limitName != null) {
showPage = false;
}
messageRequestListToPlayer(sender, requests, page, totalRequests, showPage);
}
} else {
// there was an error.
}
}
else if (command.getName().equalsIgnoreCase("tp-id")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
player.sendMessage(ChatColor.GREEN + "[ModReq] Teleporting you to request " + requestId);
Location loc = stringToLocation(req.getRequestLocation());
player.teleport(loc);
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("claim")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if (req.getStatus() == RequestStatus.OPEN) {
req.setStatus(RequestStatus.CLAIMED);
req.setAssignedMod(senderName);
reqTable.save(req);
messageMods(String.format("%s%s is now handling request #%d", ChatColor.GREEN, senderName, requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("unclaim")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if (req.getAssignedMod().equalsIgnoreCase(senderName) && req.getStatus() == RequestStatus.CLAIMED) {
req.setStatus(RequestStatus.OPEN);
req.setAssignedMod(null);
reqTable.save(req);
messageMods(String.format("%s%s is no longer handling request #%d", ChatColor.GREEN, senderName, requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("done")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
String doneMessage = null;
if (args.length > 1) {
StringBuilder doneMessageBuilder = new StringBuilder(args[1]);
for (int i = 2; i < args.length; i++) {
doneMessageBuilder.append(" ").append(args[i]);
}
doneMessage = doneMessageBuilder.toString();
}
Request req = reqTable.getRequest(requestId);
if (req != null && req.getStatus() == RequestStatus.CLOSED) {
sender.sendMessage(ChatColor.RED + "Request Already Closed.");
}
else {
if (sender.hasPermission("modreq.done") && req != null) {
String msg = "";
msg = String.format("%sRequest #%d has been completed by %s", ChatColor.GREEN, requestId, senderName);
messageMods(msg);
if (doneMessage != null && doneMessage.length() != 0) {
msg = String.format("Close Message - %s%s", ChatColor.GRAY, doneMessage);
messageMods(msg);
}
}
else {
if (!req.getPlayerName().equalsIgnoreCase(senderName)) {
req = null;
sender.sendMessage(String.format("%s[ModReq] Error, you can only close your own requests.", ChatColor.RED));
}
}
if (req != null) {
req.setStatus(RequestStatus.CLOSED);
req.setCloseTime(System.currentTimeMillis());
req.setCloseMessage(doneMessage);
req.setAssignedMod(senderName);
Player requestCreator = getServer().getPlayerExact(req.getPlayerName());
if (requestCreator != null) {
if (!requestCreator.getName().equalsIgnoreCase(senderName)) {
String message = "";
if (doneMessage != null && doneMessage.length() != 0) {
message = String.format("%s completed your request - %s%s", senderName, ChatColor.GRAY, doneMessage);
} else {
message = String.format("%s completed your request", senderName);
}
requestCreator.sendMessage(ChatColor.GREEN + message);
}
else {
if (!sender.hasPermission("modreq.done")) {
messageMods(ChatColor.GREEN + String.format("Request #%d no longer needs to be handled", requestId));
sender.sendMessage(ChatColor.GREEN + String.format("Request #%d has been closed by you.", requestId));
}
}
req.setCloseSeenByUser(true);
}
reqTable.save(req);
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
}
else if (command.getName().equalsIgnoreCase("reopen")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
if (sender instanceof Player) {
Player player = (Player)sender;
Request req = reqTable.getRequest(requestId);
if ((req.getAssignedMod().equalsIgnoreCase(senderName) && req.getStatus() == RequestStatus.CLAIMED) || req.getStatus() == RequestStatus.CLOSED) {
req.setStatus(RequestStatus.OPEN);
req.setAssignedMod(null);
req.setCloseSeenByUser(false);
reqTable.save(req);
messageMods(ChatColor.GREEN + String.format("[ModReq] Request #%d is no longer claimed.", requestId));
}
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
} else if (command.getName().equalsIgnoreCase("elevate")) {
if (args.length == 0) {
return false;
}
int requestId = 0;
try {
requestId = Integer.parseInt(args[0]);
Request req = reqTable.getRequest(requestId);
if (req.getStatus() == RequestStatus.OPEN) {
req.setFlagForAdmin(true);
messageMods(String.format("%s[ModReq] Request #%d has been flagged for admin.", ChatColor.GREEN, req.getId()));
reqTable.save(req);
}
}
catch (NumberFormatException ex) {
sender.sendMessage(ChatColor.RED + "[ModReq] Error: Expected a number for request.");
}
} else if ( command.getName().equalsIgnoreCase("mr-reset")) {
try {
resetDatabase();
sender.sendMessage(ChatColor.GREEN + "[ModReq] Database has been reset.");
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Failed to reset database", ex);
}
}
return true;
}
|
diff --git a/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java b/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java
index d5ec1cdd3..94b87e830 100644
--- a/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java
+++ b/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java
@@ -1,741 +1,741 @@
package org.apache.maven.continuum.buildcontroller;
/*
* 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 java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.BuildResultDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.dao.ProjectGroupDao;
import org.apache.continuum.dao.ProjectScmRootDao;
import org.apache.continuum.model.project.ProjectScmRoot;
import org.apache.continuum.utils.ContinuumUtils;
import org.apache.maven.continuum.core.action.AbstractContinuumAction;
import org.apache.maven.continuum.core.action.ExecuteBuilderContinuumAction;
import org.apache.maven.continuum.execution.ContinuumBuildExecutor;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.execution.manager.BuildExecutorManager;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildResult;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.project.ProjectDependency;
import org.apache.maven.continuum.model.scm.ChangeFile;
import org.apache.maven.continuum.model.scm.ChangeSet;
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.store.ContinuumObjectNotFoundException;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.apache.maven.continuum.utils.WorkingDirectoryService;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.repository.ScmRepositoryException;
import org.codehaus.plexus.action.ActionManager;
import org.codehaus.plexus.action.ActionNotFoundException;
import org.codehaus.plexus.taskqueue.execution.TaskExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author <a href="mailto:[email protected]">Trygve Laugstøl</a>
* @version $Id$
* @plexus.component role="org.apache.maven.continuum.buildcontroller.BuildController" role-hint="default"
*/
public class DefaultBuildController
implements BuildController
{
private static final Logger log = LoggerFactory.getLogger( DefaultBuildController.class );
/**
* @plexus.requirement
*/
private BuildDefinitionDao buildDefinitionDao;
/**
* @plexus.requirement
*/
private BuildResultDao buildResultDao;
/**
* @plexus.requirement
*/
private ProjectDao projectDao;
/**
* @plexus.requirement
*/
private ProjectGroupDao projectGroupDao;
/**
* @plexus.requirement
*/
private ProjectScmRootDao projectScmRootDao;
/**
* @plexus.requirement
*/
private ContinuumNotificationDispatcher notifierDispatcher;
/**
* @plexus.requirement
*/
private ActionManager actionManager;
/**
* @plexus.requirement
*/
private WorkingDirectoryService workingDirectoryService;
/**
* @plexus.requirement
*/
private BuildExecutorManager buildExecutorManager;
// ----------------------------------------------------------------------
// BuildController Implementation
// ----------------------------------------------------------------------
/**
* @param projectId
* @param buildDefinitionId
* @param trigger
* @throws TaskExecutionException
*/
public void build( int projectId, int buildDefinitionId, int trigger, ScmResult scmResult )
throws TaskExecutionException
{
log.info( "Initializing build" );
BuildContext context = initializeBuildContext( projectId, buildDefinitionId, trigger, scmResult );
// ignore this if AlwaysBuild ?
if ( !checkScmResult( context ) )
{
log.info( "Error updating from SCM, not building" );
return;
}
log.info( "Starting build of " + context.getProject().getName() );
startBuild( context );
try
{
checkProjectDependencies( context );
if ( !shouldBuild( context ) )
{
return;
}
Map<String, Object> actionContext = context.getActionContext();
try
{
performAction( "update-project-from-working-directory", context );
}
catch ( TaskExecutionException e )
{
updateBuildResult( context, ContinuumUtils.throwableToString( e ) );
//just log the error but don't stop the build from progressing in order not to suppress any build result messages there
log.error( "Error executing action update-project-from-working-directory '", e );
}
performAction( "execute-builder", context );
performAction( "deploy-artifact", context );
context.setCancelled( ExecuteBuilderContinuumAction.isCancelled( actionContext ) );
String s = AbstractContinuumAction.getBuildId( actionContext, null );
if ( s != null && !context.isCancelled() )
{
try
{
context.setBuildResult( buildResultDao.getBuildResult( Integer.valueOf( s ) ) );
}
catch ( NumberFormatException e )
{
throw new TaskExecutionException( "Internal error: build id not an integer", e );
}
catch ( ContinuumObjectNotFoundException e )
{
throw new TaskExecutionException( "Internal error: Cannot find build result", e );
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error loading build result", e );
}
}
}
finally
{
endBuild( context );
}
}
/**
* Checks if the build should be marked as ERROR and notifies the end of the build.
*
* @param context
* @throws TaskExecutionException
*/
private void endBuild( BuildContext context )
throws TaskExecutionException
{
Project project = context.getProject();
try
{
if ( project.getState() != ContinuumProjectState.NEW &&
project.getState() != ContinuumProjectState.CHECKEDOUT &&
project.getState() != ContinuumProjectState.OK && project.getState() != ContinuumProjectState.FAILED &&
project.getState() != ContinuumProjectState.ERROR && !context.isCancelled() )
{
try
{
String s = AbstractContinuumAction.getBuildId( context.getActionContext(), null );
if ( s != null )
{
BuildResult buildResult = buildResultDao.getBuildResult( Integer.valueOf( s ) );
project.setState( buildResult.getState() );
projectDao.updateProject( project );
}
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error storing the project", e );
}
}
}
finally
{
if ( !context.isCancelled() )
{
notifierDispatcher.buildComplete( project, context.getBuildDefinition(), context.getBuildResult() );
}
}
}
private void updateBuildResult( BuildContext context, String error )
throws TaskExecutionException
{
BuildResult build = context.getBuildResult();
if ( build == null )
{
build = makeAndStoreBuildResult( context, error );
}
else
{
updateBuildResult( build, context );
build.setError( error );
try
{
buildResultDao.updateBuildResult( build );
build = buildResultDao.getBuildResult( build.getId() );
context.setBuildResult( build );
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error updating build result", e );
}
}
context.getProject().setState( build.getState() );
try
{
projectDao.updateProject( context.getProject() );
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error updating project", e );
}
}
private void updateBuildResult( BuildResult build, BuildContext context )
{
if ( build.getScmResult() == null && context.getScmResult() != null )
{
build.setScmResult( context.getScmResult() );
}
if ( build.getModifiedDependencies() == null && context.getModifiedDependencies() != null )
{
build.setModifiedDependencies( context.getModifiedDependencies() );
}
}
private void startBuild( BuildContext context )
throws TaskExecutionException
{
Project project = context.getProject();
project.setOldState( project.getState() );
project.setState( ContinuumProjectState.BUILDING );
try
{
projectDao.updateProject( project );
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error persisting project", e );
}
notifierDispatcher.buildStarted( project, context.getBuildDefinition() );
}
/**
* Initializes a BuildContext for the build.
*
* @param projectId
* @param buildDefinitionId
* @param trigger
* @return
* @throws TaskExecutionException
*/
protected BuildContext initializeBuildContext( int projectId, int buildDefinitionId, int trigger,
ScmResult scmResult )
throws TaskExecutionException
{
BuildContext context = new BuildContext();
context.setStartTime( System.currentTimeMillis() );
context.setTrigger( trigger );
try
{
Project project = projectDao.getProject( projectId );
context.setProject( project );
BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId );
context.setBuildDefinition( buildDefinition );
BuildResult oldBuildResult =
buildResultDao.getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId );
context.setOldBuildResult( oldBuildResult );
context.setScmResult( scmResult );
// CONTINUUM-1871 olamy if continuum is killed during building oldBuildResult will have a endTime 0
// this means all changes since the project has been loaded in continuum will be in memory
// now we will load all BuildResult with an Id bigger or equals than the oldBuildResult one
//if ( oldBuildResult != null )
//{
// context.setOldScmResult(
// getOldScmResults( projectId, oldBuildResult.getBuildNumber(), oldBuildResult.getEndTime() ) );
//}
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error initializing the build context", e );
}
Map<String, Object> actionContext = context.getActionContext();
AbstractContinuumAction.setProjectId( actionContext, projectId );
AbstractContinuumAction.setProject( actionContext, context.getProject() );
AbstractContinuumAction.setBuildDefinitionId( actionContext, buildDefinitionId );
AbstractContinuumAction.setBuildDefinition( actionContext, context.getBuildDefinition() );
AbstractContinuumAction.setTrigger( actionContext, trigger );
AbstractContinuumAction.setScmResult( actionContext, context.getScmResult() );
if ( context.getOldBuildResult() != null )
{
AbstractContinuumAction.setOldBuildId( actionContext, context.getOldBuildResult().getId() );
}
return context;
}
private void performAction( String actionName, BuildContext context )
throws TaskExecutionException
{
String error;
TaskExecutionException exception;
try
{
log.info( "Performing action " + actionName );
actionManager.lookup( actionName ).execute( context.getActionContext() );
return;
}
catch ( ActionNotFoundException e )
{
error = ContinuumUtils.throwableToString( e );
exception = new TaskExecutionException( "Error looking up action '" + actionName + "'", e );
}
catch ( ScmRepositoryException e )
{
error = getValidationMessages( e ) + "\n" + ContinuumUtils.throwableToString( e );
exception = new TaskExecutionException( "SCM error while executing '" + actionName + "'", e );
}
catch ( ScmException e )
{
error = ContinuumUtils.throwableToString( e );
exception = new TaskExecutionException( "SCM error while executing '" + actionName + "'", e );
}
catch ( Exception e )
{
exception = new TaskExecutionException( "Error executing action '" + actionName + "'", e );
error = ContinuumUtils.throwableToString( exception );
}
// TODO: clean this up. We catch the original exception from the action, and then update the buildresult
// for it - we need to because of the specialized error message for SCM.
// If updating the buildresult fails, log the previous error and throw the new one.
// If updating the buildresult succeeds, throw the original exception. The build result should NOT
// be updated again - a TaskExecutionException is final, no further action should be taken upon it.
try
{
updateBuildResult( context, error );
}
catch ( TaskExecutionException e )
{
log.error( "Error updating build result after receiving the following exception: ", exception );
throw e;
}
throw exception;
}
protected boolean shouldBuild( BuildContext context )
throws TaskExecutionException
{
BuildDefinition buildDefinition = context.getBuildDefinition();
if ( buildDefinition.isBuildFresh() )
{
log.info( "FreshBuild configured, building" );
return true;
}
if ( buildDefinition.isAlwaysBuild() )
{
log.info( "AlwaysBuild configured, building" );
return true;
}
if ( context.getOldBuildResult() == null )
{
- log.info( "The project was never be built with the current build definition, building" );
+ log.info( "The project has never been built with the current build definition, building" );
return true;
}
Project project = context.getProject();
//CONTINUUM-1428
if ( project.getOldState() == ContinuumProjectState.ERROR ||
context.getOldBuildResult().getState() == ContinuumProjectState.ERROR )
{
log.info( "Latest state was 'ERROR', building" );
return true;
}
if ( context.getTrigger() == ContinuumProjectState.TRIGGER_FORCED )
{
log.info( "The project build is forced, building" );
return true;
}
boolean shouldBuild = false;
boolean allChangesUnknown = true;
if ( project.getOldState() != ContinuumProjectState.NEW &&
project.getOldState() != ContinuumProjectState.CHECKEDOUT &&
context.getTrigger() != ContinuumProjectState.TRIGGER_FORCED &&
project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT )
{
// Check SCM changes
allChangesUnknown = checkAllChangesUnknown( context.getScmResult().getChanges() );
if ( allChangesUnknown )
{
if ( !context.getScmResult().getChanges().isEmpty() )
{
log.info(
"The project was not built because all changes are unknown (maybe local modifications or ignored files not defined in your SCM tool." );
}
else
{
log.info(
"The project was not built because no changes were detected in sources since the last build." );
}
}
// Check dependencies changes
if ( context.getModifiedDependencies() != null && !context.getModifiedDependencies().isEmpty() )
{
log.info( "Found dependencies changes, building" );
shouldBuild = true;
}
}
// Check changes
if ( !shouldBuild && ( ( !allChangesUnknown && !context.getScmResult().getChanges().isEmpty() ) ||
project.getExecutorId().equals( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ) ) )
{
try
{
ContinuumBuildExecutor executor = buildExecutorManager.getBuildExecutor( project.getExecutorId() );
shouldBuild = executor.shouldBuild( context.getScmResult().getChanges(), project,
workingDirectoryService.getWorkingDirectory( project ),
context.getBuildDefinition() );
}
catch ( Exception e )
{
updateBuildResult( context, ContinuumUtils.throwableToString( e ) );
throw new TaskExecutionException( "Can't determine if the project should build or not", e );
}
}
if ( shouldBuild )
{
log.info( "Changes found in the current project, building" );
}
else
{
project.setState( project.getOldState() );
project.setOldState( 0 );
try
{
projectDao.updateProject( project );
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error storing project", e );
}
log.info( "No changes in the current project, not building" );
}
return shouldBuild;
}
private boolean checkAllChangesUnknown( List<ChangeSet> changes )
{
for ( ChangeSet changeSet : changes )
{
List<ChangeFile> changeFiles = changeSet.getFiles();
for ( ChangeFile changeFile : changeFiles )
{
if ( !"unknown".equalsIgnoreCase( changeFile.getStatus() ) )
{
return false;
}
}
}
return true;
}
private String getValidationMessages( ScmRepositoryException ex )
{
List<String> messages = ex.getValidationMessages();
StringBuffer message = new StringBuffer();
if ( messages != null && !messages.isEmpty() )
{
for ( Iterator<String> i = messages.iterator(); i.hasNext(); )
{
message.append( i.next() );
if ( i.hasNext() )
{
message.append( System.getProperty( "line.separator" ) );
}
}
}
return message.toString();
}
protected void checkProjectDependencies( BuildContext context )
{
if ( context.getOldBuildResult() == null )
{
return;
}
try
{
Project project = projectDao.getProjectWithAllDetails( context.getProject().getId() );
List<ProjectDependency> dependencies = project.getDependencies();
if ( dependencies == null )
{
dependencies = new ArrayList<ProjectDependency>();
}
if ( project.getParent() != null )
{
dependencies.add( project.getParent() );
}
if ( dependencies.isEmpty() )
{
return;
}
List<ProjectDependency> modifiedDependencies = new ArrayList<ProjectDependency>();
for ( ProjectDependency dep : dependencies )
{
Project dependencyProject =
projectDao.getProject( dep.getGroupId(), dep.getArtifactId(), dep.getVersion() );
if ( dependencyProject != null )
{
List<BuildResult> buildResults =
buildResultDao.getBuildResultsInSuccessForProject( dependencyProject.getId(),
context.getOldBuildResult().getEndTime() );
if ( buildResults != null && !buildResults.isEmpty() )
{
log.debug( "Dependency changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" +
dep.getVersion() );
modifiedDependencies.add( dep );
}
else
{
log.debug( "Dependency not changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" +
dep.getVersion() );
}
}
else
{
log.debug( "Skip non Continuum project: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" +
dep.getVersion() );
}
}
context.setModifiedDependencies( modifiedDependencies );
AbstractContinuumAction.setUpdatedDependencies( context.getActionContext(), modifiedDependencies );
}
catch ( ContinuumStoreException e )
{
log.warn( "Can't get the project dependencies", e );
}
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
private BuildResult makeAndStoreBuildResult( BuildContext context, String error )
throws TaskExecutionException
{
// Project project, ScmResult scmResult, long startTime, int trigger )
// project, scmResult, startTime, trigger );
BuildResult build = new BuildResult();
build.setState( ContinuumProjectState.ERROR );
build.setTrigger( context.getTrigger() );
build.setStartTime( context.getStartTime() );
build.setEndTime( System.currentTimeMillis() );
updateBuildResult( build, context );
build.setScmResult( context.getScmResult() );
build.setBuildDefinition( context.getBuildDefinition() );
if ( error != null )
{
build.setError( error );
}
try
{
buildResultDao.addBuildResult( context.getProject(), build );
build = buildResultDao.getBuildResult( build.getId() );
context.setBuildResult( build );
return build;
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error storing build result", e );
}
}
/**
* Check to see if there was a error while checking out/updating the project
*
* @param context The build context
* @return true if scm result is ok
* @throws TaskExecutionException
*/
private boolean checkScmResult( BuildContext context )
throws TaskExecutionException
{
Project project = context.getProject();
int projectGroupId = project.getProjectGroup().getId();
List<ProjectScmRoot> scmRoots = projectScmRootDao.getProjectScmRootByProjectGroup( projectGroupId );
for ( ProjectScmRoot projectScmRoot : scmRoots )
{
if ( project.getScmUrl().startsWith( projectScmRoot.getScmRootAddress() ) )
{
if ( projectScmRoot.getState() == ContinuumProjectState.UPDATED )
{
return true;
}
break;
}
}
return false;
}
}
| true | true | protected boolean shouldBuild( BuildContext context )
throws TaskExecutionException
{
BuildDefinition buildDefinition = context.getBuildDefinition();
if ( buildDefinition.isBuildFresh() )
{
log.info( "FreshBuild configured, building" );
return true;
}
if ( buildDefinition.isAlwaysBuild() )
{
log.info( "AlwaysBuild configured, building" );
return true;
}
if ( context.getOldBuildResult() == null )
{
log.info( "The project was never be built with the current build definition, building" );
return true;
}
Project project = context.getProject();
//CONTINUUM-1428
if ( project.getOldState() == ContinuumProjectState.ERROR ||
context.getOldBuildResult().getState() == ContinuumProjectState.ERROR )
{
log.info( "Latest state was 'ERROR', building" );
return true;
}
if ( context.getTrigger() == ContinuumProjectState.TRIGGER_FORCED )
{
log.info( "The project build is forced, building" );
return true;
}
boolean shouldBuild = false;
boolean allChangesUnknown = true;
if ( project.getOldState() != ContinuumProjectState.NEW &&
project.getOldState() != ContinuumProjectState.CHECKEDOUT &&
context.getTrigger() != ContinuumProjectState.TRIGGER_FORCED &&
project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT )
{
// Check SCM changes
allChangesUnknown = checkAllChangesUnknown( context.getScmResult().getChanges() );
if ( allChangesUnknown )
{
if ( !context.getScmResult().getChanges().isEmpty() )
{
log.info(
"The project was not built because all changes are unknown (maybe local modifications or ignored files not defined in your SCM tool." );
}
else
{
log.info(
"The project was not built because no changes were detected in sources since the last build." );
}
}
// Check dependencies changes
if ( context.getModifiedDependencies() != null && !context.getModifiedDependencies().isEmpty() )
{
log.info( "Found dependencies changes, building" );
shouldBuild = true;
}
}
// Check changes
if ( !shouldBuild && ( ( !allChangesUnknown && !context.getScmResult().getChanges().isEmpty() ) ||
project.getExecutorId().equals( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ) ) )
{
try
{
ContinuumBuildExecutor executor = buildExecutorManager.getBuildExecutor( project.getExecutorId() );
shouldBuild = executor.shouldBuild( context.getScmResult().getChanges(), project,
workingDirectoryService.getWorkingDirectory( project ),
context.getBuildDefinition() );
}
catch ( Exception e )
{
updateBuildResult( context, ContinuumUtils.throwableToString( e ) );
throw new TaskExecutionException( "Can't determine if the project should build or not", e );
}
}
if ( shouldBuild )
{
log.info( "Changes found in the current project, building" );
}
else
{
project.setState( project.getOldState() );
project.setOldState( 0 );
try
{
projectDao.updateProject( project );
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error storing project", e );
}
log.info( "No changes in the current project, not building" );
}
return shouldBuild;
}
| protected boolean shouldBuild( BuildContext context )
throws TaskExecutionException
{
BuildDefinition buildDefinition = context.getBuildDefinition();
if ( buildDefinition.isBuildFresh() )
{
log.info( "FreshBuild configured, building" );
return true;
}
if ( buildDefinition.isAlwaysBuild() )
{
log.info( "AlwaysBuild configured, building" );
return true;
}
if ( context.getOldBuildResult() == null )
{
log.info( "The project has never been built with the current build definition, building" );
return true;
}
Project project = context.getProject();
//CONTINUUM-1428
if ( project.getOldState() == ContinuumProjectState.ERROR ||
context.getOldBuildResult().getState() == ContinuumProjectState.ERROR )
{
log.info( "Latest state was 'ERROR', building" );
return true;
}
if ( context.getTrigger() == ContinuumProjectState.TRIGGER_FORCED )
{
log.info( "The project build is forced, building" );
return true;
}
boolean shouldBuild = false;
boolean allChangesUnknown = true;
if ( project.getOldState() != ContinuumProjectState.NEW &&
project.getOldState() != ContinuumProjectState.CHECKEDOUT &&
context.getTrigger() != ContinuumProjectState.TRIGGER_FORCED &&
project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT )
{
// Check SCM changes
allChangesUnknown = checkAllChangesUnknown( context.getScmResult().getChanges() );
if ( allChangesUnknown )
{
if ( !context.getScmResult().getChanges().isEmpty() )
{
log.info(
"The project was not built because all changes are unknown (maybe local modifications or ignored files not defined in your SCM tool." );
}
else
{
log.info(
"The project was not built because no changes were detected in sources since the last build." );
}
}
// Check dependencies changes
if ( context.getModifiedDependencies() != null && !context.getModifiedDependencies().isEmpty() )
{
log.info( "Found dependencies changes, building" );
shouldBuild = true;
}
}
// Check changes
if ( !shouldBuild && ( ( !allChangesUnknown && !context.getScmResult().getChanges().isEmpty() ) ||
project.getExecutorId().equals( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ) ) )
{
try
{
ContinuumBuildExecutor executor = buildExecutorManager.getBuildExecutor( project.getExecutorId() );
shouldBuild = executor.shouldBuild( context.getScmResult().getChanges(), project,
workingDirectoryService.getWorkingDirectory( project ),
context.getBuildDefinition() );
}
catch ( Exception e )
{
updateBuildResult( context, ContinuumUtils.throwableToString( e ) );
throw new TaskExecutionException( "Can't determine if the project should build or not", e );
}
}
if ( shouldBuild )
{
log.info( "Changes found in the current project, building" );
}
else
{
project.setState( project.getOldState() );
project.setOldState( 0 );
try
{
projectDao.updateProject( project );
}
catch ( ContinuumStoreException e )
{
throw new TaskExecutionException( "Error storing project", e );
}
log.info( "No changes in the current project, not building" );
}
return shouldBuild;
}
|
diff --git a/web/src/main/java/de/betterform/agent/web/WebUtil.java b/web/src/main/java/de/betterform/agent/web/WebUtil.java
index fad1e7ec..03b20e89 100644
--- a/web/src/main/java/de/betterform/agent/web/WebUtil.java
+++ b/web/src/main/java/de/betterform/agent/web/WebUtil.java
@@ -1,356 +1,364 @@
/*
* Copyright (c) 2010. betterForm Project - http://www.betterform.de
* Licensed under the terms of BSD License
*/
package de.betterform.agent.web;
import de.betterform.xml.xforms.ui.Filename;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import de.betterform.connector.http.AbstractHTTPConnector;
import de.betterform.xml.xforms.XFormsProcessor;
import de.betterform.xml.xforms.model.submission.RequestHeaders;
import de.betterform.xml.xslt.TransformerService;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* Collection of static methods to be re-used by different Servlets/Filter implementations.
*
* @author Joern Turner
*/
public class WebUtil {
private static final Log LOGGER = LogFactory.getLog(WebUtil.class);
public static final String HTML_CONTENT_TYPE = "text/html;charset=UTF-8";
public static final String HTTP_SESSION_ID = "httpSessionId";
private static final String FILENAME = "fileName";
private static final String PLAIN_PATH = "plainPath";
private static final String CONTEXT_PATH = "contextPath";
public static String getRequestURI(HttpServletRequest request) {
StringBuffer buffer = new StringBuffer(request.getScheme());
buffer.append("://");
buffer.append(request.getServerName());
buffer.append(":");
buffer.append(request.getServerPort());
buffer.append(request.getContextPath());
return buffer.toString();
}
public static void printSessionKeys(HttpSession session) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("--------------- session dump ---------------");
Enumeration keys = session.getAttributeNames();
if (keys.hasMoreElements()) {
LOGGER.debug("--- existing keys in session --- ");
while (keys.hasMoreElements()) {
String s = (String) keys.nextElement();
LOGGER.debug("existing sessionkey: " + s + ":" + session.getAttribute(s));
}
} else {
LOGGER.debug("--- no keys present in session ---");
}
}
}
public static void nonCachingResponse(HttpServletResponse response) {
response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
}
/**
*
* @return String for use as root of URLs
*/
public static String getContextRoot(HttpServletRequest request) {
if (request.getAttribute(WebProcessor.ALTERNATIVE_ROOT) != null) {
return (String) request.getAttribute(WebProcessor.ALTERNATIVE_ROOT);
} else {
return request.getContextPath();
}
}
/**
* fetches the XFormsSession from the HTTP Session
*
* @param request the HTTP Request
* @return the xformsSession for the request
*/
public static WebProcessor getWebProcessor(HttpServletRequest request) {
// String key = request.getParameter("sessionKey");
// XFormsSessionManager manager = (XFormsSessionManager) session.getAttribute(XFormsSessionManager.XFORMS_SESSION_MANAGER);
// XFormsSession xFormsSession = manager.getWebProcessor(key);
String key = request.getParameter("sessionKey");
if (key == null) {
LOGGER.warn("Request " + request + " has no parameter session key");
return null;
} else {
return getWebProcessor(key);
}
}
/**
* fetches the XFormsSession from the HTTP Session
*
* @param request the HTTP Request
* @param session the HTTP Session
* @return the xformsSession for the request
*/
public static WebProcessor getWebProcessor(HttpServletRequest request, HttpSession session) {
// String key = request.getParameter("sessionKey");
// XFormsSessionManager manager = (XFormsSessionManager) session.getAttribute(XFormsSessionManager.XFORMS_SESSION_MANAGER);
// XFormsSession xFormsSession = manager.getWebProcessor(key);
return getWebProcessor(request);
}
public static WebProcessor getWebProcessor(String key) {
if (key == null || key.equals("")) {
LOGGER.warn("SessionKey is null");
return null;
}
Cache cache = CacheManager.getInstance().getCache("xfSessionCache");
if(cache == null || cache.get(key) == null) {
LOGGER.warn("No xformsSession for key " + key + " in Cache");
return null;
}
net.sf.ehcache.Element elem = cache.get(key);
WebProcessor webProcessor = (WebProcessor) elem.getObjectValue();
if (webProcessor == null) {
LOGGER.warn("Cached WebProcessor for key '" + key + "' is null");
return null;
}
// XStream xStream = new XStream();
// String xml = xStream.toXML(webProcessor);
// LOGGER.debug(xml);
return webProcessor;
}
public static boolean removeSession(String key) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("removing key: '" + key + "' from cache");
}
Cache xfSessionCache = CacheManager.getInstance().getCache("xfSessionCache");
boolean removedSession = false;
if (xfSessionCache != null) {
removedSession = xfSessionCache.remove(key);
}
return removedSession;
}
public static String decodeUrl(String formPath, HttpServletRequest request) throws UnsupportedEncodingException {
String decoded = URLDecoder.decode(formPath, "UTF-8");
if (decoded.startsWith("http://")) {
return decoded;
} else {
String requestURI = getRequestURI(request);
return requestURI + formPath;
}
}
/**
* stores cookies that may exist in request and passes them on to processor for usage in
* HTTPConnectors. Instance loading and submission then uses these cookies. Important for
* applications using auth.
* <p/>
* NOTE: this method should be called *before* the Adapter is initialized cause the cookies may
* already be needed for setup (e.g. loading of XForms via Http)
*/
public static void storeCookies(HttpServletRequest request, XFormsProcessor processor) {
javax.servlet.http.Cookie[] cookiesIn = request.getCookies();
if (cookiesIn != null) {
BasicClientCookie[] commonsCookies = new BasicClientCookie[cookiesIn.length];
for (int i = 0; i < cookiesIn.length; i += 1) {
javax.servlet.http.Cookie c = cookiesIn[i];
commonsCookies[i] = new BasicClientCookie(c.getName(),c.getValue());
commonsCookies[i].setDomain(c.getDomain());
commonsCookies[i].setPath(c.getPath());
commonsCookies[i].setAttribute(ClientCookie.MAX_AGE_ATTR, Integer.toString(c.getMaxAge()));
commonsCookies[i].setSecure(c.getSecure());
if (WebUtil.LOGGER.isDebugEnabled()) {
WebUtil.LOGGER.debug("adding cookie >>>>>");
WebUtil.LOGGER.debug("name: " + c.getName());
WebUtil.LOGGER.debug("value: " + c.getValue());
WebUtil.LOGGER.debug("path: " + c.getPath());
WebUtil.LOGGER.debug("maxAge: " + c.getMaxAge());
WebUtil.LOGGER.debug("secure: " + c.getSecure());
WebUtil.LOGGER.debug("adding cookie done <<<<<");
}
}
processor.setContextParam(AbstractHTTPConnector.REQUEST_COOKIE, commonsCookies);
}
}
/**
* copy all http headers from client request into betterForm context map as map HTTP_HEADERS. This map
* will be picked up in AbstractHttpConnector to configure a proper request for the internal http-client.
*/
public static void copyHttpHeaders(HttpServletRequest request, XFormsProcessor processor) {
RequestHeaders httpHeaders = new RequestHeaders();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
httpHeaders.addHeader(headerName, request.getHeader(headerName));
if (WebUtil.LOGGER.isDebugEnabled()) {
WebUtil.LOGGER.debug("keeping httpheader: " + headerName + " value: " + request.getHeader(headerName));
}
}
processor.setContextParam(AbstractHTTPConnector.HTTP_REQUEST_HEADERS, httpHeaders);
}
/**
* returns an URL which is passed as request param and decodes it if necessary
*
* @param request the HttpServletRequest
* @return an unencoded absolute Url or a relative Url
* @throws java.io.UnsupportedEncodingException
* in case URL is not correctly encoded
* @throws java.net.MalformedURLException in case URL is not valid
*/
public static String getFormUrlAsString(HttpServletRequest request) throws UnsupportedEncodingException, MalformedURLException {
String formPath = request.getParameter(WebFactory.FORM_PARAM_NAME);
return decodeUrl(formPath, request);
}
/**
* this method is responsible for passing all context information needed by the Adapter and Processor from
* ServletRequest to Context. Will be called only once when the form-session is inited (GET).
* <p/>
* <p/>
* todo: better logging of context params
*
* @param request the Servlet request to fetch params from
* @param httpSession the Http Session context
* @param processor the XFormsProcessor which receives the context params
* @param sessionkey the key to identify the XFormsSession
*/
public static void setContextParams(HttpServletRequest request,
HttpSession httpSession,
XFormsProcessor processor,
String sessionkey) {
Map servletMap = new HashMap();
servletMap.put(WebProcessor.SESSION_ID, sessionkey);
processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);
//adding requestURI to context
processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));
//adding request URL to context
String requestURL = request.getRequestURL().toString();
processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);
// the web app name with an '/' prepended e.g. '/betterform' by default
String contextRoot = WebUtil.getContextRoot(request);
processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
}
String requestPath = "";
+ URL url=null;
+ String plainPath ="";
try {
- URL url = new URL(requestURL);
+ url = new URL(requestURL);
requestPath = url.getPath();
} catch (MalformedURLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if(requestPath.length() != 0){
//adding request path e.g. '/betterform/forms/demo/registration.xhtml'
processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);
//adding filename of requested doc to context
- String fileName = requestPath.substring(requestPath.lastIndexOf('/')+1,requestPath.length());
+ String fileName = requestPath.substring(requestPath.lastIndexOf('/')+1,requestPath.length());//FILENAME xforms
processor.setContextParam(FILENAME, fileName);
- //adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
- String plainPath = requestPath.substring(contextRoot.length()+1,requestPath.length() - fileName.length());
- processor.setContextParam(PLAIN_PATH, plainPath);
+ if(requestURL.contains(contextRoot)){ //case1: contextRoot is a part of the URL
+ //adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
+ plainPath = requestPath.substring(contextRoot.length()+1,requestPath.length() - fileName.length());
+ processor.setContextParam(PLAIN_PATH, plainPath);
+ }
+ else{//case2: contextRoot is not a part of the URL
+ String[] urlParts=requestURL.split("/");
+ plainPath=urlParts[urlParts.length-2];
+ }
//adding contextPath - requestPath without the filename
processor.setContextParam(CONTEXT_PATH,contextRoot+"/"+plainPath);
+ }
- }
//adding session id to context
processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
//adding context absolute path to context
//adding pathInfo to context - attention: this is only available when a servlet is requested
String s1=request.getPathInfo();
if(s1!=null){
processor.setContextParam(WebProcessor.PATH_INFO, s1);
}
processor.setContextParam(WebProcessor.QUERY_STRING, (request.getQueryString() != null ? request.getQueryString() : ""));
//storing the realpath for webapp
String realPath = httpSession.getServletContext().getRealPath("");
if (realPath == null) {
realPath = httpSession.getServletContext().getRealPath(".");
}
File f = new File(realPath);
URI fileURI = null;
fileURI = f.toURI();
processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("real path of webapp: " + realPath);
}
//storing the TransformerService
processor.setContextParam(TransformerService.TRANSFORMER_SERVICE, httpSession.getServletContext().getAttribute(TransformerService.class.getName()));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("TransformerService: " + httpSession.getServletContext().getAttribute(TransformerService.class.getName()));
}
//[2] read any request params that are *not* betterForm params and pass them into the context map
Enumeration params = request.getParameterNames();
String s;
while (params.hasMoreElements()) {
s = (String) params.nextElement();
//store all request-params we don't use in the context map of XFormsProcessorImpl
String value = request.getParameter(s);
processor.setContextParam(s, value);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("added request param '" + s + "' added to context");
LOGGER.debug("param value'" + value);
}
}
}
public static boolean isMediaTypeXML(String s) {
boolean isXML;
isXML = s.endsWith("+xml")
|| ((s.equals("text")
|| s.equals("application"))
&& (s.equals("xml")
|| s.equals("xml-external-parsed-entity")));
return isXML;
}
}
| false | true | public static void setContextParams(HttpServletRequest request,
HttpSession httpSession,
XFormsProcessor processor,
String sessionkey) {
Map servletMap = new HashMap();
servletMap.put(WebProcessor.SESSION_ID, sessionkey);
processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);
//adding requestURI to context
processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));
//adding request URL to context
String requestURL = request.getRequestURL().toString();
processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);
// the web app name with an '/' prepended e.g. '/betterform' by default
String contextRoot = WebUtil.getContextRoot(request);
processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
}
String requestPath = "";
try {
URL url = new URL(requestURL);
requestPath = url.getPath();
} catch (MalformedURLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if(requestPath.length() != 0){
//adding request path e.g. '/betterform/forms/demo/registration.xhtml'
processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);
//adding filename of requested doc to context
String fileName = requestPath.substring(requestPath.lastIndexOf('/')+1,requestPath.length());
processor.setContextParam(FILENAME, fileName);
//adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
String plainPath = requestPath.substring(contextRoot.length()+1,requestPath.length() - fileName.length());
processor.setContextParam(PLAIN_PATH, plainPath);
//adding contextPath - requestPath without the filename
processor.setContextParam(CONTEXT_PATH,contextRoot+"/"+plainPath);
}
//adding session id to context
processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
//adding context absolute path to context
//adding pathInfo to context - attention: this is only available when a servlet is requested
String s1=request.getPathInfo();
if(s1!=null){
processor.setContextParam(WebProcessor.PATH_INFO, s1);
}
processor.setContextParam(WebProcessor.QUERY_STRING, (request.getQueryString() != null ? request.getQueryString() : ""));
//storing the realpath for webapp
String realPath = httpSession.getServletContext().getRealPath("");
if (realPath == null) {
realPath = httpSession.getServletContext().getRealPath(".");
}
File f = new File(realPath);
URI fileURI = null;
fileURI = f.toURI();
processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("real path of webapp: " + realPath);
}
//storing the TransformerService
processor.setContextParam(TransformerService.TRANSFORMER_SERVICE, httpSession.getServletContext().getAttribute(TransformerService.class.getName()));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("TransformerService: " + httpSession.getServletContext().getAttribute(TransformerService.class.getName()));
}
//[2] read any request params that are *not* betterForm params and pass them into the context map
Enumeration params = request.getParameterNames();
String s;
while (params.hasMoreElements()) {
s = (String) params.nextElement();
//store all request-params we don't use in the context map of XFormsProcessorImpl
String value = request.getParameter(s);
processor.setContextParam(s, value);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("added request param '" + s + "' added to context");
LOGGER.debug("param value'" + value);
}
}
}
| public static void setContextParams(HttpServletRequest request,
HttpSession httpSession,
XFormsProcessor processor,
String sessionkey) {
Map servletMap = new HashMap();
servletMap.put(WebProcessor.SESSION_ID, sessionkey);
processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);
//adding requestURI to context
processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));
//adding request URL to context
String requestURL = request.getRequestURL().toString();
processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);
// the web app name with an '/' prepended e.g. '/betterform' by default
String contextRoot = WebUtil.getContextRoot(request);
processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
}
String requestPath = "";
URL url=null;
String plainPath ="";
try {
url = new URL(requestURL);
requestPath = url.getPath();
} catch (MalformedURLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if(requestPath.length() != 0){
//adding request path e.g. '/betterform/forms/demo/registration.xhtml'
processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);
//adding filename of requested doc to context
String fileName = requestPath.substring(requestPath.lastIndexOf('/')+1,requestPath.length());//FILENAME xforms
processor.setContextParam(FILENAME, fileName);
if(requestURL.contains(contextRoot)){ //case1: contextRoot is a part of the URL
//adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
plainPath = requestPath.substring(contextRoot.length()+1,requestPath.length() - fileName.length());
processor.setContextParam(PLAIN_PATH, plainPath);
}
else{//case2: contextRoot is not a part of the URL
String[] urlParts=requestURL.split("/");
plainPath=urlParts[urlParts.length-2];
}
//adding contextPath - requestPath without the filename
processor.setContextParam(CONTEXT_PATH,contextRoot+"/"+plainPath);
}
//adding session id to context
processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
//adding context absolute path to context
//adding pathInfo to context - attention: this is only available when a servlet is requested
String s1=request.getPathInfo();
if(s1!=null){
processor.setContextParam(WebProcessor.PATH_INFO, s1);
}
processor.setContextParam(WebProcessor.QUERY_STRING, (request.getQueryString() != null ? request.getQueryString() : ""));
//storing the realpath for webapp
String realPath = httpSession.getServletContext().getRealPath("");
if (realPath == null) {
realPath = httpSession.getServletContext().getRealPath(".");
}
File f = new File(realPath);
URI fileURI = null;
fileURI = f.toURI();
processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("real path of webapp: " + realPath);
}
//storing the TransformerService
processor.setContextParam(TransformerService.TRANSFORMER_SERVICE, httpSession.getServletContext().getAttribute(TransformerService.class.getName()));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("TransformerService: " + httpSession.getServletContext().getAttribute(TransformerService.class.getName()));
}
//[2] read any request params that are *not* betterForm params and pass them into the context map
Enumeration params = request.getParameterNames();
String s;
while (params.hasMoreElements()) {
s = (String) params.nextElement();
//store all request-params we don't use in the context map of XFormsProcessorImpl
String value = request.getParameter(s);
processor.setContextParam(s, value);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("added request param '" + s + "' added to context");
LOGGER.debug("param value'" + value);
}
}
}
|
diff --git a/jbpm-form-modeler-core/jbpm-form-modeler-service/jbpm-form-modeler-ui/src/main/java/org/jbpm/formModeler/core/processing/impl/FormProcessorImpl.java b/jbpm-form-modeler-core/jbpm-form-modeler-service/jbpm-form-modeler-ui/src/main/java/org/jbpm/formModeler/core/processing/impl/FormProcessorImpl.java
index de9b1f41..2c48d7f8 100755
--- a/jbpm-form-modeler-core/jbpm-form-modeler-service/jbpm-form-modeler-ui/src/main/java/org/jbpm/formModeler/core/processing/impl/FormProcessorImpl.java
+++ b/jbpm-form-modeler-core/jbpm-form-modeler-service/jbpm-form-modeler-ui/src/main/java/org/jbpm/formModeler/core/processing/impl/FormProcessorImpl.java
@@ -1,516 +1,516 @@
/**
* Copyright (C) 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.formModeler.core.processing.impl;
import au.com.bytecode.opencsv.CSVParser;
import org.apache.commons.logging.Log;
import org.jbpm.formModeler.api.model.DataHolder;
import org.jbpm.formModeler.core.FieldHandlersManager;
import org.jbpm.formModeler.core.processing.FieldHandler;
import org.jbpm.formModeler.core.processing.FormProcessor;
import org.jbpm.formModeler.core.processing.FormStatusData;
import org.jbpm.formModeler.core.processing.ProcessingMessagedException;
import org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler;
import org.jbpm.formModeler.core.processing.formProcessing.FormChangeProcessor;
import org.jbpm.formModeler.core.processing.formProcessing.FormChangeResponse;
import org.jbpm.formModeler.core.processing.formProcessing.NamespaceManager;
import org.jbpm.formModeler.core.processing.formStatus.FormStatus;
import org.jbpm.formModeler.core.processing.formStatus.FormStatusManager;
import org.jbpm.formModeler.api.model.Field;
import org.jbpm.formModeler.api.model.Form;
import org.jbpm.formModeler.api.model.wrappers.I18nSet;
import org.apache.commons.lang.StringUtils;
import org.jbpm.formModeler.core.config.FormManagerImpl;
import org.jbpm.formModeler.api.client.FormRenderContext;
import org.jbpm.formModeler.api.client.FormRenderContextManager;
import org.jbpm.formModeler.service.cdi.CDIBeanLocator;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.*;
@ApplicationScoped
public class FormProcessorImpl implements FormProcessor, Serializable {
@Inject
private Log log;
// TODO: fix formulas
//@Inject
private FormChangeProcessor formChangeProcessor;
@Inject
private FieldHandlersManager fieldHandlersManager;
@Inject
FormRenderContextManager formRenderContextManager;
private CSVParser rangeParser = new CSVParser(';');
private CSVParser optionParser = new CSVParser(',');
protected FormStatus getContextFormStatus(FormRenderContext context) {
return FormStatusManager.lookup().getFormStatus(context.getForm().getId(), context.getUID());
}
protected FormStatus getFormStatus(Form form, String namespace) {
return getFormStatus(form, namespace, new HashMap());
}
protected FormStatus getFormStatus(Form form, String namespace, Map currentValues) {
FormStatus formStatus = FormStatusManager.lookup().getFormStatus(form.getId(), namespace);
return formStatus != null ? formStatus : createFormStatus(form, namespace, currentValues);
}
protected boolean existsFormStatus(Long formId, String namespace) {
FormStatus formStatus = FormStatusManager.lookup().getFormStatus(formId, namespace);
return formStatus != null;
}
protected FormStatus createFormStatus(Form form, String namespace, Map currentValues) {
FormStatus fStatus = FormStatusManager.lookup().createFormStatus(form.getId(), namespace);
setDefaultValues(form, namespace, currentValues);
return fStatus;
}
protected void setDefaultValues(Form form, String namespace, Map currentValues) {
if (form != null) {
Set formFields = form.getFormFields();
Map params = new HashMap(5);
Map rangeFormulas = (Map) getAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS);
if (rangeFormulas == null) {
rangeFormulas = new HashMap();
setAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS, rangeFormulas);
}
for (Iterator iterator = formFields.iterator(); iterator.hasNext();) {
Field field = (Field) iterator.next();
Object value = currentValues.get(field.getFieldName());
String inputName = getPrefix(form, namespace) + field.getFieldName();
try {
FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType());
if ((value instanceof Map && !((Map)value).containsKey(FORM_MODE)) && !(value instanceof I18nSet)) ((Map)value).put(FORM_MODE, currentValues.get(FORM_MODE));
Map paramValue = handler.getParamValue(inputName, value, field.getFieldPattern());
if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue);
// Init ranges for simple combos
String rangeFormula = field.getRangeFormula();
if (!StringUtils.isEmpty(rangeFormula) && rangeFormula.startsWith("{") && rangeFormula.endsWith("}")) {
rangeFormula = rangeFormula.substring(1, rangeFormula.length() - 1);
String[] options = rangeParser.parseLine(rangeFormula);
if (options != null) {
Map rangeValues = new TreeMap();
for (String option : options) {
String[] values = optionParser.parseLine(option);
if (values != null && values.length == 2) {
rangeValues.put(values[0], values[1]);
}
}
rangeFormulas.put(field.getFieldName(), rangeValues);
}
}
/*
TODO: implement again formulas for default values
Object defaultValue = pField.get("defaultValueFormula");
String inputName = getPrefix(pf, namespace) + pField.getFieldName();
try {
String pattern = (String) pField.get("pattern");
Object value = currentValues.get(pField.getFieldName());
FieldHandler handler = pField.getFieldType().getManager();
if (value == null) {
if (defaultValue != null) {
if (!defaultValue.toString().startsWith("=")) {
log.error("Incorrect formula specified for field " + pField.getFieldName());
continue;
}
if (handler instanceof DefaultFieldHandler)
value = ((DefaultFieldHandler) handler).evaluateFormula(pField, defaultValue.toString().substring(1), "", new HashMap(0), "", namespace, new Date());
}
}
if ((value instanceof Map && !((Map)value).containsKey(FormProcessor.FORM_MODE)) && !(value instanceof I18nSet) && !(value instanceof I18nObject)) ((Map)value).put(FormProcessor.FORM_MODE, currentValues.get(FormProcessor.FORM_MODE));
Map paramValue = handler.getParamValue(inputName, value, pattern);
if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue); */
} catch (Exception e) {
log.error("Error obtaining default values for " + inputName, e);
}
}
setValues(form, namespace, params, null, true);
}
}
protected void destroyFormStatus(Form form, String namespace) {
FormStatusManager.lookup().destroyFormStatus(form.getId(), namespace);
}
public void setValues(Form form, String namespace, Map parameterMap, Map filesMap) {
setValues(form, namespace, parameterMap, filesMap, false);
}
public void setValues(Form form, String namespace, Map parameterMap, Map filesMap, boolean incremental) {
if (form != null) {
namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE);
FormStatus formStatus = getFormStatus(form, namespace);
// if (!incremental) formStatus.getWrongFields().clear();
if (incremental) {
Map mergedParameterMap = new HashMap();
if (formStatus.getLastParameterMap() != null)
mergedParameterMap.putAll(formStatus.getLastParameterMap());
if (parameterMap != null)
mergedParameterMap.putAll(parameterMap);
formStatus.setLastParameterMap(mergedParameterMap);
} else {
formStatus.setLastParameterMap(parameterMap);
}
String inputsPrefix = getPrefix(form, namespace);
for (Field field : form.getFormFields()) {
setFieldValue(field, formStatus, inputsPrefix, parameterMap, filesMap, incremental);
}
}
}
public void modify(Form form, String namespace, String fieldName, Object value) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getInputValues().put(fieldName, value);
propagateChangesToParentFormStatuses(formStatus, fieldName, value);
}
public void setAttribute(Form form, String namespace, String attributeName, Object attributeValue) {
if (form != null) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getAttributes().put(attributeName, attributeValue);
}
}
public Object getAttribute(Form form, String namespace, String attributeName) {
if (form != null){
FormStatus formStatus = getFormStatus(form, namespace);
return formStatus.getAttributes().get(attributeName);
}
return null;
}
protected void setFieldValue(Field field, FormStatus formStatus, String inputsPrefix, Map parameterMap, Map filesMap, boolean incremental) {
String fieldName = field.getFieldName();
String inputName = inputsPrefix + fieldName;
FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType());
try {
Object previousValue = formStatus.getInputValues().get(fieldName);
boolean isRequired = field.getFieldRequired().booleanValue();
if (!handler.isEvaluable(inputName, parameterMap, filesMap) && !(handler.isEmpty(previousValue) && isRequired)) return;
Object value = null;
boolean emptyNumber = false;
try {
value = handler.getValue(field, inputName, parameterMap, filesMap, field.getFieldType().getFieldClass(), previousValue);
} catch (NumericFieldHandler.EmptyNumberException ene) {
//Treat this case in particular, as returning null in a numeric field would make related formulas not working.
emptyNumber = true;
}
if (incremental && value == null && !emptyNumber) {
if (log.isDebugEnabled()) log.debug("Refusing to overwrite input value for parameter " + fieldName);
} else {
formStatus.getInputValues().put(fieldName, value);
try {
propagateChangesToParentFormStatuses(formStatus, fieldName, value);
} catch (Exception e) {
log.error("Error modifying formStatus: ", e);
}
boolean isEmpty = handler.isEmpty(value);
if (isRequired && isEmpty && !incremental) {
log.debug("Missing required field " + fieldName);
formStatus.getWrongFields().add(fieldName);
} else {
formStatus.removeWrongField(fieldName);
}
}
} catch (ProcessingMessagedException pme) {
log.debug("Processing field: ", pme);
formStatus.addErrorMessages(fieldName, pme.getMessages());
} catch (Exception e) {
log.debug("Error setting field value:", e);
if (!incremental) {
formStatus.getInputValues().put(fieldName, null);
formStatus.getWrongFields().add(fieldName);
}
}
}
protected void propagateChangesToParentFormStatuses(FormStatus formStatus, String fieldName, Object value) {
FormStatus parent = FormStatusManager.lookup().getParent(formStatus);
if (parent != null) {
String fieldNameInParent = NamespaceManager.lookup().getNamespace(formStatus.getNamespace()).getFieldNameInParent();
Object valueInParent = parent.getInputValues().get(fieldNameInParent);
if (valueInParent != null) {
Map parentMapObjectRepresentation = null;
if (valueInParent instanceof Map) {
parentMapObjectRepresentation = (Map) valueInParent;
} else if (valueInParent instanceof Map[]) {
//Take the correct value
Map editFieldPositions = (Map) parent.getAttributes().get(FormStatusData.EDIT_FIELD_POSITIONS);
if (editFieldPositions != null) {
Integer pos = (Integer) editFieldPositions.get(fieldNameInParent);
if (pos != null) {
parentMapObjectRepresentation = ((Map[]) valueInParent)[pos.intValue()];
}
}
}
if (parentMapObjectRepresentation != null) {
//Copy my value to parent
parentMapObjectRepresentation.put(fieldName, value);
propagateChangesToParentFormStatuses(parent, fieldNameInParent, valueInParent);
}
}
}
}
public FormStatusData read(String ctxUid) {
FormStatusDataImpl data = null;
try {
FormRenderContext context = formRenderContextManager.getFormRenderContext(ctxUid);
if (context == null ) return null;
FormStatus formStatus = getContextFormStatus(context);
boolean isNew = formStatus == null;
if (isNew) {
formStatus = createContextFormStatus(context);
}
data = new FormStatusDataImpl(formStatus, isNew);
} catch (Exception e) {
log.error("Error: ", e);
}
return data;
}
protected FormStatus createContextFormStatus(FormRenderContext context) throws Exception {
Map values = new HashMap();
Map<String, Object> bindingData = context.getBindingData();
if (bindingData != null && !bindingData.isEmpty()) {
Form form = context.getForm();
Set<Field> fields = form.getFormFields();
if (fields != null) {
for (Field field : form.getFormFields()) {
String bindingString = field.getBindingStr();
if (!StringUtils.isEmpty(bindingString)) {
bindingString = bindingString.substring(1, bindingString.length() - 1);
boolean canSetValue = bindingString.indexOf("/") > 0;
Object value = null;
if (canSetValue) {
String holderId = bindingString.substring(0, bindingString.indexOf("/"));
String holderFieldId = bindingString.substring(holderId.length() + 1);
DataHolder holder = form.getDataHolderById(holderId);
if (holder != null && !StringUtils.isEmpty(holderFieldId)) {
Object holderValue = bindingData.get(holder.getId());
if (holderValue == null) continue;
value = holder.readValue(holderValue, holderFieldId);
}
} else {
value = bindingData.get(bindingString);
}
values.put(field.getFieldName(), value);
}
}
}
}
return getFormStatus(context.getForm(), context.getUID(), values);
}
public FormStatusData read(Form form, String namespace, Map currentValues) {
boolean exists = existsFormStatus(form.getId(), namespace);
if (currentValues == null) currentValues = new HashMap();
FormStatus formStatus = getFormStatus(form, namespace, currentValues);
FormStatusDataImpl data = null;
try {
data = new FormStatusDataImpl(formStatus, !exists);
} catch (Exception e) {
log.error("Error: ", e);
}
return data;
}
public FormStatusData read(Form form, String namespace) {
return read(form, namespace, new HashMap<String, Object>());
}
public void flushPendingCalculations(Form form, String namespace) {
if (formChangeProcessor != null) {
formChangeProcessor.process(form, namespace, new FormChangeResponse());//Response is ignored, we just need the session values.
}
}
public void persist(String ctxUid) throws Exception {
ctxUid = StringUtils.defaultIfEmpty(ctxUid, FormProcessor.DEFAULT_NAMESPACE);
persist(formRenderContextManager.getFormRenderContext(ctxUid));
}
public void persist(FormRenderContext context) throws Exception {
Form form = context.getForm();
Map mapToPersist = getFilteredMapRepresentationToPersist(form, context.getUID());
Map<String, Object> result = new HashMap<String, Object>();
for (Iterator it = mapToPersist.keySet().iterator(); it.hasNext();) {
String fieldName = (String) it.next();
Field field = form.getField(fieldName);
if (field != null) {
String bindingString = field.getBindingStr();
if (!StringUtils.isEmpty(bindingString)) {
bindingString = bindingString.substring(1, bindingString.length() - 1);
boolean canBind = bindingString.indexOf("/") > 0;
if (canBind) {
String holderId = bindingString.substring(0, bindingString.indexOf("/"));
String holderFieldId = bindingString.substring(holderId.length() + 1);
DataHolder holder = form.getDataHolderById(holderId);
if (holder != null && !StringUtils.isEmpty(holderFieldId)) {
Object value = context.getBindingData().get(holderId);
holder.writeValue(value, holderFieldId, mapToPersist.get(fieldName));
if (!result.containsKey(holderId)) result.put(holderId, value);
}
else canBind = false;
}
if (!canBind) {
log.debug("Unable to bind DataHolder for field '" + fieldName + "' to '" + bindingString + "'. This may be caused because bindingString is incorrect or the form doesn't contains the defined DataHolder.");
- if (!result.containsKey(fieldName)) result.put(fieldName, mapToPersist.get(fieldName));
+ if (!result.containsKey(bindingString)) result.put(bindingString, mapToPersist.get(fieldName));
}
}
}
}
context.setPersistedData(result);
}
public Map getMapRepresentationToPersist(Form form, String namespace) throws Exception {
namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE);
flushPendingCalculations(form, namespace);
Map m = new HashMap();
FormStatus formStatus = getFormStatus(form, namespace);
if (!formStatus.getWrongFields().isEmpty()) {
throw new IllegalArgumentException("Validation error.");
}
fillObjectValues(m, formStatus.getInputValues(), form);
Set s = (Set) m.get(MODIFIED_FIELD_NAMES);
if (s == null) {
m.put(MODIFIED_FIELD_NAMES, s = new TreeSet());
}
s.addAll(form.getFieldNames());
return m;
}
protected Map getFilteredMapRepresentationToPersist(Form form, String namespace) throws Exception {
Map inputValues = getMapRepresentationToPersist(form, namespace);
Map mapToPersist = filterMapRepresentationToPersist(inputValues);
return mapToPersist;
}
public Map filterMapRepresentationToPersist(Map inputValues) throws Exception {
Map filteredMap = new HashMap();
Set keys = inputValues.keySet();
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
filteredMap.put(key, inputValues.get(key));
}
return filteredMap;
}
/**
* Copy to obj values read from status map values
*
* @param obj
* @param values
* @throws Exception
*/
protected void fillObjectValues(final Map obj, Map values, Form form) throws Exception {
Map valuesToSet = new HashMap();
for (Iterator it = values.keySet().iterator(); it.hasNext();) {
String propertyName = (String) it.next();
Object propertyValue = values.get(propertyName);
valuesToSet.put(propertyName, propertyValue);
}
obj.putAll(valuesToSet);
}
protected FormManagerImpl getFormsManager() {
return (FormManagerImpl) CDIBeanLocator.getBeanByType(FormManagerImpl.class);
}
@Override
public void clear(FormRenderContext context) {
clear(context.getForm(), context.getUID());
}
@Override
public void clear(String ctxUID) {
clear(formRenderContextManager.getFormRenderContext(ctxUID));
}
public void clear(Form form, String namespace) {
if (log.isDebugEnabled())
log.debug("Clearing form status for form " + form.getName() + " with namespace '" + namespace + "'");
destroyFormStatus(form, namespace);
}
public void clearField(Form form, String namespace, String fieldName) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getInputValues().remove(fieldName);
}
public void clearFieldErrors(Form form, String namespace) {
FormStatusManager.lookup().cascadeClearWrongFields(form.getId(), namespace);
}
public void forceWrongField(Form form, String namespace, String fieldName) {
FormStatusManager.lookup().getFormStatus(form.getId(), namespace).getWrongFields().add(fieldName);
}
protected String getPrefix(Form form, String namespace) {
return namespace + FormProcessor.NAMESPACE_SEPARATOR + form.getId() + FormProcessor.NAMESPACE_SEPARATOR;
}
}
| true | true | protected void setDefaultValues(Form form, String namespace, Map currentValues) {
if (form != null) {
Set formFields = form.getFormFields();
Map params = new HashMap(5);
Map rangeFormulas = (Map) getAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS);
if (rangeFormulas == null) {
rangeFormulas = new HashMap();
setAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS, rangeFormulas);
}
for (Iterator iterator = formFields.iterator(); iterator.hasNext();) {
Field field = (Field) iterator.next();
Object value = currentValues.get(field.getFieldName());
String inputName = getPrefix(form, namespace) + field.getFieldName();
try {
FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType());
if ((value instanceof Map && !((Map)value).containsKey(FORM_MODE)) && !(value instanceof I18nSet)) ((Map)value).put(FORM_MODE, currentValues.get(FORM_MODE));
Map paramValue = handler.getParamValue(inputName, value, field.getFieldPattern());
if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue);
// Init ranges for simple combos
String rangeFormula = field.getRangeFormula();
if (!StringUtils.isEmpty(rangeFormula) && rangeFormula.startsWith("{") && rangeFormula.endsWith("}")) {
rangeFormula = rangeFormula.substring(1, rangeFormula.length() - 1);
String[] options = rangeParser.parseLine(rangeFormula);
if (options != null) {
Map rangeValues = new TreeMap();
for (String option : options) {
String[] values = optionParser.parseLine(option);
if (values != null && values.length == 2) {
rangeValues.put(values[0], values[1]);
}
}
rangeFormulas.put(field.getFieldName(), rangeValues);
}
}
/*
TODO: implement again formulas for default values
Object defaultValue = pField.get("defaultValueFormula");
String inputName = getPrefix(pf, namespace) + pField.getFieldName();
try {
String pattern = (String) pField.get("pattern");
Object value = currentValues.get(pField.getFieldName());
FieldHandler handler = pField.getFieldType().getManager();
if (value == null) {
if (defaultValue != null) {
if (!defaultValue.toString().startsWith("=")) {
log.error("Incorrect formula specified for field " + pField.getFieldName());
continue;
}
if (handler instanceof DefaultFieldHandler)
value = ((DefaultFieldHandler) handler).evaluateFormula(pField, defaultValue.toString().substring(1), "", new HashMap(0), "", namespace, new Date());
}
}
if ((value instanceof Map && !((Map)value).containsKey(FormProcessor.FORM_MODE)) && !(value instanceof I18nSet) && !(value instanceof I18nObject)) ((Map)value).put(FormProcessor.FORM_MODE, currentValues.get(FormProcessor.FORM_MODE));
Map paramValue = handler.getParamValue(inputName, value, pattern);
if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue); */
} catch (Exception e) {
log.error("Error obtaining default values for " + inputName, e);
}
}
setValues(form, namespace, params, null, true);
}
}
protected void destroyFormStatus(Form form, String namespace) {
FormStatusManager.lookup().destroyFormStatus(form.getId(), namespace);
}
public void setValues(Form form, String namespace, Map parameterMap, Map filesMap) {
setValues(form, namespace, parameterMap, filesMap, false);
}
public void setValues(Form form, String namespace, Map parameterMap, Map filesMap, boolean incremental) {
if (form != null) {
namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE);
FormStatus formStatus = getFormStatus(form, namespace);
// if (!incremental) formStatus.getWrongFields().clear();
if (incremental) {
Map mergedParameterMap = new HashMap();
if (formStatus.getLastParameterMap() != null)
mergedParameterMap.putAll(formStatus.getLastParameterMap());
if (parameterMap != null)
mergedParameterMap.putAll(parameterMap);
formStatus.setLastParameterMap(mergedParameterMap);
} else {
formStatus.setLastParameterMap(parameterMap);
}
String inputsPrefix = getPrefix(form, namespace);
for (Field field : form.getFormFields()) {
setFieldValue(field, formStatus, inputsPrefix, parameterMap, filesMap, incremental);
}
}
}
public void modify(Form form, String namespace, String fieldName, Object value) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getInputValues().put(fieldName, value);
propagateChangesToParentFormStatuses(formStatus, fieldName, value);
}
public void setAttribute(Form form, String namespace, String attributeName, Object attributeValue) {
if (form != null) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getAttributes().put(attributeName, attributeValue);
}
}
public Object getAttribute(Form form, String namespace, String attributeName) {
if (form != null){
FormStatus formStatus = getFormStatus(form, namespace);
return formStatus.getAttributes().get(attributeName);
}
return null;
}
protected void setFieldValue(Field field, FormStatus formStatus, String inputsPrefix, Map parameterMap, Map filesMap, boolean incremental) {
String fieldName = field.getFieldName();
String inputName = inputsPrefix + fieldName;
FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType());
try {
Object previousValue = formStatus.getInputValues().get(fieldName);
boolean isRequired = field.getFieldRequired().booleanValue();
if (!handler.isEvaluable(inputName, parameterMap, filesMap) && !(handler.isEmpty(previousValue) && isRequired)) return;
Object value = null;
boolean emptyNumber = false;
try {
value = handler.getValue(field, inputName, parameterMap, filesMap, field.getFieldType().getFieldClass(), previousValue);
} catch (NumericFieldHandler.EmptyNumberException ene) {
//Treat this case in particular, as returning null in a numeric field would make related formulas not working.
emptyNumber = true;
}
if (incremental && value == null && !emptyNumber) {
if (log.isDebugEnabled()) log.debug("Refusing to overwrite input value for parameter " + fieldName);
} else {
formStatus.getInputValues().put(fieldName, value);
try {
propagateChangesToParentFormStatuses(formStatus, fieldName, value);
} catch (Exception e) {
log.error("Error modifying formStatus: ", e);
}
boolean isEmpty = handler.isEmpty(value);
if (isRequired && isEmpty && !incremental) {
log.debug("Missing required field " + fieldName);
formStatus.getWrongFields().add(fieldName);
} else {
formStatus.removeWrongField(fieldName);
}
}
} catch (ProcessingMessagedException pme) {
log.debug("Processing field: ", pme);
formStatus.addErrorMessages(fieldName, pme.getMessages());
} catch (Exception e) {
log.debug("Error setting field value:", e);
if (!incremental) {
formStatus.getInputValues().put(fieldName, null);
formStatus.getWrongFields().add(fieldName);
}
}
}
protected void propagateChangesToParentFormStatuses(FormStatus formStatus, String fieldName, Object value) {
FormStatus parent = FormStatusManager.lookup().getParent(formStatus);
if (parent != null) {
String fieldNameInParent = NamespaceManager.lookup().getNamespace(formStatus.getNamespace()).getFieldNameInParent();
Object valueInParent = parent.getInputValues().get(fieldNameInParent);
if (valueInParent != null) {
Map parentMapObjectRepresentation = null;
if (valueInParent instanceof Map) {
parentMapObjectRepresentation = (Map) valueInParent;
} else if (valueInParent instanceof Map[]) {
//Take the correct value
Map editFieldPositions = (Map) parent.getAttributes().get(FormStatusData.EDIT_FIELD_POSITIONS);
if (editFieldPositions != null) {
Integer pos = (Integer) editFieldPositions.get(fieldNameInParent);
if (pos != null) {
parentMapObjectRepresentation = ((Map[]) valueInParent)[pos.intValue()];
}
}
}
if (parentMapObjectRepresentation != null) {
//Copy my value to parent
parentMapObjectRepresentation.put(fieldName, value);
propagateChangesToParentFormStatuses(parent, fieldNameInParent, valueInParent);
}
}
}
}
public FormStatusData read(String ctxUid) {
FormStatusDataImpl data = null;
try {
FormRenderContext context = formRenderContextManager.getFormRenderContext(ctxUid);
if (context == null ) return null;
FormStatus formStatus = getContextFormStatus(context);
boolean isNew = formStatus == null;
if (isNew) {
formStatus = createContextFormStatus(context);
}
data = new FormStatusDataImpl(formStatus, isNew);
} catch (Exception e) {
log.error("Error: ", e);
}
return data;
}
protected FormStatus createContextFormStatus(FormRenderContext context) throws Exception {
Map values = new HashMap();
Map<String, Object> bindingData = context.getBindingData();
if (bindingData != null && !bindingData.isEmpty()) {
Form form = context.getForm();
Set<Field> fields = form.getFormFields();
if (fields != null) {
for (Field field : form.getFormFields()) {
String bindingString = field.getBindingStr();
if (!StringUtils.isEmpty(bindingString)) {
bindingString = bindingString.substring(1, bindingString.length() - 1);
boolean canSetValue = bindingString.indexOf("/") > 0;
Object value = null;
if (canSetValue) {
String holderId = bindingString.substring(0, bindingString.indexOf("/"));
String holderFieldId = bindingString.substring(holderId.length() + 1);
DataHolder holder = form.getDataHolderById(holderId);
if (holder != null && !StringUtils.isEmpty(holderFieldId)) {
Object holderValue = bindingData.get(holder.getId());
if (holderValue == null) continue;
value = holder.readValue(holderValue, holderFieldId);
}
} else {
value = bindingData.get(bindingString);
}
values.put(field.getFieldName(), value);
}
}
}
}
return getFormStatus(context.getForm(), context.getUID(), values);
}
public FormStatusData read(Form form, String namespace, Map currentValues) {
boolean exists = existsFormStatus(form.getId(), namespace);
if (currentValues == null) currentValues = new HashMap();
FormStatus formStatus = getFormStatus(form, namespace, currentValues);
FormStatusDataImpl data = null;
try {
data = new FormStatusDataImpl(formStatus, !exists);
} catch (Exception e) {
log.error("Error: ", e);
}
return data;
}
public FormStatusData read(Form form, String namespace) {
return read(form, namespace, new HashMap<String, Object>());
}
public void flushPendingCalculations(Form form, String namespace) {
if (formChangeProcessor != null) {
formChangeProcessor.process(form, namespace, new FormChangeResponse());//Response is ignored, we just need the session values.
}
}
public void persist(String ctxUid) throws Exception {
ctxUid = StringUtils.defaultIfEmpty(ctxUid, FormProcessor.DEFAULT_NAMESPACE);
persist(formRenderContextManager.getFormRenderContext(ctxUid));
}
public void persist(FormRenderContext context) throws Exception {
Form form = context.getForm();
Map mapToPersist = getFilteredMapRepresentationToPersist(form, context.getUID());
Map<String, Object> result = new HashMap<String, Object>();
for (Iterator it = mapToPersist.keySet().iterator(); it.hasNext();) {
String fieldName = (String) it.next();
Field field = form.getField(fieldName);
if (field != null) {
String bindingString = field.getBindingStr();
if (!StringUtils.isEmpty(bindingString)) {
bindingString = bindingString.substring(1, bindingString.length() - 1);
boolean canBind = bindingString.indexOf("/") > 0;
if (canBind) {
String holderId = bindingString.substring(0, bindingString.indexOf("/"));
String holderFieldId = bindingString.substring(holderId.length() + 1);
DataHolder holder = form.getDataHolderById(holderId);
if (holder != null && !StringUtils.isEmpty(holderFieldId)) {
Object value = context.getBindingData().get(holderId);
holder.writeValue(value, holderFieldId, mapToPersist.get(fieldName));
if (!result.containsKey(holderId)) result.put(holderId, value);
}
else canBind = false;
}
if (!canBind) {
log.debug("Unable to bind DataHolder for field '" + fieldName + "' to '" + bindingString + "'. This may be caused because bindingString is incorrect or the form doesn't contains the defined DataHolder.");
if (!result.containsKey(fieldName)) result.put(fieldName, mapToPersist.get(fieldName));
}
}
}
}
context.setPersistedData(result);
}
public Map getMapRepresentationToPersist(Form form, String namespace) throws Exception {
namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE);
flushPendingCalculations(form, namespace);
Map m = new HashMap();
FormStatus formStatus = getFormStatus(form, namespace);
if (!formStatus.getWrongFields().isEmpty()) {
throw new IllegalArgumentException("Validation error.");
}
fillObjectValues(m, formStatus.getInputValues(), form);
Set s = (Set) m.get(MODIFIED_FIELD_NAMES);
if (s == null) {
m.put(MODIFIED_FIELD_NAMES, s = new TreeSet());
}
s.addAll(form.getFieldNames());
return m;
}
protected Map getFilteredMapRepresentationToPersist(Form form, String namespace) throws Exception {
Map inputValues = getMapRepresentationToPersist(form, namespace);
Map mapToPersist = filterMapRepresentationToPersist(inputValues);
return mapToPersist;
}
public Map filterMapRepresentationToPersist(Map inputValues) throws Exception {
Map filteredMap = new HashMap();
Set keys = inputValues.keySet();
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
filteredMap.put(key, inputValues.get(key));
}
return filteredMap;
}
/**
* Copy to obj values read from status map values
*
* @param obj
* @param values
* @throws Exception
*/
protected void fillObjectValues(final Map obj, Map values, Form form) throws Exception {
Map valuesToSet = new HashMap();
for (Iterator it = values.keySet().iterator(); it.hasNext();) {
String propertyName = (String) it.next();
Object propertyValue = values.get(propertyName);
valuesToSet.put(propertyName, propertyValue);
}
obj.putAll(valuesToSet);
}
protected FormManagerImpl getFormsManager() {
return (FormManagerImpl) CDIBeanLocator.getBeanByType(FormManagerImpl.class);
}
@Override
public void clear(FormRenderContext context) {
clear(context.getForm(), context.getUID());
}
@Override
public void clear(String ctxUID) {
clear(formRenderContextManager.getFormRenderContext(ctxUID));
}
public void clear(Form form, String namespace) {
if (log.isDebugEnabled())
log.debug("Clearing form status for form " + form.getName() + " with namespace '" + namespace + "'");
destroyFormStatus(form, namespace);
}
public void clearField(Form form, String namespace, String fieldName) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getInputValues().remove(fieldName);
}
public void clearFieldErrors(Form form, String namespace) {
FormStatusManager.lookup().cascadeClearWrongFields(form.getId(), namespace);
}
public void forceWrongField(Form form, String namespace, String fieldName) {
FormStatusManager.lookup().getFormStatus(form.getId(), namespace).getWrongFields().add(fieldName);
}
protected String getPrefix(Form form, String namespace) {
return namespace + FormProcessor.NAMESPACE_SEPARATOR + form.getId() + FormProcessor.NAMESPACE_SEPARATOR;
}
}
| protected void setDefaultValues(Form form, String namespace, Map currentValues) {
if (form != null) {
Set formFields = form.getFormFields();
Map params = new HashMap(5);
Map rangeFormulas = (Map) getAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS);
if (rangeFormulas == null) {
rangeFormulas = new HashMap();
setAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS, rangeFormulas);
}
for (Iterator iterator = formFields.iterator(); iterator.hasNext();) {
Field field = (Field) iterator.next();
Object value = currentValues.get(field.getFieldName());
String inputName = getPrefix(form, namespace) + field.getFieldName();
try {
FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType());
if ((value instanceof Map && !((Map)value).containsKey(FORM_MODE)) && !(value instanceof I18nSet)) ((Map)value).put(FORM_MODE, currentValues.get(FORM_MODE));
Map paramValue = handler.getParamValue(inputName, value, field.getFieldPattern());
if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue);
// Init ranges for simple combos
String rangeFormula = field.getRangeFormula();
if (!StringUtils.isEmpty(rangeFormula) && rangeFormula.startsWith("{") && rangeFormula.endsWith("}")) {
rangeFormula = rangeFormula.substring(1, rangeFormula.length() - 1);
String[] options = rangeParser.parseLine(rangeFormula);
if (options != null) {
Map rangeValues = new TreeMap();
for (String option : options) {
String[] values = optionParser.parseLine(option);
if (values != null && values.length == 2) {
rangeValues.put(values[0], values[1]);
}
}
rangeFormulas.put(field.getFieldName(), rangeValues);
}
}
/*
TODO: implement again formulas for default values
Object defaultValue = pField.get("defaultValueFormula");
String inputName = getPrefix(pf, namespace) + pField.getFieldName();
try {
String pattern = (String) pField.get("pattern");
Object value = currentValues.get(pField.getFieldName());
FieldHandler handler = pField.getFieldType().getManager();
if (value == null) {
if (defaultValue != null) {
if (!defaultValue.toString().startsWith("=")) {
log.error("Incorrect formula specified for field " + pField.getFieldName());
continue;
}
if (handler instanceof DefaultFieldHandler)
value = ((DefaultFieldHandler) handler).evaluateFormula(pField, defaultValue.toString().substring(1), "", new HashMap(0), "", namespace, new Date());
}
}
if ((value instanceof Map && !((Map)value).containsKey(FormProcessor.FORM_MODE)) && !(value instanceof I18nSet) && !(value instanceof I18nObject)) ((Map)value).put(FormProcessor.FORM_MODE, currentValues.get(FormProcessor.FORM_MODE));
Map paramValue = handler.getParamValue(inputName, value, pattern);
if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue); */
} catch (Exception e) {
log.error("Error obtaining default values for " + inputName, e);
}
}
setValues(form, namespace, params, null, true);
}
}
protected void destroyFormStatus(Form form, String namespace) {
FormStatusManager.lookup().destroyFormStatus(form.getId(), namespace);
}
public void setValues(Form form, String namespace, Map parameterMap, Map filesMap) {
setValues(form, namespace, parameterMap, filesMap, false);
}
public void setValues(Form form, String namespace, Map parameterMap, Map filesMap, boolean incremental) {
if (form != null) {
namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE);
FormStatus formStatus = getFormStatus(form, namespace);
// if (!incremental) formStatus.getWrongFields().clear();
if (incremental) {
Map mergedParameterMap = new HashMap();
if (formStatus.getLastParameterMap() != null)
mergedParameterMap.putAll(formStatus.getLastParameterMap());
if (parameterMap != null)
mergedParameterMap.putAll(parameterMap);
formStatus.setLastParameterMap(mergedParameterMap);
} else {
formStatus.setLastParameterMap(parameterMap);
}
String inputsPrefix = getPrefix(form, namespace);
for (Field field : form.getFormFields()) {
setFieldValue(field, formStatus, inputsPrefix, parameterMap, filesMap, incremental);
}
}
}
public void modify(Form form, String namespace, String fieldName, Object value) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getInputValues().put(fieldName, value);
propagateChangesToParentFormStatuses(formStatus, fieldName, value);
}
public void setAttribute(Form form, String namespace, String attributeName, Object attributeValue) {
if (form != null) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getAttributes().put(attributeName, attributeValue);
}
}
public Object getAttribute(Form form, String namespace, String attributeName) {
if (form != null){
FormStatus formStatus = getFormStatus(form, namespace);
return formStatus.getAttributes().get(attributeName);
}
return null;
}
protected void setFieldValue(Field field, FormStatus formStatus, String inputsPrefix, Map parameterMap, Map filesMap, boolean incremental) {
String fieldName = field.getFieldName();
String inputName = inputsPrefix + fieldName;
FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType());
try {
Object previousValue = formStatus.getInputValues().get(fieldName);
boolean isRequired = field.getFieldRequired().booleanValue();
if (!handler.isEvaluable(inputName, parameterMap, filesMap) && !(handler.isEmpty(previousValue) && isRequired)) return;
Object value = null;
boolean emptyNumber = false;
try {
value = handler.getValue(field, inputName, parameterMap, filesMap, field.getFieldType().getFieldClass(), previousValue);
} catch (NumericFieldHandler.EmptyNumberException ene) {
//Treat this case in particular, as returning null in a numeric field would make related formulas not working.
emptyNumber = true;
}
if (incremental && value == null && !emptyNumber) {
if (log.isDebugEnabled()) log.debug("Refusing to overwrite input value for parameter " + fieldName);
} else {
formStatus.getInputValues().put(fieldName, value);
try {
propagateChangesToParentFormStatuses(formStatus, fieldName, value);
} catch (Exception e) {
log.error("Error modifying formStatus: ", e);
}
boolean isEmpty = handler.isEmpty(value);
if (isRequired && isEmpty && !incremental) {
log.debug("Missing required field " + fieldName);
formStatus.getWrongFields().add(fieldName);
} else {
formStatus.removeWrongField(fieldName);
}
}
} catch (ProcessingMessagedException pme) {
log.debug("Processing field: ", pme);
formStatus.addErrorMessages(fieldName, pme.getMessages());
} catch (Exception e) {
log.debug("Error setting field value:", e);
if (!incremental) {
formStatus.getInputValues().put(fieldName, null);
formStatus.getWrongFields().add(fieldName);
}
}
}
protected void propagateChangesToParentFormStatuses(FormStatus formStatus, String fieldName, Object value) {
FormStatus parent = FormStatusManager.lookup().getParent(formStatus);
if (parent != null) {
String fieldNameInParent = NamespaceManager.lookup().getNamespace(formStatus.getNamespace()).getFieldNameInParent();
Object valueInParent = parent.getInputValues().get(fieldNameInParent);
if (valueInParent != null) {
Map parentMapObjectRepresentation = null;
if (valueInParent instanceof Map) {
parentMapObjectRepresentation = (Map) valueInParent;
} else if (valueInParent instanceof Map[]) {
//Take the correct value
Map editFieldPositions = (Map) parent.getAttributes().get(FormStatusData.EDIT_FIELD_POSITIONS);
if (editFieldPositions != null) {
Integer pos = (Integer) editFieldPositions.get(fieldNameInParent);
if (pos != null) {
parentMapObjectRepresentation = ((Map[]) valueInParent)[pos.intValue()];
}
}
}
if (parentMapObjectRepresentation != null) {
//Copy my value to parent
parentMapObjectRepresentation.put(fieldName, value);
propagateChangesToParentFormStatuses(parent, fieldNameInParent, valueInParent);
}
}
}
}
public FormStatusData read(String ctxUid) {
FormStatusDataImpl data = null;
try {
FormRenderContext context = formRenderContextManager.getFormRenderContext(ctxUid);
if (context == null ) return null;
FormStatus formStatus = getContextFormStatus(context);
boolean isNew = formStatus == null;
if (isNew) {
formStatus = createContextFormStatus(context);
}
data = new FormStatusDataImpl(formStatus, isNew);
} catch (Exception e) {
log.error("Error: ", e);
}
return data;
}
protected FormStatus createContextFormStatus(FormRenderContext context) throws Exception {
Map values = new HashMap();
Map<String, Object> bindingData = context.getBindingData();
if (bindingData != null && !bindingData.isEmpty()) {
Form form = context.getForm();
Set<Field> fields = form.getFormFields();
if (fields != null) {
for (Field field : form.getFormFields()) {
String bindingString = field.getBindingStr();
if (!StringUtils.isEmpty(bindingString)) {
bindingString = bindingString.substring(1, bindingString.length() - 1);
boolean canSetValue = bindingString.indexOf("/") > 0;
Object value = null;
if (canSetValue) {
String holderId = bindingString.substring(0, bindingString.indexOf("/"));
String holderFieldId = bindingString.substring(holderId.length() + 1);
DataHolder holder = form.getDataHolderById(holderId);
if (holder != null && !StringUtils.isEmpty(holderFieldId)) {
Object holderValue = bindingData.get(holder.getId());
if (holderValue == null) continue;
value = holder.readValue(holderValue, holderFieldId);
}
} else {
value = bindingData.get(bindingString);
}
values.put(field.getFieldName(), value);
}
}
}
}
return getFormStatus(context.getForm(), context.getUID(), values);
}
public FormStatusData read(Form form, String namespace, Map currentValues) {
boolean exists = existsFormStatus(form.getId(), namespace);
if (currentValues == null) currentValues = new HashMap();
FormStatus formStatus = getFormStatus(form, namespace, currentValues);
FormStatusDataImpl data = null;
try {
data = new FormStatusDataImpl(formStatus, !exists);
} catch (Exception e) {
log.error("Error: ", e);
}
return data;
}
public FormStatusData read(Form form, String namespace) {
return read(form, namespace, new HashMap<String, Object>());
}
public void flushPendingCalculations(Form form, String namespace) {
if (formChangeProcessor != null) {
formChangeProcessor.process(form, namespace, new FormChangeResponse());//Response is ignored, we just need the session values.
}
}
public void persist(String ctxUid) throws Exception {
ctxUid = StringUtils.defaultIfEmpty(ctxUid, FormProcessor.DEFAULT_NAMESPACE);
persist(formRenderContextManager.getFormRenderContext(ctxUid));
}
public void persist(FormRenderContext context) throws Exception {
Form form = context.getForm();
Map mapToPersist = getFilteredMapRepresentationToPersist(form, context.getUID());
Map<String, Object> result = new HashMap<String, Object>();
for (Iterator it = mapToPersist.keySet().iterator(); it.hasNext();) {
String fieldName = (String) it.next();
Field field = form.getField(fieldName);
if (field != null) {
String bindingString = field.getBindingStr();
if (!StringUtils.isEmpty(bindingString)) {
bindingString = bindingString.substring(1, bindingString.length() - 1);
boolean canBind = bindingString.indexOf("/") > 0;
if (canBind) {
String holderId = bindingString.substring(0, bindingString.indexOf("/"));
String holderFieldId = bindingString.substring(holderId.length() + 1);
DataHolder holder = form.getDataHolderById(holderId);
if (holder != null && !StringUtils.isEmpty(holderFieldId)) {
Object value = context.getBindingData().get(holderId);
holder.writeValue(value, holderFieldId, mapToPersist.get(fieldName));
if (!result.containsKey(holderId)) result.put(holderId, value);
}
else canBind = false;
}
if (!canBind) {
log.debug("Unable to bind DataHolder for field '" + fieldName + "' to '" + bindingString + "'. This may be caused because bindingString is incorrect or the form doesn't contains the defined DataHolder.");
if (!result.containsKey(bindingString)) result.put(bindingString, mapToPersist.get(fieldName));
}
}
}
}
context.setPersistedData(result);
}
public Map getMapRepresentationToPersist(Form form, String namespace) throws Exception {
namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE);
flushPendingCalculations(form, namespace);
Map m = new HashMap();
FormStatus formStatus = getFormStatus(form, namespace);
if (!formStatus.getWrongFields().isEmpty()) {
throw new IllegalArgumentException("Validation error.");
}
fillObjectValues(m, formStatus.getInputValues(), form);
Set s = (Set) m.get(MODIFIED_FIELD_NAMES);
if (s == null) {
m.put(MODIFIED_FIELD_NAMES, s = new TreeSet());
}
s.addAll(form.getFieldNames());
return m;
}
protected Map getFilteredMapRepresentationToPersist(Form form, String namespace) throws Exception {
Map inputValues = getMapRepresentationToPersist(form, namespace);
Map mapToPersist = filterMapRepresentationToPersist(inputValues);
return mapToPersist;
}
public Map filterMapRepresentationToPersist(Map inputValues) throws Exception {
Map filteredMap = new HashMap();
Set keys = inputValues.keySet();
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
filteredMap.put(key, inputValues.get(key));
}
return filteredMap;
}
/**
* Copy to obj values read from status map values
*
* @param obj
* @param values
* @throws Exception
*/
protected void fillObjectValues(final Map obj, Map values, Form form) throws Exception {
Map valuesToSet = new HashMap();
for (Iterator it = values.keySet().iterator(); it.hasNext();) {
String propertyName = (String) it.next();
Object propertyValue = values.get(propertyName);
valuesToSet.put(propertyName, propertyValue);
}
obj.putAll(valuesToSet);
}
protected FormManagerImpl getFormsManager() {
return (FormManagerImpl) CDIBeanLocator.getBeanByType(FormManagerImpl.class);
}
@Override
public void clear(FormRenderContext context) {
clear(context.getForm(), context.getUID());
}
@Override
public void clear(String ctxUID) {
clear(formRenderContextManager.getFormRenderContext(ctxUID));
}
public void clear(Form form, String namespace) {
if (log.isDebugEnabled())
log.debug("Clearing form status for form " + form.getName() + " with namespace '" + namespace + "'");
destroyFormStatus(form, namespace);
}
public void clearField(Form form, String namespace, String fieldName) {
FormStatus formStatus = getFormStatus(form, namespace);
formStatus.getInputValues().remove(fieldName);
}
public void clearFieldErrors(Form form, String namespace) {
FormStatusManager.lookup().cascadeClearWrongFields(form.getId(), namespace);
}
public void forceWrongField(Form form, String namespace, String fieldName) {
FormStatusManager.lookup().getFormStatus(form.getId(), namespace).getWrongFields().add(fieldName);
}
protected String getPrefix(Form form, String namespace) {
return namespace + FormProcessor.NAMESPACE_SEPARATOR + form.getId() + FormProcessor.NAMESPACE_SEPARATOR;
}
}
|
diff --git a/validator/src/main/java/org/jboss/jca/validator/Validation.java b/validator/src/main/java/org/jboss/jca/validator/Validation.java
index 49a5b904c..e87ff26ba 100644
--- a/validator/src/main/java/org/jboss/jca/validator/Validation.java
+++ b/validator/src/main/java/org/jboss/jca/validator/Validation.java
@@ -1,602 +1,602 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jca.validator;
import org.jboss.jca.common.annotations.Annotations;
import org.jboss.jca.common.api.metadata.ra.AdminObject;
import org.jboss.jca.common.api.metadata.ra.ConfigProperty;
import org.jboss.jca.common.api.metadata.ra.ConnectionDefinition;
import org.jboss.jca.common.api.metadata.ra.Connector;
import org.jboss.jca.common.api.metadata.ra.Connector.Version;
import org.jboss.jca.common.api.metadata.ra.MessageListener;
import org.jboss.jca.common.api.metadata.ra.ResourceAdapter1516;
import org.jboss.jca.common.api.metadata.ra.XsdString;
import org.jboss.jca.common.api.metadata.ra.ra10.Connector10;
import org.jboss.jca.common.metadata.MetadataFactory;
import org.jboss.jca.common.spi.annotations.repository.AnnotationRepository;
import org.jboss.jca.common.spi.annotations.repository.AnnotationScanner;
import org.jboss.jca.common.spi.annotations.repository.AnnotationScannerFactory;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* A Validation.
*
* @author Jeff Zhang</a>
* @version $Revision: $
*/
public class Validation
{
private static final int SUCCESS = 0;
private static final int FAIL = 1;
private static final int OTHER = 2;
/**
* validate
* @param url The url
* @param output directory of output
* @return The system exit code
*/
public static int validate(URL url, String output)
{
return validate(url, output, null);
}
/**
* validate
* @param url The url
* @param output directory of output
* @param classpath classpath of including
* @return The system exit code
*/
public static int validate(URL url, String output, String[] classpath)
{
if (url == null || !(url.toExternalForm().endsWith(".rar") || url.toExternalForm().endsWith(".rar/")))
return FAIL;
int exitCode = SUCCESS;
File destination = null;
try
{
File f = new File(url.toURI());
if (!f.exists())
throw new IOException("Archive " + url.toExternalForm() + " doesnt exists");
File root = null;
if (f.isFile())
{
destination = new File(SecurityActions.getSystemProperty("java.io.tmpdir"), "/tmp/");
root = extract(f, destination);
}
else
{
root = f;
}
// Create classloader
URL[] allurls;
URL[] urls = getUrls(root);
if (classpath != null && classpath.length > 0)
{
List<URL> listUrl = new ArrayList<URL>();
for (URL u : urls)
listUrl.add(u);
for (String jar : classpath)
{
if (jar.endsWith(".jar"))
listUrl.add(new File(jar).toURI().toURL());
}
allurls = listUrl.toArray(new URL[listUrl.size()]);
}
else
allurls = urls;
URLClassLoader cl = SecurityActions.createURLCLassLoader(allurls,
SecurityActions.getThreadContextClassLoader());
SecurityActions.setThreadContextClassLoader(cl);
// Parse metadata
MetadataFactory metadataFactory = new MetadataFactory();
Connector cmd = metadataFactory.getStandardMetaData(root);
// Annotation scanning
Annotations annotator = new Annotations();
AnnotationScanner scanner = AnnotationScannerFactory.getAnnotationScanner();
AnnotationRepository repository = scanner.scan(cl.getURLs(), cl);
cmd = annotator.merge(cmd, repository, cl);
List<Validate> validateClasses = new ArrayList<Validate>();
List<Failure> failures = new ArrayList<Failure>();
Validator validator = new Validator();
validateClasses.addAll(createResourceAdapter(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createManagedConnectionFactory(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createActivationSpec(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createAdminObject(cmd, failures, validator.getResourceBundle(), cl));
List<Failure> classFailures = validator.validate(validateClasses);
if (classFailures != null && classFailures.size() > 0)
failures.addAll(classFailures);
if (failures != null && failures.size() > 0)
{
FailureHelper fh = new FailureHelper(failures);
File reportDirectory = new File(output);
- if (!reportDirectory.mkdirs())
+ if (!reportDirectory.exists() && !reportDirectory.mkdirs())
{
- throw new IOException(output + " can't be created");
+ throw new IOException("The output directory '" + output + "' can't be created");
}
String reportName = url.getFile();
int lastSlashIndex = reportName.lastIndexOf("/");
int lastSepaIndex = reportName.lastIndexOf(File.separator);
int lastIndex = lastSlashIndex > lastSepaIndex ? lastSlashIndex : lastSepaIndex;
if (lastIndex != -1)
reportName = reportName.substring(lastIndex + 1);
reportName += ".log";
File report = new File(reportDirectory, reportName);
FileWriter fw = null;
BufferedWriter bw = null;
try
{
fw = new FileWriter(report);
bw = new BufferedWriter(fw, 8192);
bw.write(fh.asText(validator.getResourceBundle()));
bw.flush();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if (bw != null)
bw.close();
if (fw != null)
fw.close();
}
catch (IOException ignore)
{
// Ignore
}
}
exitCode = FAIL;
}
exitCode = SUCCESS;
}
catch (Exception e)
{
e.printStackTrace();
exitCode = OTHER;
}
if (destination != null)
{
try
{
recursiveDelete(destination);
}
catch (IOException ioe)
{
// Ignore
}
}
return exitCode;
}
/**
* createResourceAdapter
* @param cmd connector metadata
* @param failures list of failures
* @param rb ResourceBundle
* @param cl classloador
* @return list of validate objects
*/
private static List<Validate> createResourceAdapter(Connector cmd,
List<Failure> failures, ResourceBundle rb, ClassLoader cl)
{
List<Validate> result = new ArrayList<Validate>();
if (!(cmd instanceof Connector10) && cmd.getResourceadapter() != null
&& ((ResourceAdapter1516) cmd.getResourceadapter()).getResourceadapterClass() != null)
{
try
{
Class<?> clazz = Class.forName(((ResourceAdapter1516) cmd.getResourceadapter()).getResourceadapterClass(),
true, cl);
List<? extends ConfigProperty> configProperties = cmd.getResourceadapter().getConfigProperties();
ValidateClass vc = new ValidateClass(Key.RESOURCE_ADAPTER, clazz, configProperties);
result.add(vc);
}
catch (ClassNotFoundException e)
{
Failure failure = new Failure(Severity.ERROR,
rb.getString("uncategorized"),
rb.getString("ra.cnfe"),
e.getMessage());
failures.add(failure);
}
}
return result;
}
/**
* createManagedConnectionFactory
* @param cmd connector metadata
* @param failures list of failures
* @param rb ResourceBundle
* @param cl classloador
* @return list of validate objects
*/
private static List<Validate> createManagedConnectionFactory(Connector cmd,
List<Failure> failures, ResourceBundle rb, ClassLoader cl)
{
List<Validate> result = new ArrayList<Validate>();
if (cmd.getResourceadapter() != null
&& cmd.getVersion() != Version.V_10
&& ((ResourceAdapter1516) cmd.getResourceadapter()).getOutboundResourceadapter() != null
&& ((ResourceAdapter1516) cmd.getResourceadapter()).getOutboundResourceadapter().
getConnectionDefinitions() != null)
{
List<ConnectionDefinition> cdMetas = ((ResourceAdapter1516) cmd.getResourceadapter())
.getOutboundResourceadapter().getConnectionDefinitions();
if (cdMetas.size() > 0)
{
for (ConnectionDefinition cdMeta : cdMetas)
{
if (cdMeta.getManagedConnectionFactoryClass() != null)
{
try
{
Class<?> clazz = Class.forName(cdMeta.getManagedConnectionFactoryClass().getValue(), true, cl);
List<? extends ConfigProperty> configProperties = cdMeta.getConfigProperties();
ValidateClass vc = new ValidateClass(Key.MANAGED_CONNECTION_FACTORY, clazz, configProperties);
result.add(vc);
}
catch (ClassNotFoundException e)
{
Failure failure = new Failure(Severity.ERROR,
rb.getString("uncategorized"),
rb.getString("mcf.cnfe"),
e.getMessage());
failures.add(failure);
}
}
}
}
}
return result;
}
/**
* createActivationSpec
* @param cmd connector metadata
* @param failures list of failures
* @param rb ResourceBundle
* @param cl classloador
* @return list of validate objects
*/
private static List<Validate> createActivationSpec(Connector cmd,
List<Failure> failures, ResourceBundle rb, ClassLoader cl)
{
List<Validate> result = new ArrayList<Validate>();
if (cmd.getResourceadapter() != null
&& cmd.getVersion() != Version.V_10
&& ((ResourceAdapter1516) cmd.getResourceadapter()).getInboundResourceadapter() != null &&
((ResourceAdapter1516) cmd.getResourceadapter()).getInboundResourceadapter().getMessageadapter() != null &&
((ResourceAdapter1516) cmd.getResourceadapter()).getInboundResourceadapter().getMessageadapter()
.getMessagelisteners() != null)
{
List<MessageListener> mlMetas = ((ResourceAdapter1516) cmd.getResourceadapter())
.getInboundResourceadapter().getMessageadapter()
.getMessagelisteners();
if (mlMetas.size() > 0)
{
for (MessageListener mlMeta : mlMetas)
{
if (mlMeta.getActivationspec() != null && mlMeta.getActivationspec().getClass() != null
&& !mlMeta.getActivationspec().getActivationspecClass().equals(XsdString.NULL_XSDSTRING))
{
try
{
Class<?> clazz = Class.forName(mlMeta.getActivationspec().getActivationspecClass().getValue(),
true, cl);
List<? extends ConfigProperty> configProperties = mlMeta.getActivationspec().getConfigProperties();
ValidateClass vc = new ValidateClass(Key.ACTIVATION_SPEC, clazz, configProperties);
result.add(vc);
}
catch (ClassNotFoundException e)
{
Failure failure = new Failure(Severity.ERROR,
rb.getString("uncategorized"),
rb.getString("as.cnfe"),
e.getMessage());
failures.add(failure);
}
}
}
}
}
return result;
}
/**
* createAdminObject
* @param cmd connector metadata
* @param failures list of failures
* @param rb ResourceBundle
* @param cl classloador
* @return list of validate objects
*/
private static List<Validate> createAdminObject(Connector cmd,
List<Failure> failures, ResourceBundle rb, ClassLoader cl)
{
List<Validate> result = new ArrayList<Validate>();
if (cmd.getResourceadapter() != null
&& cmd.getVersion() != Version.V_10
&& ((ResourceAdapter1516) cmd.getResourceadapter()).getAdminObjects() != null)
{
List<AdminObject> aoMetas = ((ResourceAdapter1516) cmd.getResourceadapter()).getAdminObjects();
if (aoMetas.size() > 0)
{
for (AdminObject aoMeta : aoMetas)
{
if (aoMeta.getAdminobjectClass() != null
&& !aoMeta.getAdminobjectClass().equals(XsdString.NULL_XSDSTRING))
{
try
{
Class<?> clazz = Class.forName(aoMeta.getAdminobjectClass().getValue(), true, cl);
List<? extends ConfigProperty> configProperties = aoMeta.getConfigProperties();
ValidateClass vc = new ValidateClass(Key.ADMIN_OBJECT, clazz, configProperties);
result.add(vc);
}
catch (ClassNotFoundException e)
{
Failure failure = new Failure(Severity.ERROR,
rb.getString("uncategorized"),
rb.getString("ao.cnfe"),
e.getMessage());
failures.add(failure);
}
}
}
}
}
return result;
}
/**
* Extract a JAR type file
* @param file The file
* @param directory The directory where the file should be extracted
* @return The root of the extracted JAR file
* @exception IOException Thrown if an error occurs
*/
private static File extract(File file, File directory) throws IOException
{
if (file == null)
throw new IllegalArgumentException("File is null");
if (directory == null)
throw new IllegalArgumentException("Directory is null");
File target = new File(directory, file.getName());
if (target.exists())
recursiveDelete(target);
if (!target.mkdirs())
throw new IOException("Could not create " + target);
JarFile jar = new JarFile(file);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements())
{
JarEntry je = entries.nextElement();
File copy = new File(target, je.getName());
if (!je.isDirectory())
{
InputStream in = null;
OutputStream out = null;
// Make sure that the directory is _really_ there
if (copy.getParentFile() != null && !copy.getParentFile().exists())
{
if (!copy.getParentFile().mkdirs())
throw new IOException("Could not create " + copy.getParentFile());
}
try
{
in = new BufferedInputStream(jar.getInputStream(je));
out = new BufferedOutputStream(new FileOutputStream(copy));
byte[] buffer = new byte[4096];
for (;;)
{
int nBytes = in.read(buffer);
if (nBytes <= 0)
break;
out.write(buffer, 0, nBytes);
}
out.flush();
}
finally
{
try
{
if (out != null)
out.close();
}
catch (IOException ignore)
{
// Ignore
}
try
{
if (in != null)
in.close();
}
catch (IOException ignore)
{
// Ignore
}
}
}
else
{
if (!copy.exists())
{
if (!copy.mkdirs())
throw new IOException("Could not create " + copy);
}
else
{
if (!copy.isDirectory())
throw new IOException(copy + " isn't a directory");
}
}
}
return target;
}
/**
* Recursive delete
* @param f The file handler
* @exception IOException Thrown if a file could not be deleted
*/
private static void recursiveDelete(File f) throws IOException
{
if (f != null && f.exists())
{
File[] files = f.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
if (files[i].isDirectory())
{
recursiveDelete(files[i]);
}
else
{
if (!files[i].delete())
throw new IOException("Could not delete " + files[i]);
}
}
}
if (!f.delete())
throw new IOException("Could not delete " + f);
}
}
/**
* Get the URLs for the directory and all libraries located in the directory
* @param directory The directory
* @return The URLs
* @exception MalformedURLException MalformedURLException
* @exception IOException IOException
*/
private static URL[] getUrls(File directory) throws MalformedURLException, IOException
{
List<URL> list = new LinkedList<URL>();
if (directory.exists() && directory.isDirectory())
{
// Add directory
list.add(directory.toURI().toURL());
// Add the contents of the directory too
File[] jars = directory.listFiles(new FilenameFilter()
{
/**
* Accept
* @param dir The directory
* @param name The name
* @return True if accepts; otherwise false
*/
public boolean accept(File dir, String name)
{
return name.endsWith(".jar");
}
});
if (jars != null)
{
for (int j = 0; j < jars.length; j++)
{
list.add(jars[j].getCanonicalFile().toURI().toURL());
}
}
}
return list.toArray(new URL[list.size()]);
}
}
| false | true | public static int validate(URL url, String output, String[] classpath)
{
if (url == null || !(url.toExternalForm().endsWith(".rar") || url.toExternalForm().endsWith(".rar/")))
return FAIL;
int exitCode = SUCCESS;
File destination = null;
try
{
File f = new File(url.toURI());
if (!f.exists())
throw new IOException("Archive " + url.toExternalForm() + " doesnt exists");
File root = null;
if (f.isFile())
{
destination = new File(SecurityActions.getSystemProperty("java.io.tmpdir"), "/tmp/");
root = extract(f, destination);
}
else
{
root = f;
}
// Create classloader
URL[] allurls;
URL[] urls = getUrls(root);
if (classpath != null && classpath.length > 0)
{
List<URL> listUrl = new ArrayList<URL>();
for (URL u : urls)
listUrl.add(u);
for (String jar : classpath)
{
if (jar.endsWith(".jar"))
listUrl.add(new File(jar).toURI().toURL());
}
allurls = listUrl.toArray(new URL[listUrl.size()]);
}
else
allurls = urls;
URLClassLoader cl = SecurityActions.createURLCLassLoader(allurls,
SecurityActions.getThreadContextClassLoader());
SecurityActions.setThreadContextClassLoader(cl);
// Parse metadata
MetadataFactory metadataFactory = new MetadataFactory();
Connector cmd = metadataFactory.getStandardMetaData(root);
// Annotation scanning
Annotations annotator = new Annotations();
AnnotationScanner scanner = AnnotationScannerFactory.getAnnotationScanner();
AnnotationRepository repository = scanner.scan(cl.getURLs(), cl);
cmd = annotator.merge(cmd, repository, cl);
List<Validate> validateClasses = new ArrayList<Validate>();
List<Failure> failures = new ArrayList<Failure>();
Validator validator = new Validator();
validateClasses.addAll(createResourceAdapter(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createManagedConnectionFactory(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createActivationSpec(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createAdminObject(cmd, failures, validator.getResourceBundle(), cl));
List<Failure> classFailures = validator.validate(validateClasses);
if (classFailures != null && classFailures.size() > 0)
failures.addAll(classFailures);
if (failures != null && failures.size() > 0)
{
FailureHelper fh = new FailureHelper(failures);
File reportDirectory = new File(output);
if (!reportDirectory.mkdirs())
{
throw new IOException(output + " can't be created");
}
String reportName = url.getFile();
int lastSlashIndex = reportName.lastIndexOf("/");
int lastSepaIndex = reportName.lastIndexOf(File.separator);
int lastIndex = lastSlashIndex > lastSepaIndex ? lastSlashIndex : lastSepaIndex;
if (lastIndex != -1)
reportName = reportName.substring(lastIndex + 1);
reportName += ".log";
File report = new File(reportDirectory, reportName);
FileWriter fw = null;
BufferedWriter bw = null;
try
{
fw = new FileWriter(report);
bw = new BufferedWriter(fw, 8192);
bw.write(fh.asText(validator.getResourceBundle()));
bw.flush();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if (bw != null)
bw.close();
if (fw != null)
fw.close();
}
catch (IOException ignore)
{
// Ignore
}
}
exitCode = FAIL;
}
exitCode = SUCCESS;
}
catch (Exception e)
{
e.printStackTrace();
exitCode = OTHER;
}
if (destination != null)
{
try
{
recursiveDelete(destination);
}
catch (IOException ioe)
{
// Ignore
}
}
return exitCode;
}
| public static int validate(URL url, String output, String[] classpath)
{
if (url == null || !(url.toExternalForm().endsWith(".rar") || url.toExternalForm().endsWith(".rar/")))
return FAIL;
int exitCode = SUCCESS;
File destination = null;
try
{
File f = new File(url.toURI());
if (!f.exists())
throw new IOException("Archive " + url.toExternalForm() + " doesnt exists");
File root = null;
if (f.isFile())
{
destination = new File(SecurityActions.getSystemProperty("java.io.tmpdir"), "/tmp/");
root = extract(f, destination);
}
else
{
root = f;
}
// Create classloader
URL[] allurls;
URL[] urls = getUrls(root);
if (classpath != null && classpath.length > 0)
{
List<URL> listUrl = new ArrayList<URL>();
for (URL u : urls)
listUrl.add(u);
for (String jar : classpath)
{
if (jar.endsWith(".jar"))
listUrl.add(new File(jar).toURI().toURL());
}
allurls = listUrl.toArray(new URL[listUrl.size()]);
}
else
allurls = urls;
URLClassLoader cl = SecurityActions.createURLCLassLoader(allurls,
SecurityActions.getThreadContextClassLoader());
SecurityActions.setThreadContextClassLoader(cl);
// Parse metadata
MetadataFactory metadataFactory = new MetadataFactory();
Connector cmd = metadataFactory.getStandardMetaData(root);
// Annotation scanning
Annotations annotator = new Annotations();
AnnotationScanner scanner = AnnotationScannerFactory.getAnnotationScanner();
AnnotationRepository repository = scanner.scan(cl.getURLs(), cl);
cmd = annotator.merge(cmd, repository, cl);
List<Validate> validateClasses = new ArrayList<Validate>();
List<Failure> failures = new ArrayList<Failure>();
Validator validator = new Validator();
validateClasses.addAll(createResourceAdapter(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createManagedConnectionFactory(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createActivationSpec(cmd, failures, validator.getResourceBundle(), cl));
validateClasses.addAll(createAdminObject(cmd, failures, validator.getResourceBundle(), cl));
List<Failure> classFailures = validator.validate(validateClasses);
if (classFailures != null && classFailures.size() > 0)
failures.addAll(classFailures);
if (failures != null && failures.size() > 0)
{
FailureHelper fh = new FailureHelper(failures);
File reportDirectory = new File(output);
if (!reportDirectory.exists() && !reportDirectory.mkdirs())
{
throw new IOException("The output directory '" + output + "' can't be created");
}
String reportName = url.getFile();
int lastSlashIndex = reportName.lastIndexOf("/");
int lastSepaIndex = reportName.lastIndexOf(File.separator);
int lastIndex = lastSlashIndex > lastSepaIndex ? lastSlashIndex : lastSepaIndex;
if (lastIndex != -1)
reportName = reportName.substring(lastIndex + 1);
reportName += ".log";
File report = new File(reportDirectory, reportName);
FileWriter fw = null;
BufferedWriter bw = null;
try
{
fw = new FileWriter(report);
bw = new BufferedWriter(fw, 8192);
bw.write(fh.asText(validator.getResourceBundle()));
bw.flush();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if (bw != null)
bw.close();
if (fw != null)
fw.close();
}
catch (IOException ignore)
{
// Ignore
}
}
exitCode = FAIL;
}
exitCode = SUCCESS;
}
catch (Exception e)
{
e.printStackTrace();
exitCode = OTHER;
}
if (destination != null)
{
try
{
recursiveDelete(destination);
}
catch (IOException ioe)
{
// Ignore
}
}
return exitCode;
}
|
diff --git a/oneway/g4/Player.java b/oneway/g4/Player.java
index dcc07bc..fffe7f3 100644
--- a/oneway/g4/Player.java
+++ b/oneway/g4/Player.java
@@ -1,53 +1,54 @@
package oneway.g4;
import java.util.Collections;
import java.util.List;
import oneway.sim.MovingCar;
import oneway.sim.Parking;
public class Player extends oneway.sim.Player
{
private int currentTime = -1;
public Player() {}
public void init(int nsegments, int[] nblocks, int[] capacity)
{
this.nsegments = nsegments;
this.nblocks = nblocks;
this.capacity = capacity.clone();
}
public void setLights(MovingCar[] movingCars,
Parking[] left,
Parking[] right,
boolean[] llights,
boolean[] rlights)
{
currentTime++;
Node node = new Node(currentTime, nsegments, nblocks, movingCars,
left, right, capacity, llights, rlights);
List<Node> children = node.successors();
Collections.sort(children);
+ if (children.size() == 0) return;
Node choice = children.get(0);
//Node choice = new Searcher().best(node);
boolean[] newLLights = choice.getLLights();
boolean[] newRLights = choice.getRLights();
for(int i = 0; i < nsegments; i++) {
llights[i] = newLLights[i];
rlights[i] = newRLights[i];
}
}
private int nsegments;
private int[] nblocks;
private int[] capacity;
}
| true | true | public void setLights(MovingCar[] movingCars,
Parking[] left,
Parking[] right,
boolean[] llights,
boolean[] rlights)
{
currentTime++;
Node node = new Node(currentTime, nsegments, nblocks, movingCars,
left, right, capacity, llights, rlights);
List<Node> children = node.successors();
Collections.sort(children);
Node choice = children.get(0);
//Node choice = new Searcher().best(node);
boolean[] newLLights = choice.getLLights();
boolean[] newRLights = choice.getRLights();
for(int i = 0; i < nsegments; i++) {
llights[i] = newLLights[i];
rlights[i] = newRLights[i];
}
}
| public void setLights(MovingCar[] movingCars,
Parking[] left,
Parking[] right,
boolean[] llights,
boolean[] rlights)
{
currentTime++;
Node node = new Node(currentTime, nsegments, nblocks, movingCars,
left, right, capacity, llights, rlights);
List<Node> children = node.successors();
Collections.sort(children);
if (children.size() == 0) return;
Node choice = children.get(0);
//Node choice = new Searcher().best(node);
boolean[] newLLights = choice.getLLights();
boolean[] newRLights = choice.getRLights();
for(int i = 0; i < nsegments; i++) {
llights[i] = newLLights[i];
rlights[i] = newRLights[i];
}
}
|
diff --git a/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/APITestingCG.java b/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/APITestingCG.java
index 93d0f22..aacb54f 100644
--- a/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/APITestingCG.java
+++ b/APITestingCG/src/cz/cvut/fit/hybljan2/apitestingcg/APITestingCG.java
@@ -1,82 +1,86 @@
package cz.cvut.fit.hybljan2.apitestingcg;
import cz.cvut.fit.hybljan2.apitestingcg.apimodel.API;
import cz.cvut.fit.hybljan2.apitestingcg.configuration.ConfigurationReader;
import cz.cvut.fit.hybljan2.apitestingcg.configuration.model.ApiViewConfiguration;
import cz.cvut.fit.hybljan2.apitestingcg.configuration.model.Configuration;
import cz.cvut.fit.hybljan2.apitestingcg.configuration.model.GeneratorJobConfiguration;
import cz.cvut.fit.hybljan2.apitestingcg.configuration.model.ScannerConfiguration;
import cz.cvut.fit.hybljan2.apitestingcg.generator.*;
import cz.cvut.fit.hybljan2.apitestingcg.scanner.APIScanner;
import cz.cvut.fit.hybljan2.apitestingcg.scanner.ByteCodeScanner;
import cz.cvut.fit.hybljan2.apitestingcg.scanner.SourceScanner;
import cz.cvut.fit.hybljan2.apitestingcg.view.APIViewForm;
import java.util.HashMap;
import java.util.Map;
/**
* @author Jan Hýbl
*/
public class APITestingCG {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String pathToConfigFile = "configuration.xml";
if (args.length == 1) {
pathToConfigFile = args[0];
}
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-c")) { // read path to configuration file
pathToConfigFile = args[i + 1];
}
// there will be other args processing
}
Map<String, API> apiMap = new HashMap<String, API>();
ConfigurationReader cr = new ConfigurationReader();
Configuration configuration = cr.parseConfiguration(pathToConfigFile);
APIScanner scanner = null;
APIScanner sourceScanner = new SourceScanner();
APIScanner bytecodeScanner = new ByteCodeScanner();
for (ScannerConfiguration sc : configuration.getApiConfigurations()) {
switch (sc.getSource()) {
case SOURCECODE:
scanner = sourceScanner;
break;
case BYTECODE:
scanner = bytecodeScanner;
break;
}
scanner.setConfiguration(sc);
API api = scanner.scan();
System.out.println("Loaded api: " + sc.getId());
apiMap.put(sc.getId(), api);
}
for (ApiViewConfiguration ac : configuration.getViewConfigurations()) {
System.out.println("Creating new ApiViewForm: " + ac.getApiId());
new APIViewForm(apiMap.get(ac.getApiId())).setVisible(true);
}
Generator[] generators = {
new ExtenderGenerator(configuration.getGeneratorConfiguration()),
new InstantiatorGenerator(configuration.getGeneratorConfiguration()),
new AnnotationGenerator(configuration.getGeneratorConfiguration())
};
for (GeneratorJobConfiguration gjc : configuration.getGeneratorJobConfigurations()) {
System.out.println("Generating code for api " + gjc.getApiId());
for (Generator generator : generators) {
- generator.generate(apiMap.get(gjc.getApiId()), gjc);
+ try{
+ generator.generate(apiMap.get(gjc.getApiId()), gjc);
+ } catch (NullPointerException e) {
+ System.err.println("API with id \'" + gjc.getApiId() + "\' was not found. Skipping it.");;
+ }
}
}
}
}
| true | true | public static void main(String[] args) {
String pathToConfigFile = "configuration.xml";
if (args.length == 1) {
pathToConfigFile = args[0];
}
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-c")) { // read path to configuration file
pathToConfigFile = args[i + 1];
}
// there will be other args processing
}
Map<String, API> apiMap = new HashMap<String, API>();
ConfigurationReader cr = new ConfigurationReader();
Configuration configuration = cr.parseConfiguration(pathToConfigFile);
APIScanner scanner = null;
APIScanner sourceScanner = new SourceScanner();
APIScanner bytecodeScanner = new ByteCodeScanner();
for (ScannerConfiguration sc : configuration.getApiConfigurations()) {
switch (sc.getSource()) {
case SOURCECODE:
scanner = sourceScanner;
break;
case BYTECODE:
scanner = bytecodeScanner;
break;
}
scanner.setConfiguration(sc);
API api = scanner.scan();
System.out.println("Loaded api: " + sc.getId());
apiMap.put(sc.getId(), api);
}
for (ApiViewConfiguration ac : configuration.getViewConfigurations()) {
System.out.println("Creating new ApiViewForm: " + ac.getApiId());
new APIViewForm(apiMap.get(ac.getApiId())).setVisible(true);
}
Generator[] generators = {
new ExtenderGenerator(configuration.getGeneratorConfiguration()),
new InstantiatorGenerator(configuration.getGeneratorConfiguration()),
new AnnotationGenerator(configuration.getGeneratorConfiguration())
};
for (GeneratorJobConfiguration gjc : configuration.getGeneratorJobConfigurations()) {
System.out.println("Generating code for api " + gjc.getApiId());
for (Generator generator : generators) {
generator.generate(apiMap.get(gjc.getApiId()), gjc);
}
}
}
| public static void main(String[] args) {
String pathToConfigFile = "configuration.xml";
if (args.length == 1) {
pathToConfigFile = args[0];
}
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-c")) { // read path to configuration file
pathToConfigFile = args[i + 1];
}
// there will be other args processing
}
Map<String, API> apiMap = new HashMap<String, API>();
ConfigurationReader cr = new ConfigurationReader();
Configuration configuration = cr.parseConfiguration(pathToConfigFile);
APIScanner scanner = null;
APIScanner sourceScanner = new SourceScanner();
APIScanner bytecodeScanner = new ByteCodeScanner();
for (ScannerConfiguration sc : configuration.getApiConfigurations()) {
switch (sc.getSource()) {
case SOURCECODE:
scanner = sourceScanner;
break;
case BYTECODE:
scanner = bytecodeScanner;
break;
}
scanner.setConfiguration(sc);
API api = scanner.scan();
System.out.println("Loaded api: " + sc.getId());
apiMap.put(sc.getId(), api);
}
for (ApiViewConfiguration ac : configuration.getViewConfigurations()) {
System.out.println("Creating new ApiViewForm: " + ac.getApiId());
new APIViewForm(apiMap.get(ac.getApiId())).setVisible(true);
}
Generator[] generators = {
new ExtenderGenerator(configuration.getGeneratorConfiguration()),
new InstantiatorGenerator(configuration.getGeneratorConfiguration()),
new AnnotationGenerator(configuration.getGeneratorConfiguration())
};
for (GeneratorJobConfiguration gjc : configuration.getGeneratorJobConfigurations()) {
System.out.println("Generating code for api " + gjc.getApiId());
for (Generator generator : generators) {
try{
generator.generate(apiMap.get(gjc.getApiId()), gjc);
} catch (NullPointerException e) {
System.err.println("API with id \'" + gjc.getApiId() + "\' was not found. Skipping it.");;
}
}
}
}
|
diff --git a/src/main/java/com/griefcraft/util/matchers/WallMatcher.java b/src/main/java/com/griefcraft/util/matchers/WallMatcher.java
index 8d6073eb..fbd21061 100644
--- a/src/main/java/com/griefcraft/util/matchers/WallMatcher.java
+++ b/src/main/java/com/griefcraft/util/matchers/WallMatcher.java
@@ -1,157 +1,157 @@
/*
* Copyright 2011 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package com.griefcraft.util.matchers;
import com.griefcraft.util.ProtectionFinder;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import java.util.EnumSet;
import java.util.Set;
/**
* Matches wall entities
* TODO fix buttons and levers
*/
public class WallMatcher implements ProtectionFinder.Matcher {
/**
* Blocks that can be attached to the wall and be protected.
* This assumes that the block is DESTROYED if the wall they are attached to is broken.
*/
public static final Set<Material> PROTECTABLES_WALL = EnumSet.of(Material.WALL_SIGN);
/**
* Those evil levers and buttons have all different bits for directions. Gah!
*/
public static final Set<Material> PROTECTABLES_LEVERS_ET_AL = EnumSet.of(Material.STONE_BUTTON, Material.LEVER);
/**
* Same as PROTECTABLE_WALL, except the facing direction is reversed,
* such as trap doors
*/
public static final Set<Material> PROTECTABLES_WALL_REVERSE = EnumSet.of(Material.TRAP_DOOR);
/**
* Possible faces around the base block that protections could be at
*/
public static final BlockFace[] POSSIBLE_FACES = new BlockFace[]{ BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST };
public boolean matches(ProtectionFinder finder) {
// The block we are working on
Block block = finder.getBaseBlock();
// Match wall signs to the wall it's attached to
for (BlockFace blockFace : POSSIBLE_FACES) {
Block face; // the relative block
if ((face = block.getRelative(blockFace)) != null) {
// Try and match it
Block matched = tryMatchBlock(face, blockFace);
// We found something ..! Try and load the protection
if (matched != null) {
finder.addBlock(matched);
return true;
}
}
}
return false;
}
/**
* Try and match a wall block
*
* @param block
* @param matchingFace
* @return
*/
private Block tryMatchBlock(Block block, BlockFace matchingFace) {
byte direction = block.getData();
// Blocks such as wall signs
if (PROTECTABLES_WALL.contains(block.getType())) {
- byte EAST = 0x05;
- byte WEST = 0x04;
- byte SOUTH = 0x03;
- byte NORTH = 0x02;
+ byte EAST = 0x02;
+ byte WEST = 0x03;
+ byte SOUTH = 0x05;
+ byte NORTH = 0x04;
if (matchingFace == BlockFace.EAST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.WEST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & NORTH) == NORTH) {
return block;
}
}
// Levers, buttons
else if (PROTECTABLES_LEVERS_ET_AL.contains(block.getType())) {
byte EAST = 0x4;
byte WEST = 0x3;
byte SOUTH = 0x1;
byte NORTH = 0x2;
if (matchingFace == BlockFace.EAST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.WEST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & NORTH) == NORTH) {
return block;
}
}
// Blocks such as trap doors
else if (PROTECTABLES_WALL_REVERSE.contains(block.getType())) {
byte EAST = 0x01;
byte WEST = 0x00;
byte SOUTH = 0x02;
byte NORTH = 0x03;
if (matchingFace == BlockFace.WEST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.EAST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & NORTH) == NORTH) {
return block;
}
}
return null;
}
}
| true | true | private Block tryMatchBlock(Block block, BlockFace matchingFace) {
byte direction = block.getData();
// Blocks such as wall signs
if (PROTECTABLES_WALL.contains(block.getType())) {
byte EAST = 0x05;
byte WEST = 0x04;
byte SOUTH = 0x03;
byte NORTH = 0x02;
if (matchingFace == BlockFace.EAST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.WEST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & NORTH) == NORTH) {
return block;
}
}
// Levers, buttons
else if (PROTECTABLES_LEVERS_ET_AL.contains(block.getType())) {
byte EAST = 0x4;
byte WEST = 0x3;
byte SOUTH = 0x1;
byte NORTH = 0x2;
if (matchingFace == BlockFace.EAST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.WEST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & NORTH) == NORTH) {
return block;
}
}
// Blocks such as trap doors
else if (PROTECTABLES_WALL_REVERSE.contains(block.getType())) {
byte EAST = 0x01;
byte WEST = 0x00;
byte SOUTH = 0x02;
byte NORTH = 0x03;
if (matchingFace == BlockFace.WEST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.EAST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & NORTH) == NORTH) {
return block;
}
}
return null;
}
| private Block tryMatchBlock(Block block, BlockFace matchingFace) {
byte direction = block.getData();
// Blocks such as wall signs
if (PROTECTABLES_WALL.contains(block.getType())) {
byte EAST = 0x02;
byte WEST = 0x03;
byte SOUTH = 0x05;
byte NORTH = 0x04;
if (matchingFace == BlockFace.EAST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.WEST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & NORTH) == NORTH) {
return block;
}
}
// Levers, buttons
else if (PROTECTABLES_LEVERS_ET_AL.contains(block.getType())) {
byte EAST = 0x4;
byte WEST = 0x3;
byte SOUTH = 0x1;
byte NORTH = 0x2;
if (matchingFace == BlockFace.EAST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.WEST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & NORTH) == NORTH) {
return block;
}
}
// Blocks such as trap doors
else if (PROTECTABLES_WALL_REVERSE.contains(block.getType())) {
byte EAST = 0x01;
byte WEST = 0x00;
byte SOUTH = 0x02;
byte NORTH = 0x03;
if (matchingFace == BlockFace.WEST && (direction & EAST) == EAST) {
return block;
} else if (matchingFace == BlockFace.EAST && (direction & WEST) == WEST) {
return block;
} else if (matchingFace == BlockFace.NORTH && (direction & SOUTH) == SOUTH) {
return block;
} else if (matchingFace == BlockFace.SOUTH && (direction & NORTH) == NORTH) {
return block;
}
}
return null;
}
|
diff --git a/src/main/java/edu/mayo/cts2/framework/plugin/service/exist/profile/valuesetdefinition/ExistValueSetDefinitionResolutionService.java b/src/main/java/edu/mayo/cts2/framework/plugin/service/exist/profile/valuesetdefinition/ExistValueSetDefinitionResolutionService.java
index d82d347..5b0f3dd 100644
--- a/src/main/java/edu/mayo/cts2/framework/plugin/service/exist/profile/valuesetdefinition/ExistValueSetDefinitionResolutionService.java
+++ b/src/main/java/edu/mayo/cts2/framework/plugin/service/exist/profile/valuesetdefinition/ExistValueSetDefinitionResolutionService.java
@@ -1,210 +1,209 @@
/*
* Copyright: (c) 2004-2012 Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Except as contained in the copyright notice above, or as used to identify
* MFMER as the author of this software, the trade names, trademarks, service
* marks, or product names of the copyright holder shall not be used in
* advertising, promotion or otherwise in connection with this software without
* prior written authorization of the copyright holder.
*
* 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 edu.mayo.cts2.framework.plugin.service.exist.profile.valuesetdefinition;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import edu.mayo.cts2.framework.model.command.Page;
import edu.mayo.cts2.framework.model.command.ResolvedFilter;
import edu.mayo.cts2.framework.model.command.ResolvedReadContext;
import edu.mayo.cts2.framework.model.core.ComponentReference;
import edu.mayo.cts2.framework.model.core.MatchAlgorithmReference;
import edu.mayo.cts2.framework.model.core.PredicateReference;
import edu.mayo.cts2.framework.model.core.SortCriteria;
import edu.mayo.cts2.framework.model.core.URIAndEntityName;
import edu.mayo.cts2.framework.model.directory.DirectoryResult;
import edu.mayo.cts2.framework.model.entity.EntityDirectoryEntry;
import edu.mayo.cts2.framework.model.service.core.NameOrURI;
import edu.mayo.cts2.framework.model.service.core.Query;
import edu.mayo.cts2.framework.model.util.ModelUtils;
import edu.mayo.cts2.framework.model.valuesetdefinition.ResolvedValueSet;
import edu.mayo.cts2.framework.model.valuesetdefinition.ResolvedValueSetDirectoryEntry;
import edu.mayo.cts2.framework.plugin.service.exist.profile.AbstractExistService;
import edu.mayo.cts2.framework.plugin.service.exist.profile.resolvedvalueset.ExistResolvedValueSetQueryService;
import edu.mayo.cts2.framework.plugin.service.exist.profile.resolvedvalueset.ExistResolvedValueSetResolutionService;
import edu.mayo.cts2.framework.service.command.restriction.ResolvedValueSetQueryServiceRestrictions;
import edu.mayo.cts2.framework.service.profile.resolvedvalueset.ResolvedValueSetQuery;
import edu.mayo.cts2.framework.service.profile.resolvedvalueset.name.ResolvedValueSetReadId;
import edu.mayo.cts2.framework.service.profile.valuesetdefinition.ResolvedValueSetResolutionEntityQuery;
import edu.mayo.cts2.framework.service.profile.valuesetdefinition.ResolvedValueSetResult;
import edu.mayo.cts2.framework.service.profile.valuesetdefinition.ValueSetDefinitionResolutionService;
import edu.mayo.cts2.framework.service.profile.valuesetdefinition.name.ValueSetDefinitionReadId;
import edu.mayo.cts2.framework.util.spring.AggregateService;
@Component
@AggregateService
public class ExistValueSetDefinitionResolutionService
extends AbstractExistService
implements ValueSetDefinitionResolutionService {
@Autowired(required = false)
@Qualifier("valueSetDefinitionResolutionServiceImpl")
private ValueSetDefinitionResolutionService valueSetResolutionImpl;
@Resource
private ExistResolvedValueSetQueryService existResolvedValueSetQueryService;
@Resource
private ExistResolvedValueSetResolutionService existResolvedValueSetResolutionService;
@Override
public Set<PredicateReference> getKnownProperties() {
if (valueSetResolutionImpl != null)
{
return valueSetResolutionImpl.getKnownProperties();
}
return null;
}
@Override
public Set<? extends MatchAlgorithmReference> getSupportedMatchAlgorithms() {
if (valueSetResolutionImpl != null)
{
return valueSetResolutionImpl.getSupportedMatchAlgorithms();
}
return null;
}
@Override
public Set<? extends ComponentReference> getSupportedSearchReferences() {
if (valueSetResolutionImpl != null)
{
return valueSetResolutionImpl.getSupportedSearchReferences();
}
return null;
}
@Override
public Set<? extends ComponentReference> getSupportedSortReferences() {
if (valueSetResolutionImpl != null)
{
return valueSetResolutionImpl.getSupportedSortReferences();
}
return null;
}
/*
* If the valueSetResolutionImpl is not provided - this falls through to the old implementation
* that doesn't really resolve anything... it looks to see if there is one (and only one)
* ResolvedValueSet for the definition. If so, return that.
*
* TODO: decide if the old code should just be removed - assume valueSetResolutionImpl will be deployed with this?
* Or otherwise retire this T ODO?
*
* (non-Javadoc)
* @see edu.mayo.cts2.framework.service.profile.valuesetdefinition.ValueSetDefinitionResolutionService#resolveDefinition(edu.mayo.cts2.framework.service.profile.valuesetdefinition.name.ValueSetDefinitionReadId, java.util.Set, edu.mayo.cts2.framework.model.service.core.NameOrURI, edu.mayo.cts2.framework.service.profile.valuesetdefinition.ResolvedValueSetResolutionEntityQuery, edu.mayo.cts2.framework.model.core.SortCriteria, edu.mayo.cts2.framework.model.command.ResolvedReadContext, edu.mayo.cts2.framework.model.command.Page)
*/
@Override
public ResolvedValueSetResult<URIAndEntityName> resolveDefinition(
final ValueSetDefinitionReadId id,
Set<NameOrURI> codeSystemVersions,
NameOrURI tag,
- ResolvedValueSetResolutionEntityQuery query,
SortCriteria sort,
ResolvedReadContext context,
Page page) {
if (valueSetResolutionImpl != null)
{
- return valueSetResolutionImpl.resolveDefinition(id, codeSystemVersions, tag, query, sort, context, page);
+ return valueSetResolutionImpl.resolveDefinition(id, codeSystemVersions, tag, sort, context, page);
}
ResolvedValueSetQuery resolvedValueSetQuery = new ResolvedValueSetQuery(){
@Override
public Set<ResolvedFilter> getFilterComponent() {
return null;
}
@Override
public Query getQuery() {
return null;
}
@Override
public ResolvedValueSetQueryServiceRestrictions getResolvedValueSetQueryServiceRestrictions() {
ResolvedValueSetQueryServiceRestrictions restrictions = new ResolvedValueSetQueryServiceRestrictions();
restrictions.setValueSets(new HashSet<NameOrURI>(Arrays.asList(id.getValueSet())));
return restrictions;
}
};
DirectoryResult<ResolvedValueSetDirectoryEntry> summaries =
existResolvedValueSetQueryService.getResourceSummaries(resolvedValueSetQuery, sort, page);
if(summaries != null && summaries.getEntries() != null && summaries.getEntries().size() == 1){
ResolvedValueSetDirectoryEntry summary = summaries.getEntries().get(0);
ResolvedValueSetReadId identifier =
new ResolvedValueSetReadId(
summary.getResourceName(),
id.getValueSet(),
ModelUtils.nameOrUriFromName(id.getName()));
return this.existResolvedValueSetResolutionService.
getResolution(
identifier,
null,
page);
} else {
throw new UnsupportedOperationException();
}
}
@Override
public ResolvedValueSet resolveDefinitionAsCompleteSet(
ValueSetDefinitionReadId arg0,
Set<NameOrURI> arg1,
NameOrURI arg2,
ResolvedReadContext arg3) {
if (valueSetResolutionImpl != null)
{
return valueSetResolutionImpl.resolveDefinitionAsCompleteSet(arg0, arg1, arg2, arg3);
}
throw new UnsupportedOperationException();
}
@Override
public ResolvedValueSetResult<EntityDirectoryEntry> resolveDefinitionAsEntityDirectory(
ValueSetDefinitionReadId arg0,
Set<NameOrURI> arg1,
NameOrURI arg2,
ResolvedValueSetResolutionEntityQuery arg3,
SortCriteria arg4,
ResolvedReadContext arg5, Page arg6) {
if (valueSetResolutionImpl != null)
{
return valueSetResolutionImpl.resolveDefinitionAsEntityDirectory(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
}
throw new UnsupportedOperationException();
}
}
| false | true | public ResolvedValueSetResult<URIAndEntityName> resolveDefinition(
final ValueSetDefinitionReadId id,
Set<NameOrURI> codeSystemVersions,
NameOrURI tag,
ResolvedValueSetResolutionEntityQuery query,
SortCriteria sort,
ResolvedReadContext context,
Page page) {
if (valueSetResolutionImpl != null)
{
return valueSetResolutionImpl.resolveDefinition(id, codeSystemVersions, tag, query, sort, context, page);
}
ResolvedValueSetQuery resolvedValueSetQuery = new ResolvedValueSetQuery(){
@Override
public Set<ResolvedFilter> getFilterComponent() {
return null;
}
@Override
public Query getQuery() {
return null;
}
@Override
public ResolvedValueSetQueryServiceRestrictions getResolvedValueSetQueryServiceRestrictions() {
ResolvedValueSetQueryServiceRestrictions restrictions = new ResolvedValueSetQueryServiceRestrictions();
restrictions.setValueSets(new HashSet<NameOrURI>(Arrays.asList(id.getValueSet())));
return restrictions;
}
};
DirectoryResult<ResolvedValueSetDirectoryEntry> summaries =
existResolvedValueSetQueryService.getResourceSummaries(resolvedValueSetQuery, sort, page);
if(summaries != null && summaries.getEntries() != null && summaries.getEntries().size() == 1){
ResolvedValueSetDirectoryEntry summary = summaries.getEntries().get(0);
ResolvedValueSetReadId identifier =
new ResolvedValueSetReadId(
summary.getResourceName(),
id.getValueSet(),
ModelUtils.nameOrUriFromName(id.getName()));
return this.existResolvedValueSetResolutionService.
getResolution(
identifier,
null,
page);
} else {
throw new UnsupportedOperationException();
}
}
| public ResolvedValueSetResult<URIAndEntityName> resolveDefinition(
final ValueSetDefinitionReadId id,
Set<NameOrURI> codeSystemVersions,
NameOrURI tag,
SortCriteria sort,
ResolvedReadContext context,
Page page) {
if (valueSetResolutionImpl != null)
{
return valueSetResolutionImpl.resolveDefinition(id, codeSystemVersions, tag, sort, context, page);
}
ResolvedValueSetQuery resolvedValueSetQuery = new ResolvedValueSetQuery(){
@Override
public Set<ResolvedFilter> getFilterComponent() {
return null;
}
@Override
public Query getQuery() {
return null;
}
@Override
public ResolvedValueSetQueryServiceRestrictions getResolvedValueSetQueryServiceRestrictions() {
ResolvedValueSetQueryServiceRestrictions restrictions = new ResolvedValueSetQueryServiceRestrictions();
restrictions.setValueSets(new HashSet<NameOrURI>(Arrays.asList(id.getValueSet())));
return restrictions;
}
};
DirectoryResult<ResolvedValueSetDirectoryEntry> summaries =
existResolvedValueSetQueryService.getResourceSummaries(resolvedValueSetQuery, sort, page);
if(summaries != null && summaries.getEntries() != null && summaries.getEntries().size() == 1){
ResolvedValueSetDirectoryEntry summary = summaries.getEntries().get(0);
ResolvedValueSetReadId identifier =
new ResolvedValueSetReadId(
summary.getResourceName(),
id.getValueSet(),
ModelUtils.nameOrUriFromName(id.getName()));
return this.existResolvedValueSetResolutionService.
getResolution(
identifier,
null,
page);
} else {
throw new UnsupportedOperationException();
}
}
|
diff --git a/EmoStatus/src/com/thesis/emostatus/MonitorInfoActivity.java b/EmoStatus/src/com/thesis/emostatus/MonitorInfoActivity.java
index 4ad98ac..e2fee10 100644
--- a/EmoStatus/src/com/thesis/emostatus/MonitorInfoActivity.java
+++ b/EmoStatus/src/com/thesis/emostatus/MonitorInfoActivity.java
@@ -1,74 +1,74 @@
package com.thesis.emostatus;
/**
* Created by vito on 25-11-13.
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.widget.ExpandableListAdapter;
import android.widget.SimpleExpandableListAdapter;
public class MonitorInfoActivity extends ExpandableListActivity {
private static final String NAME = "NAME";
private static final String IS_EVEN = "IS_EVEN";
private ExpandableListAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
Map<String, String> curGroupMap1 = new HashMap<String, String>();
groupData.add(curGroupMap1);
curGroupMap1.put(NAME, "Skype");
List<Map<String, String>> children1 = new ArrayList<Map<String, String>>();
Map<String, String> curChildMap11 = new HashMap<String, String>();
children1.add(curChildMap11);
- curChildMap11.put(IS_EVEN, "EL sistema detectará el estado anímico a partir de las videollamadas que se hagan en el dispositivo del usuario.");
+ curChildMap11.put(IS_EVEN, "El sistema detectará el estado anímico a partir de las videollamadas que se hagan en el dispositivo del usuario.");
childData.add(children1);
Map<String, String> curGroupMap2 = new HashMap<String, String>();
groupData.add(curGroupMap2);
curGroupMap2.put(NAME, "Grabación");
List<Map<String, String>> children2 = new ArrayList<Map<String, String>>();
Map<String, String> curChildMap21 = new HashMap<String, String>();
children2.add(curChildMap21);
curChildMap21.put(IS_EVEN, "El sistema detectará el estado anímico a partir de las grabaciones de voz que se hagan utilizando el micrófono del dispositivo del usuario.");
Map<String, String> curChildMap22 = new HashMap<String, String>();
children2.add(curChildMap22);
- curChildMap22.put(IS_EVEN, "Las grabaciones se harán con una determinada frecuencia(ej: cada 15 min). Tú solo debese preocuparte de configurar los días, y el horario de grabación.");
+ curChildMap22.put(IS_EVEN, "Las grabaciones se harán con una determinada frecuencia(ej: cada 15 min). Tú solo debes preocuparte de configurar los días, y el horario de grabación.");
childData.add(children2);
// Set up our adapter
mAdapter = new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[] { NAME},
new int[] { android.R.id.text1},
childData,
R.layout.info_info,
new String[] {IS_EVEN },
new int[] { R.id.title}
);
setListAdapter(mAdapter);
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
Map<String, String> curGroupMap1 = new HashMap<String, String>();
groupData.add(curGroupMap1);
curGroupMap1.put(NAME, "Skype");
List<Map<String, String>> children1 = new ArrayList<Map<String, String>>();
Map<String, String> curChildMap11 = new HashMap<String, String>();
children1.add(curChildMap11);
curChildMap11.put(IS_EVEN, "EL sistema detectará el estado anímico a partir de las videollamadas que se hagan en el dispositivo del usuario.");
childData.add(children1);
Map<String, String> curGroupMap2 = new HashMap<String, String>();
groupData.add(curGroupMap2);
curGroupMap2.put(NAME, "Grabación");
List<Map<String, String>> children2 = new ArrayList<Map<String, String>>();
Map<String, String> curChildMap21 = new HashMap<String, String>();
children2.add(curChildMap21);
curChildMap21.put(IS_EVEN, "El sistema detectará el estado anímico a partir de las grabaciones de voz que se hagan utilizando el micrófono del dispositivo del usuario.");
Map<String, String> curChildMap22 = new HashMap<String, String>();
children2.add(curChildMap22);
curChildMap22.put(IS_EVEN, "Las grabaciones se harán con una determinada frecuencia(ej: cada 15 min). Tú solo debese preocuparte de configurar los días, y el horario de grabación.");
childData.add(children2);
// Set up our adapter
mAdapter = new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[] { NAME},
new int[] { android.R.id.text1},
childData,
R.layout.info_info,
new String[] {IS_EVEN },
new int[] { R.id.title}
);
setListAdapter(mAdapter);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
Map<String, String> curGroupMap1 = new HashMap<String, String>();
groupData.add(curGroupMap1);
curGroupMap1.put(NAME, "Skype");
List<Map<String, String>> children1 = new ArrayList<Map<String, String>>();
Map<String, String> curChildMap11 = new HashMap<String, String>();
children1.add(curChildMap11);
curChildMap11.put(IS_EVEN, "El sistema detectará el estado anímico a partir de las videollamadas que se hagan en el dispositivo del usuario.");
childData.add(children1);
Map<String, String> curGroupMap2 = new HashMap<String, String>();
groupData.add(curGroupMap2);
curGroupMap2.put(NAME, "Grabación");
List<Map<String, String>> children2 = new ArrayList<Map<String, String>>();
Map<String, String> curChildMap21 = new HashMap<String, String>();
children2.add(curChildMap21);
curChildMap21.put(IS_EVEN, "El sistema detectará el estado anímico a partir de las grabaciones de voz que se hagan utilizando el micrófono del dispositivo del usuario.");
Map<String, String> curChildMap22 = new HashMap<String, String>();
children2.add(curChildMap22);
curChildMap22.put(IS_EVEN, "Las grabaciones se harán con una determinada frecuencia(ej: cada 15 min). Tú solo debes preocuparte de configurar los días, y el horario de grabación.");
childData.add(children2);
// Set up our adapter
mAdapter = new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[] { NAME},
new int[] { android.R.id.text1},
childData,
R.layout.info_info,
new String[] {IS_EVEN },
new int[] { R.id.title}
);
setListAdapter(mAdapter);
}
|
diff --git a/src/org/jacorb/idl/UnionType.java b/src/org/jacorb/idl/UnionType.java
index 140704535..91e086525 100644
--- a/src/org/jacorb/idl/UnionType.java
+++ b/src/org/jacorb/idl/UnionType.java
@@ -1,1179 +1,1179 @@
package org.jacorb.idl;
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2002 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.util.*;
class UnionType
extends TypeDeclaration
implements Scope
{
/** the union's discriminator's type spec */
TypeSpec switch_type_spec;
SwitchBody switch_body;
boolean written = false;
private ScopeData scopeData;
private boolean allCasesCovered = false;
private boolean switch_is_enum = false;
private boolean switch_is_bool = false;
private boolean switch_is_longlong = false;
private boolean explicit_default_case = false;
private int labels;
public UnionType( int num )
{
super( num );
pack_name = "";
}
public Object clone()
{
UnionType ut = new UnionType( new_num() );
ut.switch_type_spec = this.switch_type_spec;
ut.switch_body = switch_body;
ut.pack_name = this.pack_name;
ut.name = this.name;
ut.written = this.written;
ut.scopeData = this.scopeData;
ut.enclosing_symbol = this.enclosing_symbol;
ut.token = this.token;
return ut;
}
public void setScopeData( ScopeData data )
{
scopeData = data;
}
public ScopeData getScopeData()
{
return scopeData;
}
public TypeDeclaration declaration()
{
return this;
}
public void setEnclosingSymbol( IdlSymbol s )
{
if( enclosing_symbol != null && enclosing_symbol != s )
throw new RuntimeException( "Compiler Error: trying to reassign container for " + name );
enclosing_symbol = s;
if (switch_body != null)
{
switch_body.setEnclosingSymbol( s );
}
}
public String typeName()
{
if( typeName == null )
setPrintPhaseNames();
return typeName;
}
public String className()
{
String fullName = typeName();
if( fullName.indexOf( '.' ) > 0 )
{
return fullName.substring( fullName.lastIndexOf( '.' ) + 1 );
}
else
{
return fullName;
}
}
public String printReadExpression( String Streamname )
{
return typeName() + "Helper.read(" + Streamname + ")";
}
public String printWriteStatement( String var_name, String streamname )
{
return typeName() + "Helper.write(" + streamname + "," + var_name + ");";
}
public String holderName()
{
return typeName() + "Holder";
}
public void set_included( boolean i )
{
included = i;
}
public void setSwitchType( TypeSpec s )
{
switch_type_spec = s;
}
public void setSwitchBody( SwitchBody sb )
{
switch_body = sb;
}
public void setPackage( String s )
{
s = parser.pack_replace( s );
if( pack_name.length() > 0 )
{
pack_name = new String( s + "." + pack_name);
}
else
{
pack_name = s;
}
if (switch_type_spec != null)
{
switch_type_spec.setPackage (s);
}
if (switch_body != null)
{
switch_body.setPackage( s );
}
}
public boolean basic()
{
return false;
}
public void parse()
{
boolean justAnotherOne = false;
escapeName();
ConstrTypeSpec ctspec = new ConstrTypeSpec( new_num() );
try
{
ScopedName.definePseudoScope( full_name() );
ctspec.c_type_spec = this;
NameTable.define( full_name(), "type-union" );
TypeMap.typedef( full_name(), ctspec );
}
catch (NameAlreadyDefined nad)
{
if (parser.get_pending (full_name ()) != null)
{
if (switch_type_spec == null )
{
justAnotherOne = true;
}
// else actual definition
if( !full_name().equals( "org.omg.CORBA.TypeCode" ) && switch_type_spec != null )
{
TypeMap.replaceForwardDeclaration( full_name(), ctspec );
}
}
else
{
Environment.output( 4, nad );
parser.error( "Union " + full_name() + " already defined", token );
}
}
if (switch_type_spec != null)
{
// Resolve scoped names and aliases
TypeSpec ts;
if( switch_type_spec.type_spec instanceof ScopedName )
{
ts = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
while( ts instanceof ScopedName || ts instanceof AliasTypeSpec )
{
if( ts instanceof ScopedName )
{
ts = ( (ScopedName)ts ).resolvedTypeSpec();
}
else
{
ts = ( (AliasTypeSpec)ts ).originalType();
}
}
addImportedName( switch_type_spec.typeName() );
}
else
{
ts = switch_type_spec.type_spec;
}
// Check if we have a valid discriminator type
if
( !(
( ( ts instanceof SwitchTypeSpec ) &&
( ( (SwitchTypeSpec)ts ).isSwitchable() ) )
||
( ( ts instanceof BaseType ) &&
( ( (BaseType)ts ).isSwitchType() ) )
||
( ( ts instanceof ConstrTypeSpec ) &&
( ( (ConstrTypeSpec)ts ).c_type_spec instanceof EnumType ) )
) )
{
parser.error( "Illegal Switch Type: " + ts.typeName(), token );
}
switch_type_spec.parse();
switch_body.setTypeSpec( switch_type_spec );
switch_body.setUnion( this );
ScopedName.addRecursionScope( typeName() );
switch_body.parse();
ScopedName.removeRecursionScope( typeName() );
// Fixup array typing
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
c.element_spec.t = getElementType( c.element_spec );
}
NameTable.parsed_interfaces.put( full_name(), "" );
parser.remove_pending( full_name() );
}
else if( !justAnotherOne )
{
// i am forward declared, must set myself as
// pending further parsing
parser.set_pending( full_name() );
}
}
/**
* @returns a string for an expression of type TypeCode that
* describes this type
*/
public String getTypeCodeExpression()
{
return typeName() + "Helper.type()";
}
public String getTypeCodeExpression( Set knownTypes )
{
if( knownTypes.contains( this ) )
{
return this.getRecursiveTypeCodeExpression();
}
else
{
return this.getTypeCodeExpression();
}
}
private void printClassComment( String className, PrintWriter ps )
{
ps.println( "/**" );
ps.println( " *\tGenerated from IDL definition of union " +
"\"" + className + "\"" );
ps.println( " *\t@author JacORB IDL compiler " );
ps.println( " */\n" );
}
public void printUnionClass( String className, PrintWriter pw )
{
if( !pack_name.equals( "" ) )
pw.println( "package " + pack_name + ";" );
printImport( pw );
printClassComment( className, pw );
pw.println( "public" + parser.getFinalString() + " class " + className );
pw.println( "\timplements org.omg.CORBA.portable.IDLEntity" );
pw.println( "{" );
TypeSpec ts = switch_type_spec.typeSpec();
while( ts instanceof ScopedName || ts instanceof AliasTypeSpec )
{
if( ts instanceof ScopedName )
ts = ( (ScopedName)ts ).resolvedTypeSpec();
if( ts instanceof AliasTypeSpec )
ts = ( (AliasTypeSpec)ts ).originalType();
}
pw.println( "\tprivate " + ts.typeName() + " discriminator;" );
/* find a "default" value */
String defaultStr = "";
/* start by concatenating all case label lists into one list
* (this list is used only for finding a default)
*/
int def = 0;
java.util.Vector allCaseLabels = new java.util.Vector();
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
for( int i = 0; i < c.case_label_list.v.size(); i++ )
{
labels++; // the overall number of labels is needed in a number of places...
Object ce = c.case_label_list.v.elementAt( i );
if( ce != null )
{
if( ce instanceof ConstExpr )
{
allCaseLabels.addElement( ( (ConstExpr)ce ).value() );
}
else
{
allCaseLabels.addElement( ( (ScopedName)ce ).resolvedName() ); // this is a scoped name
Environment.output( 4, "Adding " + ( (ScopedName)ce ).resolvedName() + " case labels." );
}
}
else
{
def = 1;
explicit_default_case = true;
}
}
}
/* if switch type is an enum, the default is null */
if( ( ts instanceof ConstrTypeSpec &&
( (ConstrTypeSpec)ts ).declaration() instanceof EnumType ) )
{
this.switch_is_enum = true;
EnumType et = (EnumType)( (ConstrTypeSpec)ts ).declaration();
if( allCaseLabels.size() + def > et.size() )
{
lexer.emit_warn( "Too many case labels in definition of union " +
full_name() + ", default cannot apply", token );
}
if( allCaseLabels.size() + def == et.size() )
{
allCasesCovered = true;
}
for( int i = 0; i < et.size(); i++ )
{
String qualifiedCaseLabel =
ts.typeName() + "." + (String)et.enumlist.v.elementAt( i );
if( !( allCaseLabels.contains( qualifiedCaseLabel ) ) )
{
defaultStr = qualifiedCaseLabel;
break;
}
}
}
else
{
if( ts instanceof BaseType )
{
ts = ( (BaseType)ts ).typeSpec();
}
if( ts instanceof BooleanType )
{
this.switch_is_bool = true;
// find a "default" for boolean
if( allCaseLabels.size() + def > 2 )
{
parser.error( "Case label error: too many default labels.", token );
return;
}
else if( allCaseLabels.size() == 1 )
{
if( ( (String)allCaseLabels.elementAt( 0 ) ).equals( "true" ) )
defaultStr = "false";
else
defaultStr = "true";
}
else
{
// labels for both true and false -> no default possible
}
}
else if( ts instanceof CharType )
{
// find a "default" for char
for( short s = 0; s < 256; s++ )
{
if( !( allCaseLabels.contains( new Character( (char)s ).toString() ) ) )
{
defaultStr = "(char)" + s;
break;
}
}
}
else if( ts instanceof IntType )
{
int maxint = 65536; // 2^16, max short
if( ts instanceof LongType )
maxint = 2147483647; // -2^31, max long
for( int i = 0; i < maxint; i++ )
{
if( !( allCaseLabels.contains( String.valueOf( i ) ) ) )
{
defaultStr = Integer.toString( i );
break;
}
}
if( ts instanceof LongLongType )
{
this.switch_is_longlong = true;
}
}
else
{
System.err.println( "Something went wrong in UnionType, "
+ "could not identify switch type "
+ switch_type_spec.type_spec );
}
}
/* print members */
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
int caseLabelNum = c.case_label_list.v.size();
String label[] = new String[ caseLabelNum ];
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null ) // null means "default"
{
label[ i ] = null;
}
else if( o != null && o instanceof ConstExpr )
{
label[ i ] = ( (ConstExpr)o ).value();
}
else if( o instanceof ScopedName )
{
label[ i ] = ( (ScopedName)o ).typeName();
}
}
pw.println( "\tprivate " + c.element_spec.t.typeName()
+ " " + c.element_spec.d.name() + ";" );
}
/*
* print a constructor for class member initialization
*/
pw.println( "\n\tpublic " + className + " ()" );
pw.println( "\t{" );
pw.println( "\t}\n" );
/*
* print an accessor method for the discriminator
*/
pw.println( "\tpublic " + ts.typeName() + " discriminator ()" );
pw.println( "\t{" );
pw.println( "\t\treturn discriminator;" );
pw.println( "\t}\n" );
/*
* print accessor and modifiers for each case label and branch
*/
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
boolean thisCaseIsDefault = false;
int caseLabelNum = c.case_label_list.v.size();
String label[] = new String[ caseLabelNum ];
/* make case labels available as strings */
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null ) // null means "default"
{
label[ i ] = null;
thisCaseIsDefault = true;
}
else if( o instanceof ConstExpr )
label[ i ] = ( (ConstExpr)o ).value();
else if( o instanceof ScopedName )
label[ i ] = ( (ScopedName)o ).typeName();
}
// accessors
pw.println( "\tpublic " + c.element_spec.t.typeName()
+ " " + c.element_spec.d.name() + " ()" );
pw.println( "\t{" );
// if( switch_is_enum )
// pw.print("\t\tif( !discriminator.equals( ");
// else
pw.print( "\t\tif( discriminator != " );
for( int i = 0; i < caseLabelNum; i++ )
{
if( label[ i ] == null )
pw.print( defaultStr );
else
pw.print( label[ i ] );
if( i < caseLabelNum - 1 )
{
// if( switch_is_enum )
// pw.print(") && !discriminator.equals( ");
// else
pw.print( " && discriminator != " );
}
}
pw.println( ")\n\t\t\tthrow new org.omg.CORBA.BAD_OPERATION();" );
pw.println( "\t\treturn " + c.element_spec.d.name() + ";" );
pw.println( "\t}\n" );
// modifiers
pw.println( "\tpublic void " + c.element_spec.d.name() +
" (" + c.element_spec.t.typeName() + " _x)" );
pw.println( "\t{" );
pw.print( "\t\tdiscriminator = " );
if( label[ 0 ] == null )
pw.println( defaultStr + ";" );
else
pw.println( label[ 0 ] + ";" );
pw.println( "\t\t" + c.element_spec.d.name() + " = _x;" );
pw.println( "\t}\n" );
if( caseLabelNum > 1 || thisCaseIsDefault )
{
pw.println( "\tpublic void " + c.element_spec.d.name() + "( " +
ts.typeName() + " _discriminator, " +
c.element_spec.t.typeName() + " _x )" );
pw.println( "\t{" );
pw.print( "\t\tif( _discriminator != " );
for( int i = 0; i < caseLabelNum; i++ )
{
if( label[ i ] != null )
pw.print( label[ i ] );
else
pw.print( defaultStr );
if( i < caseLabelNum - 1 )
{
pw.print( " && _discriminator != " );
}
}
pw.println( ")\n\t\t\tthrow new org.omg.CORBA.BAD_OPERATION();" );
pw.println( "\t\tdiscriminator = _discriminator;" );
pw.println( "\t\t" + c.element_spec.d.name() + " = _x;" );
pw.println( "\t}\n" );
}
}
/* if there is no default case and case labels do not cover
* all discriminator values, we have to generate __defaultmethods
*/
if( def == 0 && defaultStr.length() > 0 )
{
pw.println( "\tpublic void __default ()" );
pw.println( "\t{" );
pw.println( "\t\tdiscriminator = " + defaultStr + ";" );
pw.println( "\t}" );
pw.println( "\tpublic void __default (" + ts.typeName() + " _discriminator)" );
pw.println( "\t{" );
pw.println( "\t\tdiscriminator = _discriminator;" );
pw.println( "\t}" );
}
pw.println( "}" );
}
public void printHolderClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Holder" );
ps.println( "\timplements org.omg.CORBA.portable.Streamable" );
ps.println( "{" );
ps.println( "\tpublic " + className + " value;\n" );
ps.println( "\tpublic " + className + "Holder ()" );
ps.println( "\t{" );
ps.println( "\t}" );
ps.println( "\tpublic " + className + "Holder (final " + className + " initial)" );
ps.println( "\t{" );
ps.println( "\t\tvalue = initial;" );
ps.println( "\t}" );
ps.println( "\tpublic org.omg.CORBA.TypeCode _type ()" );
ps.println( "\t{" );
ps.println( "\t\treturn " + className + "Helper.type ();" );
ps.println( "\t}" );
ps.println( "\tpublic void _read (final org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\tvalue = " + className + "Helper.read (in);" );
ps.println( "\t}" );
ps.println( "\tpublic void _write (final org.omg.CORBA.portable.OutputStream out)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + "Helper.write (out, value);" );
ps.println( "\t}" );
ps.println( "}" );
}
private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
- int mi = 0;
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
+ int mi = switch_body.caseListVector.size () - 1;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
- ps.print( "\t\t\tmembers[" + ( mi++ ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
+ ps.print( "\t\t\tmembers[" + ( mi-- ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
/** generate required classes */
public void print( PrintWriter ps )
{
setPrintPhaseNames();
/** no code generation for included definitions */
if( included && !generateIncluded() )
return;
/** only write once */
if( written )
{
return;
}
// Forward declaration
if (switch_type_spec != null)
{
try
{
switch_body.print( ps );
String className = className();
String path = parser.out_dir + fileSeparator +
pack_name.replace( '.', fileSeparator );
File dir = new File( path );
if( !dir.exists() )
if( !dir.mkdirs() )
{
org.jacorb.idl.parser.fatal_error( "Unable to create " + path, null );
}
/** print the mapped java class */
String fname = className + ".java";
PrintWriter decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printUnionClass( className, decl_ps );
decl_ps.close();
/** print the holder class */
fname = className + "Holder.java";
decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printHolderClass( className, decl_ps );
decl_ps.close();
/** print the helper class */
fname = className + "Helper.java";
decl_ps = new PrintWriter( new java.io.FileWriter( new File( dir, fname ) ) );
printHelperClass( className, decl_ps );
decl_ps.close();
written = true;
}
catch( java.io.IOException i )
{
System.err.println( "File IO error" );
i.printStackTrace();
}
}
}
private TypeSpec getElementType( ElementSpec element )
{
TypeSpec tspec = element.t;
// Arrays are handled as a special case. Parser generates
// an ArrayDeclarator for an array, need to spot this and
// create appropriate type information with an ArrayTypeSpec.
if( element.d.d instanceof ArrayDeclarator )
{
tspec = new ArrayTypeSpec( new_num(), tspec,
(ArrayDeclarator)element.d.d, pack_name );
tspec.parse();
}
return tspec;
}
}
| false | true | private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
int mi = 0;
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
ps.print( "\t\t\tmembers[" + ( mi++ ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
| private void printHelperClass( String className, PrintWriter ps )
{
if( !pack_name.equals( "" ) )
ps.println( "package " + pack_name + ";" );
printImport( ps );
printClassComment( className, ps );
ps.println( "public" + parser.getFinalString() + " class " + className + "Helper" );
ps.println( "{" );
ps.println( "\tprivate static org.omg.CORBA.TypeCode _type;" );
String _type = typeName();
TypeSpec.printInsertExtractMethods( ps, typeName() );
printIdMethod( ps );
/** read method */
ps.println( "\tpublic static " + className + " read (org.omg.CORBA.portable.InputStream in)" );
ps.println( "\t{" );
ps.println( "\t\t" + className + " result = new " + className + " ();" );
TypeSpec switch_ts_resolved = switch_type_spec;
if( switch_type_spec.type_spec instanceof ScopedName )
{
switch_ts_resolved = ( (ScopedName)switch_type_spec.type_spec ).resolvedTypeSpec();
}
String indent1 = "\t\t\t";
String indent2 = "\t\t\t\t";
if( switch_is_longlong )
{
indent1 = "\t\t";
indent2 = "\t\t\t";
}
String case_str = "case ";
String colon_str = ":";
String default_str = "default:";
if( switch_is_enum )
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " disc = " +
switch_ts_resolved.toString() + ".from_int(in.read_long());" );
ps.println( "\t\tswitch (disc.value ())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_ts_resolved.toString() + " "
+ switch_ts_resolved.printReadStatement( "disc", "in" ) );
if( switch_is_bool )
{
/* special case: boolean is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else if( switch_is_longlong )
{
/* special case: long is not a switch type in java */
case_str = "if (disc == ";
colon_str = ")";
default_str = "else";
}
else
{
ps.println( "\t\tswitch (disc)" );
ps.println( "\t\t{" );
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter defaultWriter = new PrintWriter( bos );
PrintWriter alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
{
t = ( (ScopedName)t ).resolvedTypeSpec();
}
t = t.typeSpec();
String varname = "_var";
ps.println( indent2 + t.typeName() + " " + varname + ";" );
ps.println( indent2 + t.printReadStatement( varname, "in" ) );
ps.print( indent2 + "result." + d.name() + " (" );
if( caseLabelNum > 1 )
{
ps.print( "disc," );
}
ps.println( varname + ");" );
// no "break" written for default case or for "if" construct
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return result;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
if( !explicit_default_case && !switch_is_bool && !switch_is_longlong && !allCasesCovered )
{
defaultWriter.println( "\t\t\tdefault: result.__default (disc);" );
}
if( !explicit_default_case && switch_is_longlong )
{
defaultWriter.println( "\t\tresult.__default (disc);" );
defaultWriter.println( "\t\treturn result;" );
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" ); // close switch statement
}
if( !switch_is_longlong )
{
ps.println( "\t\treturn result;" );
}
ps.println( "\t}" );
/** write method */
ps.println( "\tpublic static void write (org.omg.CORBA.portable.OutputStream out, " + className + " s)" );
ps.println( "\t{" );
if( switch_is_enum )
{
ps.println( "\t\tout.write_long(s.discriminator().value());" );
ps.println( "\t\tswitch(s.discriminator().value())" );
ps.println( "\t\t{" );
}
else
{
ps.println( "\t\t" + switch_type_spec.typeSpec().printWriteStatement( "s.discriminator ()", "out" ) + ";" );
if( switch_is_bool )
{
/* special case: booleans are no switch type in java */
case_str = "if(s.discriminator()==";
// colon_str and default_str are already set correctly
}
else if( switch_is_longlong )
{
ps.println( "\t\tlong disc = s.discriminator ();" );
}
else
{
ps.println( "\t\tswitch (s.discriminator ())" );
ps.println( "\t\t{" );
}
}
bos = new ByteArrayOutputStream();
defaultWriter = new PrintWriter( bos );
alt = null;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
boolean was_default = false;
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
if( o == null )
{
// null means "default"
defaultWriter.println( indent1 + default_str );
was_default = true;
}
else if( o != null && o instanceof ConstExpr )
{
ps.println( indent1 + case_str + ( (ConstExpr)o ).value() + colon_str );
}
else if( o instanceof ScopedName )
{
String _t = ( (ScopedName)o ).typeName();
if( switch_is_enum )
ps.println( indent1 + case_str + _t.substring( 0, _t.lastIndexOf( '.' ) + 1 )
+ "_" + _t.substring( _t.lastIndexOf( '.' ) + 1 ) + colon_str );
else
ps.println( indent1 + case_str + _t + colon_str );
}
if( i == caseLabelNum - 1 )
{
if( o == null )
{
alt = ps;
ps = defaultWriter;
}
ps.println( indent1 + "{" );
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
t = t.typeSpec();
ps.println( indent2 + t.printWriteStatement( "s." + d.name() + " ()", "out" ) );
// no "break" written for default case
if( o != null && !switch_is_bool && !switch_is_longlong )
{
ps.println( indent2 + "break;" );
}
if( switch_is_longlong )
{
ps.println( indent2 + "return;" );
}
ps.println( indent1 + "}" );
if( o == null )
{
ps = alt;
}
}
}
if( switch_is_bool && !was_default )
{
case_str = "else " + case_str;
}
}
defaultWriter.close();
if( bos.size() > 0 )
{
ps.print( bos.toString() );
}
/* close switch statement */
if( !switch_is_bool && !switch_is_longlong )
{
ps.println( "\t\t}" );
}
ps.println( "\t}" );
/** type() */
ps.println( "\tpublic static org.omg.CORBA.TypeCode type ()" );
ps.println( "\t{" );
ps.println( "\t\tif (_type == null)" );
ps.println( "\t\t{" );
ps.println( "\t\t\torg.omg.CORBA.UnionMember[] members = new org.omg.CORBA.UnionMember[" + labels + "];" );
ps.println( "\t\t\torg.omg.CORBA.Any label_any;" );
TypeSpec label_t = switch_type_spec.typeSpec();
while( label_t instanceof ScopedName || label_t instanceof AliasTypeSpec )
{
if( label_t instanceof ScopedName )
label_t = ( (ScopedName)label_t ).resolvedTypeSpec();
if( label_t instanceof AliasTypeSpec )
label_t = ( (AliasTypeSpec)label_t ).originalType();
}
label_t = label_t.typeSpec();
int mi = switch_body.caseListVector.size () - 1;
for( Enumeration e = switch_body.caseListVector.elements(); e.hasMoreElements(); )
{
Case c = (Case)e.nextElement();
TypeSpec t = c.element_spec.t;
while( t instanceof ScopedName || t instanceof AliasTypeSpec )
{
if( t instanceof ScopedName )
t = ( (ScopedName)t ).resolvedTypeSpec();
if( t instanceof AliasTypeSpec )
t = ( (AliasTypeSpec)t ).originalType();
}
t = t.typeSpec();
Declarator d = c.element_spec.d;
int caseLabelNum = c.case_label_list.v.size();
for( int i = 0; i < caseLabelNum; i++ )
{
Object o = c.case_label_list.v.elementAt( i );
ps.println( "\t\t\tlabel_any = org.omg.CORBA.ORB.init().create_any ();" );
if( o == null )
{
ps.println( "\t\t\tlabel_any.insert_octet ((byte)0);" );
}
else if( label_t instanceof BaseType )
{
if( ( label_t instanceof CharType ) ||
( label_t instanceof BooleanType ) ||
( label_t instanceof LongType ) ||
( label_t instanceof LongLongType ) )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " (" );
}
else if( label_t instanceof ShortType )
{
ps.print( "\t\t\tlabel_any." + label_t.printInsertExpression() + " ((short)" );
}
else
{
throw new RuntimeException( "Compiler error: unrecognized BaseType: "
+ label_t.typeName() + ":" + label_t + ": " + label_t.typeSpec()
+ ": " + label_t.getClass().getName() );
}
ps.println( ( (ConstExpr)o ).value() + ");" );
}
else if( switch_is_enum )
{
String _t = ( (ScopedName)o ).typeName();
ps.println( "\t\t\t" + _t.substring( 0, _t.lastIndexOf( '.' ) )
+ "Helper.insert( label_any, " + _t + " );" );
}
else
{
throw new Error( "Compiler error: unrecognized label type: " + label_t.typeName() );
}
ps.print( "\t\t\tmembers[" + ( mi-- ) + "] = new org.omg.CORBA.UnionMember (\"" + d.deEscapeName() + "\", label_any, " );
if( t instanceof ConstrTypeSpec )
{
ps.print( t.typeSpec().toString() + "Helper.type()," );
}
else
{
ps.print( t.typeSpec().getTypeCodeExpression() + "," );
}
ps.println( "null);" );
}
}
ps.print( "\t\t\t _type = org.omg.CORBA.ORB.init().create_union_tc(id(),\"" + className() + "\"," );
ps.println( switch_type_spec.typeSpec().getTypeCodeExpression() + ", members);" );
ps.println( "\t\t}" );
ps.println( "\t\treturn _type;" );
ps.println( "\t}" );
ps.println( "}" ); // end of helper class
}
|
diff --git a/src/ui/GameSetup.java b/src/ui/GameSetup.java
index 7d90ef4..3bcc2e0 100644
--- a/src/ui/GameSetup.java
+++ b/src/ui/GameSetup.java
@@ -1,162 +1,162 @@
package src.ui;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import src.GameMain;
import src.core.Game;
import src.core.Map;
import src.ui.controller.GameController;
public class GameSetup extends JPanel {
private static final long serialVersionUID = 1L;
private static final String createGameText = "Create your game:";
private static final String createNameText = "Game name:";
private JLabel createGameLabel;
private JLabel mapLabel;
protected JButton playButton;
protected JButton cancelButton;
protected JLabel createNameLabel;
protected JTextField createNameField;
private JScrollPane mapListPane;
protected JList mapList;
private MapComponent mc;
protected GameMain gameMain;
public GameSetup() {
super(new GridBagLayout());
setSize(800, 600);
mc = new MapComponent(true);
mc.setGridOn(true);
mc.setSize(400, 400);
createGameLabel = new JLabel(createGameText);
mapLabel = new JLabel("Map:");
createNameLabel = new JLabel(createNameText);
createNameField = new JTextField("");
cancelButton = new JButton("Cancel");
playButton = new JButton("Begin Game");
Object mapNames[] = Map.getMapNames().toArray();
mapList = new JList(mapNames);
mapList.setSelectedIndex(0);
mc.setMap(Map.getMapByName((String)mapNames[0]));
mapList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mapList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
mc.setMap(Map.getMapByName((String)mapList.getSelectedValue()));
}
});
mapListPane = new JScrollPane(mapList);
}
public GameSetup(GameMain gameMain) {
this();
this.gameMain = gameMain;
setupLayout();
setupButtonActions();
}
public void setupLayout(){
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(0,0,10,0);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
add(createGameLabel, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
add(mapLabel, c);
c.gridx = 0;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
add(mapListPane, c);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
- c.insets = new Insets(0,20,0,0);
+ c.insets = new Insets(0,20,10,0);
mc.setPreferredSize(new Dimension(400, 400));
add(mc, c);
c.gridx = 0;
c.gridy = 4;
c.gridwidth = 1;
c.ipady = 20;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(0,0,0,0);
add(cancelButton, c);
c.gridx = 3;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(0,0,0,0);
c.anchor = GridBagConstraints.LINE_END;
add(playButton, c);
}
public void setupButtonActions() {
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TitleScreen titleScreen = new TitleScreen(gameMain);
gameMain.showScreen(titleScreen);
}
});
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Map m = Map.getMapByName(getMapName());
Game g = new Game();
g.setMap(m);
GameController gc = new GameController();
gc.setGame(g);
gc.setGameMain(gameMain);
SingleGamePanel gamePanel = new SingleGamePanel(gc);
gameMain.showScreen(gamePanel);
gc.start();
}
});
}
public String getMapName() {
return (String) mapList.getSelectedValue();
}
}
| true | true | public void setupLayout(){
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(0,0,10,0);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
add(createGameLabel, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
add(mapLabel, c);
c.gridx = 0;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
add(mapListPane, c);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(0,20,0,0);
mc.setPreferredSize(new Dimension(400, 400));
add(mc, c);
c.gridx = 0;
c.gridy = 4;
c.gridwidth = 1;
c.ipady = 20;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(0,0,0,0);
add(cancelButton, c);
c.gridx = 3;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(0,0,0,0);
c.anchor = GridBagConstraints.LINE_END;
add(playButton, c);
}
| public void setupLayout(){
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(0,0,10,0);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
add(createGameLabel, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
add(mapLabel, c);
c.gridx = 0;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
add(mapListPane, c);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(0,20,10,0);
mc.setPreferredSize(new Dimension(400, 400));
add(mc, c);
c.gridx = 0;
c.gridy = 4;
c.gridwidth = 1;
c.ipady = 20;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(0,0,0,0);
add(cancelButton, c);
c.gridx = 3;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(0,0,0,0);
c.anchor = GridBagConstraints.LINE_END;
add(playButton, c);
}
|
diff --git a/parser/org/eclipse/cdt/internal/core/parser/scanner2/CharArrayMap.java b/parser/org/eclipse/cdt/internal/core/parser/scanner2/CharArrayMap.java
index ab3a4ad5d..851ad3bc2 100644
--- a/parser/org/eclipse/cdt/internal/core/parser/scanner2/CharArrayMap.java
+++ b/parser/org/eclipse/cdt/internal/core/parser/scanner2/CharArrayMap.java
@@ -1,186 +1,186 @@
/**********************************************************************
* Copyright (c) 2004 IBM 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-v10.html
*
* Contributors:
* IBM - Initial implementation
***********************************************************************/
package org.eclipse.cdt.internal.core.parser.scanner2;
/**
* @author Doug Schaefer
*/
public abstract class CharArrayMap {
private char[][] keyTable;
private int[] hashTable;
private int[] nextTable;
protected int currEntry = -1;
protected CharArrayMap(int initialSize) {
int size = 1;
while (size < initialSize)
size <<= 1;
keyTable = new char[size][];
hashTable = new int[size * 2];
nextTable = new int[size];
}
protected int capacity() {
return keyTable.length;
}
private int hash(char[] buffer, int start, int len) {
return CharArrayUtils.hash(buffer, start, len) & (hashTable.length - 1);
}
private int hash(char[] buffer) {
return hash(buffer, 0, buffer.length);
}
private void insert(int i) {
insert(i, hash(keyTable[i], 0, keyTable[i].length));
}
private void insert(int i, int hash) {
if (hashTable[hash] == 0) {
hashTable[hash] = i + 1;
} else {
// need to link
int j = hashTable[hash] - 1;
while (nextTable[j] != 0)
j = nextTable[j] - 1;
nextTable[j] = i + 1;
}
}
protected void resize(int size) {
char[][] oldKeyTable = keyTable;
keyTable = new char[size][];
System.arraycopy(oldKeyTable, 0, keyTable, 0, oldKeyTable.length);
// Need to rehash everything
hashTable = new int[size * 2];
nextTable = new int[size];
for (int i = 0; i < oldKeyTable.length; ++i) {
insert(i);
}
}
private void resize() {
resize(keyTable.length << 1);
}
protected final int add(char[] buffer, int start, int len) {
int hash = hash(buffer, start, len);
if (hashTable[hash] == 0) {
if( (currEntry + 1) >= keyTable.length){
//need to recompute hash for this add, recurse.
resize();
return add( buffer, start, len );
}
currEntry++;
keyTable[currEntry] = CharArrayUtils.extract(buffer, start, len);
insert(currEntry, hash);
return currEntry;
}
// is the key already registered?
int i = hashTable[hash] - 1;
if (CharArrayUtils.equals(buffer, start, len, keyTable[i]))
// yup
return i;
// follow the next chain
int last = i;
for (i = nextTable[i] - 1; i >= 0; i = nextTable[i] - 1) {
if (CharArrayUtils.equals(buffer, start, len, keyTable[i]))
// yup this time
return i;
last = i;
}
// nope, add it in
- if (++currEntry >= keyTable.length){
+ if (currEntry + 1 >= keyTable.length){
//need to recompute hash for this add, recurse
resize();
return add( buffer, start, len );
}
currEntry++;
keyTable[currEntry] = CharArrayUtils.extract(buffer, start, len);
nextTable[last] = currEntry + 1;
return currEntry;
}
protected final int lookup(char[] buffer, int start, int len) {
int hash = hash(buffer, start, len);
if (hashTable[hash] == 0)
return -1;
int i = hashTable[hash] - 1;
if (CharArrayUtils.equals(buffer, start, len, keyTable[i]))
return i;
// Follow the next chain
for (i = nextTable[i] - 1; i >= 0; i = nextTable[i] - 1)
if (CharArrayUtils.equals(buffer, start, len, keyTable[i]))
return i;
return -1;
}
protected void removeEntry(int i) {
// Remove the hash entry
int hash = hash(keyTable[i]);
if (hashTable[hash] == i + 1)
hashTable[hash] = nextTable[i];
else {
// find entry pointing to me
int j = hashTable[hash] - 1;
while (nextTable[j] != 0 && nextTable[j] != i + 1)
j = nextTable[j] - 1;
nextTable[j] = nextTable[i];
}
if (i < currEntry) {
// shift everything over
System.arraycopy(keyTable, i + 1, keyTable, i, currEntry - i);
System.arraycopy(nextTable, i + 1, nextTable, i, currEntry - i);
// adjust hash and next entries for things that moved
for (int j = 0; j < hashTable.length; ++j)
if (hashTable[j] > i)
--hashTable[j];
for (int j = 0; j < nextTable.length; ++j)
if (nextTable[j] > i)
--nextTable[j];
}
// last entry is now free
keyTable[currEntry] = null;
nextTable[currEntry] = 0;
--currEntry;
}
public void dumpNexts() {
for (int i = 0; i < nextTable.length; ++i) {
if (nextTable[i] == 0)
continue;
System.out.print(i);
for (int j = nextTable[i] - 1; j >= 0; j = nextTable[j] - 1)
System.out.print(" -> " + j); //$NON-NLS-1$
System.out.println(""); //$NON-NLS-1$
}
}
}
| true | true | protected final int add(char[] buffer, int start, int len) {
int hash = hash(buffer, start, len);
if (hashTable[hash] == 0) {
if( (currEntry + 1) >= keyTable.length){
//need to recompute hash for this add, recurse.
resize();
return add( buffer, start, len );
}
currEntry++;
keyTable[currEntry] = CharArrayUtils.extract(buffer, start, len);
insert(currEntry, hash);
return currEntry;
}
// is the key already registered?
int i = hashTable[hash] - 1;
if (CharArrayUtils.equals(buffer, start, len, keyTable[i]))
// yup
return i;
// follow the next chain
int last = i;
for (i = nextTable[i] - 1; i >= 0; i = nextTable[i] - 1) {
if (CharArrayUtils.equals(buffer, start, len, keyTable[i]))
// yup this time
return i;
last = i;
}
// nope, add it in
if (++currEntry >= keyTable.length){
//need to recompute hash for this add, recurse
resize();
return add( buffer, start, len );
}
currEntry++;
keyTable[currEntry] = CharArrayUtils.extract(buffer, start, len);
nextTable[last] = currEntry + 1;
return currEntry;
}
| protected final int add(char[] buffer, int start, int len) {
int hash = hash(buffer, start, len);
if (hashTable[hash] == 0) {
if( (currEntry + 1) >= keyTable.length){
//need to recompute hash for this add, recurse.
resize();
return add( buffer, start, len );
}
currEntry++;
keyTable[currEntry] = CharArrayUtils.extract(buffer, start, len);
insert(currEntry, hash);
return currEntry;
}
// is the key already registered?
int i = hashTable[hash] - 1;
if (CharArrayUtils.equals(buffer, start, len, keyTable[i]))
// yup
return i;
// follow the next chain
int last = i;
for (i = nextTable[i] - 1; i >= 0; i = nextTable[i] - 1) {
if (CharArrayUtils.equals(buffer, start, len, keyTable[i]))
// yup this time
return i;
last = i;
}
// nope, add it in
if (currEntry + 1 >= keyTable.length){
//need to recompute hash for this add, recurse
resize();
return add( buffer, start, len );
}
currEntry++;
keyTable[currEntry] = CharArrayUtils.extract(buffer, start, len);
nextTable[last] = currEntry + 1;
return currEntry;
}
|
diff --git a/src/main/java/org/codinjutsu/tools/jenkins/logic/JenkinsRequestManager.java b/src/main/java/org/codinjutsu/tools/jenkins/logic/JenkinsRequestManager.java
index c12aacc..d097813 100644
--- a/src/main/java/org/codinjutsu/tools/jenkins/logic/JenkinsRequestManager.java
+++ b/src/main/java/org/codinjutsu/tools/jenkins/logic/JenkinsRequestManager.java
@@ -1,357 +1,360 @@
/*
* Copyright (c) 2012 David Boissier
*
* 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.codinjutsu.tools.jenkins.logic;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.CharSequenceReader;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codinjutsu.tools.jenkins.JenkinsConfiguration;
import org.codinjutsu.tools.jenkins.exception.ConfigurationException;
import org.codinjutsu.tools.jenkins.model.*;
import org.codinjutsu.tools.jenkins.security.SecurityClient;
import org.codinjutsu.tools.jenkins.security.SecurityClientFactory;
import org.codinjutsu.tools.jenkins.security.SecurityMode;
import org.codinjutsu.tools.jenkins.util.RssUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import java.io.IOException;
import java.net.URL;
import java.util.*;
public class JenkinsRequestManager {
private static final String JENKINS_DESCRIPTION = "description";
private static final String JOB = "job";
private static final String JOB_NAME = "name";
private static final String JOB_HEALTH = "healthReport";
private static final String JOB_HEALTH_ICON = "iconUrl";
private static final String JOB_HEALTH_DESCRIPTION = "description";
private static final String JOB_URL = "url";
private static final String JOB_COLOR = "color";
private static final String JOB_LAST_BUILD = "lastBuild";
private static final String JOB_IS_BUILDABLE = "buildable";
private static final String JOB_IS_IN_QUEUE = "inQueue";
private static final String VIEW = "view";
private static final String PRIMARY_VIEW = "primaryView";
private static final String VIEW_NAME = "name";
private static final String VIEW_URL = "url";
private static final String BUILD_IS_BUILDING = "building";
private static final String BUILD_ID = "id";
private static final String BUILD_RESULT = "result";
private static final String BUILD_URL = "url";
private static final String BUILD_NUMBER = "number";
private static final String PARAMETER_PROPERTY = "property";
private static final String PARAMETER_DEFINITION = "parameterDefinition";
private static final String PARAMETER_NAME = "name";
private static final String PARAMETER_TYPE = "type";
private static final String PARAMETER_DEFAULT_PARAM = "defaultParameterValue";
private static final String PARAMETER_DEFAULT_PARAM_VALUE = "value";
private static final String PARAMETER_CHOICE = "choice";
private static final String RSS_ENTRY = "entry";
private static final String RSS_TITLE = "title";
private static final String RSS_LINK = "link";
private static final String RSS_LINK_HREF = "href";
private static final String RSS_PUBLISHED = "published";
private static final String JENKINS_ROOT_TAG = "jenkins";
private static final String HUDSON_ROOT_TAG = "hudson";
private static final Logger LOG = Logger.getLogger(JenkinsRequestManager.class);
private final UrlBuilder urlBuilder;
private SecurityClient securityClient;
public JenkinsRequestManager(String crumbDataFile) {
this(SecurityClientFactory.none(crumbDataFile));
}
public JenkinsRequestManager(SecurityClient securityClient) {
this.urlBuilder = new UrlBuilder();
this.securityClient = securityClient;
}
public Jenkins loadJenkinsWorkspace(JenkinsConfiguration configuration) {
URL url = urlBuilder.createJenkinsWorkspaceUrl(configuration);
String jenkinsWorkspaceData = securityClient.execute(url);
Document doc = buildDocument(jenkinsWorkspaceData);
Jenkins jenkins = createJenkins(doc, configuration.getServerUrl());
jenkins.setPrimaryView(createPreferredView(doc));
jenkins.setViews(createJenkinsViews(doc));
return jenkins;
}
public Map<String, Build> loadJenkinsRssLatestBuilds(JenkinsConfiguration configuration) {
URL url = urlBuilder.createRssLatestUrl(configuration.getServerUrl());
String rssData = securityClient.execute(url);
Document doc = buildDocument(rssData);
return createLatestBuildList(doc);
}
public List<Job> loadJenkinsView(String viewUrl) {
URL url = urlBuilder.createViewUrl(viewUrl);
String jenkinsViewData = securityClient.execute(url);
Document doc = buildDocument(jenkinsViewData);
return createJenkinsJobs(doc);
}
public Job loadJob(String jenkinsJobUrl) {
URL url = urlBuilder.createJobUrl(jenkinsJobUrl);
String jenkinsJobData = securityClient.execute(url);
Document doc = buildDocument(jenkinsJobData);
Element jobElement = doc.getRootElement();
return createJob(jobElement);
}
private Document buildDocument(String jenkinsXmlData) {
CharSequenceReader jenkinsDataReader = new CharSequenceReader(jenkinsXmlData);
try {
return getXMLBuilder().build(jenkinsDataReader);
} catch (JDOMException e) {
LOG.error("Unexpected xml document. Actual :\n" + jenkinsXmlData, e);
throw new RuntimeException("Unexpected xml document. See IntelliJ logs.");
} catch (IOException e) {
LOG.error("Error during reading the xml response.", e);
throw new RuntimeException("Error during reading the xml response. See IntelliJ logs.");
} finally {
IOUtils.closeQuietly(jenkinsDataReader);
}
}
public void runBuild(Job job, JenkinsConfiguration configuration) {
URL url = urlBuilder.createRunJobUrl(job.getUrl(), configuration);
securityClient.execute(url);
}
public void runParameterizedBuild(Job job, JenkinsConfiguration configuration, Map<String, String> paramValueMap) {
URL url = urlBuilder.createRunParameterizedJobUrl(job.getUrl(), configuration, paramValueMap);
securityClient.execute(url);
}
public void authenticate(final String serverUrl, SecurityMode securityMode, final String username, final String passwordFile, String crumbDataFile) {
securityClient = SecurityClientFactory.create(securityMode, username, passwordFile, crumbDataFile);
securityClient.connect(urlBuilder.createAuthenticationUrl(serverUrl));
}
private Jenkins createJenkins(Document doc, String serverUrl) {
Element jenkinsElement = doc.getRootElement();
if (!StringUtils.equals(JENKINS_ROOT_TAG, jenkinsElement.getName())
&& !StringUtils.equals(HUDSON_ROOT_TAG, jenkinsElement.getName())) {
throw new ConfigurationException("The root tag is should be 'hudson'. Actual : '" + jenkinsElement.getName() + "'");
}
String description = jenkinsElement.getChildText(JENKINS_DESCRIPTION);
if (description == null) {
description = "";
}
return new Jenkins(description, serverUrl);
}
private Build createLastBuild(Element jobLastBuild) {
String isBuilding = jobLastBuild.getChildText(BUILD_IS_BUILDING);
String isSuccess = jobLastBuild.getChildText(BUILD_RESULT);
String number = jobLastBuild.getChildText(BUILD_NUMBER);
String buildUrl = jobLastBuild.getChildText(BUILD_URL);
String date = jobLastBuild.getChildText(BUILD_ID);
return Build.createBuildFromWorkspace(buildUrl, number, isSuccess, isBuilding, date);
}
private View createPreferredView(Document doc) {
Element primaryView = doc.getRootElement().getChild(PRIMARY_VIEW);
if (primaryView != null) {
String viewName = primaryView.getChildText(VIEW_NAME);
String viewUrl = primaryView.getChildText(VIEW_URL);
return View.createView(viewName, viewUrl);
}
return null;
}
private List<View> createJenkinsViews(Document doc) {
List<View> views = new ArrayList<View>();
List<Element> viewElement = doc.getRootElement().getChildren(VIEW);
for (Element element : viewElement) {
String viewName = element.getChildText(VIEW_NAME);
String viewUrl = element.getChildText(VIEW_URL);
View view = View.createView(viewName, viewUrl);
List<Element> subViewElements = element.getChildren(VIEW);
if (subViewElements != null && !subViewElements.isEmpty()) {
for (Element subViewElement : subViewElements) {
String subViewName = subViewElement.getChildText(VIEW_NAME);
String subViewUrl = subViewElement.getChildText(VIEW_URL);
view.addSubView(View.createNestedView(subViewName, subViewUrl));
}
}
views.add(view);
}
return views;
}
private List<Job> createJenkinsJobs(Document doc) {
List<Element> jobElements = doc.getRootElement().getChildren(JOB);
List<Job> jobs = new LinkedList<Job>();
for (Element jobElement : jobElements) {
jobs.add(createJob(jobElement));
}
return jobs;
}
private void setJobParameters(Job job, List<Element> parameterDefinitions) {
for (Element parameterDefinition : parameterDefinitions) {
String paramName = parameterDefinition.getChildText(PARAMETER_NAME);
String paramType = parameterDefinition.getChildText(PARAMETER_TYPE);
String defaultParamValue = null;
Element defaultParamElement = parameterDefinition.getChild(PARAMETER_DEFAULT_PARAM);
if (defaultParamElement != null) {
defaultParamValue = defaultParamElement.getChildText(PARAMETER_DEFAULT_PARAM_VALUE);
}
String[] choices = extractChoices(parameterDefinition);
job.addParameter(paramName, paramType, defaultParamValue, choices);
}
}
private String[] extractChoices(Element parameterDefinition) {
List<Element> choices = parameterDefinition.getChildren(PARAMETER_CHOICE);
String[] paramValues = new String[0];
if (choices != null && !choices.isEmpty()) {
paramValues = new String[choices.size()];
for (int i = 0; i < choices.size(); i++) {
Element choice = choices.get(i);
paramValues[i] = choice.getText();
}
}
return paramValues;
}
private Job createJob(Element jobElement) {
String jobName = jobElement.getChildText(JOB_NAME);
String jobColor = jobElement.getChildText(JOB_COLOR);
String jobUrl = jobElement.getChildText(JOB_URL);
String inQueue = jobElement.getChildText(JOB_IS_IN_QUEUE);
String buildable = jobElement.getChildText(JOB_IS_BUILDABLE);
Job job = Job.createJob(jobName, jobColor, jobUrl, inQueue, buildable);
Job.Health jobHealth = getJobHealth(jobElement);
if (jobHealth != null) {
job.setHealth(jobHealth);
}
Element lastBuild = jobElement.getChild(JOB_LAST_BUILD);
if (lastBuild != null) {
job.setLastBuild(createLastBuild(lastBuild));
}
- Element property = jobElement.getChild(PARAMETER_PROPERTY);
- if (property != null) {
- setJobParameters(job, property.getChildren(PARAMETER_DEFINITION));
+ List<Element> propertyList = jobElement.getChildren(PARAMETER_PROPERTY);
+ for (Element property : propertyList) {
+ List parameterDefinitions = property.getChildren(PARAMETER_DEFINITION);
+ if (!parameterDefinitions.isEmpty()) {
+ setJobParameters(job, parameterDefinitions);
+ }
}
return job;
}
private Job.Health getJobHealth(Element jobElement) {
String jobHealthLevel = null;
String jobHealthDescription = null;
Element jobHealthElement = jobElement.getChild(JOB_HEALTH);
if (jobHealthElement != null) {
jobHealthLevel = jobHealthElement.getChildText(JOB_HEALTH_ICON);
if (StringUtils.isNotEmpty(jobHealthLevel)) {
if (jobHealthLevel.endsWith(".png"))
jobHealthLevel = jobHealthLevel.substring(0, jobHealthLevel.lastIndexOf(".png"));
else {
jobHealthLevel = jobHealthLevel.substring(0, jobHealthLevel.lastIndexOf(".gif"));
}
} else {
jobHealthLevel = null;
}
jobHealthDescription = jobHealthElement.getChildText(JOB_HEALTH_DESCRIPTION);
}
if (!StringUtils.isEmpty(jobHealthLevel)) {
return Job.Health.createHealth(jobHealthLevel, jobHealthDescription);
}
return null;
}
private Map<String, Build> createLatestBuildList(Document doc) {
Map<String, Build> buildMap = new LinkedHashMap<String, Build>();
Element rootElement = doc.getRootElement();
List<Element> elements = rootElement.getChildren(RSS_ENTRY, rootElement.getNamespace());
for (Element element : elements) {
String title = element.getChildText(RSS_TITLE, rootElement.getNamespace());
String publishedBuild = element.getChildText(RSS_PUBLISHED, rootElement.getNamespace());
String jobName = RssUtil.extractBuildJob(title);
String number = RssUtil.extractBuildNumber(title);
BuildStatusEnum status = RssUtil.extractStatus(title);
Element linkElement = element.getChild(RSS_LINK, rootElement.getNamespace());
String link = linkElement.getAttributeValue(RSS_LINK_HREF);
if (!BuildStatusEnum.NULL.equals(status)) {
buildMap.put(jobName, Build.createBuildFromRss(link, number, status.getStatus(), Boolean.FALSE.toString(), publishedBuild, title));
}
}
return buildMap;
}
private static SAXBuilder getXMLBuilder() {
SAXBuilder saxBuilder = new SAXBuilder();
saxBuilder.setValidation(false);
return saxBuilder;
}
}
| true | true | private Job createJob(Element jobElement) {
String jobName = jobElement.getChildText(JOB_NAME);
String jobColor = jobElement.getChildText(JOB_COLOR);
String jobUrl = jobElement.getChildText(JOB_URL);
String inQueue = jobElement.getChildText(JOB_IS_IN_QUEUE);
String buildable = jobElement.getChildText(JOB_IS_BUILDABLE);
Job job = Job.createJob(jobName, jobColor, jobUrl, inQueue, buildable);
Job.Health jobHealth = getJobHealth(jobElement);
if (jobHealth != null) {
job.setHealth(jobHealth);
}
Element lastBuild = jobElement.getChild(JOB_LAST_BUILD);
if (lastBuild != null) {
job.setLastBuild(createLastBuild(lastBuild));
}
Element property = jobElement.getChild(PARAMETER_PROPERTY);
if (property != null) {
setJobParameters(job, property.getChildren(PARAMETER_DEFINITION));
}
return job;
}
| private Job createJob(Element jobElement) {
String jobName = jobElement.getChildText(JOB_NAME);
String jobColor = jobElement.getChildText(JOB_COLOR);
String jobUrl = jobElement.getChildText(JOB_URL);
String inQueue = jobElement.getChildText(JOB_IS_IN_QUEUE);
String buildable = jobElement.getChildText(JOB_IS_BUILDABLE);
Job job = Job.createJob(jobName, jobColor, jobUrl, inQueue, buildable);
Job.Health jobHealth = getJobHealth(jobElement);
if (jobHealth != null) {
job.setHealth(jobHealth);
}
Element lastBuild = jobElement.getChild(JOB_LAST_BUILD);
if (lastBuild != null) {
job.setLastBuild(createLastBuild(lastBuild));
}
List<Element> propertyList = jobElement.getChildren(PARAMETER_PROPERTY);
for (Element property : propertyList) {
List parameterDefinitions = property.getChildren(PARAMETER_DEFINITION);
if (!parameterDefinitions.isEmpty()) {
setJobParameters(job, parameterDefinitions);
}
}
return job;
}
|
diff --git a/src/main/java/se/diabol/pipefitter/PipelineFactory.java b/src/main/java/se/diabol/pipefitter/PipelineFactory.java
index eb17488..66612c7 100644
--- a/src/main/java/se/diabol/pipefitter/PipelineFactory.java
+++ b/src/main/java/se/diabol/pipefitter/PipelineFactory.java
@@ -1,58 +1,59 @@
package se.diabol.pipefitter;
import se.diabol.pipefitter.model.Pipeline;
import se.diabol.pipefitter.model.Stage;
import se.diabol.pipefitter.model.Task;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import hudson.model.AbstractProject;
import se.diabol.pipefitter.model.Pipeline;
import se.diabol.pipefitter.model.Stage;
import se.diabol.pipefitter.model.Task;
import se.diabol.pipefitter.model.status.StatusFactory;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static se.diabol.pipefitter.model.status.StatusFactory.idle;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static java.util.Collections.singleton;
/**
* @author Per Huss <[email protected]>
*/
public class PipelineFactory
{
static List<AbstractProject> getAllDownstreamJobs(AbstractProject first) {
List<AbstractProject> jobs = newArrayList();
jobs.add(first);
List<AbstractProject> downstreamProjects = first.getDownstreamProjects();
for (AbstractProject project : downstreamProjects) {
jobs.addAll(getAllDownstreamJobs(project));
}
return jobs;
}
public static Pipeline extractPipeline(String name, AbstractProject<?, ?> firstJob)
{
Map<String, Stage> stages = newLinkedHashMap();
for (AbstractProject job : getAllDownstreamJobs(firstJob))
{
PipelineProperty property = (PipelineProperty) job.getProperty(PipelineProperty.class);
- Task task = new Task(job.getDisplayName(), StatusFactory.idle()); // todo: Null not idle
- String stageName = property != null? property.getStageName(): job.getDisplayName();
+ String taskName = property != null && !property.getTaskName().equals("") ? property.getTaskName(): job.getDisplayName();
+ Task task = new Task(taskName, StatusFactory.idle()); // todo: Null not idle
+ String stageName = property != null && !property.getStageName().equals("")? property.getStageName(): job.getDisplayName();
Stage stage = stages.get(stageName);
if(stage == null)
stage = new Stage(stageName, Collections.<Task>emptyList());
stages.put(stageName,
new Stage(stage.getName(), newArrayList(concat(stage.getTasks(), singleton(task)))));
}
return new Pipeline(name, newArrayList(stages.values()));
}
}
| true | true | public static Pipeline extractPipeline(String name, AbstractProject<?, ?> firstJob)
{
Map<String, Stage> stages = newLinkedHashMap();
for (AbstractProject job : getAllDownstreamJobs(firstJob))
{
PipelineProperty property = (PipelineProperty) job.getProperty(PipelineProperty.class);
Task task = new Task(job.getDisplayName(), StatusFactory.idle()); // todo: Null not idle
String stageName = property != null? property.getStageName(): job.getDisplayName();
Stage stage = stages.get(stageName);
if(stage == null)
stage = new Stage(stageName, Collections.<Task>emptyList());
stages.put(stageName,
new Stage(stage.getName(), newArrayList(concat(stage.getTasks(), singleton(task)))));
}
return new Pipeline(name, newArrayList(stages.values()));
}
| public static Pipeline extractPipeline(String name, AbstractProject<?, ?> firstJob)
{
Map<String, Stage> stages = newLinkedHashMap();
for (AbstractProject job : getAllDownstreamJobs(firstJob))
{
PipelineProperty property = (PipelineProperty) job.getProperty(PipelineProperty.class);
String taskName = property != null && !property.getTaskName().equals("") ? property.getTaskName(): job.getDisplayName();
Task task = new Task(taskName, StatusFactory.idle()); // todo: Null not idle
String stageName = property != null && !property.getStageName().equals("")? property.getStageName(): job.getDisplayName();
Stage stage = stages.get(stageName);
if(stage == null)
stage = new Stage(stageName, Collections.<Task>emptyList());
stages.put(stageName,
new Stage(stage.getName(), newArrayList(concat(stage.getTasks(), singleton(task)))));
}
return new Pipeline(name, newArrayList(stages.values()));
}
|
diff --git a/TFC_Shared/src/TFC/Containers/ContainerTFC.java b/TFC_Shared/src/TFC/Containers/ContainerTFC.java
index ec6465748..a334dfc70 100644
--- a/TFC_Shared/src/TFC/Containers/ContainerTFC.java
+++ b/TFC_Shared/src/TFC/Containers/ContainerTFC.java
@@ -1,123 +1,127 @@
package TFC.Containers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class ContainerTFC extends Container
{
@Override
public boolean canInteractWith(EntityPlayer var1) {
// TODO Auto-generated method stub
return true;
}
@Override
protected boolean mergeItemStack(ItemStack is, int slotStart, int slotFinish, boolean par4)
{
boolean var5 = false;
int slotIndex = slotStart;
if (par4)
{
slotIndex = slotFinish - 1;
}
Slot slot;
ItemStack slotstack;
if (is.isStackable())
{
while (is.stackSize > 0 && (!par4 && slotIndex < slotFinish || par4 && slotIndex >= slotStart))
{
slot = (Slot)this.inventorySlots.get(slotIndex);
slotstack = slot.getStack();
- if (slotstack != null && slotstack.itemID == is.itemID && (!is.getHasSubtypes() || is.getItemDamage() == slotstack.getItemDamage()) && ItemStack.areItemStackTagsEqual(is, slotstack) &&
- slotstack.stackSize < slot.getSlotStackLimit())
+ if (slotstack != null
+ && slotstack.itemID == is.itemID
+ && !is.getHasSubtypes()
+ && is.getItemDamage() == slotstack.getItemDamage()
+ && ItemStack.areItemStackTagsEqual(is, slotstack)
+ && slotstack.stackSize < slot.getSlotStackLimit())
{
int mergedStackSize = is.stackSize + getSmaller(slotstack.stackSize, slot.getSlotStackLimit());
//First we check if we can add the two stacks together and the resulting stack is smaller than the maximum size for the slot or the stack
if (mergedStackSize <= is.getMaxStackSize() && mergedStackSize <= slot.getSlotStackLimit())
{
is.stackSize = 0;
slotstack.stackSize = mergedStackSize;
slot.onSlotChanged();
var5 = true;
}
else if (slotstack.stackSize < is.getMaxStackSize())
{
is.stackSize -= is.getMaxStackSize() - slotstack.stackSize;
slotstack.stackSize = is.getMaxStackSize();
slot.onSlotChanged();
var5 = true;
}
}
if (par4)
{
--slotIndex;
}
else
{
++slotIndex;
}
}
}
if (is.stackSize > 0)
{
if (par4)
{
slotIndex = slotFinish - 1;
}
else
{
slotIndex = slotStart;
}
while (!par4 && slotIndex < slotFinish || par4 && slotIndex >= slotStart)
{
slot = (Slot)this.inventorySlots.get(slotIndex);
slotstack = slot.getStack();
if (slotstack == null && slot.isItemValid(is) && slot.getSlotStackLimit() < is.stackSize)
{
slot.putStack(is.copy());
slot.onSlotChanged();
is.stackSize -= slot.getSlotStackLimit();
var5 = true;
break;
}
else if (slotstack == null && slot.isItemValid(is))
{
slot.putStack(is.copy());
slot.onSlotChanged();
is.stackSize = 0;
var5 = true;
break;
}
if (par4)
{
--slotIndex;
}
else
{
++slotIndex;
}
}
}
return var5;
}
protected int getSmaller(int i, int j)
{
if(i < j) return i;
else return j;
}
}
| true | true | protected boolean mergeItemStack(ItemStack is, int slotStart, int slotFinish, boolean par4)
{
boolean var5 = false;
int slotIndex = slotStart;
if (par4)
{
slotIndex = slotFinish - 1;
}
Slot slot;
ItemStack slotstack;
if (is.isStackable())
{
while (is.stackSize > 0 && (!par4 && slotIndex < slotFinish || par4 && slotIndex >= slotStart))
{
slot = (Slot)this.inventorySlots.get(slotIndex);
slotstack = slot.getStack();
if (slotstack != null && slotstack.itemID == is.itemID && (!is.getHasSubtypes() || is.getItemDamage() == slotstack.getItemDamage()) && ItemStack.areItemStackTagsEqual(is, slotstack) &&
slotstack.stackSize < slot.getSlotStackLimit())
{
int mergedStackSize = is.stackSize + getSmaller(slotstack.stackSize, slot.getSlotStackLimit());
//First we check if we can add the two stacks together and the resulting stack is smaller than the maximum size for the slot or the stack
if (mergedStackSize <= is.getMaxStackSize() && mergedStackSize <= slot.getSlotStackLimit())
{
is.stackSize = 0;
slotstack.stackSize = mergedStackSize;
slot.onSlotChanged();
var5 = true;
}
else if (slotstack.stackSize < is.getMaxStackSize())
{
is.stackSize -= is.getMaxStackSize() - slotstack.stackSize;
slotstack.stackSize = is.getMaxStackSize();
slot.onSlotChanged();
var5 = true;
}
}
if (par4)
{
--slotIndex;
}
else
{
++slotIndex;
}
}
}
if (is.stackSize > 0)
{
if (par4)
{
slotIndex = slotFinish - 1;
}
else
{
slotIndex = slotStart;
}
while (!par4 && slotIndex < slotFinish || par4 && slotIndex >= slotStart)
{
slot = (Slot)this.inventorySlots.get(slotIndex);
slotstack = slot.getStack();
if (slotstack == null && slot.isItemValid(is) && slot.getSlotStackLimit() < is.stackSize)
{
slot.putStack(is.copy());
slot.onSlotChanged();
is.stackSize -= slot.getSlotStackLimit();
var5 = true;
break;
}
else if (slotstack == null && slot.isItemValid(is))
{
slot.putStack(is.copy());
slot.onSlotChanged();
is.stackSize = 0;
var5 = true;
break;
}
if (par4)
{
--slotIndex;
}
else
{
++slotIndex;
}
}
}
return var5;
}
| protected boolean mergeItemStack(ItemStack is, int slotStart, int slotFinish, boolean par4)
{
boolean var5 = false;
int slotIndex = slotStart;
if (par4)
{
slotIndex = slotFinish - 1;
}
Slot slot;
ItemStack slotstack;
if (is.isStackable())
{
while (is.stackSize > 0 && (!par4 && slotIndex < slotFinish || par4 && slotIndex >= slotStart))
{
slot = (Slot)this.inventorySlots.get(slotIndex);
slotstack = slot.getStack();
if (slotstack != null
&& slotstack.itemID == is.itemID
&& !is.getHasSubtypes()
&& is.getItemDamage() == slotstack.getItemDamage()
&& ItemStack.areItemStackTagsEqual(is, slotstack)
&& slotstack.stackSize < slot.getSlotStackLimit())
{
int mergedStackSize = is.stackSize + getSmaller(slotstack.stackSize, slot.getSlotStackLimit());
//First we check if we can add the two stacks together and the resulting stack is smaller than the maximum size for the slot or the stack
if (mergedStackSize <= is.getMaxStackSize() && mergedStackSize <= slot.getSlotStackLimit())
{
is.stackSize = 0;
slotstack.stackSize = mergedStackSize;
slot.onSlotChanged();
var5 = true;
}
else if (slotstack.stackSize < is.getMaxStackSize())
{
is.stackSize -= is.getMaxStackSize() - slotstack.stackSize;
slotstack.stackSize = is.getMaxStackSize();
slot.onSlotChanged();
var5 = true;
}
}
if (par4)
{
--slotIndex;
}
else
{
++slotIndex;
}
}
}
if (is.stackSize > 0)
{
if (par4)
{
slotIndex = slotFinish - 1;
}
else
{
slotIndex = slotStart;
}
while (!par4 && slotIndex < slotFinish || par4 && slotIndex >= slotStart)
{
slot = (Slot)this.inventorySlots.get(slotIndex);
slotstack = slot.getStack();
if (slotstack == null && slot.isItemValid(is) && slot.getSlotStackLimit() < is.stackSize)
{
slot.putStack(is.copy());
slot.onSlotChanged();
is.stackSize -= slot.getSlotStackLimit();
var5 = true;
break;
}
else if (slotstack == null && slot.isItemValid(is))
{
slot.putStack(is.copy());
slot.onSlotChanged();
is.stackSize = 0;
var5 = true;
break;
}
if (par4)
{
--slotIndex;
}
else
{
++slotIndex;
}
}
}
return var5;
}
|
diff --git a/src/model/Snake.java b/src/model/Snake.java
index b14360c..f1b60e2 100644
--- a/src/model/Snake.java
+++ b/src/model/Snake.java
@@ -1,284 +1,286 @@
package model;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import controller.ConvertLedType;
/**
* Snake has a position, speed, length
*
* @author Spencer Owen
* @version 1.0
*/
public class Snake
{
public Logger logger = Logger.getLogger(this.getClass() );
private int color;
private int length;
private int speed;
private long lastMoveTime;
/*Travel Direction
* 0 = north
* 1 = east
* 2 = south
* 3 = west
* 4 = up
* 5 = down
*/
private int travelDirection;
private int score;
private ArrayList<Integer> bodyPositions;
private boolean alive;
/*
* Constructor for objects of class Snake
*/
public Snake(int color, int travelDirection, ArrayList<Integer> bodyPositions, int speed)
{
logger.debug("Calling snake constructor with color = int (instead of string)" );
logger.info("Creating a Snake, color=" + color + " travelDirection=" + travelDirection );
this.color = color;
this.length = 3;
this.speed = speed;
this.lastMoveTime = System.currentTimeMillis();
this.travelDirection = travelDirection;
this.score = 0;
this.bodyPositions = bodyPositions;
this.alive = true;
}
public Snake(String color, int travelDirection, ArrayList<Integer> bodyPositions, int speed)
{
logger.debug("Calling snake constructor with color = string (instead of int)" );
logger.info("Creating a Snake, color=" + color + " travelDirection=" + travelDirection );
//Allow user to pass in "FFFFFF" and then convert it to the number
//integers are faster to compute than strings
this.color = ConvertLedType.hexToInt(color);
this.length = 3;
this.speed = speed;
this.lastMoveTime = System.currentTimeMillis();
this.travelDirection = travelDirection;
this.score = 0;
this.bodyPositions = bodyPositions;
this.alive = true;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public void setColor(String color) {
this.color = ConvertLedType.hexToInt(color);
}
public int getLength() {
return length;
}
public void setLength(int length) {
//TODO: This should not be negative, or greater than the number of leds per cube (4096) in our case;
this.length = length;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
//TODO:This should not be negative
this.speed = speed;
}
public int getTravelDirection() {
return travelDirection;
}
public void setTravelDirection(int travelDirection) {
//TODO: Should not be any number except 0 - 5
/*
* Travel Direction
* 0 = north //z++
* 1 = east //x++
* 2 = south //z--
* 3 = west //x--
* 4 = up //y++
* 5 = down //y--
*/
/*
* The user should not be able to set their direction to 180 degrees opposite
* If they try to, ignore it, but add it to the logs
* Example; Travel Direction = north, user can not set direction to south
* Example; Travel Direction = west, user can not set direction to east
*/
this.travelDirection = travelDirection;
logger.debug("TravelDirection set to " + travelDirection);
}
public int getScore() {
return score;
}
public void setScore(int score) {
//TODO: allow negative scores
//TODO: test that we are within 65,000 the maximum of Integer
//Add the additional points to the existing score
this.score = this.score + score;
}
/**
* Returns an arrayList of the positions of the snake
* All positions are in absolute values and assume origin = 0 (not 1)
* Example a snake 4 long might return -> bodyPositions[31,32,33,34]
* @return
*/
public ArrayList<Integer> getBodyPositions() {
return bodyPositions;
}
public void setBodyPositions(ArrayList<Integer> bodyPositions) {
//TODO: non of the items should be negative
//Is is it really worth checking this? It would be expensive
this.bodyPositions = bodyPositions;
}
/**
* Returns true if user is alive, false if user is dead
*
* @return alive
*/
public boolean isAlive() {
return alive;
}
public void setAlive(boolean alive) {
//TODO: if we try and set the state to a state we are already in, we should log it
this.alive = alive;
}
public long getLastMoveTime() {
return lastMoveTime;
}
public void setLastMoveTime(long lastMoveTime) {
this.lastMoveTime = lastMoveTime;
}
public void advanceForward()
{
//TODO: Logic to shift arrayList
ArrayList<Integer> anArrayList = this.getBodyPositions();
int headPosition = anArrayList.get(0);
int headPositionX = controller.ConvertLedType.absoluteToXPositionInRow(headPosition);
int headPositionY = controller.ConvertLedType.absoluteToYPositionInPanel(headPosition);
int headPositionZ = controller.ConvertLedType.absoluteToZPositionInCube(headPosition);
/*
* Travel Direction
* 0 = north //z++
* 1 = east //x++
* 2 = south //z--
* 3 = west //x--
* 4 = up //y++
* 5 = down //y--
*/
int direction = this.getTravelDirection();
if( direction == 0)
{
//add 1 to z because we are moving north
headPositionZ++;
}
else if(direction == 1)
{
//add 1 to x because we are moving east
headPositionX++;
}
else if(direction == 2)
{
//subtract 1 from z because we are moving south
headPositionZ--;
}
else if(direction == 3)
{
//subtract 1 from x because we are moving west
headPositionX--;
}
else if(direction == 4)
{
//add 1 to y because we are moving up
+ logger.debug("snake direction = down, (5 should = " + direction +" Incrementing Head position (y) by 1");
headPositionY++;
}
else if(direction == 5)
{
//subtract 1 from y because we are moving down
- headPositionY++;
+ logger.debug("snake direction = down, (5 should = " + direction +" Decrementing Head position (y) by 1");
+ headPositionY--;
}
else
{
throw new IllegalStateException("SnakeController.advanceForward() must receive a direction between 0 and 5, received: " + direction );
}
//Save new position to array after we convert it back
anArrayList.add( 0, ConvertLedType.relativeToAbsolute( headPositionX, headPositionY, headPositionZ ));
System.out.println("Snake is now at "+ anArrayList.get(0));
//Save new array to Snake Bean
this.setBodyPositions( anArrayList );
//Mark the arrayList null so it will be cleaned up by the garbage collector
anArrayList = null;
}
}
| false | true | public void advanceForward()
{
//TODO: Logic to shift arrayList
ArrayList<Integer> anArrayList = this.getBodyPositions();
int headPosition = anArrayList.get(0);
int headPositionX = controller.ConvertLedType.absoluteToXPositionInRow(headPosition);
int headPositionY = controller.ConvertLedType.absoluteToYPositionInPanel(headPosition);
int headPositionZ = controller.ConvertLedType.absoluteToZPositionInCube(headPosition);
/*
* Travel Direction
* 0 = north //z++
* 1 = east //x++
* 2 = south //z--
* 3 = west //x--
* 4 = up //y++
* 5 = down //y--
*/
int direction = this.getTravelDirection();
if( direction == 0)
{
//add 1 to z because we are moving north
headPositionZ++;
}
else if(direction == 1)
{
//add 1 to x because we are moving east
headPositionX++;
}
else if(direction == 2)
{
//subtract 1 from z because we are moving south
headPositionZ--;
}
else if(direction == 3)
{
//subtract 1 from x because we are moving west
headPositionX--;
}
else if(direction == 4)
{
//add 1 to y because we are moving up
headPositionY++;
}
else if(direction == 5)
{
//subtract 1 from y because we are moving down
headPositionY++;
}
else
{
throw new IllegalStateException("SnakeController.advanceForward() must receive a direction between 0 and 5, received: " + direction );
}
//Save new position to array after we convert it back
anArrayList.add( 0, ConvertLedType.relativeToAbsolute( headPositionX, headPositionY, headPositionZ ));
System.out.println("Snake is now at "+ anArrayList.get(0));
//Save new array to Snake Bean
this.setBodyPositions( anArrayList );
//Mark the arrayList null so it will be cleaned up by the garbage collector
anArrayList = null;
}
| public void advanceForward()
{
//TODO: Logic to shift arrayList
ArrayList<Integer> anArrayList = this.getBodyPositions();
int headPosition = anArrayList.get(0);
int headPositionX = controller.ConvertLedType.absoluteToXPositionInRow(headPosition);
int headPositionY = controller.ConvertLedType.absoluteToYPositionInPanel(headPosition);
int headPositionZ = controller.ConvertLedType.absoluteToZPositionInCube(headPosition);
/*
* Travel Direction
* 0 = north //z++
* 1 = east //x++
* 2 = south //z--
* 3 = west //x--
* 4 = up //y++
* 5 = down //y--
*/
int direction = this.getTravelDirection();
if( direction == 0)
{
//add 1 to z because we are moving north
headPositionZ++;
}
else if(direction == 1)
{
//add 1 to x because we are moving east
headPositionX++;
}
else if(direction == 2)
{
//subtract 1 from z because we are moving south
headPositionZ--;
}
else if(direction == 3)
{
//subtract 1 from x because we are moving west
headPositionX--;
}
else if(direction == 4)
{
//add 1 to y because we are moving up
logger.debug("snake direction = down, (5 should = " + direction +" Incrementing Head position (y) by 1");
headPositionY++;
}
else if(direction == 5)
{
//subtract 1 from y because we are moving down
logger.debug("snake direction = down, (5 should = " + direction +" Decrementing Head position (y) by 1");
headPositionY--;
}
else
{
throw new IllegalStateException("SnakeController.advanceForward() must receive a direction between 0 and 5, received: " + direction );
}
//Save new position to array after we convert it back
anArrayList.add( 0, ConvertLedType.relativeToAbsolute( headPositionX, headPositionY, headPositionZ ));
System.out.println("Snake is now at "+ anArrayList.get(0));
//Save new array to Snake Bean
this.setBodyPositions( anArrayList );
//Mark the arrayList null so it will be cleaned up by the garbage collector
anArrayList = null;
}
|
diff --git a/demos/src/main/java/com/datatorrent/demos/visualdata/Application.java b/demos/src/main/java/com/datatorrent/demos/visualdata/Application.java
index 34233ca0c..3bf5ad927 100644
--- a/demos/src/main/java/com/datatorrent/demos/visualdata/Application.java
+++ b/demos/src/main/java/com/datatorrent/demos/visualdata/Application.java
@@ -1,88 +1,88 @@
/*
* Copyright (c) 2013 DataTorrent, Inc. 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.datatorrent.demos.visualdata;
import java.net.URI;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import com.datatorrent.api.DAG;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.demos.pi.PiCalculateOperator;
import com.datatorrent.lib.io.ConsoleOutputOperator;
import com.datatorrent.lib.io.PubSubWebSocketOutputOperator;
import com.datatorrent.lib.testbench.RandomEventGenerator;
/**
* Visual data demo.
*/
public class Application implements StreamingApplication {
private final Locality locality = null;
@Override
public void populateDAG(DAG dag, Configuration conf) {
dag.setAttribute(DAG.APPLICATION_NAME, "VisualDataDemo");
int maxValue = 30000;
RandomEventGenerator rand = dag.addOperator("random", new RandomEventGenerator());
rand.setMinvalue(0);
rand.setMaxvalue(maxValue);
ChartValueGenerator chartValue = dag.addOperator("chartValue", new ChartValueGenerator());
chartValue.setRandomIncrement(5);
ChartValueGenerator chartValue2 = dag.addOperator("chartValue2", new ChartValueGenerator());
chartValue2.setRandomIncrement(20);
PiCalculateOperator calc = dag.addOperator("picalc", new PiCalculateOperator());
calc.setBase(maxValue * maxValue);
dag.addStream("rand_calc", rand.integer_data, calc.input).setLocality(locality);
String gatewayAddress = dag.getValue(DAG.GATEWAY_ADDRESS);
if (!StringUtils.isEmpty(gatewayAddress)) {
URI uri = URI.create("ws://" + gatewayAddress + "/pubsub");
PubSubWebSocketOutputOperator<Object> wsOut = dag.addOperator("wsOut",
new PubSubWebSocketOutputOperator<Object>());
wsOut.setUri(uri);
wsOut.setTopic("app.visualdata.piValue");
dag.addStream("ws_pi_data", calc.output, wsOut.input);
PubSubWebSocketOutputOperator<Object> wsChartOut = dag.addOperator("wsChartOut",
new PubSubWebSocketOutputOperator<Object>());
wsChartOut.setUri(uri);
wsChartOut.setTopic("app.visualdata.chartValue");
dag.addStream("ws_chart_data", chartValue.output, wsChartOut.input);
PubSubWebSocketOutputOperator<Object> wsChartOut2 = dag.addOperator("wsChartOut2",
new PubSubWebSocketOutputOperator<Object>());
- wsChartOut.setUri(uri);
- wsChartOut.setTopic("app.visualdata.chartValue2");
+ wsChartOut2.setUri(uri);
+ wsChartOut2.setTopic("app.visualdata.chartValue2");
dag.addStream("ws_chart_data2", chartValue2.output, wsChartOut2.input);
} else {
ConsoleOutputOperator console = dag.addOperator("console_out", new ConsoleOutputOperator());
dag.addStream("rand_console", calc.output, console.input).setLocality(locality);
ConsoleOutputOperator chartConsole = dag.addOperator("chart_out", new ConsoleOutputOperator());
dag.addStream("chart_console", chartValue.output, chartConsole.input).setLocality(locality);
ConsoleOutputOperator chartConsole2 = dag.addOperator("chart_out2", new ConsoleOutputOperator());
dag.addStream("chart_console2", chartValue2.output, chartConsole2.input).setLocality(locality);
}
}
}
| true | true | public void populateDAG(DAG dag, Configuration conf) {
dag.setAttribute(DAG.APPLICATION_NAME, "VisualDataDemo");
int maxValue = 30000;
RandomEventGenerator rand = dag.addOperator("random", new RandomEventGenerator());
rand.setMinvalue(0);
rand.setMaxvalue(maxValue);
ChartValueGenerator chartValue = dag.addOperator("chartValue", new ChartValueGenerator());
chartValue.setRandomIncrement(5);
ChartValueGenerator chartValue2 = dag.addOperator("chartValue2", new ChartValueGenerator());
chartValue2.setRandomIncrement(20);
PiCalculateOperator calc = dag.addOperator("picalc", new PiCalculateOperator());
calc.setBase(maxValue * maxValue);
dag.addStream("rand_calc", rand.integer_data, calc.input).setLocality(locality);
String gatewayAddress = dag.getValue(DAG.GATEWAY_ADDRESS);
if (!StringUtils.isEmpty(gatewayAddress)) {
URI uri = URI.create("ws://" + gatewayAddress + "/pubsub");
PubSubWebSocketOutputOperator<Object> wsOut = dag.addOperator("wsOut",
new PubSubWebSocketOutputOperator<Object>());
wsOut.setUri(uri);
wsOut.setTopic("app.visualdata.piValue");
dag.addStream("ws_pi_data", calc.output, wsOut.input);
PubSubWebSocketOutputOperator<Object> wsChartOut = dag.addOperator("wsChartOut",
new PubSubWebSocketOutputOperator<Object>());
wsChartOut.setUri(uri);
wsChartOut.setTopic("app.visualdata.chartValue");
dag.addStream("ws_chart_data", chartValue.output, wsChartOut.input);
PubSubWebSocketOutputOperator<Object> wsChartOut2 = dag.addOperator("wsChartOut2",
new PubSubWebSocketOutputOperator<Object>());
wsChartOut.setUri(uri);
wsChartOut.setTopic("app.visualdata.chartValue2");
dag.addStream("ws_chart_data2", chartValue2.output, wsChartOut2.input);
} else {
ConsoleOutputOperator console = dag.addOperator("console_out", new ConsoleOutputOperator());
dag.addStream("rand_console", calc.output, console.input).setLocality(locality);
ConsoleOutputOperator chartConsole = dag.addOperator("chart_out", new ConsoleOutputOperator());
dag.addStream("chart_console", chartValue.output, chartConsole.input).setLocality(locality);
ConsoleOutputOperator chartConsole2 = dag.addOperator("chart_out2", new ConsoleOutputOperator());
dag.addStream("chart_console2", chartValue2.output, chartConsole2.input).setLocality(locality);
}
}
| public void populateDAG(DAG dag, Configuration conf) {
dag.setAttribute(DAG.APPLICATION_NAME, "VisualDataDemo");
int maxValue = 30000;
RandomEventGenerator rand = dag.addOperator("random", new RandomEventGenerator());
rand.setMinvalue(0);
rand.setMaxvalue(maxValue);
ChartValueGenerator chartValue = dag.addOperator("chartValue", new ChartValueGenerator());
chartValue.setRandomIncrement(5);
ChartValueGenerator chartValue2 = dag.addOperator("chartValue2", new ChartValueGenerator());
chartValue2.setRandomIncrement(20);
PiCalculateOperator calc = dag.addOperator("picalc", new PiCalculateOperator());
calc.setBase(maxValue * maxValue);
dag.addStream("rand_calc", rand.integer_data, calc.input).setLocality(locality);
String gatewayAddress = dag.getValue(DAG.GATEWAY_ADDRESS);
if (!StringUtils.isEmpty(gatewayAddress)) {
URI uri = URI.create("ws://" + gatewayAddress + "/pubsub");
PubSubWebSocketOutputOperator<Object> wsOut = dag.addOperator("wsOut",
new PubSubWebSocketOutputOperator<Object>());
wsOut.setUri(uri);
wsOut.setTopic("app.visualdata.piValue");
dag.addStream("ws_pi_data", calc.output, wsOut.input);
PubSubWebSocketOutputOperator<Object> wsChartOut = dag.addOperator("wsChartOut",
new PubSubWebSocketOutputOperator<Object>());
wsChartOut.setUri(uri);
wsChartOut.setTopic("app.visualdata.chartValue");
dag.addStream("ws_chart_data", chartValue.output, wsChartOut.input);
PubSubWebSocketOutputOperator<Object> wsChartOut2 = dag.addOperator("wsChartOut2",
new PubSubWebSocketOutputOperator<Object>());
wsChartOut2.setUri(uri);
wsChartOut2.setTopic("app.visualdata.chartValue2");
dag.addStream("ws_chart_data2", chartValue2.output, wsChartOut2.input);
} else {
ConsoleOutputOperator console = dag.addOperator("console_out", new ConsoleOutputOperator());
dag.addStream("rand_console", calc.output, console.input).setLocality(locality);
ConsoleOutputOperator chartConsole = dag.addOperator("chart_out", new ConsoleOutputOperator());
dag.addStream("chart_console", chartValue.output, chartConsole.input).setLocality(locality);
ConsoleOutputOperator chartConsole2 = dag.addOperator("chart_out2", new ConsoleOutputOperator());
dag.addStream("chart_console2", chartValue2.output, chartConsole2.input).setLocality(locality);
}
}
|
diff --git a/src/main/java/com/google/gerrit/server/mail/EmailHeader.java b/src/main/java/com/google/gerrit/server/mail/EmailHeader.java
index 151e5600e..2d82c1d1c 100644
--- a/src/main/java/com/google/gerrit/server/mail/EmailHeader.java
+++ b/src/main/java/com/google/gerrit/server/mail/EmailHeader.java
@@ -1,106 +1,107 @@
// 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.google.gerrit.server.mail;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
abstract class EmailHeader {
abstract boolean isEmpty();
abstract void write(Writer w) throws IOException;
static class String extends EmailHeader {
private java.lang.String value;
String(java.lang.String v) {
value = v;
}
@Override
boolean isEmpty() {
return value == null || value.length() == 0;
}
@Override
void write(Writer w) throws IOException {
w.write(value);
}
}
static class Date extends EmailHeader {
private java.util.Date value;
Date(java.util.Date v) {
value = v;
}
@Override
boolean isEmpty() {
return value == null;
}
@Override
void write(Writer w) throws IOException {
final SimpleDateFormat fmt;
// Mon, 1 Jun 2009 10:49:44 -0700
fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
w.write(fmt.format(value));
}
}
static class AddressList extends EmailHeader {
private final List<Address> list = new ArrayList<Address>();
AddressList() {
}
AddressList(Address addr) {
add(addr);
}
void add(Address addr) {
list.add(addr);
}
@Override
boolean isEmpty() {
return list.isEmpty();
}
@Override
void write(Writer w) throws IOException {
int len = 8;
boolean first = true;
for (final Address addr : list) {
java.lang.String s = addr.toHeaderString();
- if (!first && 72 < len + s.length()) {
+ if (first) {
+ first = false;
+ } else if (72 < len + s.length()) {
w.write(",\r\n\t");
len = 8;
first = true;
- }
- if (!first) {
+ } else {
w.write(", ");
- first = false;
}
w.write(s);
+ len += s.length();
}
}
}
}
| false | true | void write(Writer w) throws IOException {
int len = 8;
boolean first = true;
for (final Address addr : list) {
java.lang.String s = addr.toHeaderString();
if (!first && 72 < len + s.length()) {
w.write(",\r\n\t");
len = 8;
first = true;
}
if (!first) {
w.write(", ");
first = false;
}
w.write(s);
}
}
| void write(Writer w) throws IOException {
int len = 8;
boolean first = true;
for (final Address addr : list) {
java.lang.String s = addr.toHeaderString();
if (first) {
first = false;
} else if (72 < len + s.length()) {
w.write(",\r\n\t");
len = 8;
first = true;
} else {
w.write(", ");
}
w.write(s);
len += s.length();
}
}
|
diff --git a/src/com/dmdirc/Server.java b/src/com/dmdirc/Server.java
index 2f05ace99..f76b8fa09 100644
--- a/src/com/dmdirc/Server.java
+++ b/src/com/dmdirc/Server.java
@@ -1,1672 +1,1677 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.dmdirc;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.actions.wrappers.AliasWrapper;
import com.dmdirc.commandparser.CommandManager;
import com.dmdirc.commandparser.CommandType;
import com.dmdirc.commandparser.parsers.RawCommandParser;
import com.dmdirc.config.ConfigManager;
import com.dmdirc.config.Identity;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.interfaces.AwayStateListener;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.interfaces.InviteListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.parser.common.DefaultStringConverter;
import com.dmdirc.parser.common.IgnoreList;
import com.dmdirc.parser.common.ParserError;
import com.dmdirc.parser.interfaces.ChannelInfo;
import com.dmdirc.parser.interfaces.ClientInfo;
import com.dmdirc.parser.interfaces.Parser;
import com.dmdirc.parser.interfaces.SecureParser;
import com.dmdirc.parser.interfaces.StringConverter;
import com.dmdirc.parser.common.MyInfo;
import com.dmdirc.parser.irc.IRCParser;
import com.dmdirc.ui.WindowManager;
import com.dmdirc.ui.input.TabCompleter;
import com.dmdirc.ui.input.TabCompletionType;
import com.dmdirc.ui.interfaces.InputWindow;
import com.dmdirc.ui.interfaces.ServerWindow;
import com.dmdirc.ui.interfaces.Window;
import com.dmdirc.ui.messages.Formatter;
import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.net.ssl.TrustManager;
/**
* The Server class represents the client's view of a server. It maintains
* a list of all channels, queries, etc, and handles parser callbacks pertaining
* to the server.
*
* @author chris
*/
public class Server extends WritableFrameContainer implements
Serializable, ConfigChangeListener {
// <editor-fold defaultstate="collapsed" desc="Properties">
// <editor-fold defaultstate="collapsed" desc="Static">
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** The name of the general domain. */
private static final String DOMAIN_GENERAL = "general".intern();
/** The name of the profile domain. */
private static final String DOMAIN_PROFILE = "profile".intern();
/** The name of the server domain. */
private static final String DOMAIN_SERVER = "server".intern();
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Instance">
/** Open channels that currently exist on the server. */
private final Map<String, Channel> channels = new Hashtable<String, Channel>();
/** Open query windows on the server. */
private final List<Query> queries = new ArrayList<Query>();
/** The Parser instance handling this server. */
private transient Parser parser;
/**
* Object used to synchronoise access to parser. This object should be
* locked by anything requiring that the parser reference remains the same
* for a duration of time, or by anything which is updating the parser
* reference.
*
* If used in conjunction with myStateLock, the parserLock must always be
* locked INSIDE the myStateLock to prevent deadlocks.
*/
private final Object parserLock = new Object();
/** The IRC Parser Thread. */
private transient Thread parserThread;
/** The raw frame used for this server instance. */
private Raw raw;
/** The ServerWindow corresponding to this server. */
private ServerWindow window;
/** The address of the server we're connecting to. */
private URI address;
/** The profile we're using. */
private transient Identity profile;
/** The current state of this server. */
private final ServerStatus myState = new ServerStatus(this);
/** Object used to synchronoise access to myState. */
private final Object myStateLock = new Object();
/** The timer we're using to delay reconnects. */
private Timer reconnectTimer;
/** The tabcompleter used for this server. */
private final TabCompleter tabCompleter = new TabCompleter();
/** The last activated internal frame for this server. */
private FrameContainer activeFrame = this;
/** Our reason for being away, if any. */
private String awayMessage;
/** Our event handler. */
private final ServerEventHandler eventHandler = new ServerEventHandler(this);
/** A list of outstanding invites. */
private final List<Invite> invites = new ArrayList<Invite>();
/** Our ignore list. */
private final IgnoreList ignoreList = new IgnoreList();
/** Our string convertor. */
private StringConverter converter = new DefaultStringConverter();
// </editor-fold>
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Constructors">
/**
* Creates a new server which will connect to the specified URL with
* the specified profile.
*
* @since 0.6.4
* @param uri The address of the server to connect to
* @param profile The profile to use
*/
public Server(final URI uri, final Identity profile) {
super("server-disconnected", uri.getHost(),
new ConfigManager("", "", uri.getHost()));
this.address = uri;
this.profile = profile;
window = Main.getUI().getServer(this);
ServerManager.getServerManager().registerServer(this);
WindowManager.addWindow(window);
tabCompleter.addEntries(TabCompletionType.COMMAND,
AliasWrapper.getAliasWrapper().getAliases());
tabCompleter.addEntries(TabCompletionType.COMMAND,
CommandManager.getCommandNames(CommandType.TYPE_SERVER));
tabCompleter.addEntries(TabCompletionType.COMMAND,
CommandManager.getCommandNames(CommandType.TYPE_GLOBAL));
window.getInputHandler().setTabCompleter(tabCompleter);
updateIcon();
window.open();
new Timer("Server Who Timer").schedule(new TimerTask() {
@Override
public void run() {
for (Channel channel : channels.values()) {
channel.checkWho();
}
}
}, 0, getConfigManager().getOptionInt(DOMAIN_GENERAL, "whotime"));
if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "showrawwindow")) {
addRaw();
}
getConfigManager().addChangeListener("formatter", "serverName", this);
getConfigManager().addChangeListener("formatter", "serverTitle", this);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Connection, disconnection & reconnection">
/**
* Connects to a new server with the previously supplied address and profile.
*
* @since 0.6.3m2
*/
public void connect() {
connect(address, profile);
}
/**
* Connects to a new server with the specified details.
*
* @param address The address of the server to connect to
* @param profile The profile to use
* @since 0.6.4
*/
@Precondition({
"The current parser is null or not connected",
"The specified profile is not null"
})
@SuppressWarnings("fallthrough")
public void connect(final URI address, final Identity profile) {
assert profile != null;
synchronized (myStateLock) {
switch (myState.getState()) {
case RECONNECT_WAIT:
reconnectTimer.cancel();
break;
case CLOSING:
// Ignore the connection attempt
return;
case CONNECTED:
case CONNECTING:
disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage"));
case DISCONNECTING:
while (!myState.getState().isDisconnected()) {
try {
synchronized (myState) {
myState.wait();
}
} catch (InterruptedException ex) {
return;
}
}
break;
default:
// Do nothing
break;
}
synchronized (parserLock) {
if (parser != null) {
throw new IllegalArgumentException("Connection attempt while parser "
+ "is still connected.\n\nMy state:" + getState());
}
getConfigManager().migrate("", "", address.getHost());
this.address = address;
this.profile = profile;
updateTitle();
updateIcon();
parser = buildParser();
- final URI connectAddress = parser.getURI();
+ final URI connectAddress;
+ if (parser != null) {
+ connectAddress = parser.getURI();
+ } else {
+ connectAddress = address;
+ }
if (parser == null) {
addLine("serverUnknownProtocol", connectAddress.getScheme());
return;
}
addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort());
myState.transition(ServerState.CONNECTING);
doCallbacks();
awayMessage = null;
removeInvites();
window.setAwayIndicator(false);
try {
parserThread = new Thread(parser, "IRC Parser thread");
parserThread.start();
} catch (IllegalThreadStateException ex) {
Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex);
}
}
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this);
}
/**
* Reconnects to the IRC server with a specified reason.
*
* @param reason The quit reason to send
*/
public void reconnect(final String reason) {
synchronized (myStateLock) {
if (myState.getState() == ServerState.CLOSING) {
return;
}
disconnect(reason);
connect(address, profile);
}
}
/**
* Reconnects to the IRC server.
*/
public void reconnect() {
reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage"));
}
/**
* Disconnects from the server with the default quit message.
*/
public void disconnect() {
disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage"));
}
/**
* Disconnects from the server.
*
* @param reason disconnect reason
*/
public void disconnect(final String reason) {
synchronized (myStateLock) {
switch (myState.getState()) {
case CLOSING:
case DISCONNECTING:
case DISCONNECTED:
case TRANSIENTLY_DISCONNECTED:
return;
case RECONNECT_WAIT:
reconnectTimer.cancel();
break;
default:
break;
}
clearChannels();
synchronized (parserLock) {
if (parser == null) {
myState.transition(ServerState.DISCONNECTED);
} else {
myState.transition(ServerState.DISCONNECTING);
removeInvites();
updateIcon();
parserThread.interrupt();
parser.disconnect(reason);
}
}
if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
"closechannelsonquit")) {
closeChannels();
}
if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
"closequeriesonquit")) {
closeQueries();
}
}
}
/**
* Schedules a reconnect attempt to be performed after a user-defiend delay.
*/
@Precondition("The server state is transiently disconnected")
private void doDelayedReconnect() {
synchronized (myStateLock) {
if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) {
throw new IllegalStateException("doDelayedReconnect when not "
+ "transiently disconnected\n\nState: " + myState);
}
final int delay = Math.max(1000,
getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay"));
handleNotification("connectRetry", getName(), delay / 1000);
reconnectTimer = new Timer("Server Reconnect Timer");
reconnectTimer.schedule(new TimerTask() {
@Override
public void run() {
synchronized (myStateLock) {
if (myState.getState() == ServerState.RECONNECT_WAIT) {
myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
reconnect();
}
}
}
}, delay);
myState.transition(ServerState.RECONNECT_WAIT);
updateIcon();
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Child windows">
/**
* Determines whether the server knows of the specified channel.
*
* @param channel The channel to be checked
* @return True iff the channel is known, false otherwise
*/
public boolean hasChannel(final String channel) {
return channels.containsKey(converter.toLowerCase(channel));
}
/**
* Retrieves the specified channel belonging to this server.
*
* @param channel The channel to be retrieved
* @return The appropriate channel object
*/
public Channel getChannel(final String channel) {
return channels.get(converter.toLowerCase(channel));
}
/**
* Retrieves a list of channel names belonging to this server.
*
* @return list of channel names belonging to this server
*/
public List<String> getChannels() {
final ArrayList<String> res = new ArrayList<String>();
for (String channel : channels.keySet()) {
res.add(channel);
}
return res;
}
/**
* Determines whether the server knows of the specified query.
*
* @param host The host of the query to look for
* @return True iff the query is known, false otherwise
*/
public boolean hasQuery(final String host) {
final String nick = parser.parseHostmask(host)[0];
for (Query query : queries) {
if (converter.equalsIgnoreCase(parser.parseHostmask(query.getHost())[0], nick)) {
return true;
}
}
return false;
}
/**
* Retrieves the specified query belonging to this server.
*
* @param host The host of the query to look for
* @return The appropriate query object
*/
public Query getQuery(final String host) {
final String nick = parser.parseHostmask(host)[0];
for (Query query : queries) {
if (converter.equalsIgnoreCase(parser.parseHostmask(query.getHost())[0], nick)) {
return query;
}
}
throw new IllegalArgumentException("No such query: " + host);
}
/**
* Retrieves a list of queries belonging to this server.
*
* @return list of queries belonging to this server
*/
public List<Query> getQueries() {
return new ArrayList<Query>(queries);
}
/**
* Adds a raw window to this server.
*/
public void addRaw() {
if (raw == null) {
raw = new Raw(this, new RawCommandParser(this));
synchronized (parserLock) {
if (parser != null) {
raw.registerCallbacks();
}
}
} else {
raw.activateFrame();
}
}
/**
* Retrieves the raw window associated with this server.
*
* @return The raw window associated with this server.
*/
public Raw getRaw() {
return raw;
}
/**
* Removes our reference to the raw object (presumably after it has been
* closed).
*/
public void delRaw() {
raw = null; //NOPMD
}
/**
* Removes a specific channel and window from this server.
*
* @param chan channel to remove
*/
public void delChannel(final String chan) {
tabCompleter.removeEntry(TabCompletionType.CHANNEL, chan);
channels.remove(converter.toLowerCase(chan));
}
/**
* Adds a specific channel and window to this server.
*
* @param chan channel to add
*/
public void addChannel(final ChannelInfo chan) {
synchronized (myStateLock) {
if (myState.getState() == ServerState.CLOSING) {
// Can't join channels while the server is closing
return;
}
}
if (hasChannel(chan.getName())) {
getChannel(chan.getName()).setChannelInfo(chan);
getChannel(chan.getName()).selfJoin();
} else {
final Channel newChan = new Channel(this, chan);
tabCompleter.addEntry(TabCompletionType.CHANNEL, chan.getName());
channels.put(converter.toLowerCase(chan.getName()), newChan);
newChan.show();
}
}
/**
* Adds a query to this server.
*
* @param host host of the remote client being queried
*/
public void addQuery(final String host) {
synchronized (myStateLock) {
if (myState.getState() == ServerState.CLOSING) {
// Can't open queries while the server is closing
return;
}
}
if (!hasQuery(host)) {
final Query newQuery = new Query(this, host);
tabCompleter.addEntry(TabCompletionType.QUERY_NICK, parser.parseHostmask(host)[0]);
queries.add(newQuery);
}
}
/**
* Deletes a query from this server.
*
* @param query The query that should be removed.
*/
public void delQuery(final Query query) {
tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, query.getNickname());
queries.remove(query);
}
/** {@inheritDoc} */
@Override
public boolean ownsFrame(final Window target) {
// Check if it's our server frame
if (window != null && window.equals(target)) { return true; }
// Check if it's the raw frame
if (raw != null && raw.ownsFrame(target)) { return true; }
// Check if it's a channel frame
for (Channel channel : channels.values()) {
if (channel.ownsFrame(target)) { return true; }
}
// Check if it's a query frame
for (Query query : queries) {
if (query.ownsFrame(target)) { return true; }
}
return false;
}
/**
* Sets the specified frame as the most-recently activated.
*
* @param source The frame that was activated
*/
public void setActiveFrame(final FrameContainer source) {
activeFrame = source;
}
/**
* Retrieves a list of all children of this server instance.
*
* @return A list of this server's children
*/
public List<WritableFrameContainer> getChildren() {
final List<WritableFrameContainer> res = new ArrayList<WritableFrameContainer>();
if (raw != null) {
res.add(raw);
}
res.addAll(channels.values());
res.addAll(queries);
return res;
}
/**
* Closes all open channel windows associated with this server.
*/
private void closeChannels() {
for (Channel channel : new ArrayList<Channel>(channels.values())) {
channel.close();
}
}
/**
* Clears the nicklist of all open channels.
*/
private void clearChannels() {
for (Channel channel : channels.values()) {
channel.resetWindow();
}
}
/**
* Closes all open query windows associated with this server.
*/
private void closeQueries() {
for (Query query : new ArrayList<Query>(queries)) {
query.close();
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Miscellaneous methods">
/**
* Builds an appropriately configured {@link IRCParser} for this server.
*
* @return A configured IRC parser.
*/
private Parser buildParser() {
final CertificateManager certManager = new CertificateManager(address.getHost(),
getConfigManager());
final MyInfo myInfo = buildMyInfo();
final Parser myParser = new ParserFactory().getParser(myInfo, address);
if (myParser instanceof SecureParser) {
final SecureParser secureParser = (SecureParser) myParser;
secureParser.setTrustManagers(new TrustManager[]{certManager});
secureParser.setKeyManagers(certManager.getKeyManager());
}
if (myParser != null) {
myParser.setIgnoreList(ignoreList);
myParser.setPingTimerInterval(getConfigManager().getOptionInt(DOMAIN_SERVER,
"pingtimer"));
myParser.setPingTimerFraction((int) (getConfigManager().getOptionInt(DOMAIN_SERVER,
"pingfrequency") / myParser.getPingTimerInterval()));
if (getConfigManager().hasOptionString(DOMAIN_GENERAL, "bindip")) {
myParser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip"));
}
}
return myParser;
}
/**
* Retrieves the MyInfo object used for the IRC Parser.
*
* @return The MyInfo object for our profile
*/
@Precondition({
"The current profile is not null",
"The current profile specifies at least one nickname"
})
private MyInfo buildMyInfo() {
Logger.assertTrue(profile != null);
Logger.assertTrue(!profile.getOptionList(DOMAIN_PROFILE, "nicknames").isEmpty());
final MyInfo myInfo = new MyInfo();
myInfo.setNickname(profile.getOptionList(DOMAIN_PROFILE, "nicknames").get(0));
myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname"));
if (profile.hasOptionString(DOMAIN_PROFILE, "ident")) {
myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident"));
}
return myInfo;
}
/**
* Updates this server's icon.
*/
private void updateIcon() {
final String icon = myState.getState() == ServerState.CONNECTED
? address.getScheme().endsWith("s") ? "secure-server" : "server"
: "server-disconnected";
setIcon(icon);
}
/**
* Registers callbacks.
*/
private void doCallbacks() {
if (raw != null) {
raw.registerCallbacks();
}
eventHandler.registerCallbacks();
for (Query query : queries) {
query.reregister();
}
}
/**
* Joins the specified channel with the specified key.
*
* @since 0.6.3m1
* @param channel The channel to be joined
* @param key The key for the channel
*/
public void join(final String channel, final String key) {
synchronized (myStateLock) {
if (myState.getState() == ServerState.CONNECTED) {
removeInvites(channel);
if (hasChannel(channel)) {
// TODO: Need to pass key?
getChannel(channel).join();
getChannel(channel).activateFrame();
} else {
parser.joinChannel(channel, key);
}
} else {
// TODO: Need to pass key
// TODO (uris): address.getChannels().add(channel);
}
}
}
/**
* Joins the specified channel, or adds it to the auto-join list if the
* server is not connected.
*
* @param channel The channel to be joined
*/
public void join(final String channel) {
synchronized (myStateLock) {
if (myState.getState() == ServerState.CONNECTED) {
removeInvites(channel);
if (hasChannel(channel)) {
getChannel(channel).join();
getChannel(channel).activateFrame();
} else {
parser.joinChannel(channel);
}
} else {
// TODO(uris): address.getChannels().add(channel);
}
}
}
/** {@inheritDoc} */
@Override
public void sendLine(final String line) {
synchronized (myStateLock) {
synchronized (parserLock) {
if (parser != null && myState.getState() == ServerState.CONNECTED) {
if (!line.isEmpty()) {
parser.sendRawMessage(window.getTranscoder().encode(line));
}
}
}
}
}
/** {@inheritDoc} */
@Override
public int getMaxLineLength() {
synchronized (parserLock) {
return parser == null ? -1 : parser.getMaxLength();
}
}
/**
* Retrieves the parser used for this connection.
*
* @return IRCParser this connection's parser
*/
public Parser getParser() {
return parser;
}
/**
* Retrieves the profile that's in use for this server.
*
* @return The profile in use by this server
*/
public Identity getProfile() {
return profile;
}
/**
* Retrieves the name of this server's network. The network name is
* determined using the following rules:
*
* 1. If the server includes its network name in the 005 information, we
* use that
* 2. If the server's name ends in biz, com, info, net or org, we use the
* second level domain (e.g., foo.com)
* 3. If the server's name contains more than two dots, we drop everything
* up to and including the first part, and use the remainder
* 4. In all other cases, we use the full server name
*
* @return The name of this server's network
*/
public String getNetwork() {
synchronized (parserLock) {
if (parser == null) {
throw new IllegalStateException("getNetwork called when "
+ "parser is null (state: " + getState() + ")");
} else if (parser.getNetworkName().isEmpty()) {
return getNetworkFromServerName(parser.getServerName());
} else {
return parser.getNetworkName();
}
}
}
/**
* Determines whether this server is currently connected to the specified
* network.
*
* @param target The network to check for
* @return True if this server is connected to the network, false otherwise
* @since 0.6.3m1rc3
*/
public boolean isNetwork(String target) {
synchronized (myStateLock) {
synchronized (parserLock) {
if (parser == null) {
return false;
} else {
return getNetwork().equalsIgnoreCase(target);
}
}
}
}
/**
* Calculates a network name from the specified server name. This method
* implements parts 2-4 of the procedure documented at getNetwork().
*
* @param serverName The server name to parse
* @return A network name for the specified server
*/
protected static String getNetworkFromServerName(final String serverName) {
final String[] parts = serverName.split("\\.");
final String[] tlds = {"biz", "com", "info", "net", "org"};
boolean isTLD = false;
for (String tld : tlds) {
if (serverName.endsWith("." + tld)) {
isTLD = true;
}
}
if (isTLD && parts.length > 2) {
return parts[parts.length - 2] + "." + parts[parts.length - 1];
} else if (parts.length > 2) {
final StringBuilder network = new StringBuilder();
for (int i = 1; i < parts.length; i++) {
if (network.length() > 0) {
network.append('.');
}
network.append(parts[i]);
}
return network.toString();
} else {
return serverName;
}
}
/**
* Retrieves the name of this server's IRCd.
*
* @return The name of this server's IRCd
*/
public String getIrcd() {
return parser.getServerSoftwareType();
}
/**
* Returns the current away status.
*
* @return True if the client is marked as away, false otherwise
*/
public boolean isAway() {
return awayMessage != null;
}
/**
* Gets the current away message.
*
* @return Null if the client isn't away, or a textual away message if it is
*/
public String getAwayMessage() {
return awayMessage;
}
/**
* Returns the tab completer for this connection.
*
* @return The tab completer for this server
*/
public TabCompleter getTabCompleter() {
return tabCompleter;
}
/** {@inheritDoc} */
@Override
public InputWindow getFrame() {
return window;
}
/**
* Retrieves the current state for this server.
*
* @return This server's state
*/
public ServerState getState() {
return myState.getState();
}
/**
* Retrieves the status object for this server. Effecting state transitions
* on the object returned by this method will almost certainly cause
* problems.
*
* @since 0.6.3m1
* @return This server's status object.
*/
public ServerStatus getStatus() {
return myState;
}
/** {@inheritDoc} */
@Override
public void windowClosing() {
synchronized (myStateLock) {
// 1: Make the window non-visible
window.setVisible(false);
// 2: Remove any callbacks or listeners
eventHandler.unregisterCallbacks();
// 3: Trigger any actions neccessary
disconnect();
myState.transition(ServerState.CLOSING);
}
closeChannels();
closeQueries();
removeInvites();
if (raw != null) {
raw.close();
}
// 4: Trigger action for the window closing
// 5: Inform any parents that the window is closing
ServerManager.getServerManager().unregisterServer(this);
// 6: Remove the window from the window manager
WindowManager.removeWindow(window);
// 7: Remove any references to the window and parents
window = null; //NOPMD
parser = null; //NOPMD
}
/**
* Passes the arguments to the most recently activated frame for this
* server. If the frame isn't know, or isn't visible, use this frame
* instead.
*
* @param messageType The type of message to send
* @param args The arguments for the message
*/
public void addLineToActive(final String messageType, final Object... args) {
if (activeFrame == null || !activeFrame.getFrame().isVisible()) {
activeFrame = this;
}
activeFrame.getFrame().addLine(messageType, args);
}
/**
* Passes the arguments to all frames for this server.
*
* @param messageType The type of message to send
* @param args The arguments of the message
*/
public void addLineToAll(final String messageType, final Object... args) {
for (Channel channel : channels.values()) {
channel.getFrame().addLine(messageType, args);
}
for (Query query : queries) {
query.getFrame().addLine(messageType, args);
}
addLine(messageType, args);
}
/**
* Replies to an incoming CTCP message.
*
* @param source The source of the message
* @param type The CTCP type
* @param args The CTCP arguments
*/
public void sendCTCPReply(final String source, final String type, final String args) {
if (type.equalsIgnoreCase("VERSION")) {
parser.sendCTCPReply(source, "VERSION", "DMDirc " +
getConfigManager().getOption("version", "version")
+ " - http://www.dmdirc.com/");
} else if (type.equalsIgnoreCase("PING")) {
parser.sendCTCPReply(source, "PING", args);
} else if (type.equalsIgnoreCase("CLIENTINFO")) {
parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO");
}
}
/**
* Determines if the specified channel name is valid. A channel name is
* valid if we already have an existing Channel with the same name, or
* we have a valid parser instance and the parser says it's valid.
*
* @param channelName The name of the channel to test
* @return True if the channel name is valid, false otherwise
*/
public boolean isValidChannelName(final String channelName) {
synchronized (parserLock) {
return hasChannel(channelName)
|| (parser != null && parser.isValidChannelName(channelName));
}
}
/**
* Returns the server instance associated with this frame.
*
* @return the associated server connection
*/
@Override
public Server getServer() {
return this;
}
/** {@inheritDoc} */
@Override
protected boolean processNotificationArg(final Object arg, final List<Object> args) {
if (arg instanceof ClientInfo) {
final ClientInfo clientInfo = (ClientInfo) arg;
args.add(clientInfo.getNickname());
args.add(clientInfo.getUsername());
args.add(clientInfo.getHostname());
return true;
} else {
return super.processNotificationArg(arg, args);
}
}
/**
* Updates the name and title of this window.
*/
public void updateTitle() {
synchronized (parserLock) {
final Object[] arguments = new Object[]{
address.getHost(), parser == null ? "Unknown" : parser.getServerName(),
address.getPort(), parser == null ? "Unknown" : getNetwork(),
parser == null ? "Unknown" : parser.getLocalClient().getNickname()
};
setName(Formatter.formatMessage(getConfigManager(),
"serverName", arguments));
window.setTitle(Formatter.formatMessage(getConfigManager(),
"serverTitle", arguments));
}
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
if ("formatter".equals(domain)) {
updateTitle();
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Parser callbacks">
/**
* Called when the server says that the nickname we're trying to use is
* already in use.
*
* @param nickname The nickname that we were trying to use
*/
public void onNickInUse(final String nickname) {
final String lastNick = parser.getLocalClient().getNickname();
// If our last nick is still valid, ignore the in use message
if (!converter.equalsIgnoreCase(lastNick, nickname)) {
return;
}
String newNick = lastNick + new Random().nextInt(10);
final List<String> alts = profile.getOptionList(DOMAIN_PROFILE, "nicknames");
int offset = 0;
// Loop so we can check case sensitivity
for (String alt : alts) {
offset++;
if (converter.equalsIgnoreCase(alt, lastNick)) {
break;
}
}
if (offset < alts.size() && !alts.get(offset).isEmpty()) {
newNick = alts.get(offset);
}
parser.getLocalClient().setNickname(newNick);
}
/**
* Called when the server sends a numeric event.
*
* @param numeric The numeric code for the event
* @param tokens The (tokenised) arguments of the event
*/
public void onNumeric(final int numeric, final String[] tokens) {
String snumeric = String.valueOf(numeric);
if (numeric < 10) {
snumeric = "00" + snumeric;
} else if (numeric < 100) {
snumeric = "0" + snumeric;
}
final String withIrcd = "numeric_" + parser.getServerSoftwareType() + "_" + snumeric;
final String sansIrcd = "numeric_" + snumeric;
StringBuffer target = null;
if (getConfigManager().hasOptionString("formatter", withIrcd)) {
target = new StringBuffer(withIrcd);
} else if (getConfigManager().hasOptionString("formatter", sansIrcd)) {
target = new StringBuffer(sansIrcd);
} else if (getConfigManager().hasOptionString("formatter", "numeric_unknown")) {
target = new StringBuffer("numeric_unknown");
}
ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, target, this,
Integer.valueOf(numeric), tokens);
if (target != null) {
handleNotification(target.toString(), (Object[]) tokens);
}
}
/**
* Called when the socket has been closed.
*/
public void onSocketClosed() {
if (Thread.holdsLock(myState)) {
new Thread(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
onSocketClosed();
}
}, "Socket closed deferred thread").start();
return;
}
handleNotification("socketClosed", getName());
ActionManager.processEvent(CoreActionType.SERVER_DISCONNECTED, null, this);
eventHandler.unregisterCallbacks();
synchronized (myStateLock) {
if (myState.getState() == ServerState.CLOSING
|| myState.getState() == ServerState.DISCONNECTED) {
// This has been triggered via .disconect()
return;
}
if (myState.getState() == ServerState.DISCONNECTING) {
myState.transition(ServerState.DISCONNECTED);
} else {
myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
}
clearChannels();
synchronized (parserLock) {
parser = null;
}
updateIcon();
if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
"closechannelsondisconnect")) {
closeChannels();
}
if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
"closequeriesondisconnect")) {
closeQueries();
}
removeInvites();
updateAwayState(null);
if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
"reconnectondisconnect")
&& myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) {
doDelayedReconnect();
}
}
}
/**
* Called when an error was encountered while connecting.
*
* @param errorInfo The parser's error information
*/
@Precondition("The current server state is CONNECTING")
public void onConnectError(final ParserError errorInfo) {
synchronized (myStateLock) {
if (myState.getState() == ServerState.CLOSING
|| myState.getState() == ServerState.DISCONNECTING) {
// Do nothing
return;
} else if (myState.getState() != ServerState.CONNECTING) {
// Shouldn't happen
throw new IllegalStateException("Connect error when not "
+ "connecting\n\n" + getStatus().getTransitionHistory());
}
myState.transition(ServerState.TRANSIENTLY_DISCONNECTED);
synchronized (parserLock) {
parser = null;
}
updateIcon();
String description;
if (errorInfo.getException() == null) {
description = errorInfo.getData();
} else {
final Exception exception = errorInfo.getException();
if (exception instanceof java.net.UnknownHostException) {
description = "Unknown host (unable to resolve)";
} else if (exception instanceof java.net.NoRouteToHostException) {
description = "No route to host";
} else if (exception instanceof java.net.SocketException
|| exception instanceof javax.net.ssl.SSLException) {
description = exception.getMessage();
} else {
Logger.appError(ErrorLevel.LOW, "Unknown socket error", exception);
description = "Unknown error: " + exception.getMessage();
}
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTERROR, null,
this, description);
handleNotification("connectError", getName(), description);
if (getConfigManager().getOptionBool(DOMAIN_GENERAL,
"reconnectonconnectfailure")) {
doDelayedReconnect();
}
}
}
/**
* Called when we fail to receive a ping reply within a set period of time.
*/
public void onPingFailed() {
Main.getUI().getStatusBar().setMessage("No ping reply from "
+ getName() + " for over "
+ ((int) (Math.floor(parser.getPingTime() / 1000.0)))
+ " seconds.", null, 10);
ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this,
Long.valueOf(parser.getPingTime()));
if (parser.getPingTime()
>= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout")) {
handleNotification("stonedServer", getName());
reconnect();
}
}
/**
* Called after the parser receives the 005 headers from the server.
*/
@Precondition("State is CONNECTING")
public void onPost005() {
synchronized (myStateLock) {
if (myState.getState() != ServerState.CONNECTING) {
// Shouldn't happen
throw new IllegalStateException("Received onPost005 while not "
+ "connecting\n\n" + myState.getTransitionHistory());
}
if (myState.getState() != ServerState.CONNECTING) {
// We've transitioned while waiting for the lock. Just abort.
return;
}
myState.transition(ServerState.CONNECTED);
getConfigManager().migrate(parser.getServerSoftwareType(), getNetwork(), getName());
updateIcon();
updateTitle();
updateIgnoreList();
converter = parser.getStringConverter();
if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "rejoinchannels")) {
for (Channel chan : channels.values()) {
chan.join();
}
}
checkModeAliases();
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this);
}
/**
* Checks that we have the neccessary mode aliases for this server.
*/
private void checkModeAliases() {
// Check we have mode aliases
final String modes = parser.getBooleanChannelModes() + parser.getListChannelModes()
+ parser.getParameterChannelModes() + parser.getDoubleParameterChannelModes();
final String umodes = parser.getUserModes();
final StringBuffer missingModes = new StringBuffer();
final StringBuffer missingUmodes = new StringBuffer();
for (char mode : modes.toCharArray()) {
if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "mode" + mode)) {
missingModes.append(mode);
}
}
for (char mode : umodes.toCharArray()) {
if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "umode" + mode)) {
missingUmodes.append(mode);
}
}
if (missingModes.length() + missingUmodes.length() > 0) {
final StringBuffer missing = new StringBuffer("Missing mode aliases: ");
if (missingModes.length() > 0) {
missing.append("channel: +");
missing.append(missingModes);
}
if (missingUmodes.length() > 0) {
if (missingModes.length() > 0) {
missing.append(' ');
}
missing.append("user: +");
missing.append(missingUmodes);
}
Logger.appError(ErrorLevel.LOW, missing.toString() + " ["
+ parser.getServerSoftwareType() + "]",
new Exception(missing.toString() + "\n" // NOPMD
+ "Network: " + getNetwork() + "\n"
+ "IRCd: " + parser.getServerSoftware()
+ " (" + parser.getServerSoftwareType() + ")\n"
+ "Mode alias version: "
+ getConfigManager().getOption("identity", "modealiasversion")
+ "\n\n"));
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Ignore lists">
/**
* Retrieves this server's ignore list.
*
* @return This server's ignore list
*/
public IgnoreList getIgnoreList() {
return ignoreList;
}
/**
* Updates this server's ignore list to use the entries stored in the
* config manager.
*/
public void updateIgnoreList() {
ignoreList.clear();
ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist"));
}
/**
* Saves the contents of our ignore list to the network identity.
*/
public void saveIgnoreList() {
getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList());
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Identity handling">
/**
* Retrieves the identity for this server.
*
* @return This server's identity
*/
public Identity getServerIdentity() {
return IdentityManager.getServerConfig(getName());
}
/**
* Retrieves the identity for this server's network.
*
* @return This server's network identity
*/
public Identity getNetworkIdentity() {
return IdentityManager.getNetworkConfig(getNetwork());
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Invite handling">
/**
* Adds an invite listener to this server.
*
* @param listener The listener to be added
*/
public void addInviteListener(final InviteListener listener) {
synchronized (listeners) {
listeners.add(InviteListener.class, listener);
}
}
/**
* Removes an invite listener from this server.
*
* @param listener The listener to be removed
*/
public void removeInviteListener(final InviteListener listener) {
synchronized (listeners) {
listeners.remove(InviteListener.class, listener);
}
}
/**
* Adds an invite to this server, and fires the appropriate listeners.
*
* @param invite The invite to be added
*/
public void addInvite(final Invite invite) {
synchronized (invites) {
for (Invite oldInvite : new ArrayList<Invite>(invites)) {
if (oldInvite.getChannel().equals(invite.getChannel())) {
removeInvite(oldInvite);
}
}
invites.add(invite);
synchronized (listeners) {
for (InviteListener listener : listeners.get(InviteListener.class)) {
listener.inviteReceived(this, invite);
}
}
}
}
/**
* Removes all invites for the specified channel.
*
* @param channel The channel to remove invites for
*/
public void removeInvites(final String channel) {
for (Invite invite : new ArrayList<Invite>(invites)) {
if (invite.getChannel().equals(channel)) {
removeInvite(invite);
}
}
}
/**
* Removes all invites for all channels.
*/
private void removeInvites() {
for (Invite invite : new ArrayList<Invite>(invites)) {
removeInvite(invite);
}
}
/**
* Removes an invite from this server, and fires the appropriate listeners.
*
* @param invite The invite to be removed
*/
public void removeInvite(final Invite invite) {
synchronized (invites) {
invites.remove(invite);
synchronized (listeners) {
for (InviteListener listener : listeners.get(InviteListener.class)) {
listener.inviteExpired(this, invite);
}
}
}
}
/**
* Retusnt the list of invites for this server.
*
* @return Invite list
*/
public List<Invite> getInvites() {
return invites;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Away state handling">
/**
* Adds an away state lisener to this server.
*
* @param listener The listener to be added
*/
public void addAwayStateListener(final AwayStateListener listener) {
synchronized (listeners) {
listeners.add(AwayStateListener.class, listener);
}
}
/**
* Removes an away state lisener from this server.
*
* @param listener The listener to be removed
*/
public void removeAwayStateListener(final AwayStateListener listener) {
synchronized (listeners) {
listeners.remove(AwayStateListener.class, listener);
}
}
/**
* Updates our away state and fires the relevant listeners.
*
* @param message The away message to use, or null if we're not away.
*/
public void updateAwayState(final String message) {
if ((awayMessage != null && awayMessage.equals(message))
|| (awayMessage == null && message == null)) {
return;
}
awayMessage = message;
synchronized (listeners) {
if (message == null) {
for (AwayStateListener listener : listeners.get(AwayStateListener.class)) {
listener.onBack();
}
} else {
for (AwayStateListener listener : listeners.get(AwayStateListener.class)) {
listener.onAway(message);
}
}
}
}
// </editor-fold>
}
| true | true | public void connect(final URI address, final Identity profile) {
assert profile != null;
synchronized (myStateLock) {
switch (myState.getState()) {
case RECONNECT_WAIT:
reconnectTimer.cancel();
break;
case CLOSING:
// Ignore the connection attempt
return;
case CONNECTED:
case CONNECTING:
disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage"));
case DISCONNECTING:
while (!myState.getState().isDisconnected()) {
try {
synchronized (myState) {
myState.wait();
}
} catch (InterruptedException ex) {
return;
}
}
break;
default:
// Do nothing
break;
}
synchronized (parserLock) {
if (parser != null) {
throw new IllegalArgumentException("Connection attempt while parser "
+ "is still connected.\n\nMy state:" + getState());
}
getConfigManager().migrate("", "", address.getHost());
this.address = address;
this.profile = profile;
updateTitle();
updateIcon();
parser = buildParser();
final URI connectAddress = parser.getURI();
if (parser == null) {
addLine("serverUnknownProtocol", connectAddress.getScheme());
return;
}
addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort());
myState.transition(ServerState.CONNECTING);
doCallbacks();
awayMessage = null;
removeInvites();
window.setAwayIndicator(false);
try {
parserThread = new Thread(parser, "IRC Parser thread");
parserThread.start();
} catch (IllegalThreadStateException ex) {
Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex);
}
}
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this);
}
| public void connect(final URI address, final Identity profile) {
assert profile != null;
synchronized (myStateLock) {
switch (myState.getState()) {
case RECONNECT_WAIT:
reconnectTimer.cancel();
break;
case CLOSING:
// Ignore the connection attempt
return;
case CONNECTED:
case CONNECTING:
disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage"));
case DISCONNECTING:
while (!myState.getState().isDisconnected()) {
try {
synchronized (myState) {
myState.wait();
}
} catch (InterruptedException ex) {
return;
}
}
break;
default:
// Do nothing
break;
}
synchronized (parserLock) {
if (parser != null) {
throw new IllegalArgumentException("Connection attempt while parser "
+ "is still connected.\n\nMy state:" + getState());
}
getConfigManager().migrate("", "", address.getHost());
this.address = address;
this.profile = profile;
updateTitle();
updateIcon();
parser = buildParser();
final URI connectAddress;
if (parser != null) {
connectAddress = parser.getURI();
} else {
connectAddress = address;
}
if (parser == null) {
addLine("serverUnknownProtocol", connectAddress.getScheme());
return;
}
addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort());
myState.transition(ServerState.CONNECTING);
doCallbacks();
awayMessage = null;
removeInvites();
window.setAwayIndicator(false);
try {
parserThread = new Thread(parser, "IRC Parser thread");
parserThread.start();
} catch (IllegalThreadStateException ex) {
Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex);
}
}
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this);
}
|
diff --git a/bootstrap-samples/src/main/java/de/agilecoders/wicket/samples/pages/ExtensionsPage.java b/bootstrap-samples/src/main/java/de/agilecoders/wicket/samples/pages/ExtensionsPage.java
index f582cb8b..5b618190 100644
--- a/bootstrap-samples/src/main/java/de/agilecoders/wicket/samples/pages/ExtensionsPage.java
+++ b/bootstrap-samples/src/main/java/de/agilecoders/wicket/samples/pages/ExtensionsPage.java
@@ -1,213 +1,213 @@
package de.agilecoders.wicket.samples.pages;
import com.google.common.collect.Lists;
import de.agilecoders.wicket.core.markup.html.bootstrap.block.Code;
import de.agilecoders.wicket.core.markup.html.bootstrap.button.dropdown.DropDownButton;
import de.agilecoders.wicket.core.markup.html.bootstrap.button.dropdown.MenuBookmarkablePageLink;
import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig;
import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.Modal;
import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.TextContentModal;
import de.agilecoders.wicket.core.markup.html.bootstrap.image.Icon;
import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType;
import de.agilecoders.wicket.extensions.javascript.jasny.FileUploadField;
import de.agilecoders.wicket.extensions.javascript.jasny.InputMaskBehavior;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.behavior.Draggable;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.behavior.DraggableConfig;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.behavior.Resizable;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.button.DropDownAutoOpen;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.contextmenu.ButtonListContextMenu;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.html5player.Html5Player;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.html5player.Html5VideoConfig;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.html5player.Video;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.OpenWebIconType;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.OpenWebIconsCssReference;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.tour.TourBehavior;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.tour.TourStep;
import de.agilecoders.wicket.samples.panels.pagination.InfinitePaginationPanel;
import org.apache.wicket.Component;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.TransparentWebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.wicketstuff.annotation.mount.MountPath;
import java.util.List;
/**
* The {@code ExtensionsPage}
*
* @author miha
*/
@MountPath(value = "/extensions")
public class ExtensionsPage extends BasePage {
/**
* Construct.
*
* @param parameters the current page parameters.
*/
public ExtensionsPage(PageParameters parameters) {
super(parameters);
List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(
new Video("http://ia700305.us.archive.org/18/items/CopyingIsNotTheft/CINT_Nik_H264_720.ogv", "video/ogg"),
new Video("http://ia700305.us.archive.org/18/items/CopyingIsNotTheft/CINT_Nik_H264_720_512kb.mp4", "video/mp4")
);
add(new Html5Player("video", Model.ofList(videos)));
add(new Code("video-code", Model.of("List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(\n"
+ "\t\tnew Video(\"video.ogv\", \"video/ogg\"),\n"
+ "\t\tnew Video(\"video.mp4\", \"video/mp4\")\n"
+ ");\n"
+ "add(new Html5Player(\"video\", Model.ofList(videos)));")));
add(new Html5Player("video-custom", Model.ofList(videos), new Html5VideoConfig().showProgressBar(false).autoHideControlBar(false)).setWidth(680).setHeight(360));
add(new Code("video-custom-code", Model.of("List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(\n"
+ "\t\tnew Video(\"video.ogv\", \"video/ogg\"),\n"
+ "\t\tnew Video(\"video.mp4\", \"video/mp4\")\n"
+ ");\n"
+ "add(new Html5Player(\"video\", Model.ofList(videos),\n"
+ "\tnew Html5VideoConfig().showProgressBar(false).autoHideControlBar(false))\n"
+ "\t\t.setWidth(680).setHeight(360));")));
final List<? extends AbstractLink> buttons = Lists.<AbstractLink>newArrayList(
new MenuBookmarkablePageLink<DatePickerPage>(DatePickerPage.class, Model.of("DatePicker")).setIconType(IconType.time),
new MenuBookmarkablePageLink<IssuesPage>(IssuesPage.class, Model.of("Github Issues")).setIconType(IconType.book),
new MenuBookmarkablePageLink<ExtensionsPage>(ExtensionsPage.class, Model.of("Extensions")).setIconType(IconType.qrcode)
);
final Component contextPanel = new TransparentWebMarkupContainer("context-panel");
final ButtonListContextMenu contextMenu = new ButtonListContextMenu("contextmenu", Model.ofList(buttons));
contextMenu.assignTo(contextPanel);
add(contextMenu, contextPanel,
new Code("context-code", Model.of(""
+ "final List<? extends AbstractLink> buttons = Lists.<AbstractLink>newArrayList(\n"
+ "\tnew MenuBookmarkablePageLink<>(...),\n"
+ "\t[...]\n"
+ ");\n"
+ "final Component contextPanel = new TransparentWebMarkupContainer(\"context-panel\");\n"
+ "final ButtonListContextMenu contextMenu = new ButtonListContextMenu(\"contextmenu\", \n"
+ "\t\tModel.ofList(buttons));\n"
+ "contextMenu.assignTo(contextPanel);\n"
+ "add(contextMenu, contextPanel,")));
Modal draggableModal = new TextContentModal("draggable-modal", Model.of("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."));
- draggableModal.add(new Draggable(new DraggableConfig().withHandle(".modal-header").withCursor("move")));
- draggableModal.add(new Resizable());
+// draggableModal.add(new Draggable(new DraggableConfig().withHandle(".modal-header").withCursor("move")));
+// draggableModal.add(new Resizable());
draggableModal.setUseKeyboard(true).addCloseButton();
draggableModal.setFadeIn(false);
Label draggableButton = new Label("open-draggable", "Open Modal Dialog");
draggableModal.addOpenerAttributesTo(draggableButton);
add(draggableModal, draggableButton, new Code("draggable-code", Model.of("")));
DropDownButton dropDownButton = new DropDownButton("dropdown", Model.of("open-on-hover")) {
@Override
protected List<AbstractLink> newSubMenuButtons(String buttonMarkupId) {
return Lists.<AbstractLink>newArrayList(
new MenuBookmarkablePageLink<DatePickerPage>(DatePickerPage.class, Model.of("DatePicker")).setIconType(IconType.time),
new MenuBookmarkablePageLink<IssuesPage>(IssuesPage.class, Model.of("Github Issues")).setIconType(IconType.book),
new MenuBookmarkablePageLink<ExtensionsPage>(ExtensionsPage.class, Model.of("Extensions")).setIconType(IconType.qrcode)
);
}
};
dropDownButton.add(new DropDownAutoOpen());
add(dropDownButton, new Code("dropdown-code", Model.of("dropDownButton.add(new DropDownAutoOpen());")));
addTour();
add(new Icon("html5-colored", OpenWebIconType.html5_colored_large), new Icon("apml", OpenWebIconType.apml), new Icon("feed", OpenWebIconType.feed_colored_large));
add(new Icon("html5", OpenWebIconType.html5), new Code("openwebicon-code", Model.of("response.render(JavaScriptHeaderItem.forReference(OpenWebIconsCssReference.instance()));\n\nadd(new Icon(\"html5\", OpenWebIconType.html5));")));
addJasnyFileUploadDemo();
addJasnyInputMaskDemo();
add(new InfinitePaginationPanel("infinite"));
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(CssHeaderItem.forReference(OpenWebIconsCssReference.instance()));
}
private void addJasnyFileUploadDemo() {
FileUploadField fileUpload = new FileUploadField("fileUpload");
add(fileUpload);
}
private void addJasnyInputMaskDemo() {
TextField textField = new TextField("inputMask", Model.of("l0rdn1kk0n"));
InputMaskBehavior inputMask = new InputMaskBehavior() {
@Override
protected String getMask() {
// Allow entering l0rdn1kk0n
return "a9aaa9aa9a";
}
};
textField.add(inputMask);
add(textField);
}
/**
* Demo for TourBehavior. Issue #116
*/
private void addTour() {
RepeatingView view = new RepeatingView("tourDemo");
add(view);
Label stepOne = new Label(view.newChildId(), "Step One");
view.add(stepOne);
Label stepTwo = new Label(view.newChildId(), "Step Two");
view.add(stepTwo);
Label stepThree = new Label(view.newChildId(), "Step Three");
view.add(stepThree);
TourBehavior tourBehavior = new TourBehavior() {
@Override
protected CharSequence createExtraConfig() {
return "if ( tour.ended() ) {\n" +
" $('<div class=\"alert\">\\\n" +
" <button class=\"close\" data-dismiss=\"alert\">×</button>\\\n" +
" You ended the demo tour. <a href=\"\" class=\"restart\">Restart the demo tour.</a>\\\n" +
" </div>').prependTo(\".content\").alert();\n" +
" }\n" +
"\n" +
" $(\".restart\").click(function (e) {\n" +
" e.preventDefault();\n" +
" tour.restart();\n" +
" $(this).parents(\".alert\").alert(\"close\");\n" +
" });";
}
};
tourBehavior.addStep(new TourStep()
.title(Model.of("Step One Title"))
.element(stepOne)
.content(Model.of("Some longer help content <strong> for step <span style='color: red'>1</span>.")));
tourBehavior.addStep(new TourStep()
.title(new ResourceModel("tour.step.two"))
.element(stepTwo)
.placement(TooltipConfig.Placement.left)
.content(Model.of("Some longer help content <strong> for step <span style='color: red'>2</span>."))
.backdrop(true));
tourBehavior.addStep(new TourStep()
.title(Model.of("Step Three Title"))
.element(stepThree)
.placement(TooltipConfig.Placement.left)
.content(Model.of("Some longer help content <strong> for step <span style='color: red'>3</span>.")));
view.add(tourBehavior);
}
@Override
protected boolean hasNavigation() {
return true;
}
}
| true | true | public ExtensionsPage(PageParameters parameters) {
super(parameters);
List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(
new Video("http://ia700305.us.archive.org/18/items/CopyingIsNotTheft/CINT_Nik_H264_720.ogv", "video/ogg"),
new Video("http://ia700305.us.archive.org/18/items/CopyingIsNotTheft/CINT_Nik_H264_720_512kb.mp4", "video/mp4")
);
add(new Html5Player("video", Model.ofList(videos)));
add(new Code("video-code", Model.of("List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(\n"
+ "\t\tnew Video(\"video.ogv\", \"video/ogg\"),\n"
+ "\t\tnew Video(\"video.mp4\", \"video/mp4\")\n"
+ ");\n"
+ "add(new Html5Player(\"video\", Model.ofList(videos)));")));
add(new Html5Player("video-custom", Model.ofList(videos), new Html5VideoConfig().showProgressBar(false).autoHideControlBar(false)).setWidth(680).setHeight(360));
add(new Code("video-custom-code", Model.of("List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(\n"
+ "\t\tnew Video(\"video.ogv\", \"video/ogg\"),\n"
+ "\t\tnew Video(\"video.mp4\", \"video/mp4\")\n"
+ ");\n"
+ "add(new Html5Player(\"video\", Model.ofList(videos),\n"
+ "\tnew Html5VideoConfig().showProgressBar(false).autoHideControlBar(false))\n"
+ "\t\t.setWidth(680).setHeight(360));")));
final List<? extends AbstractLink> buttons = Lists.<AbstractLink>newArrayList(
new MenuBookmarkablePageLink<DatePickerPage>(DatePickerPage.class, Model.of("DatePicker")).setIconType(IconType.time),
new MenuBookmarkablePageLink<IssuesPage>(IssuesPage.class, Model.of("Github Issues")).setIconType(IconType.book),
new MenuBookmarkablePageLink<ExtensionsPage>(ExtensionsPage.class, Model.of("Extensions")).setIconType(IconType.qrcode)
);
final Component contextPanel = new TransparentWebMarkupContainer("context-panel");
final ButtonListContextMenu contextMenu = new ButtonListContextMenu("contextmenu", Model.ofList(buttons));
contextMenu.assignTo(contextPanel);
add(contextMenu, contextPanel,
new Code("context-code", Model.of(""
+ "final List<? extends AbstractLink> buttons = Lists.<AbstractLink>newArrayList(\n"
+ "\tnew MenuBookmarkablePageLink<>(...),\n"
+ "\t[...]\n"
+ ");\n"
+ "final Component contextPanel = new TransparentWebMarkupContainer(\"context-panel\");\n"
+ "final ButtonListContextMenu contextMenu = new ButtonListContextMenu(\"contextmenu\", \n"
+ "\t\tModel.ofList(buttons));\n"
+ "contextMenu.assignTo(contextPanel);\n"
+ "add(contextMenu, contextPanel,")));
Modal draggableModal = new TextContentModal("draggable-modal", Model.of("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."));
draggableModal.add(new Draggable(new DraggableConfig().withHandle(".modal-header").withCursor("move")));
draggableModal.add(new Resizable());
draggableModal.setUseKeyboard(true).addCloseButton();
draggableModal.setFadeIn(false);
Label draggableButton = new Label("open-draggable", "Open Modal Dialog");
draggableModal.addOpenerAttributesTo(draggableButton);
add(draggableModal, draggableButton, new Code("draggable-code", Model.of("")));
DropDownButton dropDownButton = new DropDownButton("dropdown", Model.of("open-on-hover")) {
@Override
protected List<AbstractLink> newSubMenuButtons(String buttonMarkupId) {
return Lists.<AbstractLink>newArrayList(
new MenuBookmarkablePageLink<DatePickerPage>(DatePickerPage.class, Model.of("DatePicker")).setIconType(IconType.time),
new MenuBookmarkablePageLink<IssuesPage>(IssuesPage.class, Model.of("Github Issues")).setIconType(IconType.book),
new MenuBookmarkablePageLink<ExtensionsPage>(ExtensionsPage.class, Model.of("Extensions")).setIconType(IconType.qrcode)
);
}
};
dropDownButton.add(new DropDownAutoOpen());
add(dropDownButton, new Code("dropdown-code", Model.of("dropDownButton.add(new DropDownAutoOpen());")));
addTour();
add(new Icon("html5-colored", OpenWebIconType.html5_colored_large), new Icon("apml", OpenWebIconType.apml), new Icon("feed", OpenWebIconType.feed_colored_large));
add(new Icon("html5", OpenWebIconType.html5), new Code("openwebicon-code", Model.of("response.render(JavaScriptHeaderItem.forReference(OpenWebIconsCssReference.instance()));\n\nadd(new Icon(\"html5\", OpenWebIconType.html5));")));
addJasnyFileUploadDemo();
addJasnyInputMaskDemo();
add(new InfinitePaginationPanel("infinite"));
}
| public ExtensionsPage(PageParameters parameters) {
super(parameters);
List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(
new Video("http://ia700305.us.archive.org/18/items/CopyingIsNotTheft/CINT_Nik_H264_720.ogv", "video/ogg"),
new Video("http://ia700305.us.archive.org/18/items/CopyingIsNotTheft/CINT_Nik_H264_720_512kb.mp4", "video/mp4")
);
add(new Html5Player("video", Model.ofList(videos)));
add(new Code("video-code", Model.of("List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(\n"
+ "\t\tnew Video(\"video.ogv\", \"video/ogg\"),\n"
+ "\t\tnew Video(\"video.mp4\", \"video/mp4\")\n"
+ ");\n"
+ "add(new Html5Player(\"video\", Model.ofList(videos)));")));
add(new Html5Player("video-custom", Model.ofList(videos), new Html5VideoConfig().showProgressBar(false).autoHideControlBar(false)).setWidth(680).setHeight(360));
add(new Code("video-custom-code", Model.of("List<Html5Player.IVideo> videos = Lists.<Html5Player.IVideo>newArrayList(\n"
+ "\t\tnew Video(\"video.ogv\", \"video/ogg\"),\n"
+ "\t\tnew Video(\"video.mp4\", \"video/mp4\")\n"
+ ");\n"
+ "add(new Html5Player(\"video\", Model.ofList(videos),\n"
+ "\tnew Html5VideoConfig().showProgressBar(false).autoHideControlBar(false))\n"
+ "\t\t.setWidth(680).setHeight(360));")));
final List<? extends AbstractLink> buttons = Lists.<AbstractLink>newArrayList(
new MenuBookmarkablePageLink<DatePickerPage>(DatePickerPage.class, Model.of("DatePicker")).setIconType(IconType.time),
new MenuBookmarkablePageLink<IssuesPage>(IssuesPage.class, Model.of("Github Issues")).setIconType(IconType.book),
new MenuBookmarkablePageLink<ExtensionsPage>(ExtensionsPage.class, Model.of("Extensions")).setIconType(IconType.qrcode)
);
final Component contextPanel = new TransparentWebMarkupContainer("context-panel");
final ButtonListContextMenu contextMenu = new ButtonListContextMenu("contextmenu", Model.ofList(buttons));
contextMenu.assignTo(contextPanel);
add(contextMenu, contextPanel,
new Code("context-code", Model.of(""
+ "final List<? extends AbstractLink> buttons = Lists.<AbstractLink>newArrayList(\n"
+ "\tnew MenuBookmarkablePageLink<>(...),\n"
+ "\t[...]\n"
+ ");\n"
+ "final Component contextPanel = new TransparentWebMarkupContainer(\"context-panel\");\n"
+ "final ButtonListContextMenu contextMenu = new ButtonListContextMenu(\"contextmenu\", \n"
+ "\t\tModel.ofList(buttons));\n"
+ "contextMenu.assignTo(contextPanel);\n"
+ "add(contextMenu, contextPanel,")));
Modal draggableModal = new TextContentModal("draggable-modal", Model.of("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."));
// draggableModal.add(new Draggable(new DraggableConfig().withHandle(".modal-header").withCursor("move")));
// draggableModal.add(new Resizable());
draggableModal.setUseKeyboard(true).addCloseButton();
draggableModal.setFadeIn(false);
Label draggableButton = new Label("open-draggable", "Open Modal Dialog");
draggableModal.addOpenerAttributesTo(draggableButton);
add(draggableModal, draggableButton, new Code("draggable-code", Model.of("")));
DropDownButton dropDownButton = new DropDownButton("dropdown", Model.of("open-on-hover")) {
@Override
protected List<AbstractLink> newSubMenuButtons(String buttonMarkupId) {
return Lists.<AbstractLink>newArrayList(
new MenuBookmarkablePageLink<DatePickerPage>(DatePickerPage.class, Model.of("DatePicker")).setIconType(IconType.time),
new MenuBookmarkablePageLink<IssuesPage>(IssuesPage.class, Model.of("Github Issues")).setIconType(IconType.book),
new MenuBookmarkablePageLink<ExtensionsPage>(ExtensionsPage.class, Model.of("Extensions")).setIconType(IconType.qrcode)
);
}
};
dropDownButton.add(new DropDownAutoOpen());
add(dropDownButton, new Code("dropdown-code", Model.of("dropDownButton.add(new DropDownAutoOpen());")));
addTour();
add(new Icon("html5-colored", OpenWebIconType.html5_colored_large), new Icon("apml", OpenWebIconType.apml), new Icon("feed", OpenWebIconType.feed_colored_large));
add(new Icon("html5", OpenWebIconType.html5), new Code("openwebicon-code", Model.of("response.render(JavaScriptHeaderItem.forReference(OpenWebIconsCssReference.instance()));\n\nadd(new Icon(\"html5\", OpenWebIconType.html5));")));
addJasnyFileUploadDemo();
addJasnyInputMaskDemo();
add(new InfinitePaginationPanel("infinite"));
}
|
diff --git a/SucklessGame/src/com/suckless/Selecter.java b/SucklessGame/src/com/suckless/Selecter.java
index a758492..e5a5ac1 100644
--- a/SucklessGame/src/com/suckless/Selecter.java
+++ b/SucklessGame/src/com/suckless/Selecter.java
@@ -1,85 +1,85 @@
package com.suckless;
public abstract class Selecter extends Command {
public enum StateDirection {
LEFT,
RIGHT,
UP,
DOWN,
NONE
}
public int x,y,maxX,maxY;
public StateDirection direction;
boolean first = true;
Selecter(GameObject inputObject,StateDirection dir) {
super(inputObject);
direction = dir;
}
public abstract Command handleSelect(GameObject inputObject);
@Override
public Command Select(Field[][] states, Player player){
switch(direction){
case LEFT: direction = StateDirection.DOWN;
break;
case RIGHT: direction = StateDirection.UP;
break;
case UP: return handleSelect(selectedObject);
case DOWN: return handleSelect(selectedObject);
default:
break;
}
return this;
}
@Override
public Command Update(Field[][] states, Player player){
System.out.println(String.format("%d %d", x,y));
maxX = states.length;
maxY = states[0].length;
if(first){
if(direction == StateDirection.LEFT){
x = maxX;
}else{
x = 0;
}
first = false;
}
switch(direction){
case LEFT: if(x < 0){
return null;
}
else{
x = x-1;
}
break;
case RIGHT: if(x >= maxX){
return null;
}
else{
x = x+1;
}
break;
- case UP: if(y <= 0){
+ case UP: if(y >= maxY){
return null;
}
else{
y = y+1;
}
break;
- case DOWN: if(y >= maxY){
+ case DOWN: if(y < 0){
return null;
}
else{
y = y-1;
}
break;
default:
break;
}
return this;
}
}
| false | true | public Command Update(Field[][] states, Player player){
System.out.println(String.format("%d %d", x,y));
maxX = states.length;
maxY = states[0].length;
if(first){
if(direction == StateDirection.LEFT){
x = maxX;
}else{
x = 0;
}
first = false;
}
switch(direction){
case LEFT: if(x < 0){
return null;
}
else{
x = x-1;
}
break;
case RIGHT: if(x >= maxX){
return null;
}
else{
x = x+1;
}
break;
case UP: if(y <= 0){
return null;
}
else{
y = y+1;
}
break;
case DOWN: if(y >= maxY){
return null;
}
else{
y = y-1;
}
break;
default:
break;
}
return this;
}
| public Command Update(Field[][] states, Player player){
System.out.println(String.format("%d %d", x,y));
maxX = states.length;
maxY = states[0].length;
if(first){
if(direction == StateDirection.LEFT){
x = maxX;
}else{
x = 0;
}
first = false;
}
switch(direction){
case LEFT: if(x < 0){
return null;
}
else{
x = x-1;
}
break;
case RIGHT: if(x >= maxX){
return null;
}
else{
x = x+1;
}
break;
case UP: if(y >= maxY){
return null;
}
else{
y = y+1;
}
break;
case DOWN: if(y < 0){
return null;
}
else{
y = y-1;
}
break;
default:
break;
}
return this;
}
|
diff --git a/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipNamingContextListener.java b/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipNamingContextListener.java
index 53def8239..159257111 100644
--- a/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipNamingContextListener.java
+++ b/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipNamingContextListener.java
@@ -1,306 +1,320 @@
/*
* 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.servlet.sip.startup;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipSessionsUtil;
import javax.servlet.sip.TimerService;
import org.apache.catalina.ContainerEvent;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.core.NamingContextListener;
import org.apache.log4j.Logger;
import org.apache.naming.ContextAccessController;
import org.mobicents.servlet.sip.catalina.CatalinaSipContext;
import org.mobicents.servlet.sip.core.SipContext;
/**
* Helper class used to initialize and populate the JNDI context associated
* with each context with the sip factory.
*
* @author Jean Deruelle
*
*/
public class SipNamingContextListener extends NamingContextListener {
private static transient final Logger logger = Logger.getLogger(SipNamingContextListener.class);
public static final String NAMING_CONTEXT_SIP_SUBCONTEXT_ADDED_EVENT = "addSipSubcontext";
public static final String NAMING_CONTEXT_SIP_SUBCONTEXT_REMOVED_EVENT = "removeSipSubContext";
public static final String NAMING_CONTEXT_APPNAME_SUBCONTEXT_ADDED_EVENT = "addAppNameSubcontext";
public static final String NAMING_CONTEXT_APPNAME_SUBCONTEXT_REMOVED_EVENT = "removeAppNameSubcontext";
public static final String NAMING_CONTEXT_SIP_FACTORY_ADDED_EVENT = "addSipFactory";
public static final String NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT = "removeSipFactory";
public static final String NAMING_CONTEXT_SIP_SESSIONS_UTIL_ADDED_EVENT = "addSipSessionsUtil";
public static final String NAMING_CONTEXT_SIP_SESSIONS_UTIL_REMOVED_EVENT = "removeSipSessionsUtil";
public static final String NAMING_CONTEXT_TIMER_SERVICE_ADDED_EVENT = "addTimerService";
public static final String NAMING_CONTEXT_TIMER_SERVICE_REMOVED_EVENT = "removeTimerService";
public static final String SIP_SUBCONTEXT = "sip";
public static final String SIP_FACTORY_JNDI_NAME = "SipFactory";
public static final String SIP_SESSIONS_UTIL_JNDI_NAME = "SipSessionsUtil";
public static final String TIMER_SERVICE_JNDI_NAME = "TimerService";
@Override
public void lifecycleEvent(LifecycleEvent event) {
super.lifecycleEvent(event);
if (event.getType().equalsIgnoreCase(Lifecycle.START_EVENT)) {
if (container instanceof CatalinaSipContext) {
((CatalinaSipContext)container).getSipInstanceManager().setContext(envCtx);
}
}
}
@Override
public void containerEvent(ContainerEvent event) {
super.containerEvent(event);
// Setting the context in read/write mode
ContextAccessController.setWritable(getName(), container);
String type = event.getType();
SipContext sipContext = null;
String appName = null;
if(event.getContainer() instanceof SipContext) {
sipContext = (SipContext)event.getContainer();
appName = sipContext.getApplicationName();
}
if (type.equals(NAMING_CONTEXT_SIP_SUBCONTEXT_ADDED_EVENT)) {
addSipSubcontext(envCtx);
if(logger.isDebugEnabled()) {
logger.debug("Sip Subcontext added to the JNDI context for container " + event.getContainer());
}
} else if (type.equals(NAMING_CONTEXT_SIP_SUBCONTEXT_REMOVED_EVENT)) {
removeSipSubcontext(envCtx);
if(logger.isDebugEnabled()) {
logger.debug("Sip Subcontext removed from the JNDI context for container " + event.getContainer());
}
} if (type.equals(NAMING_CONTEXT_APPNAME_SUBCONTEXT_ADDED_EVENT)) {
- addAppNameSubContext(envCtx, appName);
- if(logger.isDebugEnabled()) {
- logger.debug(appName + " Subcontext added to the JNDI context for container " + event.getContainer());
+ if(appName != null) {
+ // https://code.google.com/p/sipservlets/issues/detail?id=257
+ addAppNameSubContext(envCtx, appName);
+ if(logger.isDebugEnabled()) {
+ logger.debug(appName + " Subcontext added to the JNDI context for container " + event.getContainer());
+ }
+ } else {
+ if(logger.isDebugEnabled()) {
+ logger.debug(appName + " is null so subcontext not added to JNDI context for container " + event.getContainer());
+ }
}
} else if (type.equals(NAMING_CONTEXT_APPNAME_SUBCONTEXT_REMOVED_EVENT)) {
- removeAppNameSubContext(envCtx, appName);
- if(logger.isDebugEnabled()) {
- logger.debug(appName + " Subcontext removed from the JNDI context for container " + event.getContainer());
+ if(appName != null) {
+ // https://code.google.com/p/sipservlets/issues/detail?id=257
+ removeAppNameSubContext(envCtx, appName);
+ if(logger.isDebugEnabled()) {
+ logger.debug(appName + " Subcontext removed from the JNDI context for container " + event.getContainer());
+ }
+ } else {
+ if(logger.isDebugEnabled()) {
+ logger.debug(appName + " is null so subcontext not removed to JNDI context for container " + event.getContainer());
+ }
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_ADDED_EVENT)) {
SipFactory sipFactory = (SipFactory) event.getData();
if (sipFactory != null) {
addSipFactory(envCtx, appName, sipFactory);
if(logger.isDebugEnabled()) {
logger.debug("Sip Factory added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT)) {
SipFactory sipFactory = (SipFactory) event.getData();
if (sipFactory != null) {
removeSipFactory(envCtx, appName, sipFactory);
if(logger.isDebugEnabled()) {
logger.debug("Sip Factory removed from the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_SESSIONS_UTIL_ADDED_EVENT)) {
SipSessionsUtil sipSessionsUtil = (SipSessionsUtil) event.getData();
if (sipSessionsUtil != null) {
addSipSessionsUtil(envCtx, appName, sipSessionsUtil);
if(logger.isDebugEnabled()) {
logger.debug("SipSessionsUtil added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_SESSIONS_UTIL_REMOVED_EVENT)) {
SipSessionsUtil sipSessionsUtil = (SipSessionsUtil) event.getData();
if (sipSessionsUtil != null) {
removeSipSessionsUtil(envCtx, appName, sipSessionsUtil);
if(logger.isDebugEnabled()) {
logger.debug("SipSessionsUtil removed from the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_TIMER_SERVICE_ADDED_EVENT)) {
TimerService timerService = (TimerService) event.getData();
if (timerService != null) {
addTimerService(envCtx, appName, timerService);
if(logger.isDebugEnabled()) {
logger.debug("TimerService added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT)) {
TimerService timerService = (TimerService) event.getData();
if (timerService != null) {
removeTimerService(envCtx, appName, timerService);
if(logger.isDebugEnabled()) {
logger.debug("TimerService removed from the JNDI context for container " + event.getContainer());
}
}
}
// Setting the context in read only mode
ContextAccessController.setReadOnly(getName());
}
/**
* Removes the sip subcontext from JNDI
* @param envCtx the envContext from which the sip subcontext should be removed
*/
public static void removeSipSubcontext(Context envCtx) {
try {
envCtx.destroySubcontext(SIP_SUBCONTEXT);
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
}
/**
* Add the sip subcontext to JNDI
* @param envCtx the envContext to which the sip subcontext should be added
*/
public static void addSipSubcontext(Context envCtx) {
try {
envCtx.createSubcontext(SIP_SUBCONTEXT);
} catch (NamingException e) {
logger.error(sm.getString("naming.bindFailed", e));
}
}
/**
* Removes the app name subcontext from the jndi mapping
* @param appName sub context Name
*/
public static void removeAppNameSubContext(Context envCtx, String appName) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT);
sipContext.destroySubcontext(appName);
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
}
}
/**
* Add the application name subcontext from the jndi mapping
* @param appName sub context Name
*/
public static void addAppNameSubContext(Context envCtx, String appName) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT);
sipContext.createSubcontext(appName);
} catch (NamingException e) {
logger.error(sm.getString("naming.bindFailed", e));
}
}
}
/**
* Removes the sip sessions util binding from the jndi mapping
* @param appName the application name subcontext
* @param sipSessionsUtil the sip sessions util to remove
*/
public static void removeSipSessionsUtil(Context envCtx, String appName, SipSessionsUtil sipSessionsUtil) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT + "/" + appName);
sipContext.unbind(SIP_SESSIONS_UTIL_JNDI_NAME);
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
}
}
/**
* Add the sip sessions util binding from the jndi mapping
* and bind the sip sessions util in parameter to it
* @param appName the application name subcontext
* @param sipSessionsUtil the sip sessions util to add
*/
public static void addSipSessionsUtil(Context envCtx, String appName, SipSessionsUtil sipSessionsUtil) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT + "/" + appName);
sipContext.bind(SIP_SESSIONS_UTIL_JNDI_NAME, sipSessionsUtil);
} catch (NamingException e) {
logger.error(sm.getString("naming.bindFailed", e));
}
}
}
/**
* Removes the Timer Service binding from the jndi mapping
* @param appName the application name subcontext
* @param timerService the Timer Service to remove
*/
public static void removeTimerService(Context envCtx, String appName, TimerService timerService) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT + "/" + appName);
sipContext.unbind(TIMER_SERVICE_JNDI_NAME);
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
}
}
/**
* Add the sip timer service from the jndi mapping
* and bind the timer service in parameter to it
* @param appName the application name subcontext
* @param timerService the Timer Service to add
*/
public static void addTimerService(Context envCtx, String appName, TimerService timerService) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT + "/" + appName);
sipContext.bind(TIMER_SERVICE_JNDI_NAME, timerService);
} catch (NamingException e) {
logger.error(sm.getString("naming.bindFailed", e));
}
}
}
/**
* Removes the sip factory binding from the jndi mapping
* @param appName the application name subcontext
* @param sipFactory the sip factory to remove
*/
public static void removeSipFactory(Context envCtx, String appName, SipFactory sipFactory) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT + "/" + appName);
sipContext.unbind(SIP_FACTORY_JNDI_NAME);
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
}
}
/**
* Add the sip factory binding from the jndi mapping
* and bind the sip factory in paramter to it
* @param appName
* @param sipFactory the sip factory to add
*/
public static void addSipFactory(Context envCtx, String appName, SipFactory sipFactory) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT + "/" + appName);
sipContext.bind(SIP_FACTORY_JNDI_NAME, sipFactory);
} catch (NamingException e) {
logger.error(sm.getString("naming.bindFailed", e));
}
}
}
}
| false | true | public void containerEvent(ContainerEvent event) {
super.containerEvent(event);
// Setting the context in read/write mode
ContextAccessController.setWritable(getName(), container);
String type = event.getType();
SipContext sipContext = null;
String appName = null;
if(event.getContainer() instanceof SipContext) {
sipContext = (SipContext)event.getContainer();
appName = sipContext.getApplicationName();
}
if (type.equals(NAMING_CONTEXT_SIP_SUBCONTEXT_ADDED_EVENT)) {
addSipSubcontext(envCtx);
if(logger.isDebugEnabled()) {
logger.debug("Sip Subcontext added to the JNDI context for container " + event.getContainer());
}
} else if (type.equals(NAMING_CONTEXT_SIP_SUBCONTEXT_REMOVED_EVENT)) {
removeSipSubcontext(envCtx);
if(logger.isDebugEnabled()) {
logger.debug("Sip Subcontext removed from the JNDI context for container " + event.getContainer());
}
} if (type.equals(NAMING_CONTEXT_APPNAME_SUBCONTEXT_ADDED_EVENT)) {
addAppNameSubContext(envCtx, appName);
if(logger.isDebugEnabled()) {
logger.debug(appName + " Subcontext added to the JNDI context for container " + event.getContainer());
}
} else if (type.equals(NAMING_CONTEXT_APPNAME_SUBCONTEXT_REMOVED_EVENT)) {
removeAppNameSubContext(envCtx, appName);
if(logger.isDebugEnabled()) {
logger.debug(appName + " Subcontext removed from the JNDI context for container " + event.getContainer());
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_ADDED_EVENT)) {
SipFactory sipFactory = (SipFactory) event.getData();
if (sipFactory != null) {
addSipFactory(envCtx, appName, sipFactory);
if(logger.isDebugEnabled()) {
logger.debug("Sip Factory added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT)) {
SipFactory sipFactory = (SipFactory) event.getData();
if (sipFactory != null) {
removeSipFactory(envCtx, appName, sipFactory);
if(logger.isDebugEnabled()) {
logger.debug("Sip Factory removed from the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_SESSIONS_UTIL_ADDED_EVENT)) {
SipSessionsUtil sipSessionsUtil = (SipSessionsUtil) event.getData();
if (sipSessionsUtil != null) {
addSipSessionsUtil(envCtx, appName, sipSessionsUtil);
if(logger.isDebugEnabled()) {
logger.debug("SipSessionsUtil added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_SESSIONS_UTIL_REMOVED_EVENT)) {
SipSessionsUtil sipSessionsUtil = (SipSessionsUtil) event.getData();
if (sipSessionsUtil != null) {
removeSipSessionsUtil(envCtx, appName, sipSessionsUtil);
if(logger.isDebugEnabled()) {
logger.debug("SipSessionsUtil removed from the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_TIMER_SERVICE_ADDED_EVENT)) {
TimerService timerService = (TimerService) event.getData();
if (timerService != null) {
addTimerService(envCtx, appName, timerService);
if(logger.isDebugEnabled()) {
logger.debug("TimerService added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT)) {
TimerService timerService = (TimerService) event.getData();
if (timerService != null) {
removeTimerService(envCtx, appName, timerService);
if(logger.isDebugEnabled()) {
logger.debug("TimerService removed from the JNDI context for container " + event.getContainer());
}
}
}
// Setting the context in read only mode
ContextAccessController.setReadOnly(getName());
}
| public void containerEvent(ContainerEvent event) {
super.containerEvent(event);
// Setting the context in read/write mode
ContextAccessController.setWritable(getName(), container);
String type = event.getType();
SipContext sipContext = null;
String appName = null;
if(event.getContainer() instanceof SipContext) {
sipContext = (SipContext)event.getContainer();
appName = sipContext.getApplicationName();
}
if (type.equals(NAMING_CONTEXT_SIP_SUBCONTEXT_ADDED_EVENT)) {
addSipSubcontext(envCtx);
if(logger.isDebugEnabled()) {
logger.debug("Sip Subcontext added to the JNDI context for container " + event.getContainer());
}
} else if (type.equals(NAMING_CONTEXT_SIP_SUBCONTEXT_REMOVED_EVENT)) {
removeSipSubcontext(envCtx);
if(logger.isDebugEnabled()) {
logger.debug("Sip Subcontext removed from the JNDI context for container " + event.getContainer());
}
} if (type.equals(NAMING_CONTEXT_APPNAME_SUBCONTEXT_ADDED_EVENT)) {
if(appName != null) {
// https://code.google.com/p/sipservlets/issues/detail?id=257
addAppNameSubContext(envCtx, appName);
if(logger.isDebugEnabled()) {
logger.debug(appName + " Subcontext added to the JNDI context for container " + event.getContainer());
}
} else {
if(logger.isDebugEnabled()) {
logger.debug(appName + " is null so subcontext not added to JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_APPNAME_SUBCONTEXT_REMOVED_EVENT)) {
if(appName != null) {
// https://code.google.com/p/sipservlets/issues/detail?id=257
removeAppNameSubContext(envCtx, appName);
if(logger.isDebugEnabled()) {
logger.debug(appName + " Subcontext removed from the JNDI context for container " + event.getContainer());
}
} else {
if(logger.isDebugEnabled()) {
logger.debug(appName + " is null so subcontext not removed to JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_ADDED_EVENT)) {
SipFactory sipFactory = (SipFactory) event.getData();
if (sipFactory != null) {
addSipFactory(envCtx, appName, sipFactory);
if(logger.isDebugEnabled()) {
logger.debug("Sip Factory added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT)) {
SipFactory sipFactory = (SipFactory) event.getData();
if (sipFactory != null) {
removeSipFactory(envCtx, appName, sipFactory);
if(logger.isDebugEnabled()) {
logger.debug("Sip Factory removed from the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_SESSIONS_UTIL_ADDED_EVENT)) {
SipSessionsUtil sipSessionsUtil = (SipSessionsUtil) event.getData();
if (sipSessionsUtil != null) {
addSipSessionsUtil(envCtx, appName, sipSessionsUtil);
if(logger.isDebugEnabled()) {
logger.debug("SipSessionsUtil added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_SESSIONS_UTIL_REMOVED_EVENT)) {
SipSessionsUtil sipSessionsUtil = (SipSessionsUtil) event.getData();
if (sipSessionsUtil != null) {
removeSipSessionsUtil(envCtx, appName, sipSessionsUtil);
if(logger.isDebugEnabled()) {
logger.debug("SipSessionsUtil removed from the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_TIMER_SERVICE_ADDED_EVENT)) {
TimerService timerService = (TimerService) event.getData();
if (timerService != null) {
addTimerService(envCtx, appName, timerService);
if(logger.isDebugEnabled()) {
logger.debug("TimerService added to the JNDI context for container " + event.getContainer());
}
}
} else if (type.equals(NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT)) {
TimerService timerService = (TimerService) event.getData();
if (timerService != null) {
removeTimerService(envCtx, appName, timerService);
if(logger.isDebugEnabled()) {
logger.debug("TimerService removed from the JNDI context for container " + event.getContainer());
}
}
}
// Setting the context in read only mode
ContextAccessController.setReadOnly(getName());
}
|
diff --git a/src/java/grails/plugin/multitenant/core/spring/TenantScope.java b/src/java/grails/plugin/multitenant/core/spring/TenantScope.java
index db40eef..ea13bcd 100644
--- a/src/java/grails/plugin/multitenant/core/spring/TenantScope.java
+++ b/src/java/grails/plugin/multitenant/core/spring/TenantScope.java
@@ -1,98 +1,101 @@
package grails.plugin.multitenant.core.spring;
import grails.plugin.multitenant.core.CurrentTenant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Custom Spring scope for per-tenant Spring beans.
*
* Important: There is currently no listener making sure
* to remove any per-tenant beans when you delete a tenant.
* So if you delete a tenant this class will potentially
* hold a strong reference to tenant scoped beans belonging
* to the deleted tenant.
*
* Important: This class is expected to be thread-safe!
*
* @author Kim A. Betti
*/
public class TenantScope implements Scope, ApplicationContextAware {
public static final String NAME = "tenant";
private CurrentTenant currentTenant;
private ApplicationContext applicationContext;
private ConcurrentHashMap<Integer, Map<String, Object>> tenantBeanCache = new ConcurrentHashMap<Integer, Map<String, Object>>(50);
/**
* Return the object with the given name from the underlying scope, creating
* it if not found in the underlying storage mechanism.
*/
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Integer tenantId = currentTenant.get();
+ if (tenantId == null) { // ConcurrentHashMap does not allow nulls, so mapping to -1
+ tenantId = new Integer(-1);
+ }
Map<String, Object> beanCache = getBeanCacheForTenant(tenantId);
if (!beanCache.containsKey(name)) {
beanCache.put(name, applicationContext.getBean(name + "_prototype"));
}
return beanCache.get(name);
}
private Map<String, Object> getBeanCacheForTenant(Integer tenantId) {
if (!tenantBeanCache.containsKey(tenantId)) {
tenantBeanCache.put(tenantId, new ConcurrentHashMap<String, Object>(10));
}
return tenantBeanCache.get(tenantId);
}
@Override
public String getConversationId() {
return "tenant-scope-" + currentTenant.get();
}
/**
* Register a callback to be executed on destruction of the specified object
* in the scope (or at destruction of the entire scope, if the scope does
* not destroy individual objects but rather only terminates in its
* entirety).
*/
@Override
public void registerDestructionCallback(String name, Runnable callback) {
throw new RuntimeException("registerDestructionCallback " + name + " is not implemented");
}
/**
* Remove the object with the given name from the underlying scope.
*/
@Override
public Object remove(String name) {
throw new RuntimeException("remove " + name + " is not implemented");
}
/**
* Resolve the contextual object for the given key, if any.
*/
@Override
public Object resolveContextualObject(String key) {
throw new RuntimeException("resolveContextualObject " + key + " is not implemented");
}
public void setCurrentTenant(CurrentTenant currentTenant) {
this.currentTenant = currentTenant;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
| true | true | public Object get(String name, ObjectFactory<?> objectFactory) {
Integer tenantId = currentTenant.get();
Map<String, Object> beanCache = getBeanCacheForTenant(tenantId);
if (!beanCache.containsKey(name)) {
beanCache.put(name, applicationContext.getBean(name + "_prototype"));
}
return beanCache.get(name);
}
| public Object get(String name, ObjectFactory<?> objectFactory) {
Integer tenantId = currentTenant.get();
if (tenantId == null) { // ConcurrentHashMap does not allow nulls, so mapping to -1
tenantId = new Integer(-1);
}
Map<String, Object> beanCache = getBeanCacheForTenant(tenantId);
if (!beanCache.containsKey(name)) {
beanCache.put(name, applicationContext.getBean(name + "_prototype"));
}
return beanCache.get(name);
}
|
diff --git a/src/com/zand/areaguard/area/cache/CacheWorld.java b/src/com/zand/areaguard/area/cache/CacheWorld.java
index 1df1171..dadfe9a 100644
--- a/src/com/zand/areaguard/area/cache/CacheWorld.java
+++ b/src/com/zand/areaguard/area/cache/CacheWorld.java
@@ -1,104 +1,103 @@
package com.zand.areaguard.area.cache;
import java.util.ArrayList;
import com.zand.areaguard.area.Cuboid;
import com.zand.areaguard.area.World;
import com.zand.areaguard.area.error.ErrorCuboid;
public class CacheWorld extends World implements CacheData {
final private CacheStorage storage;
final private World world;
static private int updateTime = 30000;
private long lastUpdate = 0;
// Cached Data
private boolean exsists;
final protected ArrayList<Cuboid> cuboids = new ArrayList<Cuboid>();
private String name;
public CacheWorld(CacheStorage storage, World world) {
super(world.getId());
this.storage = storage;
this.world = world;
}
@Override
public boolean deleteCuboids() {
if (deleteCuboids()) {
cuboids.clear();
return true;
}
return false;
}
@Override
public Cuboid getCuboid(int x, int y, int z) {
for (Cuboid cuboid : getCuboids()) {
if (cuboid.pointInside(this, x, y, z))
return cuboid;
}
return ErrorCuboid.NOT_FOUND;
}
@Override
public Cuboid getCuboid(boolean active, int x, int y, int z) {
for (Cuboid cuboid : getCuboids()) {
if (cuboid.pointInside(this, x, y, z))
return cuboid;
}
return ErrorCuboid.NOT_FOUND;
}
@Override
public ArrayList<Cuboid> getCuboids() {
update();
return cuboids;
}
@Override
public ArrayList<Cuboid> getCuboids(int x, int y, int z) {
ArrayList<Cuboid> ret = new ArrayList<Cuboid>();
for (Cuboid cuboid : getCuboids()) {
if (cuboid.pointInside(this, x, y, z))
ret.add(cuboid);
}
return ret;
}
@Override
public String getName() {
update();
return name;
}
@Override
public boolean exsists() {
update();
return exsists;
}
@Override
public boolean update() {
long time = System.currentTimeMillis();
if (time - lastUpdate > updateTime) {
lastUpdate = time;
exsists = world.exsists();
name = world.getName();
cuboids.clear();
for (Cuboid cuboid : world.getCuboids())
- if (cuboid.getWorld().getId() == getId() && !cuboids.contains(cuboid))
- cuboids.add(new CacheCuboid(storage, cuboid));
+ cuboids.add(storage.getCuboid(cuboid.getId()));
System.out.println("Updated World " + getName());
}
return true;
}
}
| true | true | public boolean update() {
long time = System.currentTimeMillis();
if (time - lastUpdate > updateTime) {
lastUpdate = time;
exsists = world.exsists();
name = world.getName();
cuboids.clear();
for (Cuboid cuboid : world.getCuboids())
if (cuboid.getWorld().getId() == getId() && !cuboids.contains(cuboid))
cuboids.add(new CacheCuboid(storage, cuboid));
System.out.println("Updated World " + getName());
}
return true;
}
| public boolean update() {
long time = System.currentTimeMillis();
if (time - lastUpdate > updateTime) {
lastUpdate = time;
exsists = world.exsists();
name = world.getName();
cuboids.clear();
for (Cuboid cuboid : world.getCuboids())
cuboids.add(storage.getCuboid(cuboid.getId()));
System.out.println("Updated World " + getName());
}
return true;
}
|
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/views/CommonNavigatorPatternFilter.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/views/CommonNavigatorPatternFilter.java
index 67eb47524..c2f6673a5 100644
--- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/views/CommonNavigatorPatternFilter.java
+++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/views/CommonNavigatorPatternFilter.java
@@ -1,22 +1,22 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers 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
*******************************************************************************/
package org.eclipse.mylyn.internal.context.ui.views;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.mylyn.internal.tasks.ui.TaskListPatternFilter;
/**
* @author Mik Kersten
*/
public class CommonNavigatorPatternFilter extends TaskListPatternFilter {
@Override
- protected boolean isLeafMatch(Viewer viewer, Object element) {
+ public boolean isLeafMatch(Viewer viewer, Object element) {
return super.isLeafMatch(viewer, element);
}
}
| true | true | protected boolean isLeafMatch(Viewer viewer, Object element) {
return super.isLeafMatch(viewer, element);
}
| public boolean isLeafMatch(Viewer viewer, Object element) {
return super.isLeafMatch(viewer, element);
}
|
diff --git a/src/com/casimirlab/simpleDeadlines/data/DeadlineUtils.java b/src/com/casimirlab/simpleDeadlines/data/DeadlineUtils.java
index 27f399c..ddc923f 100644
--- a/src/com/casimirlab/simpleDeadlines/data/DeadlineUtils.java
+++ b/src/com/casimirlab/simpleDeadlines/data/DeadlineUtils.java
@@ -1,79 +1,82 @@
package com.casimirlab.simpleDeadlines.data;
import android.content.ContentValues;
import android.net.Uri;
import android.text.TextUtils;
import com.casimirlab.simpleDeadlines.R;
import java.util.List;
public final class DeadlineUtils
{
public static final int LVL_TODAY = 1;
public static final int LVL_URGENT = 3;
public static final int LVL_WORRYING = 7;
public static final int LVL_NICE = 15;
public static final int LVL_NEVERMIND = -1;
public static final int[] LVL_ALL =
{
LVL_TODAY, LVL_URGENT, LVL_WORRYING, LVL_NICE, LVL_NEVERMIND
};
public static final Uri SHARE_BASE_URI = Uri.parse("sd.casimir-lab.net");
public static Uri contentValuesToShareUri(ContentValues values)
{
Uri.Builder builder = SHARE_BASE_URI.buildUpon();
String group = values.getAsString(DeadlinesContract.DeadlinesColumns.GROUP);
builder.appendPath(values.getAsString(DeadlinesContract.DeadlinesColumns.LABEL));
if (TextUtils.isEmpty(group))
builder.appendEncodedPath("%00");
else
builder.appendPath(group);
builder.appendPath(values.getAsString(DeadlinesContract.DeadlinesColumns.DUE_DATE));
builder.appendPath(values.getAsString(DeadlinesContract.DeadlinesColumns.DONE));
return builder.build();
}
public static int resColorFromLevel(int level)
{
switch (level)
{
case LVL_TODAY:
return R.color.lvl_today;
case LVL_URGENT:
return R.color.lvl_urgent;
case LVL_WORRYING:
return R.color.lvl_worrying;
case LVL_NICE:
return R.color.lvl_nice;
default:
return R.color.lvl_other;
}
}
public static ContentValues shareUriToContentValues(Uri uri)
{
List<String> segments = uri.getPathSegments();
if (segments.size() < 4)
throw new IllegalArgumentException(String.format("Malformed Uri: %s", uri));
ContentValues values = new ContentValues(4);
if (TextUtils.isEmpty(segments.get(0)))
throw new IllegalArgumentException(String.format("Empty label: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.LABEL, segments.get(0));
- values.put(DeadlinesContract.DeadlinesColumns.GROUP, segments.get(1));
+ if (segments.get(1).getBytes()[0] == 0)
+ values.put(DeadlinesContract.DeadlinesColumns.GROUP, (String)null);
+ else
+ values.put(DeadlinesContract.DeadlinesColumns.GROUP, segments.get(1));
if (TextUtils.isEmpty(segments.get(2)) || !TextUtils.isDigitsOnly(segments.get(2)))
throw new IllegalArgumentException(String.format("Malformed date: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.DUE_DATE, Long.parseLong(segments.get(2)));
if (TextUtils.isEmpty(segments.get(3)) || !TextUtils.isDigitsOnly(segments.get(3)))
throw new IllegalArgumentException(String.format("Malformed done state: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.DONE, Integer.parseInt(segments.get(3)));
return values;
}
}
| true | true | public static ContentValues shareUriToContentValues(Uri uri)
{
List<String> segments = uri.getPathSegments();
if (segments.size() < 4)
throw new IllegalArgumentException(String.format("Malformed Uri: %s", uri));
ContentValues values = new ContentValues(4);
if (TextUtils.isEmpty(segments.get(0)))
throw new IllegalArgumentException(String.format("Empty label: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.LABEL, segments.get(0));
values.put(DeadlinesContract.DeadlinesColumns.GROUP, segments.get(1));
if (TextUtils.isEmpty(segments.get(2)) || !TextUtils.isDigitsOnly(segments.get(2)))
throw new IllegalArgumentException(String.format("Malformed date: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.DUE_DATE, Long.parseLong(segments.get(2)));
if (TextUtils.isEmpty(segments.get(3)) || !TextUtils.isDigitsOnly(segments.get(3)))
throw new IllegalArgumentException(String.format("Malformed done state: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.DONE, Integer.parseInt(segments.get(3)));
return values;
}
| public static ContentValues shareUriToContentValues(Uri uri)
{
List<String> segments = uri.getPathSegments();
if (segments.size() < 4)
throw new IllegalArgumentException(String.format("Malformed Uri: %s", uri));
ContentValues values = new ContentValues(4);
if (TextUtils.isEmpty(segments.get(0)))
throw new IllegalArgumentException(String.format("Empty label: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.LABEL, segments.get(0));
if (segments.get(1).getBytes()[0] == 0)
values.put(DeadlinesContract.DeadlinesColumns.GROUP, (String)null);
else
values.put(DeadlinesContract.DeadlinesColumns.GROUP, segments.get(1));
if (TextUtils.isEmpty(segments.get(2)) || !TextUtils.isDigitsOnly(segments.get(2)))
throw new IllegalArgumentException(String.format("Malformed date: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.DUE_DATE, Long.parseLong(segments.get(2)));
if (TextUtils.isEmpty(segments.get(3)) || !TextUtils.isDigitsOnly(segments.get(3)))
throw new IllegalArgumentException(String.format("Malformed done state: %s", uri));
values.put(DeadlinesContract.DeadlinesColumns.DONE, Integer.parseInt(segments.get(3)));
return values;
}
|
diff --git a/web/src/main/java/org/jboss/jca/web/WARDeployer.java b/web/src/main/java/org/jboss/jca/web/WARDeployer.java
index 45fcddde8..13b626a80 100644
--- a/web/src/main/java/org/jboss/jca/web/WARDeployer.java
+++ b/web/src/main/java/org/jboss/jca/web/WARDeployer.java
@@ -1,163 +1,163 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008-2009, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jca.web;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.jboss.logging.Logger;
import com.github.fungal.api.util.FileUtil;
import com.github.fungal.spi.deployers.DeployException;
import com.github.fungal.spi.deployers.Deployer;
import com.github.fungal.spi.deployers.Deployment;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* The WAR deployer for JCA/SJC
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public class WARDeployer implements Deployer
{
private static Logger log = Logger.getLogger(WARDeployer.class);
private static boolean trace = log.isTraceEnabled();
private WebServer webServer;
/**
* Constructor
*/
public WARDeployer()
{
this.webServer = null;
}
/**
* Get the web server
* @return The server
*/
public WebServer getWebServer()
{
return webServer;
}
/**
* Set the web server
* @param server The server
*/
public void setWebServer(WebServer server)
{
this.webServer = server;
}
/**
* Deploy
* @param url The url
* @param parent The parent classloader
* @return The deployment
* @exception DeployException Thrown if an error occurs during deployment
*/
public synchronized Deployment deploy(URL url, ClassLoader parent) throws DeployException
{
if (url == null || !(url.toExternalForm().endsWith(".war") || url.toExternalForm().endsWith(".war/")))
return null;
log.debug("Deploying: " + url.toExternalForm());
try
{
String path = url.toExternalForm();
// Extract context path based on .war name
String contextPath = "/";
if (!path.endsWith("/"))
{
contextPath += path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
}
else
{
int lastIndex = path.lastIndexOf('/');
int index = path.indexOf('/');
boolean done = false;
while (!done)
{
if (index + 1 <= path.length())
{
int nextIndex = path.indexOf('/', index + 1);
if (nextIndex == lastIndex)
{
done = true;
}
else
{
index = nextIndex;
}
}
else
{
done = true;
}
}
contextPath += path.substring(index + 1, path.lastIndexOf("."));
}
// Setup temporary work directory
File tmp = new File(SecurityActions.getSystemProperty("iron.jacamar.home"), "/tmp/");
File tmpDeployment = new File(tmp, "/web" + contextPath);
if (tmpDeployment.exists())
{
FileUtil fileUtil = new FileUtil();
fileUtil.recursiveDelete(tmpDeployment);
}
if (!tmpDeployment.mkdirs())
throw new IOException("Unable to create " + tmpDeployment);
// Map ROOT.war to /
if ("/ROOT".equalsIgnoreCase(contextPath))
contextPath = "/";
log.debug("ContextPath=" + contextPath);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath(contextPath);
webapp.setWar(url.toString());
webapp.setTempDirectory(tmpDeployment);
webServer.addHandler(webapp);
log.info("Deployed: " + url.toExternalForm());
return new WARDeployment(url, webapp, tmpDeployment, parent);
}
- catch (Exception e)
+ catch (Throwable t)
{
- throw new DeployException(e.getMessage(), e);
+ throw new DeployException(t.getMessage(), t);
}
}
}
| false | true | public synchronized Deployment deploy(URL url, ClassLoader parent) throws DeployException
{
if (url == null || !(url.toExternalForm().endsWith(".war") || url.toExternalForm().endsWith(".war/")))
return null;
log.debug("Deploying: " + url.toExternalForm());
try
{
String path = url.toExternalForm();
// Extract context path based on .war name
String contextPath = "/";
if (!path.endsWith("/"))
{
contextPath += path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
}
else
{
int lastIndex = path.lastIndexOf('/');
int index = path.indexOf('/');
boolean done = false;
while (!done)
{
if (index + 1 <= path.length())
{
int nextIndex = path.indexOf('/', index + 1);
if (nextIndex == lastIndex)
{
done = true;
}
else
{
index = nextIndex;
}
}
else
{
done = true;
}
}
contextPath += path.substring(index + 1, path.lastIndexOf("."));
}
// Setup temporary work directory
File tmp = new File(SecurityActions.getSystemProperty("iron.jacamar.home"), "/tmp/");
File tmpDeployment = new File(tmp, "/web" + contextPath);
if (tmpDeployment.exists())
{
FileUtil fileUtil = new FileUtil();
fileUtil.recursiveDelete(tmpDeployment);
}
if (!tmpDeployment.mkdirs())
throw new IOException("Unable to create " + tmpDeployment);
// Map ROOT.war to /
if ("/ROOT".equalsIgnoreCase(contextPath))
contextPath = "/";
log.debug("ContextPath=" + contextPath);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath(contextPath);
webapp.setWar(url.toString());
webapp.setTempDirectory(tmpDeployment);
webServer.addHandler(webapp);
log.info("Deployed: " + url.toExternalForm());
return new WARDeployment(url, webapp, tmpDeployment, parent);
}
catch (Exception e)
{
throw new DeployException(e.getMessage(), e);
}
}
| public synchronized Deployment deploy(URL url, ClassLoader parent) throws DeployException
{
if (url == null || !(url.toExternalForm().endsWith(".war") || url.toExternalForm().endsWith(".war/")))
return null;
log.debug("Deploying: " + url.toExternalForm());
try
{
String path = url.toExternalForm();
// Extract context path based on .war name
String contextPath = "/";
if (!path.endsWith("/"))
{
contextPath += path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
}
else
{
int lastIndex = path.lastIndexOf('/');
int index = path.indexOf('/');
boolean done = false;
while (!done)
{
if (index + 1 <= path.length())
{
int nextIndex = path.indexOf('/', index + 1);
if (nextIndex == lastIndex)
{
done = true;
}
else
{
index = nextIndex;
}
}
else
{
done = true;
}
}
contextPath += path.substring(index + 1, path.lastIndexOf("."));
}
// Setup temporary work directory
File tmp = new File(SecurityActions.getSystemProperty("iron.jacamar.home"), "/tmp/");
File tmpDeployment = new File(tmp, "/web" + contextPath);
if (tmpDeployment.exists())
{
FileUtil fileUtil = new FileUtil();
fileUtil.recursiveDelete(tmpDeployment);
}
if (!tmpDeployment.mkdirs())
throw new IOException("Unable to create " + tmpDeployment);
// Map ROOT.war to /
if ("/ROOT".equalsIgnoreCase(contextPath))
contextPath = "/";
log.debug("ContextPath=" + contextPath);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath(contextPath);
webapp.setWar(url.toString());
webapp.setTempDirectory(tmpDeployment);
webServer.addHandler(webapp);
log.info("Deployed: " + url.toExternalForm());
return new WARDeployment(url, webapp, tmpDeployment, parent);
}
catch (Throwable t)
{
throw new DeployException(t.getMessage(), t);
}
}
|
diff --git a/src/syslogDaemon.java b/src/syslogDaemon.java
index cd1cb36..706414a 100644
--- a/src/syslogDaemon.java
+++ b/src/syslogDaemon.java
@@ -1,112 +1,112 @@
import com.sleepycat.je.*;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.Date;
import java.io.File;
import java.nio.ByteBuffer;
/*
* This file is part of syslogUnity.
*
* syslogUnity 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.
*
* syslogUnity 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 syslogUnity. If not, see <http://www.gnu.org/licenses/>.
*/
public class syslogDaemon {
public static void main(String[] args) throws Exception {
new syslogDaemon().getEntries();
}
private void getEntries() throws Exception {
final File dbEnvDir = new File("/var/lib/syslogUnity/queueDB/");
int BUFFER_SIZE = 1024;
DatagramSocket syslog = new DatagramSocket(514);
DatagramPacket logEntry = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
envConfig.setCacheSize(20971520);
envConfig.setSharedCache(true);
final Environment env = new Environment(dbEnvDir, envConfig);
DatabaseConfig config = new DatabaseConfig();
config.setAllowCreate(true);
final Database queue = env.openDatabase(null, "logQueue", config);
final Cursor cursor;
cursor = queue.openCursor(null, null);
- LongEntry lastRecNoDbt = new LongEntry();
+ LongEntry lastRecNoDbt = new LongEntry(0);
DatabaseEntry throwaway = new DatabaseEntry();
cursor.getLast(lastRecNoDbt, throwaway, null);
long currentRecNo = lastRecNoDbt.getLong() + 1;
cursor.close();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
queue.close();
env.close();
System.out.print("Closed DB Gracefully...\n");
} catch (Exception dbe) {
System.out.print("Caught SIGINT, couldn't close queueDB successfully\n");
}
}
});
while (true) {
syslog.receive(logEntry);
InetAddress logHost = logEntry.getAddress();
String logLine = new String(logEntry.getData(), 0, logEntry.getLength());
doStuff(logLine, logHost, queue, currentRecNo);
currentRecNo++;
}
}
void doStuff(String logLine, InetAddress logHost, Database queue, long currentRecNo) {
Date logDate = new Date();
String logPriority = "";
int i;
for (i = 0; i <= logLine.length(); i++) {
if (logLine.charAt(i) == '>') break;
if (logLine.charAt(i) != '<') logPriority = logPriority + logLine.charAt(i);
}
String logData = logLine.substring(i + 1, logLine.length());
String dateEpoch = Long.toString(logDate.getTime());
String insertRecord = dateEpoch.concat("##FD##").
concat(logPriority).concat("##FD##").
concat(logHost.getHostAddress()).concat("##FD##").
concat(logData);
byte[] k = ByteBuffer.allocate(8).putLong(currentRecNo).array();
byte[] d = insertRecord.getBytes();
DatabaseEntry kdbt = new DatabaseEntry(k);
kdbt.setSize(8);
DatabaseEntry ddbt = new DatabaseEntry(d, 0, d.length);
ddbt.setSize(d.length);
try {
queue.put(null, kdbt, ddbt);
} catch (Exception dbe) {
System.out.print("Couldn't add record to database\n");
}
}
}
| true | true | private void getEntries() throws Exception {
final File dbEnvDir = new File("/var/lib/syslogUnity/queueDB/");
int BUFFER_SIZE = 1024;
DatagramSocket syslog = new DatagramSocket(514);
DatagramPacket logEntry = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
envConfig.setCacheSize(20971520);
envConfig.setSharedCache(true);
final Environment env = new Environment(dbEnvDir, envConfig);
DatabaseConfig config = new DatabaseConfig();
config.setAllowCreate(true);
final Database queue = env.openDatabase(null, "logQueue", config);
final Cursor cursor;
cursor = queue.openCursor(null, null);
LongEntry lastRecNoDbt = new LongEntry();
DatabaseEntry throwaway = new DatabaseEntry();
cursor.getLast(lastRecNoDbt, throwaway, null);
long currentRecNo = lastRecNoDbt.getLong() + 1;
cursor.close();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
queue.close();
env.close();
System.out.print("Closed DB Gracefully...\n");
} catch (Exception dbe) {
System.out.print("Caught SIGINT, couldn't close queueDB successfully\n");
}
}
});
while (true) {
syslog.receive(logEntry);
InetAddress logHost = logEntry.getAddress();
String logLine = new String(logEntry.getData(), 0, logEntry.getLength());
doStuff(logLine, logHost, queue, currentRecNo);
currentRecNo++;
}
}
| private void getEntries() throws Exception {
final File dbEnvDir = new File("/var/lib/syslogUnity/queueDB/");
int BUFFER_SIZE = 1024;
DatagramSocket syslog = new DatagramSocket(514);
DatagramPacket logEntry = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE);
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
envConfig.setCacheSize(20971520);
envConfig.setSharedCache(true);
final Environment env = new Environment(dbEnvDir, envConfig);
DatabaseConfig config = new DatabaseConfig();
config.setAllowCreate(true);
final Database queue = env.openDatabase(null, "logQueue", config);
final Cursor cursor;
cursor = queue.openCursor(null, null);
LongEntry lastRecNoDbt = new LongEntry(0);
DatabaseEntry throwaway = new DatabaseEntry();
cursor.getLast(lastRecNoDbt, throwaway, null);
long currentRecNo = lastRecNoDbt.getLong() + 1;
cursor.close();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
queue.close();
env.close();
System.out.print("Closed DB Gracefully...\n");
} catch (Exception dbe) {
System.out.print("Caught SIGINT, couldn't close queueDB successfully\n");
}
}
});
while (true) {
syslog.receive(logEntry);
InetAddress logHost = logEntry.getAddress();
String logLine = new String(logEntry.getData(), 0, logEntry.getLength());
doStuff(logLine, logHost, queue, currentRecNo);
currentRecNo++;
}
}
|
diff --git a/test/models/support/FinderTemplateTest.java b/test/models/support/FinderTemplateTest.java
index 75637e32..42be2a28 100644
--- a/test/models/support/FinderTemplateTest.java
+++ b/test/models/support/FinderTemplateTest.java
@@ -1,42 +1,40 @@
package models.support;
import models.Milestone;
import models.ModelTest;
import models.enumeration.Direction;
import models.enumeration.Matching;
import org.junit.Test;
import play.db.ebean.Model;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
public class FinderTemplateTest extends ModelTest<Milestone> {
private static Model.Finder<Long, Milestone> find = new Model.Finder<Long, Milestone>(
Long.class, Milestone.class);
@Test
public void findBy() throws Exception {
OrderParams orderParams = new OrderParams();
SearchParams searchParams = new SearchParams();
orderParams.add("dueDate", Direction.ASC);
searchParams.add("project.id", 2l, Matching.EQUALS);
- searchParams.add("completionRate", 100, Matching.LT);
List<Milestone> p2MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
- assertThat(p2MilestoneList.get(0).id).isEqualTo(4);
+ assertThat(p2MilestoneList.get(0).id).isEqualTo(3);
orderParams.clean();
searchParams.clean();
orderParams.add("dueDate", Direction.DESC);
searchParams.add("project.id", 1l, Matching.EQUALS);
- searchParams.add("completionRate", 50, Matching.EQUALS);
List<Milestone> p1MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
- assertThat(p1MilestoneList.get(0).id).isEqualTo(1);
+ assertThat(p1MilestoneList.get(0).id).isEqualTo(2);
}
}
| false | true | public void findBy() throws Exception {
OrderParams orderParams = new OrderParams();
SearchParams searchParams = new SearchParams();
orderParams.add("dueDate", Direction.ASC);
searchParams.add("project.id", 2l, Matching.EQUALS);
searchParams.add("completionRate", 100, Matching.LT);
List<Milestone> p2MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
assertThat(p2MilestoneList.get(0).id).isEqualTo(4);
orderParams.clean();
searchParams.clean();
orderParams.add("dueDate", Direction.DESC);
searchParams.add("project.id", 1l, Matching.EQUALS);
searchParams.add("completionRate", 50, Matching.EQUALS);
List<Milestone> p1MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
assertThat(p1MilestoneList.get(0).id).isEqualTo(1);
}
| public void findBy() throws Exception {
OrderParams orderParams = new OrderParams();
SearchParams searchParams = new SearchParams();
orderParams.add("dueDate", Direction.ASC);
searchParams.add("project.id", 2l, Matching.EQUALS);
List<Milestone> p2MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
assertThat(p2MilestoneList.get(0).id).isEqualTo(3);
orderParams.clean();
searchParams.clean();
orderParams.add("dueDate", Direction.DESC);
searchParams.add("project.id", 1l, Matching.EQUALS);
List<Milestone> p1MilestoneList = FinderTemplate.findBy(orderParams, searchParams, find);
assertThat(p1MilestoneList.get(0).id).isEqualTo(2);
}
|
diff --git a/org.lh.dmlj.schema.editor.parent/org.lh.dmlj.schema.editor.core/src/org/lh/dmlj/schema/editor/template/SetTemplate.java b/org.lh.dmlj.schema.editor.parent/org.lh.dmlj.schema.editor.core/src/org/lh/dmlj/schema/editor/template/SetTemplate.java
index 897da18..5a2c4b5 100644
--- a/org.lh.dmlj.schema.editor.parent/org.lh.dmlj.schema.editor.core/src/org/lh/dmlj/schema/editor/template/SetTemplate.java
+++ b/org.lh.dmlj.schema.editor.parent/org.lh.dmlj.schema.editor.core/src/org/lh/dmlj/schema/editor/template/SetTemplate.java
@@ -1,322 +1,328 @@
package org.lh.dmlj.schema.editor.template;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.lh.dmlj.schema.*;
public class SetTemplate
{
protected static String nl;
public static synchronized SetTemplate create(String lineSeparator)
{
nl = lineSeparator;
SetTemplate result = new SetTemplate();
nl = null;
return result;
}
public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
protected final String TEXT_1 = " ADD" + NL + " SET NAME IS ";
protected final String TEXT_2 = NL + " ORDER IS ";
protected final String TEXT_3 = NL + " MODE IS ";
protected final String TEXT_4 = NL + " OWNER IS ";
protected final String TEXT_5 = NL + "*+ WITHIN AREA ";
protected final String TEXT_6 = NL + " NEXT DBKEY POSITION IS ";
protected final String TEXT_7 = " " + NL + " PRIOR DBKEY POSITION IS ";
protected final String TEXT_8 = NL + " OWNER IS SYSTEM";
protected final String TEXT_9 = NL + " WITHIN AREA ";
protected final String TEXT_10 = " SUBAREA ";
protected final String TEXT_11 = NL + " WITHIN AREA ";
protected final String TEXT_12 = " OFFSET ";
protected final String TEXT_13 = " FOR ";
protected final String TEXT_14 = " ";
protected final String TEXT_15 = NL + " WITHIN AREA ";
protected final String TEXT_16 = NL + " MEMBER IS ";
protected final String TEXT_17 = NL + "*+ WITHIN AREA ";
protected final String TEXT_18 = NL + " NEXT DBKEY POSITION IS ";
protected final String TEXT_19 = " " + NL + " PRIOR DBKEY POSITION IS ";
protected final String TEXT_20 = NL + " INDEX DBKEY POSITION IS ";
protected final String TEXT_21 = NL + " INDEX DBKEY POSITION IS OMITTED";
protected final String TEXT_22 = NL + " LINKED TO OWNER" + NL + " OWNER DBKEY POSITION IS ";
protected final String TEXT_23 = NL + " ";
protected final String TEXT_24 = NL + " KEY IS (";
protected final String TEXT_25 = NL + " ";
protected final String TEXT_26 = " ";
protected final String TEXT_27 = " ";
protected final String TEXT_28 = NL + " DUPLICATES ARE ";
protected final String TEXT_29 = NL + " NATURAL SEQUENCE";
protected final String TEXT_30 = NL + " COMPRESSED";
protected final String TEXT_31 = NL + " UNCOMPRESSED";
protected final String TEXT_32 = NL + " .";
public String generate(Object argument)
{
final StringBuffer stringBuffer = new StringBuffer();
/**
* Copyright (C) 2014 Luc Hermans
*
* 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/>.
*
* Contact information: [email protected].
*/
/*
This template will generate a set's DDL syntax.
See SetTemplateTest for a JUnit testcase.
*/
Object[] args = ((List<?>) argument).toArray();
Set set = (Set) args[0];
boolean sortSchemaEntities = ((Boolean) args[1]).booleanValue();
String setName;
if (set.getName().endsWith("_")) {
setName = set.getName().substring(0, set.getName().length() - 1);
} else {
setName = set.getName();
}
String mode;
if (set.getMode() == SetMode.CHAINED) {
if (set.getOwner().getPriorDbkeyPosition() != null) {
mode = "CHAIN LINKED TO PRIOR";
} else {
mode = "CHAIN";
}
} else {
String id;
if (set.getSchema().getName().equals("IDMSNTWK") &&
set.getSchema().getVersion() == 1) {
if (setName.equals("IX-AREA")) {
id = "ID IS 1 ";
} else if (setName.equals("IX-BUFFER")) {
id = "ID IS 2 ";
} else if (setName.equals("IX-DBNAME")) {
id = "ID IS 4 ";
} else if (setName.equals("IX-DMCL")) {
id = "ID IS 5 ";
} else if (setName.equals("IX-DMCLSEGMENT")) {
id = "ID IS 6 ";
} else if (setName.equals("IX-FILE")) {
id = "ID IS 7 ";
} else if (setName.equals("IX-SEGMENT")) {
id = "ID IS 10 ";
} else {
id = "";
}
} else {
id = "";
}
IndexedSetModeSpecification indexedSetModeSpecification =
set.getIndexedSetModeSpecification();
if (indexedSetModeSpecification.getSymbolicIndexName() != null) {
mode = "INDEX " + id + "USING " +
indexedSetModeSpecification.getSymbolicIndexName();
} else if (indexedSetModeSpecification.getDisplacementPageCount() != null &&
indexedSetModeSpecification.getDisplacementPageCount() != 0) {
mode = "INDEX " + id + "BLOCK CONTAINS " +
indexedSetModeSpecification.getKeyCount() +
" KEYS DISPLACEMENT IS " +
indexedSetModeSpecification.getDisplacementPageCount();
} else {
mode = "INDEX " + id + "BLOCK CONTAINS " +
indexedSetModeSpecification.getKeyCount() + " KEYS";
}
}
stringBuffer.append(TEXT_1);
stringBuffer.append( setName );
stringBuffer.append(TEXT_2);
stringBuffer.append( set.getOrder().toString() );
stringBuffer.append(TEXT_3);
stringBuffer.append( mode );
if (set.getOwner() != null) {
String recordName;
if (set.getOwner().getRecord().getName().endsWith("_")) {
StringBuilder p =
new StringBuilder(set.getOwner().getRecord().getName());
p.setLength(p.length() - 1);
recordName = p.toString();
} else {
recordName = set.getOwner().getRecord().getName();
}
stringBuffer.append(TEXT_4);
stringBuffer.append( recordName );
stringBuffer.append(TEXT_5);
stringBuffer.append( set.getOwner().getRecord().getAreaSpecification().getArea().getName() );
stringBuffer.append(TEXT_6);
stringBuffer.append( set.getOwner().getNextDbkeyPosition() );
if (set.getOwner().getPriorDbkeyPosition() != null) {
stringBuffer.append(TEXT_7);
stringBuffer.append( set.getOwner().getPriorDbkeyPosition() );
}
} else {
AreaSpecification areaSpecification =
set.getSystemOwner().getAreaSpecification();
String areaName = areaSpecification.getArea().getName();
String symbolicSubareaName = areaSpecification.getSymbolicSubareaName();
OffsetExpression offsetExpression = areaSpecification.getOffsetExpression();
stringBuffer.append(TEXT_8);
if (symbolicSubareaName != null) {
stringBuffer.append(TEXT_9);
stringBuffer.append( areaName );
stringBuffer.append(TEXT_10);
stringBuffer.append( symbolicSubareaName );
} else if (offsetExpression != null) {
String p;
if (offsetExpression.getOffsetPageCount() != null) {
p = offsetExpression.getOffsetPageCount() + " PAGES";
} else if (offsetExpression.getOffsetPercent() != null) {
p = offsetExpression.getOffsetPercent() + " PERCENT";
} else {
p = "0";
}
String q;
if (offsetExpression.getPercent() != null) {
q = offsetExpression.getPercent() + " PERCENT";
} else if (offsetExpression.getPageCount() != null) {
q = offsetExpression.getPageCount() + " PAGES";
} else {
q = "100 PERCENT";
}
stringBuffer.append(TEXT_11);
stringBuffer.append( areaName );
stringBuffer.append(TEXT_12);
stringBuffer.append( p );
stringBuffer.append(TEXT_13);
stringBuffer.append( q );
stringBuffer.append(TEXT_14);
} else {
stringBuffer.append(TEXT_15);
stringBuffer.append( areaName );
}
}
List<MemberRole> memberRoles = new ArrayList<>(set.getMembers());
if (sortSchemaEntities) {
Collections.sort(memberRoles, new Comparator<MemberRole>() {
public int compare(MemberRole m1, MemberRole m2) {
return m1.getRecord().getName().compareTo(m2.getRecord().getName());
}
});
}
for (MemberRole memberRole : memberRoles) {
String recordName;
if (memberRole.getRecord().getName().endsWith("_")) {
StringBuilder p = new StringBuilder(memberRole.getRecord().getName());
p.setLength(p.length() - 1);
recordName = p.toString();
} else {
recordName = memberRole.getRecord().getName();
}
stringBuffer.append(TEXT_16);
stringBuffer.append( recordName );
stringBuffer.append(TEXT_17);
stringBuffer.append( memberRole.getRecord().getAreaSpecification().getArea().getName() );
if (memberRole.getNextDbkeyPosition() != null) {
stringBuffer.append(TEXT_18);
stringBuffer.append( memberRole.getNextDbkeyPosition() );
}
if (memberRole.getPriorDbkeyPosition() != null) {
stringBuffer.append(TEXT_19);
stringBuffer.append( memberRole.getPriorDbkeyPosition() );
}
if (memberRole.getIndexDbkeyPosition() != null) {
stringBuffer.append(TEXT_20);
stringBuffer.append( memberRole.getIndexDbkeyPosition() );
} else if (set.getSystemOwner() != null) {
stringBuffer.append(TEXT_21);
}
if (memberRole.getOwnerDbkeyPosition() != null) {
stringBuffer.append(TEXT_22);
stringBuffer.append( memberRole.getOwnerDbkeyPosition() );
}
stringBuffer.append(TEXT_23);
stringBuffer.append( memberRole.getMembershipOption().toString().replaceAll("_", " ") );
if (set.getOrder() == SetOrder.SORTED) {
Key key = memberRole.getSortKey();
stringBuffer.append(TEXT_24);
for (KeyElement keyElement : key.getElements()) {
String bracket;
if (keyElement == key.getElements().get(key.getElements().size() - 1)) {
bracket = ")";
} else {
bracket = "";
}
+ String elementOrDbkey;
+ if (!keyElement.isDbkey()) {
+ elementOrDbkey = keyElement.getElement().getName();
+ } else {
+ elementOrDbkey = "DBKEY";
+ }
stringBuffer.append(TEXT_25);
- stringBuffer.append( keyElement.getElement().getName() );
+ stringBuffer.append( elementOrDbkey );
stringBuffer.append(TEXT_26);
stringBuffer.append( keyElement.getSortSequence() );
stringBuffer.append(TEXT_27);
stringBuffer.append( bracket );
}
stringBuffer.append(TEXT_28);
stringBuffer.append( key.getDuplicatesOption().toString().replaceAll("_", " ") );
if (key.isNaturalSequence()) {
stringBuffer.append(TEXT_29);
}
if (set.getMode() == SetMode.INDEXED && key.isCompressed()) {
stringBuffer.append(TEXT_30);
} else if (set.getMode() == SetMode.INDEXED) {
stringBuffer.append(TEXT_31);
}
}
}
stringBuffer.append(TEXT_32);
return stringBuffer.toString();
}
}
| false | true | public String generate(Object argument)
{
final StringBuffer stringBuffer = new StringBuffer();
/**
* Copyright (C) 2014 Luc Hermans
*
* 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/>.
*
* Contact information: [email protected].
*/
/*
This template will generate a set's DDL syntax.
See SetTemplateTest for a JUnit testcase.
*/
Object[] args = ((List<?>) argument).toArray();
Set set = (Set) args[0];
boolean sortSchemaEntities = ((Boolean) args[1]).booleanValue();
String setName;
if (set.getName().endsWith("_")) {
setName = set.getName().substring(0, set.getName().length() - 1);
} else {
setName = set.getName();
}
String mode;
if (set.getMode() == SetMode.CHAINED) {
if (set.getOwner().getPriorDbkeyPosition() != null) {
mode = "CHAIN LINKED TO PRIOR";
} else {
mode = "CHAIN";
}
} else {
String id;
if (set.getSchema().getName().equals("IDMSNTWK") &&
set.getSchema().getVersion() == 1) {
if (setName.equals("IX-AREA")) {
id = "ID IS 1 ";
} else if (setName.equals("IX-BUFFER")) {
id = "ID IS 2 ";
} else if (setName.equals("IX-DBNAME")) {
id = "ID IS 4 ";
} else if (setName.equals("IX-DMCL")) {
id = "ID IS 5 ";
} else if (setName.equals("IX-DMCLSEGMENT")) {
id = "ID IS 6 ";
} else if (setName.equals("IX-FILE")) {
id = "ID IS 7 ";
} else if (setName.equals("IX-SEGMENT")) {
id = "ID IS 10 ";
} else {
id = "";
}
} else {
id = "";
}
IndexedSetModeSpecification indexedSetModeSpecification =
set.getIndexedSetModeSpecification();
if (indexedSetModeSpecification.getSymbolicIndexName() != null) {
mode = "INDEX " + id + "USING " +
indexedSetModeSpecification.getSymbolicIndexName();
} else if (indexedSetModeSpecification.getDisplacementPageCount() != null &&
indexedSetModeSpecification.getDisplacementPageCount() != 0) {
mode = "INDEX " + id + "BLOCK CONTAINS " +
indexedSetModeSpecification.getKeyCount() +
" KEYS DISPLACEMENT IS " +
indexedSetModeSpecification.getDisplacementPageCount();
} else {
mode = "INDEX " + id + "BLOCK CONTAINS " +
indexedSetModeSpecification.getKeyCount() + " KEYS";
}
}
stringBuffer.append(TEXT_1);
stringBuffer.append( setName );
stringBuffer.append(TEXT_2);
stringBuffer.append( set.getOrder().toString() );
stringBuffer.append(TEXT_3);
stringBuffer.append( mode );
if (set.getOwner() != null) {
String recordName;
if (set.getOwner().getRecord().getName().endsWith("_")) {
StringBuilder p =
new StringBuilder(set.getOwner().getRecord().getName());
p.setLength(p.length() - 1);
recordName = p.toString();
} else {
recordName = set.getOwner().getRecord().getName();
}
stringBuffer.append(TEXT_4);
stringBuffer.append( recordName );
stringBuffer.append(TEXT_5);
stringBuffer.append( set.getOwner().getRecord().getAreaSpecification().getArea().getName() );
stringBuffer.append(TEXT_6);
stringBuffer.append( set.getOwner().getNextDbkeyPosition() );
if (set.getOwner().getPriorDbkeyPosition() != null) {
stringBuffer.append(TEXT_7);
stringBuffer.append( set.getOwner().getPriorDbkeyPosition() );
}
} else {
AreaSpecification areaSpecification =
set.getSystemOwner().getAreaSpecification();
String areaName = areaSpecification.getArea().getName();
String symbolicSubareaName = areaSpecification.getSymbolicSubareaName();
OffsetExpression offsetExpression = areaSpecification.getOffsetExpression();
stringBuffer.append(TEXT_8);
if (symbolicSubareaName != null) {
stringBuffer.append(TEXT_9);
stringBuffer.append( areaName );
stringBuffer.append(TEXT_10);
stringBuffer.append( symbolicSubareaName );
} else if (offsetExpression != null) {
String p;
if (offsetExpression.getOffsetPageCount() != null) {
p = offsetExpression.getOffsetPageCount() + " PAGES";
} else if (offsetExpression.getOffsetPercent() != null) {
p = offsetExpression.getOffsetPercent() + " PERCENT";
} else {
p = "0";
}
String q;
if (offsetExpression.getPercent() != null) {
q = offsetExpression.getPercent() + " PERCENT";
} else if (offsetExpression.getPageCount() != null) {
q = offsetExpression.getPageCount() + " PAGES";
} else {
q = "100 PERCENT";
}
stringBuffer.append(TEXT_11);
stringBuffer.append( areaName );
stringBuffer.append(TEXT_12);
stringBuffer.append( p );
stringBuffer.append(TEXT_13);
stringBuffer.append( q );
stringBuffer.append(TEXT_14);
} else {
stringBuffer.append(TEXT_15);
stringBuffer.append( areaName );
}
}
List<MemberRole> memberRoles = new ArrayList<>(set.getMembers());
if (sortSchemaEntities) {
Collections.sort(memberRoles, new Comparator<MemberRole>() {
public int compare(MemberRole m1, MemberRole m2) {
return m1.getRecord().getName().compareTo(m2.getRecord().getName());
}
});
}
for (MemberRole memberRole : memberRoles) {
String recordName;
if (memberRole.getRecord().getName().endsWith("_")) {
StringBuilder p = new StringBuilder(memberRole.getRecord().getName());
p.setLength(p.length() - 1);
recordName = p.toString();
} else {
recordName = memberRole.getRecord().getName();
}
stringBuffer.append(TEXT_16);
stringBuffer.append( recordName );
stringBuffer.append(TEXT_17);
stringBuffer.append( memberRole.getRecord().getAreaSpecification().getArea().getName() );
if (memberRole.getNextDbkeyPosition() != null) {
stringBuffer.append(TEXT_18);
stringBuffer.append( memberRole.getNextDbkeyPosition() );
}
if (memberRole.getPriorDbkeyPosition() != null) {
stringBuffer.append(TEXT_19);
stringBuffer.append( memberRole.getPriorDbkeyPosition() );
}
if (memberRole.getIndexDbkeyPosition() != null) {
stringBuffer.append(TEXT_20);
stringBuffer.append( memberRole.getIndexDbkeyPosition() );
} else if (set.getSystemOwner() != null) {
stringBuffer.append(TEXT_21);
}
if (memberRole.getOwnerDbkeyPosition() != null) {
stringBuffer.append(TEXT_22);
stringBuffer.append( memberRole.getOwnerDbkeyPosition() );
}
stringBuffer.append(TEXT_23);
stringBuffer.append( memberRole.getMembershipOption().toString().replaceAll("_", " ") );
if (set.getOrder() == SetOrder.SORTED) {
Key key = memberRole.getSortKey();
stringBuffer.append(TEXT_24);
for (KeyElement keyElement : key.getElements()) {
String bracket;
if (keyElement == key.getElements().get(key.getElements().size() - 1)) {
bracket = ")";
} else {
bracket = "";
}
stringBuffer.append(TEXT_25);
stringBuffer.append( keyElement.getElement().getName() );
stringBuffer.append(TEXT_26);
stringBuffer.append( keyElement.getSortSequence() );
stringBuffer.append(TEXT_27);
stringBuffer.append( bracket );
}
stringBuffer.append(TEXT_28);
stringBuffer.append( key.getDuplicatesOption().toString().replaceAll("_", " ") );
if (key.isNaturalSequence()) {
stringBuffer.append(TEXT_29);
}
if (set.getMode() == SetMode.INDEXED && key.isCompressed()) {
stringBuffer.append(TEXT_30);
} else if (set.getMode() == SetMode.INDEXED) {
stringBuffer.append(TEXT_31);
}
}
}
stringBuffer.append(TEXT_32);
return stringBuffer.toString();
}
| public String generate(Object argument)
{
final StringBuffer stringBuffer = new StringBuffer();
/**
* Copyright (C) 2014 Luc Hermans
*
* 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/>.
*
* Contact information: [email protected].
*/
/*
This template will generate a set's DDL syntax.
See SetTemplateTest for a JUnit testcase.
*/
Object[] args = ((List<?>) argument).toArray();
Set set = (Set) args[0];
boolean sortSchemaEntities = ((Boolean) args[1]).booleanValue();
String setName;
if (set.getName().endsWith("_")) {
setName = set.getName().substring(0, set.getName().length() - 1);
} else {
setName = set.getName();
}
String mode;
if (set.getMode() == SetMode.CHAINED) {
if (set.getOwner().getPriorDbkeyPosition() != null) {
mode = "CHAIN LINKED TO PRIOR";
} else {
mode = "CHAIN";
}
} else {
String id;
if (set.getSchema().getName().equals("IDMSNTWK") &&
set.getSchema().getVersion() == 1) {
if (setName.equals("IX-AREA")) {
id = "ID IS 1 ";
} else if (setName.equals("IX-BUFFER")) {
id = "ID IS 2 ";
} else if (setName.equals("IX-DBNAME")) {
id = "ID IS 4 ";
} else if (setName.equals("IX-DMCL")) {
id = "ID IS 5 ";
} else if (setName.equals("IX-DMCLSEGMENT")) {
id = "ID IS 6 ";
} else if (setName.equals("IX-FILE")) {
id = "ID IS 7 ";
} else if (setName.equals("IX-SEGMENT")) {
id = "ID IS 10 ";
} else {
id = "";
}
} else {
id = "";
}
IndexedSetModeSpecification indexedSetModeSpecification =
set.getIndexedSetModeSpecification();
if (indexedSetModeSpecification.getSymbolicIndexName() != null) {
mode = "INDEX " + id + "USING " +
indexedSetModeSpecification.getSymbolicIndexName();
} else if (indexedSetModeSpecification.getDisplacementPageCount() != null &&
indexedSetModeSpecification.getDisplacementPageCount() != 0) {
mode = "INDEX " + id + "BLOCK CONTAINS " +
indexedSetModeSpecification.getKeyCount() +
" KEYS DISPLACEMENT IS " +
indexedSetModeSpecification.getDisplacementPageCount();
} else {
mode = "INDEX " + id + "BLOCK CONTAINS " +
indexedSetModeSpecification.getKeyCount() + " KEYS";
}
}
stringBuffer.append(TEXT_1);
stringBuffer.append( setName );
stringBuffer.append(TEXT_2);
stringBuffer.append( set.getOrder().toString() );
stringBuffer.append(TEXT_3);
stringBuffer.append( mode );
if (set.getOwner() != null) {
String recordName;
if (set.getOwner().getRecord().getName().endsWith("_")) {
StringBuilder p =
new StringBuilder(set.getOwner().getRecord().getName());
p.setLength(p.length() - 1);
recordName = p.toString();
} else {
recordName = set.getOwner().getRecord().getName();
}
stringBuffer.append(TEXT_4);
stringBuffer.append( recordName );
stringBuffer.append(TEXT_5);
stringBuffer.append( set.getOwner().getRecord().getAreaSpecification().getArea().getName() );
stringBuffer.append(TEXT_6);
stringBuffer.append( set.getOwner().getNextDbkeyPosition() );
if (set.getOwner().getPriorDbkeyPosition() != null) {
stringBuffer.append(TEXT_7);
stringBuffer.append( set.getOwner().getPriorDbkeyPosition() );
}
} else {
AreaSpecification areaSpecification =
set.getSystemOwner().getAreaSpecification();
String areaName = areaSpecification.getArea().getName();
String symbolicSubareaName = areaSpecification.getSymbolicSubareaName();
OffsetExpression offsetExpression = areaSpecification.getOffsetExpression();
stringBuffer.append(TEXT_8);
if (symbolicSubareaName != null) {
stringBuffer.append(TEXT_9);
stringBuffer.append( areaName );
stringBuffer.append(TEXT_10);
stringBuffer.append( symbolicSubareaName );
} else if (offsetExpression != null) {
String p;
if (offsetExpression.getOffsetPageCount() != null) {
p = offsetExpression.getOffsetPageCount() + " PAGES";
} else if (offsetExpression.getOffsetPercent() != null) {
p = offsetExpression.getOffsetPercent() + " PERCENT";
} else {
p = "0";
}
String q;
if (offsetExpression.getPercent() != null) {
q = offsetExpression.getPercent() + " PERCENT";
} else if (offsetExpression.getPageCount() != null) {
q = offsetExpression.getPageCount() + " PAGES";
} else {
q = "100 PERCENT";
}
stringBuffer.append(TEXT_11);
stringBuffer.append( areaName );
stringBuffer.append(TEXT_12);
stringBuffer.append( p );
stringBuffer.append(TEXT_13);
stringBuffer.append( q );
stringBuffer.append(TEXT_14);
} else {
stringBuffer.append(TEXT_15);
stringBuffer.append( areaName );
}
}
List<MemberRole> memberRoles = new ArrayList<>(set.getMembers());
if (sortSchemaEntities) {
Collections.sort(memberRoles, new Comparator<MemberRole>() {
public int compare(MemberRole m1, MemberRole m2) {
return m1.getRecord().getName().compareTo(m2.getRecord().getName());
}
});
}
for (MemberRole memberRole : memberRoles) {
String recordName;
if (memberRole.getRecord().getName().endsWith("_")) {
StringBuilder p = new StringBuilder(memberRole.getRecord().getName());
p.setLength(p.length() - 1);
recordName = p.toString();
} else {
recordName = memberRole.getRecord().getName();
}
stringBuffer.append(TEXT_16);
stringBuffer.append( recordName );
stringBuffer.append(TEXT_17);
stringBuffer.append( memberRole.getRecord().getAreaSpecification().getArea().getName() );
if (memberRole.getNextDbkeyPosition() != null) {
stringBuffer.append(TEXT_18);
stringBuffer.append( memberRole.getNextDbkeyPosition() );
}
if (memberRole.getPriorDbkeyPosition() != null) {
stringBuffer.append(TEXT_19);
stringBuffer.append( memberRole.getPriorDbkeyPosition() );
}
if (memberRole.getIndexDbkeyPosition() != null) {
stringBuffer.append(TEXT_20);
stringBuffer.append( memberRole.getIndexDbkeyPosition() );
} else if (set.getSystemOwner() != null) {
stringBuffer.append(TEXT_21);
}
if (memberRole.getOwnerDbkeyPosition() != null) {
stringBuffer.append(TEXT_22);
stringBuffer.append( memberRole.getOwnerDbkeyPosition() );
}
stringBuffer.append(TEXT_23);
stringBuffer.append( memberRole.getMembershipOption().toString().replaceAll("_", " ") );
if (set.getOrder() == SetOrder.SORTED) {
Key key = memberRole.getSortKey();
stringBuffer.append(TEXT_24);
for (KeyElement keyElement : key.getElements()) {
String bracket;
if (keyElement == key.getElements().get(key.getElements().size() - 1)) {
bracket = ")";
} else {
bracket = "";
}
String elementOrDbkey;
if (!keyElement.isDbkey()) {
elementOrDbkey = keyElement.getElement().getName();
} else {
elementOrDbkey = "DBKEY";
}
stringBuffer.append(TEXT_25);
stringBuffer.append( elementOrDbkey );
stringBuffer.append(TEXT_26);
stringBuffer.append( keyElement.getSortSequence() );
stringBuffer.append(TEXT_27);
stringBuffer.append( bracket );
}
stringBuffer.append(TEXT_28);
stringBuffer.append( key.getDuplicatesOption().toString().replaceAll("_", " ") );
if (key.isNaturalSequence()) {
stringBuffer.append(TEXT_29);
}
if (set.getMode() == SetMode.INDEXED && key.isCompressed()) {
stringBuffer.append(TEXT_30);
} else if (set.getMode() == SetMode.INDEXED) {
stringBuffer.append(TEXT_31);
}
}
}
stringBuffer.append(TEXT_32);
return stringBuffer.toString();
}
|
diff --git a/update/org.eclipse.update.configurator/src/org/eclipse/update/internal/configurator/PlatformConfiguration.java b/update/org.eclipse.update.configurator/src/org/eclipse/update/internal/configurator/PlatformConfiguration.java
index ea859c0a5..5859ace54 100644
--- a/update/org.eclipse.update.configurator/src/org/eclipse/update/internal/configurator/PlatformConfiguration.java
+++ b/update/org.eclipse.update.configurator/src/org/eclipse/update/internal/configurator/PlatformConfiguration.java
@@ -1,1274 +1,1275 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.update.internal.configurator;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.eclipse.core.internal.boot.*;
import org.eclipse.core.runtime.*;
import org.eclipse.osgi.service.datalocation.*;
import org.eclipse.update.configurator.*;
import org.w3c.dom.*;
/**
* This class is responsible for providing the features and plugins (bundles) to
* the runtime. Configuration data is stored in the configuration/org.eclipse.update/platform.xml file.
* When eclipse starts, it tries to load the config info from platform.xml.
* If the file does not exist, then it also tries to read it from a temp or backup file.
* If this does not succeed, a platform.xml is created by inspecting the eclipse
* installation directory (its features and plugin folders).
* If platform.xml already exists, a check is made to see when it was last modified
* and whether there are any file system changes that are newer (users may manually unzip
* features and plugins). In this case, the newly added features and plugins are picked up.
* A check for existence of features and plugins is also performed, to detect deletions.
*/
public class PlatformConfiguration implements IPlatformConfiguration, IConfigurationConstants {
private static PlatformConfiguration currentPlatformConfiguration = null;
private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
private static final TransformerFactory transformerFactory = TransformerFactory.newInstance();
private Configuration config;
private URL configLocation;
private HashMap externalLinkSites; // used to restore prior link site state
private long changeStamp;
private long featuresChangeStamp;
private boolean featuresChangeStampIsValid;
private long pluginsChangeStamp;
private boolean pluginsChangeStampIsValid;
private File cfgLockFile;
private RandomAccessFile cfgLockFileRAF;
private static final String ECLIPSE = "eclipse"; //$NON-NLS-1$
private static final String CONFIG_HISTORY = "history"; //$NON-NLS-1$
private static final String PLATFORM_XML = "platform.xml"; //$NON-NLS-1$
private static final String CONFIG_NAME = ConfigurationActivator.NAME_SPACE + "/" + PLATFORM_XML;
private static final String CONFIG_INI = "config.ini"; //NON-NLS-1$
private static final String CONFIG_FILE_LOCK_SUFFIX = ".lock"; //$NON-NLS-1$
private static final String CONFIG_FILE_TEMP_SUFFIX = ".tmp"; //$NON-NLS-1$
private static final String CONFIG_FILE_BAK_SUFFIX = ".bak"; //$NON-NLS-1$
private static final String CHANGES_MARKER = ".newupdates"; //$NON-NLS-1$
private static final String LINKS = "links"; //$NON-NLS-1$
private static final String[] BOOTSTRAP_PLUGINS = {}; //$NON-NLS-1$
private static final String DEFAULT_FEATURE_ID = "org.eclipse.platform"; //$NON-NLS-1$
private static final String DEFAULT_FEATURE_APPLICATION = "org.eclipse.ui.ide.workbench"; //$NON-NLS-1$
private static final String LINK_PATH = "path"; //$NON-NLS-1$
private static final String LINK_READ = "r"; //$NON-NLS-1$
private static final String LINK_READ_WRITE = "rw"; //$NON-NLS-1$
private static URL installURL;
private PlatformConfiguration(Location platformConfigLocation) throws CoreException, IOException {
this.externalLinkSites = new HashMap();
this.config = null;
// initialize configuration
initializeCurrent(platformConfigLocation);
// Detect external links. These are "soft link" to additional sites. The link
// files are usually provided by external installation programs. They are located
// relative to this configuration URL.
configureExternalLinks();
// Validate sites in the configuration. Causes any sites that do not exist to
// be removed from the configuration
validateSites();
// compute differences between configuration and actual content of the sites
// (base sites and link sites)
// Note: when the config is transient (generated by PDE, etc.) we don't reconcile
changeStamp = computeChangeStamp();
if (changeStamp > config.getDate().getTime() && !isTransient())
reconcile();
// // save configuration if there were changes
// if (config.isDirty())
// save();
// determine which plugins we will use to start the rest of the "kernel"
// (need to get core.runtime matching the executing core.boot and
// xerces matching the selected core.runtime)
// locateDefaultPlugins();
}
PlatformConfiguration(URL url) throws Exception {
this.externalLinkSites = new HashMap();
initialize(url);
}
/*
* @see IPlatformConfiguration#createSiteEntry(URL, ISitePolicy)
*/
public ISiteEntry createSiteEntry(URL url, ISitePolicy policy) {
return new SiteEntry(url, policy);
}
/*
* @see IPlatformConfiguration#createSitePolicy(int, String[])
*/
public ISitePolicy createSitePolicy(int type, String[] list) {
return new SitePolicy(type, list);
}
/*
* @see IPlatformConfiguration#createFeatureEntry(String, String, String, boolean, String, URL)
*/
public IFeatureEntry createFeatureEntry(String id, String version, String pluginVersion, boolean primary, String application, URL[] root) {
return new FeatureEntry(id, version, pluginVersion, primary, application, root);
}
/*
* @see IPlatformConfiguration#createFeatureEntry(String, String, String,
* String, boolean, String, URL)
*/
public IFeatureEntry createFeatureEntry(String id, String version, String pluginIdentifier, String pluginVersion, boolean primary, String application, URL[] root) {
return new FeatureEntry(id, version, pluginIdentifier, pluginVersion, primary, application, root);
}
/*
* @see IPlatformConfiguration#configureSite(ISiteEntry)
*/
public void configureSite(ISiteEntry entry) {
configureSite(entry, false);
}
/*
* @see IPlatformConfiguration#configureSite(ISiteEntry, boolean)
*/
public synchronized void configureSite(ISiteEntry entry, boolean replace) {
if (entry == null)
return;
URL url = entry.getURL();
if (url == null)
return;
String key = url.toExternalForm();
if (config.getSiteEntry(key) != null && !replace)
return;
if (entry instanceof SiteEntry)
config.addSiteEntry(key, (SiteEntry)entry);
}
/*
* @see IPlatformConfiguration#unconfigureSite(ISiteEntry)
*/
public synchronized void unconfigureSite(ISiteEntry entry) {
if (entry == null)
return;
URL url = entry.getURL();
if (url == null)
return;
String key = url.toExternalForm();
if (entry instanceof SiteEntry)
config.removeSiteEntry(key);
}
/*
* @see IPlatformConfiguration#getConfiguredSites()
*/
public ISiteEntry[] getConfiguredSites() {
if (config == null)
return new ISiteEntry[0];
SiteEntry[] sites = config.getSites();
ArrayList enabledSites = new ArrayList(sites.length);
for (int i=0; i<sites.length; i++) {
if (sites[i].isEnabled())
enabledSites.add(sites[i]);
}
return (ISiteEntry[])enabledSites.toArray(new ISiteEntry[enabledSites.size()]);
}
/*
* @see IPlatformConfiguration#findConfiguredSite(URL)
*/
public ISiteEntry findConfiguredSite(URL url) {
return findConfiguredSite(url, true);
}
/**
*
* @param url site url
* @param checkPlatformURL if true, check for url format that is platform:/...
* @return
*/
public SiteEntry findConfiguredSite(URL url, boolean checkPlatformURL) {
if (url == null)
return null;
String key = url.toExternalForm();
SiteEntry result = config.getSiteEntry(key);
if (result == null) { // retry with decoded URL string
try {
key = URLDecoder.decode(key, "UTF-8");
} catch (UnsupportedEncodingException e) {
// ignore
}
result = config.getSiteEntry(key);
}
if (result == null && checkPlatformURL) {
try {
result = findConfiguredSite(Utils.asPlatformURL(url), false);
} catch (Exception e) {
//ignore
}
}
return result;
}
/*
* @see IPlatformConfiguration#configureFeatureEntry(IFeatureEntry)
*/
public synchronized void configureFeatureEntry(IFeatureEntry entry) {
if (entry == null)
return;
String key = entry.getFeatureIdentifier();
if (key == null)
return;
// we should check each site and find where the feature is
// located and then configure it
if (config == null)
config = new Configuration();
SiteEntry defaultSite = config.getSiteEntry(PlatformURLHandler.PROTOCOL + PlatformURLHandler.PROTOCOL_SEPARATOR + "/" + "base" + "/");
if (defaultSite != null) {
defaultSite.addFeatureEntry(entry);
}
// else, do nothing (we need a site)
}
/*
* @see IPlatformConfiguration#unconfigureFeatureEntry(IFeatureEntry)
*/
public synchronized void unconfigureFeatureEntry(IFeatureEntry entry) {
if (entry == null)
return;
String key = entry.getFeatureIdentifier();
if (key == null)
return;
config.unconfigureFeatureEntry(entry);
}
/*
* @see IPlatformConfiguration#getConfiguredFeatureEntries()
*/
public IFeatureEntry[] getConfiguredFeatureEntries() {
ArrayList configFeatures = new ArrayList();
SiteEntry[] sites = config.getSites();
for (int i=0; i<sites.length; i++) {
FeatureEntry[] features = sites[i].getFeatureEntries();
for (int j=0; j<features.length; j++)
configFeatures.add(features[j]);
}
return (IFeatureEntry[])configFeatures.toArray(new FeatureEntry[configFeatures.size()]);
}
/*
* @see IPlatformConfiguration#findConfiguredFeatureEntry(String)
*/
public IFeatureEntry findConfiguredFeatureEntry(String id) {
if (id == null)
return null;
SiteEntry[] sites = config.getSites();
for (int i=0; i<sites.length; i++) {
FeatureEntry f = sites[i].getFeatureEntry(id);
if (f != null)
return f;
}
return null;
}
/*
* @see IPlatformConfiguration#getConfigurationLocation()
*/
public URL getConfigurationLocation() {
return configLocation;
}
/*
* @see IPlatformConfiguration#getChangeStamp()
*/
public long getChangeStamp() {
return config.getDate().getTime();
}
/*
* @see IPlatformConfiguration#getFeaturesChangeStamp()
*/
public long getFeaturesChangeStamp() {
return 0;
}
/*
* @see IPlatformConfiguration#getPluginsChangeStamp()
*/
public long getPluginsChangeStamp() {
return 0;
}
public String getApplicationIdentifier() {
// Return the app if defined in system properties
String application = System.getProperty(ECLIPSE_APPLICATION);
if (application != null)
return application;
// Otherwise, try to get it from the primary feature (aka product)
String feature = getPrimaryFeatureIdentifier();
// lookup application for feature (specified or defaulted)
if (feature != null) {
IFeatureEntry fe = findConfiguredFeatureEntry(feature);
if (fe != null) {
if (fe.getFeatureApplication() != null)
return fe.getFeatureApplication();
}
}
// return hardcoded default if we failed
return DEFAULT_FEATURE_APPLICATION;
}
/*
* @see IPlatformConfiguration#getPrimaryFeatureIdentifier()
*/
public String getPrimaryFeatureIdentifier() {
// Return the product if defined in system properties
String primaryFeatureId = System.getProperty(ECLIPSE_PRODUCT);
if (primaryFeatureId == null)
primaryFeatureId = DEFAULT_FEATURE_ID; // return hardcoded default
// check if feature exists
if (findConfiguredFeatureEntry(primaryFeatureId) == null)
return null;
else
return primaryFeatureId;
}
/*
* @see IPlatformConfiguration#getPluginPath()
*/
public URL[] getPluginPath() {
ArrayList path = new ArrayList();
Utils.debug("computed plug-in path:"); //$NON-NLS-1$
ISiteEntry[] sites = getConfiguredSites();
URL pathURL;
for (int i = 0; i < sites.length; i++) {
String[] plugins = sites[i].getPlugins();
for (int j = 0; j < plugins.length; j++) {
try {
pathURL = new URL(((SiteEntry) sites[i]).getResolvedURL(), plugins[j]);
path.add(pathURL);
Utils.debug(" " + pathURL.toString()); //$NON-NLS-1$
} catch (MalformedURLException e) {
// skip entry ...
Utils.debug(" bad URL: " + e); //$NON-NLS-1$
}
}
}
return (URL[]) path.toArray(new URL[0]);
}
/*
* @see IPlatformConfiguration#getBootstrapPluginIdentifiers()
*/
public String[] getBootstrapPluginIdentifiers() {
return BOOTSTRAP_PLUGINS;
}
/*
* @see IPlatformConfiguration#setBootstrapPluginLocation(String, URL)
*/
public void setBootstrapPluginLocation(String id, URL location) {
}
/*
* @see IPlatformConfiguration#isUpdateable()
*/
public boolean isUpdateable() {
return true;
}
/*
* @see IPlatformConfiguration#isTransient()
*/
public boolean isTransient() {
if (config != null)
return config.isTransient();
else
return false;
}
/*
* @see IPlatformConfiguration#isTransient(boolean)
*/
public void isTransient(boolean value) {
if (this != getCurrent() && config != null)
config.setTransient(value);
}
/*
* @see IPlatformConfiguration#refresh()
*/
public synchronized void refresh() {
// Reset computed values. Will be lazily refreshed
// on next access
ISiteEntry[] sites = getConfiguredSites();
for (int i = 0; i < sites.length; i++) {
// reset site entry
((SiteEntry) sites[i]).refresh();
}
}
/*
* @see IPlatformConfiguration#save()
*/
public void save() throws IOException {
if (isUpdateable())
save(configLocation);
}
/*
* @see IPlatformConfiguration#save(URL)
*/
public synchronized void save(URL url) throws IOException {
if (url == null)
throw new IOException(Messages.getString("cfig.unableToSave.noURL")); //$NON-NLS-1$
OutputStream os = null;
if (!url.getProtocol().equals("file")) { //$NON-NLS-1$
// not a file protocol - attempt to save to the URL
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
os = uc.getOutputStream();
try {
saveAsXML(os);
config.setDirty(false);
} catch (CoreException e) {
throw new IOException(Messages.getString("cfig.unableToSave", url.toExternalForm())); //$NON-NLS-1$
} finally {
os.close();
}
} else {
// file protocol - do safe i/o
File cfigFile = new File(url.getFile().replace('/', File.separatorChar));
if (!cfigFile.getName().equals(PLATFORM_XML)) {
if (cfigFile.exists() && cfigFile.isFile()) {
Utils.log("Either specify the configuration directory or a file named platform.xml, not " + cfigFile.getName());
cfigFile = cfigFile.getParentFile();
}
cfigFile = new File(cfigFile, CONFIG_NAME);
}
File workingDir = cfigFile.getParentFile();
if (workingDir != null && !workingDir.exists())
workingDir.mkdirs();
// Backup old file
if (cfigFile.exists()){
File backupDir = new File(workingDir, CONFIG_HISTORY);
if (!backupDir.exists())
backupDir.mkdir();
File preservedFile = new File(backupDir, String.valueOf(cfigFile.lastModified())+".xml");
copy(cfigFile, preservedFile);
preservedFile.setLastModified(cfigFile.lastModified());
}
// If config.ini does not exist, generate it in the configuration area
writeConfigIni(workingDir.getParentFile());
// first save the file as temp
File cfigTmp = new File(cfigFile.getAbsolutePath() + CONFIG_FILE_TEMP_SUFFIX);
os = new FileOutputStream(cfigTmp);
try {
saveAsXML(os);
try {
os.close();
os = null;
} catch (IOException e1) {
Utils.log("Could not close output stream for " + cfigTmp);
}
// set file time stamp to match that of the config element
cfigTmp.setLastModified(config.getDate().getTime());
// make the change stamp to be the same as the config file
changeStamp = config.getDate().getTime();
config.setDirty(false);
} catch (CoreException e) {
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
} finally {
if (os != null)
try {
os.close();
} catch (IOException e1) {
Utils.log("Could not close output stream for temp file " + cfigTmp);
}
}
// make the saved config the "active" one
File cfigBak = new File(cfigFile.getAbsolutePath() + CONFIG_FILE_BAK_SUFFIX);
cfigBak.delete(); // may have old .bak due to prior failure
if (cfigFile.exists())
cfigFile.renameTo(cfigBak);
// at this point we have old config (if existed) as "bak" and the
// new config as "tmp".
boolean ok = cfigTmp.renameTo(cfigFile);
if (ok) {
// at this point we have the new config "activated", and the old
// config (if it existed) as "bak"
cfigBak.delete(); // clean up
} else {
Utils.log("Could not rename temp file");
// this codepath represents a tiny failure window. The load processing
// on startup will detect missing config and will attempt to start
// with "tmp" (latest), then "bak" (the previous). We can also end up
// here if we failed to rename the current config to "bak". In that
// case we will restart with the previous state.
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
}
// TODO **** Big workaround to deal with platform.xml under configuration.
// **** Remove before M9
File M8platformXML = new File(url.getFile().replace('/', File.separatorChar));
- M8platformXML = new File(M8platformXML, "platform.xml");
+ if (!M8platformXML.getName().equals("platform.xml"))
+ M8platformXML = new File(M8platformXML, "platform.xml");
os = new FileOutputStream(M8platformXML);
try {
saveAsXML(os);
try {
os.close();
os = null;
} catch (IOException e1) {
Utils.log("Could not close output stream for " + cfigTmp);
}
// set file time stamp to match that of the config element
M8platformXML.setLastModified(config.getDate().getTime());
} catch (Exception e) {
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
} finally {
if (os != null)
try {
os.close();
} catch (IOException e1) {
Utils.log("Could not close output stream for temp file " + cfigTmp);
}
}
// TODO *** end workaround
}
}
private void writeConfigIni(File configDir) {
try {
File configIni = new File(configDir, CONFIG_INI);
if (!configIni.exists()) {
URL configIniURL = ConfigurationActivator.getBundleContext().getBundle().getEntry(CONFIG_INI);
copy(configIniURL, configIni);
}
} catch (Exception e) {
System.out.println(Messages.getString("cfg.unableToCreateConfig.ini"));
}
}
public static PlatformConfiguration getCurrent() {
return currentPlatformConfiguration;
}
/**
* Create and initialize the current platform configuration
* @param cmdArgs command line arguments (startup and boot arguments are
* already consumed)
* @param r10apps application identifies as passed on the BootLoader.run(...)
* method. Supported for R1.0 compatibility.
*/
public static synchronized void startup(URL installURL, Location platformConfigLocation) throws Exception {
PlatformConfiguration.installURL = installURL;
// create current configuration
if (currentPlatformConfiguration == null) {
currentPlatformConfiguration = new PlatformConfiguration(platformConfigLocation);
if (currentPlatformConfiguration.config == null)
throw new Exception("Cannot load configuration from " + platformConfigLocation.getURL());
if (currentPlatformConfiguration.config.isDirty())
currentPlatformConfiguration.save();
}
}
public static synchronized void shutdown() throws IOException {
// save platform configuration
PlatformConfiguration config = getCurrent();
if (config != null) {
// only save if there are changes in the config
// // TODO clean this up when merging with the rest of update code
// long lastStamp = config.config.getDate().getTime();
// long computedStamp = config.computeChangeStamp();
if (config.config.isDirty() /* || computedStamp > lastStamp */) {
try {
config.save();
} catch (IOException e) {
Utils.debug("Unable to save configuration " + e.toString()); //$NON-NLS-1$
// will recover on next startup
}
}
config.clearConfigurationLock();
}
}
private synchronized void initializeCurrent(Location platformConfigLocation) throws IOException {
// FIXME: commented out for now. Remove if not needed.
//boolean concurrentUse = false;
// Configuration URL was is specified by the OSGi layer.
// Default behavior is to look
// for configuration in the specified meta area. If not found, look
// for pre-initialized configuration in the installation location.
// If it is found it is used as the initial configuration. Otherwise
// a new configuration is created. In either case the resulting
// configuration is written into the specified configuration area.
URL configFileURL = new URL(platformConfigLocation.getURL(), CONFIG_NAME);
try {
// check concurrent use lock
// FIXME: might not need this method call.
getConfigurationLock(configFileURL);
// try loading the configuration
try {
config = loadConfig(configFileURL);
Utils.debug("Using configuration " + configFileURL.toString()); //$NON-NLS-1$
} catch (Exception e) {
// failed to load, see if we can find pre-initialized configuration.
try {
Location parentLocation = platformConfigLocation.getParentLocation();
if (parentLocation == null)
throw new IOException(); // no platform.xml found, need to create default site
URL sharedConfigFileURL = new URL(parentLocation.getURL(), CONFIG_NAME);
config = loadConfig(sharedConfigFileURL);
// pre-initialized config loaded OK ... copy any remaining update metadata
// Only copy if the default config location is not the install location
if (!sharedConfigFileURL.equals(configFileURL)) {
// need to link config info instead of using a copy
linkInitializedState(config, parentLocation, platformConfigLocation);
// copyInitializedState(sharedConfigDirURL, configPath);
Utils.debug("Configuration initialized from " + sharedConfigFileURL.toString()); //$NON-NLS-1$
}
return;
} catch (Exception ioe) {
Utils.debug("Creating default configuration from " + configFileURL.toExternalForm());
// TODO *** workaround for M8 saving of platform.xml under configuration
// *** remove before M9
if (System.getProperty("osgi.dev") != null) {
// try loading form configuration/platform.xml
try {
configFileURL = new URL(platformConfigLocation.getURL(), PLATFORM_XML);
config = loadConfig(configFileURL);
Utils.debug("Using configuration " + configFileURL.toString()); //$NON-NLS-1$
} catch (Exception tempEx) {
createDefaultConfiguration(configFileURL);
}
} else
createDefaultConfiguration(configFileURL);
}
}
} finally {
configLocation = configFileURL;
if (config.getURL() == null)
config.setURL(configFileURL);
verifyPath(configLocation);
Utils.debug("Creating configuration " + configFileURL.toString()); //$NON-NLS-1$
}
}
private synchronized void initialize(URL url) throws Exception {
if (url != null) {
config = loadConfig(url);
Utils.debug("Using configuration " + url.toString()); //$NON-NLS-1$
}
if (config == null) {
config = new Configuration();
Utils.debug("Creating empty configuration object"); //$NON-NLS-1$
}
config.setURL(url);
configLocation = url;
}
private void createDefaultConfiguration(URL url)throws IOException{
// we are creating new configuration
config = new Configuration();
config.setURL(url);
SiteEntry defaultSite = (SiteEntry)getRootSite();
configureSite(defaultSite);
try {
// parse the site directory to discover features
defaultSite.loadFromDisk(0);
} catch (CoreException e1) {
Utils.log("Cannot load default site " + defaultSite.getResolvedURL());
return;
}
}
private ISiteEntry getRootSite() {
// create default site entry for the root
ISitePolicy defaultPolicy = createSitePolicy(DEFAULT_POLICY_TYPE, DEFAULT_POLICY_LIST);
URL siteURL = null;
try {
siteURL = new URL(PlatformURLHandler.PROTOCOL + PlatformURLHandler.PROTOCOL_SEPARATOR + "/" + "base" + "/"); //$NON-NLS-1$ //$NON-NLS-2$ // try using platform-relative URL
} catch (MalformedURLException e) {
siteURL = getInstallURL(); // ensure we come up ... use absolute file URL
}
ISiteEntry defaultSite = createSiteEntry(siteURL, defaultPolicy);
return defaultSite;
}
// private void resetInitializationConfiguration(URL url) throws IOException {
// // [20111]
// if (!supportsDetection(url))
// return; // can't do ...
//
// URL resolved = resolvePlatformURL(url);
// File initCfg = new File(resolved.getFile().replace('/', File.separatorChar));
// File initDir = initCfg.getParentFile();
// resetInitializationLocation(initDir);
// }
private void resetInitializationLocation(File dir) {
// [20111]
if (dir == null || !dir.exists() || !dir.isDirectory())
return;
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory())
resetInitializationLocation(list[i]);
list[i].delete();
}
}
private boolean getConfigurationLock(URL url) {
// if (!url.getProtocol().equals("file")) //$NON-NLS-1$
// return false;
//
// verifyPath(url);
// String cfgName = url.getFile().replace('/', File.separatorChar);
// String lockName = cfgName + CONFIG_FILE_LOCK_SUFFIX;
// cfgLockFile = new File(lockName);
//
// //if the lock file already exists, try to delete,
// //assume failure means another eclipse has it open
// if (cfgLockFile.exists())
// cfgLockFile.delete();
// if (cfgLockFile.exists()) {
// throw new RuntimeException(Policy.bind("cfig.inUse", cfgName, lockName)); //$NON-NLS-1$
// }
//
// // OK so far ... open the lock file so other instances will fail
// try {
// cfgLockFileRAF = new RandomAccessFile(cfgLockFile, "rw"); //$NON-NLS-1$
// cfgLockFileRAF.writeByte(0);
// } catch (IOException e) {
// throw new RuntimeException(Policy.bind("cfig.failCreateLock", cfgName)); //$NON-NLS-1$
// }
return false;
}
private void clearConfigurationLock() {
try {
if (cfgLockFileRAF != null) {
cfgLockFileRAF.close();
cfgLockFileRAF = null;
}
} catch (IOException e) {
// ignore ...
}
if (cfgLockFile != null) {
cfgLockFile.delete();
cfgLockFile = null;
}
}
private long computeChangeStamp() {
featuresChangeStamp = computeFeaturesChangeStamp();
pluginsChangeStamp = computePluginsChangeStamp();
changeStamp = Math.max(featuresChangeStamp, pluginsChangeStamp);
// round off to seconds
changeStamp = (changeStamp/1000)*1000;
return changeStamp;
}
private long computeFeaturesChangeStamp() {
if (featuresChangeStampIsValid)
return featuresChangeStamp;
long result = 0;
ISiteEntry[] sites = config.getSites();
for (int i = 0; i < sites.length; i++) {
result = Math.max(result, sites[i].getFeaturesChangeStamp());
}
featuresChangeStamp = result;
featuresChangeStampIsValid = true;
return featuresChangeStamp;
}
private long computePluginsChangeStamp() {
if (pluginsChangeStampIsValid)
return pluginsChangeStamp;
long result = 0;
ISiteEntry[] sites = config.getSites();
for (int i = 0; i < sites.length; i++) {
result = Math.max(result, sites[i].getPluginsChangeStamp());
}
pluginsChangeStamp = result;
pluginsChangeStampIsValid = true;
return pluginsChangeStamp;
}
private void configureExternalLinks() {
URL linkURL = getInstallURL();
if (!supportsDetection(linkURL))
return;
try {
linkURL = new URL(linkURL, LINKS + "/"); //$NON-NLS-1$
} catch (MalformedURLException e) {
// skip bad links ...
Utils.debug("Unable to obtain link URL"); //$NON-NLS-1$
return;
}
File linkDir = new File(linkURL.getFile());
File[] links = linkDir.listFiles();
if (links == null || links.length == 0) {
Utils.debug("No links detected in " + linkURL.toExternalForm()); //$NON-NLS-1$
return;
}
for (int i = 0; i < links.length; i++) {
if (links[i].isDirectory())
continue;
Utils.debug("Link file " + links[i].getAbsolutePath()); //$NON-NLS-1$
Properties props = new Properties();
FileInputStream is = null;
try {
is = new FileInputStream(links[i]);
props.load(is);
configureExternalLinkSite(links[i], props);
} catch (IOException e) {
// skip bad links ...
Utils.debug(" unable to load link file " + e); //$NON-NLS-1$
continue;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// ignore ...
}
}
}
}
}
private void configureExternalLinkSite(File linkFile, Properties props) {
String path = props.getProperty(LINK_PATH);
if (path == null) {
Utils.debug(" no path definition"); //$NON-NLS-1$
return;
}
String link;
boolean updateable = true;
URL siteURL;
// parse out link information
if (path.startsWith(LINK_READ + " ")) { //$NON-NLS-1$
updateable = false;
link = path.substring(2).trim();
} else if (path.startsWith(LINK_READ_WRITE + " ")) { //$NON-NLS-1$
link = path.substring(3).trim();
} else {
link = path.trim();
}
// make sure we have a valid link specification
try {
File siteFile = new File(link);
siteFile = new File(siteFile, ECLIPSE);
siteURL = siteFile.toURL();
if (findConfiguredSite(siteURL, true) != null)
// linked site is already known
return;
} catch (MalformedURLException e) {
// ignore bad links ...
Utils.debug(" bad URL " + e); //$NON-NLS-1$
return;
}
// process the link
SiteEntry linkSite = (SiteEntry) externalLinkSites.get(siteURL);
if (linkSite == null) {
// this is a link to a new target so create site for it
ISitePolicy linkSitePolicy = createSitePolicy(DEFAULT_POLICY_TYPE, DEFAULT_POLICY_LIST);
linkSite = (SiteEntry) createSiteEntry(siteURL, linkSitePolicy);
}
// update site entry if needed
linkSite.setUpdateable(updateable);
linkSite.setLinkFileName(linkFile.getAbsolutePath());
// configure the new site
// NOTE: duplicates are not replaced (first one in wins)
configureSite(linkSite);
// there are changes in the config
config.setDirty(true);
Utils.debug(" " + (updateable ? "R/W -> " : "R/O -> ") + siteURL.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
private void validateSites() {
// check to see if all sites are valid. Remove any sites that do not exist.
SiteEntry[] list = config.getSites();
for (int i = 0; i < list.length; i++) {
URL siteURL = list[i].getResolvedURL();
if (!supportsDetection(siteURL))
continue;
File siteRoot = new File(siteURL.getFile().replace('/', File.separatorChar));
if (!siteRoot.exists()) {
unconfigureSite(list[i]);
Utils.debug("Site " + siteURL + " does not exist ... removing from configuration"); //$NON-NLS-1$ //$NON-NLS-2$
}
// If multiple paths are defined in the same link file
// or if the path changes, the old site will still be kept.
// A better algorithm could be implemented by keeping track
// of the previous content of the link file.
// TODO do the above
String linkName = list[i].getLinkFileName();
if (linkName != null) {
File linkFile = new File(linkName);
if (!linkFile.exists()) {
unconfigureSite(list[i]);
config.setDirty(true);
Utils.debug("Site " + siteURL + " is no longer linked ... removing from configuration"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
private void linkInitializedState(Configuration sharedConfig, Location sharedConfigLocation, Location newConfigLocation) {
try {
URL oldConfigIniURL = new URL(sharedConfigLocation.getURL(), CONFIG_INI);
URL newConfigIniURL = new URL(newConfigLocation.getURL(), CONFIG_INI);
if (!newConfigIniURL.getProtocol().equals("file")) //$NON-NLS-1$
return; // need to be able to do write
// modify config.ini and platform.xml to only link original files
File configIni = new File(newConfigIniURL.getFile());
Properties props = new Properties();
props.put("osgi.sharedConfiguration.area", sharedConfigLocation.getURL().toExternalForm());
props.store(new FileOutputStream(configIni), "Linked configuration");
config = new Configuration(new Date());
config.setURL(new URL(newConfigLocation.getURL(), CONFIG_NAME));
config.setLinkedConfig(sharedConfig);
config.setDirty(true);
} catch (IOException e) {
// this is an optimistic copy. If we fail, the state will be reconciled
// when the update manager is triggered.
System.out.println(e);
}
}
// private void copyInitializedState(URL source, String target) {
// try {
// if (!source.getProtocol().equals("file")) //$NON-NLS-1$
// return; // need to be able to do "dir"
//
// copy(new File(source.getFile()), new File(target));
//
// } catch (IOException e) {
// // this is an optimistic copy. If we fail, the state will be reconciled
// // when the update manager is triggered.
// }
// }
private void copy(File src, File tgt) throws IOException {
if (src.isDirectory()) {
// copy content of directories
tgt.mkdir();
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.equals(ConfigurationActivator.LAST_CONFIG_STAMP);
}
};
File[] list = src.listFiles(filter);
if (list == null)
return;
for (int i = 0; i < list.length; i++) {
copy(list[i], new File(tgt, list[i].getName()));
}
} else {
// copy individual files
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream(src);
os = new FileOutputStream(tgt);
byte[] buff = new byte[1024];
int count = is.read(buff);
while (count != -1) {
os.write(buff, 0, count);
count = is.read(buff);
}
} catch (IOException e) {
// continue ... update reconciler will have to reconstruct state
} finally {
if (is != null)
try {
is.close();
} catch (IOException e) {
// ignore ...
}
if (os != null)
try {
os.close();
} catch (IOException e) {
// ignore ...
}
}
}
}
private void copy(URL src, File tgt) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = src.openStream();
os = new FileOutputStream(tgt);
byte[] buff = new byte[1024];
int count = is.read(buff);
while (count != -1) {
os.write(buff, 0, count);
count = is.read(buff);
}
} finally {
if (is != null)
try {
is.close();
} catch (IOException e) {
// ignore ...
}
if (os != null)
try {
os.close();
} catch (IOException e) {
// ignore ...
}
}
}
private Configuration loadConfig(URL url) throws Exception {
if (url == null)
throw new IOException(Messages.getString("cfig.unableToLoad.noURL")); //$NON-NLS-1$
// try to load saved configuration file (watch for failed prior save())
ConfigurationParser parser = null;
try {
parser = new ConfigurationParser();
} catch (InvocationTargetException e) {
throw (Exception)e.getTargetException();
}
config = null;
Exception originalException = null;
try {
config = parser.parse(url);
} catch (Exception e1) {
// check for save failures, so open temp and backup configurations
originalException = e1;
try {
URL tempURL = new URL(url.toExternalForm()+CONFIG_FILE_TEMP_SUFFIX);
config = parser.parse(tempURL);
} catch (Exception e2) {
try {
URL backupUrl = new URL(url.toExternalForm()+CONFIG_FILE_BAK_SUFFIX);
config = parser.parse(backupUrl);
} catch (IOException e3) {
throw originalException; // we tried, but no config here ...
}
}
}
return config;
}
private String loadAttribute(Properties props, String name, String dflt) {
String prop = props.getProperty(name);
if (prop == null)
return dflt;
else
return prop.trim();
}
//
// private static String[] checkForNewUpdates(IPlatformConfiguration cfg, String[] args) {
// try {
// URL markerURL = new URL(cfg.getConfigurationLocation(), CHANGES_MARKER);
// File marker = new File(markerURL.getFile());
// if (!marker.exists())
// return args;
//
// // indicate -newUpdates
// marker.delete();
// String[] newArgs = new String[args.length + 1];
// newArgs[0] = CMD_NEW_UPDATES;
// System.arraycopy(args, 0, newArgs, 1, args.length);
// return newArgs;
// } catch (MalformedURLException e) {
// return args;
// }
// }
public static boolean supportsDetection(URL url) {
String protocol = url.getProtocol();
if (protocol.equals("file")) //$NON-NLS-1$
return true;
else if (protocol.equals(PlatformURLHandler.PROTOCOL)) {
URL resolved = null;
try {
resolved = resolvePlatformURL(url); // 19536
} catch (IOException e) {
return false; // we tried but failed to resolve the platform URL
}
return resolved.getProtocol().equals("file"); //$NON-NLS-1$
} else
return false;
}
private static void verifyPath(URL url) {
String protocol = url.getProtocol();
String path = null;
if (protocol.equals("file")) //$NON-NLS-1$
path = url.getFile();
else if (protocol.equals(PlatformURLHandler.PROTOCOL)) {
URL resolved = null;
try {
resolved = resolvePlatformURL(url); // 19536
if (resolved.getProtocol().equals("file")) //$NON-NLS-1$
path = resolved.getFile();
} catch (IOException e) {
// continue ...
}
}
if (path != null) {
File dir = new File(path).getParentFile();
if (dir != null)
dir.mkdirs();
}
}
public static URL resolvePlatformURL(URL url) throws IOException {
// 19536
if (url.getProtocol().equals(PlatformURLHandler.PROTOCOL)) {
URLConnection connection = url.openConnection();
if (connection instanceof PlatformURLConnection) {
url = ((PlatformURLConnection) connection).getResolvedURL();
// TODO URL resolution by platform returns url file:d:/path as opposed to file:/d:/path
File f = new File(url.getFile());
url = f.toURL();
} else {
// connection = new PlatformURLBaseConnection(url);
// url = ((PlatformURLConnection)connection).getResolvedURL();
url = getInstallURL();
}
}
return url;
}
public static URL getInstallURL() {
return installURL;
}
private void saveAsXML(OutputStream stream) throws CoreException {
try {
DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
if (config == null)
throw Utils.newCoreException("Configuration cannot be saved because it does not exist",null);
config.setDate(new Date());
Element configElement = config.toXML(doc);
doc.appendChild(configElement);
// Write out to a file
Transformer transformer=transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(stream);
transformer.transform(source,result);
//will close the stream in the caller
//stream.close();
} catch (Exception e) {
throw Utils.newCoreException("", e);
}
}
private void reconcile() throws CoreException {
long lastChange = config.getDate().getTime();
SiteEntry[] sites = config.getSites();
for (int s=0; s<sites.length; s++) {
long siteTimestamp = sites[s].getChangeStamp();
if (siteTimestamp > lastChange)
sites[s].loadFromDisk(lastChange);
}
config.setDirty(true);
}
public Configuration getConfiguration() {
return config;
}
}
| true | true | public synchronized void save(URL url) throws IOException {
if (url == null)
throw new IOException(Messages.getString("cfig.unableToSave.noURL")); //$NON-NLS-1$
OutputStream os = null;
if (!url.getProtocol().equals("file")) { //$NON-NLS-1$
// not a file protocol - attempt to save to the URL
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
os = uc.getOutputStream();
try {
saveAsXML(os);
config.setDirty(false);
} catch (CoreException e) {
throw new IOException(Messages.getString("cfig.unableToSave", url.toExternalForm())); //$NON-NLS-1$
} finally {
os.close();
}
} else {
// file protocol - do safe i/o
File cfigFile = new File(url.getFile().replace('/', File.separatorChar));
if (!cfigFile.getName().equals(PLATFORM_XML)) {
if (cfigFile.exists() && cfigFile.isFile()) {
Utils.log("Either specify the configuration directory or a file named platform.xml, not " + cfigFile.getName());
cfigFile = cfigFile.getParentFile();
}
cfigFile = new File(cfigFile, CONFIG_NAME);
}
File workingDir = cfigFile.getParentFile();
if (workingDir != null && !workingDir.exists())
workingDir.mkdirs();
// Backup old file
if (cfigFile.exists()){
File backupDir = new File(workingDir, CONFIG_HISTORY);
if (!backupDir.exists())
backupDir.mkdir();
File preservedFile = new File(backupDir, String.valueOf(cfigFile.lastModified())+".xml");
copy(cfigFile, preservedFile);
preservedFile.setLastModified(cfigFile.lastModified());
}
// If config.ini does not exist, generate it in the configuration area
writeConfigIni(workingDir.getParentFile());
// first save the file as temp
File cfigTmp = new File(cfigFile.getAbsolutePath() + CONFIG_FILE_TEMP_SUFFIX);
os = new FileOutputStream(cfigTmp);
try {
saveAsXML(os);
try {
os.close();
os = null;
} catch (IOException e1) {
Utils.log("Could not close output stream for " + cfigTmp);
}
// set file time stamp to match that of the config element
cfigTmp.setLastModified(config.getDate().getTime());
// make the change stamp to be the same as the config file
changeStamp = config.getDate().getTime();
config.setDirty(false);
} catch (CoreException e) {
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
} finally {
if (os != null)
try {
os.close();
} catch (IOException e1) {
Utils.log("Could not close output stream for temp file " + cfigTmp);
}
}
// make the saved config the "active" one
File cfigBak = new File(cfigFile.getAbsolutePath() + CONFIG_FILE_BAK_SUFFIX);
cfigBak.delete(); // may have old .bak due to prior failure
if (cfigFile.exists())
cfigFile.renameTo(cfigBak);
// at this point we have old config (if existed) as "bak" and the
// new config as "tmp".
boolean ok = cfigTmp.renameTo(cfigFile);
if (ok) {
// at this point we have the new config "activated", and the old
// config (if it existed) as "bak"
cfigBak.delete(); // clean up
} else {
Utils.log("Could not rename temp file");
// this codepath represents a tiny failure window. The load processing
// on startup will detect missing config and will attempt to start
// with "tmp" (latest), then "bak" (the previous). We can also end up
// here if we failed to rename the current config to "bak". In that
// case we will restart with the previous state.
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
}
// TODO **** Big workaround to deal with platform.xml under configuration.
// **** Remove before M9
File M8platformXML = new File(url.getFile().replace('/', File.separatorChar));
M8platformXML = new File(M8platformXML, "platform.xml");
os = new FileOutputStream(M8platformXML);
try {
saveAsXML(os);
try {
os.close();
os = null;
} catch (IOException e1) {
Utils.log("Could not close output stream for " + cfigTmp);
}
// set file time stamp to match that of the config element
M8platformXML.setLastModified(config.getDate().getTime());
} catch (Exception e) {
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
} finally {
if (os != null)
try {
os.close();
} catch (IOException e1) {
Utils.log("Could not close output stream for temp file " + cfigTmp);
}
}
// TODO *** end workaround
}
}
| public synchronized void save(URL url) throws IOException {
if (url == null)
throw new IOException(Messages.getString("cfig.unableToSave.noURL")); //$NON-NLS-1$
OutputStream os = null;
if (!url.getProtocol().equals("file")) { //$NON-NLS-1$
// not a file protocol - attempt to save to the URL
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
os = uc.getOutputStream();
try {
saveAsXML(os);
config.setDirty(false);
} catch (CoreException e) {
throw new IOException(Messages.getString("cfig.unableToSave", url.toExternalForm())); //$NON-NLS-1$
} finally {
os.close();
}
} else {
// file protocol - do safe i/o
File cfigFile = new File(url.getFile().replace('/', File.separatorChar));
if (!cfigFile.getName().equals(PLATFORM_XML)) {
if (cfigFile.exists() && cfigFile.isFile()) {
Utils.log("Either specify the configuration directory or a file named platform.xml, not " + cfigFile.getName());
cfigFile = cfigFile.getParentFile();
}
cfigFile = new File(cfigFile, CONFIG_NAME);
}
File workingDir = cfigFile.getParentFile();
if (workingDir != null && !workingDir.exists())
workingDir.mkdirs();
// Backup old file
if (cfigFile.exists()){
File backupDir = new File(workingDir, CONFIG_HISTORY);
if (!backupDir.exists())
backupDir.mkdir();
File preservedFile = new File(backupDir, String.valueOf(cfigFile.lastModified())+".xml");
copy(cfigFile, preservedFile);
preservedFile.setLastModified(cfigFile.lastModified());
}
// If config.ini does not exist, generate it in the configuration area
writeConfigIni(workingDir.getParentFile());
// first save the file as temp
File cfigTmp = new File(cfigFile.getAbsolutePath() + CONFIG_FILE_TEMP_SUFFIX);
os = new FileOutputStream(cfigTmp);
try {
saveAsXML(os);
try {
os.close();
os = null;
} catch (IOException e1) {
Utils.log("Could not close output stream for " + cfigTmp);
}
// set file time stamp to match that of the config element
cfigTmp.setLastModified(config.getDate().getTime());
// make the change stamp to be the same as the config file
changeStamp = config.getDate().getTime();
config.setDirty(false);
} catch (CoreException e) {
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
} finally {
if (os != null)
try {
os.close();
} catch (IOException e1) {
Utils.log("Could not close output stream for temp file " + cfigTmp);
}
}
// make the saved config the "active" one
File cfigBak = new File(cfigFile.getAbsolutePath() + CONFIG_FILE_BAK_SUFFIX);
cfigBak.delete(); // may have old .bak due to prior failure
if (cfigFile.exists())
cfigFile.renameTo(cfigBak);
// at this point we have old config (if existed) as "bak" and the
// new config as "tmp".
boolean ok = cfigTmp.renameTo(cfigFile);
if (ok) {
// at this point we have the new config "activated", and the old
// config (if it existed) as "bak"
cfigBak.delete(); // clean up
} else {
Utils.log("Could not rename temp file");
// this codepath represents a tiny failure window. The load processing
// on startup will detect missing config and will attempt to start
// with "tmp" (latest), then "bak" (the previous). We can also end up
// here if we failed to rename the current config to "bak". In that
// case we will restart with the previous state.
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
}
// TODO **** Big workaround to deal with platform.xml under configuration.
// **** Remove before M9
File M8platformXML = new File(url.getFile().replace('/', File.separatorChar));
if (!M8platformXML.getName().equals("platform.xml"))
M8platformXML = new File(M8platformXML, "platform.xml");
os = new FileOutputStream(M8platformXML);
try {
saveAsXML(os);
try {
os.close();
os = null;
} catch (IOException e1) {
Utils.log("Could not close output stream for " + cfigTmp);
}
// set file time stamp to match that of the config element
M8platformXML.setLastModified(config.getDate().getTime());
} catch (Exception e) {
throw new IOException(Messages.getString("cfig.unableToSave", cfigTmp.getAbsolutePath())); //$NON-NLS-1$
} finally {
if (os != null)
try {
os.close();
} catch (IOException e1) {
Utils.log("Could not close output stream for temp file " + cfigTmp);
}
}
// TODO *** end workaround
}
}
|
diff --git a/ID3Tagger/src/com/se1by/Logic.java b/ID3Tagger/src/com/se1by/Logic.java
index 148d91d..95ed641 100644
--- a/ID3Tagger/src/com/se1by/Logic.java
+++ b/ID3Tagger/src/com/se1by/Logic.java
@@ -1,123 +1,122 @@
package com.se1by;
import java.io.File;
import entagged.audioformats.AudioFile;
import entagged.audioformats.AudioFileIO;
import entagged.audioformats.Tag;
import entagged.audioformats.exceptions.CannotReadException;
import entagged.audioformats.exceptions.CannotWriteException;
public class Logic {
private File sourceFile;
private AudioFile audioFile;
private Tag tag;
public Logic(File f) {
try {
setSourceFile(f);
setAudioFile(AudioFileIO.read(f));
setTag(audioFile.getTag());
} catch (CannotReadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean saveFile(String name) {
try {
String extension = sourceFile.getName().substring(
sourceFile.getName().lastIndexOf(".") + 1);
audioFile.commit();
System.out.println(sourceFile.getParent() + "\\" + name + "."
+ extension);
- sourceFile.renameTo(new File(sourceFile.getParent() + "\\" + name
- + "." + extension));
- sourceFile = new File(sourceFile.getParent() + "\\" + name + "."
- + extension);
+ File destination = new File(sourceFile.getParent(), name + "." + extension);
+ sourceFile.renameTo(destination);
+ sourceFile = destination;
setAudioFile(AudioFileIO.read(sourceFile));
setTag(audioFile.getTag());
} catch (CannotWriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CannotReadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
public String getArtist() {
return tag.getFirstArtist();
}
public void setArtist(String artist) {
tag.setArtist(artist);
}
public String getTitle() {
return tag.getFirstTitle();
}
public void setTitle(String title) {
tag.setTitle(title);
}
public String getGenre() {
return tag.getFirstGenre();
}
public void setGenre(String genre) {
tag.setGenre(genre);
}
public String getAlbum() {
return tag.getFirstAlbum();
}
public void setAlbum(String album) {
tag.setAlbum(album);
}
public String getTrack() {
return tag.getFirstTrack();
//return tag.getTrack().toString().replaceFirst("\\D*(\\d*).*", "$1");
}
public void setTrack(String track) {
tag.setTrack(track);
}
public String getYear() {
return tag.getFirstYear();
//return tag.getYear().toString().replaceFirst("\\D*(\\d*).*", "$1");
}
public void setYear(String year) {
tag.setYear(year);
}
public File getSourceFile() {
return sourceFile;
}
public void setSourceFile(File sourceFile) {
this.sourceFile = sourceFile;
}
public AudioFile getAudioFile() {
return audioFile;
}
public void setAudioFile(AudioFile audioFile) {
this.audioFile = audioFile;
}
public Tag getTag() {
return tag;
}
public void setTag(Tag tag) {
this.tag = tag;
}
}
| true | true | public boolean saveFile(String name) {
try {
String extension = sourceFile.getName().substring(
sourceFile.getName().lastIndexOf(".") + 1);
audioFile.commit();
System.out.println(sourceFile.getParent() + "\\" + name + "."
+ extension);
sourceFile.renameTo(new File(sourceFile.getParent() + "\\" + name
+ "." + extension));
sourceFile = new File(sourceFile.getParent() + "\\" + name + "."
+ extension);
setAudioFile(AudioFileIO.read(sourceFile));
setTag(audioFile.getTag());
} catch (CannotWriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CannotReadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
| public boolean saveFile(String name) {
try {
String extension = sourceFile.getName().substring(
sourceFile.getName().lastIndexOf(".") + 1);
audioFile.commit();
System.out.println(sourceFile.getParent() + "\\" + name + "."
+ extension);
File destination = new File(sourceFile.getParent(), name + "." + extension);
sourceFile.renameTo(destination);
sourceFile = destination;
setAudioFile(AudioFileIO.read(sourceFile));
setTag(audioFile.getTag());
} catch (CannotWriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CannotReadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
|
diff --git a/src/main/java/mobisocial/cocoon/server/AMQPush.java b/src/main/java/mobisocial/cocoon/server/AMQPush.java
index 630f548..7c89c7d 100644
--- a/src/main/java/mobisocial/cocoon/server/AMQPush.java
+++ b/src/main/java/mobisocial/cocoon/server/AMQPush.java
@@ -1,610 +1,610 @@
package mobisocial.cocoon.server;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javapns.Push;
import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import javapns.notification.PushedNotifications;
import javapns.notification.ResponsePacket;
import javapns.notification.transmission.PushQueue;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import mobisocial.cocoon.model.Listener;
import mobisocial.cocoon.util.Database;
import mobisocial.crypto.CorruptIdentity;
import mobisocial.crypto.IBHashedIdentity;
import mobisocial.musubi.protocol.Message;
import net.vz.mongodb.jackson.JacksonDBCollection;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.tuple.Pair;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.mongodb.DBCollection;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.AMQP.Queue.DeclareOk;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.sun.jersey.spi.resource.Singleton;
import de.undercouch.bson4jackson.BsonFactory;
import de.undercouch.bson4jackson.BsonParser.Feature;
@Singleton
@Path("/api/0/")
public class AMQPush {
static class BadgeData {
public int amqp;
public int local;
public Date last;
}
ObjectMapper mMapper = new ObjectMapper(
new BsonFactory().enable(Feature.HONOR_DOCUMENT_LENGTH));
String mGoogleKey;
HashMap<String, BadgeData> mCounts = new HashMap<String, BadgeData>();
HashMap<String, String> mQueues = new HashMap<String, String>();
HashMap<String, String> mConsumers = new HashMap<String, String>();
HashMap<String, HashSet<String>> mNotifiers = new HashMap<String, HashSet<String>>();
HashMap<String, Listener> mListeners = new HashMap<String, Listener>();
LinkedBlockingDeque<Runnable> mJobs = new LinkedBlockingDeque<Runnable>();
String encodeAMQPname(String prefix, byte[] key) {
// TODO: WTF doesnt this put the = at the end automatically?
int excess = (key.length * 8 % 6);
String pad = "";
int equals = (6 - excess) / 2;
for (int i = 0; i < equals; ++i)
pad += "=";
return prefix + Base64.encodeBase64URLSafeString(key) + pad + "\n";
}
byte[] decodeAMQPname(String prefix, String name) {
if (!name.startsWith(prefix))
return null;
// URL-safe? automatically, no param necessary?
return Base64.decodeBase64(name.substring(prefix.length()));
}
private LinkedBlockingQueue<Pair<com.google.android.gcm.server.Message, String>> mGooglePushes = new LinkedBlockingQueue<Pair<com.google.android.gcm.server.Message, String>>();
class GooglePushThread extends Thread {
Sender mSender;
public void run() {
for (;;) {
try {
mSender = new Sender(mGoogleKey);
push();
} catch (Throwable e) {
throw new RuntimeException(e);
}
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
void push() throws IOException {
Pair<com.google.android.gcm.server.Message, String> msg = mGooglePushes
.poll();
String device_token = msg.getRight();
String push_token = device_token;
synchronized (mNotifiers) {
Listener existing = mListeners.get(device_token);
if (existing.canonicalToken != null)
push_token = existing.canonicalToken;
}
Result result = mSender.sendNoRetry(msg.getLeft(), push_token);
if (result.getMessageId() != null) {
// same device has more than on registration ID: update database
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
synchronized (mNotifiers) {
Listener existing = mListeners.get(device_token);
existing.canonicalToken = canonicalRegId;
DBCollection rawCol = Database.dbInstance()
.getCollection(Listener.COLLECTION);
JacksonDBCollection<Listener, String> col = JacksonDBCollection
.wrap(rawCol, Listener.class, String.class);
Listener match = new Listener();
match.deviceToken = existing.deviceToken;
col.update(match, existing, true, false);
}
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister
// database
System.err.println("droid unregistering invalid token "
+ device_token);
unregister(device_token);
}
}
}
}
AMQPushThread mPushThread = new AMQPushThread();
class AMQPushThread extends Thread {
Channel mIncomingChannel;
private DefaultConsumer mConsumer;
@Override
public void run() {
for (;;) {
try {
amqp();
} catch (Throwable e) {
throw new RuntimeException(e);
}
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
void amqp() throws Throwable {
final PushQueue dev_queue = Push.queue("push.p12", "pusubi", false,
1);
dev_queue.start();
final PushQueue prod_queue = Push.queue("pushprod.p12", "pusubi",
true, 1);
prod_queue.start();
for (;;) {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("bumblebee.musubi.us");
connectionFactory.setConnectionTimeout(30 * 1000);
connectionFactory.setRequestedHeartbeat(30);
Connection connection = connectionFactory.newConnection();
mIncomingChannel = connection.createChannel();
mConsumer = new DefaultConsumer(mIncomingChannel) {
@Override
public void handleDelivery(final String consumerTag,
final Envelope envelope,
final BasicProperties properties, final byte[] body)
throws IOException {
HashSet<String> threadDevices = new HashSet<String>();
synchronized (mNotifiers) {
String identity = mConsumers.get(consumerTag);
if (identity == null)
return;
HashSet<String> devices = mNotifiers.get(identity);
if (devices == null)
return;
threadDevices.addAll(devices);
}
Message m = null;
try {
m = mMapper.readValue(body, Message.class);
} catch (IOException e) {
new RuntimeException(
"Failed to parse BSON of outer message", e)
.printStackTrace();
return;
}
// don't notify for blind (profile/delete/like msgs)
if (m.l)
return;
String sender_exchange;
try {
sender_exchange = encodeAMQPname("ibeidentity-",
new IBHashedIdentity(m.s.i).at(0).identity_);
} catch (CorruptIdentity e) {
e.printStackTrace();
return;
}
Date now = new Date();
for (String device : threadDevices) {
Listener l;
synchronized (mNotifiers) {
l = mListeners.get(device);
}
// no self notify
if (l.identityExchanges.contains(sender_exchange))
continue;
int new_value = 0;
int amqp = 0;
int local = 0;
Date last;
synchronized (mCounts) {
BadgeData bd = mCounts.get(device);
if (bd == null) {
bd = new BadgeData();
mCounts.put(device, bd);
}
bd.amqp++;
amqp = bd.amqp;
local = bd.local;
new_value = bd.amqp + bd.local;
last = bd.last;
if (bd.last == null) {
bd.last = now;
} else if (bd.last != null
&& now.getTime() - bd.last.getTime() > 3 * 60 * 1000) {
bd.last = now;
last = null;
}
}
- if (l.platform.equals("android")) {
+ if (l.platform != null && l.platform.equals("android")) {
com.google.android.gcm.server.Message message = new com.google.android.gcm.server.Message.Builder()
.addData("amqp", Integer.toString(amqp))
.build();
mGooglePushes.add(Pair.of(message, device));
} else {
try {
boolean production = l.production != null
&& l.production != false;
PushNotificationPayload payload = PushNotificationPayload
.complex();
try {
if (last == null) {
payload.addAlert("New message");
payload.addSound("default");
}
payload.addBadge(new_value);
payload.addCustomDictionary("local",
local);
payload.addCustomDictionary("amqp",
amqp);
} catch (JSONException e) {
// logic error, not runtime
e.printStackTrace();
System.exit(1);
}
if (!production)
dev_queue.add(payload, device);
else
prod_queue.add(payload, device);
} catch (InvalidDeviceTokenFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
System.out.println("doing registrations");
Set<String> notifiers = new HashSet<String>();
synchronized (mNotifiers) {
notifiers.addAll(mNotifiers.keySet());
}
for (String identity : notifiers) {
DeclareOk x = mIncomingChannel.queueDeclare();
System.out.println("listening " + identity);
mIncomingChannel.exchangeDeclare(identity, "fanout", true);
mIncomingChannel.queueBind(x.getQueue(), identity, "");
String consumerTag = mIncomingChannel.basicConsume(
x.getQueue(), true, mConsumer);
synchronized (mNotifiers) {
mQueues.put(identity, x.getQueue());
mConsumers.put(consumerTag, identity);
}
}
System.out.println("done registrations");
// TODO: don't do all the feedback stuff on one thread
long last = new Date().getTime();
for (;;) {
Runnable job = mJobs.poll(60, TimeUnit.SECONDS);
long current = new Date().getTime();
if (current - last > 60 * 1000) {
PushedNotifications ps = dev_queue
.getPushedNotifications();
for (PushedNotification p : ps) {
if (p.isSuccessful())
continue;
String invalidToken = p.getDevice().getToken();
System.err.println("unregistering invalid token "
+ invalidToken);
unregister(invalidToken);
/* Find out more about what the problem was */
Exception theProblem = p.getException();
theProblem.printStackTrace();
/*
* If the problem was an error-response packet
* returned by Apple, get it
*/
ResponsePacket theErrorResponse = p.getResponse();
if (theErrorResponse != null) {
System.out.println(theErrorResponse
.getMessage());
}
}
last = new Date().getTime();
List<Device> inactiveDevices = Push.feedback(
"push.p12", "pusubi", false);
for (Device d : inactiveDevices) {
String invalidToken = d.getToken();
System.err
.println("unregistering feedback failed token token "
+ invalidToken);
unregister(invalidToken);
}
}
if (job == null)
continue;
job.run();
}
}
}
};
public AMQPush() throws IOException {
Properties props = new Properties();
props.load(new FileInputStream("google.properties"));
mGoogleKey = props.getProperty("server.key");
loadAll();
mPushThread.start();
}
private void loadAll() {
DBCollection rawCol = Database.dbInstance().getCollection(
Listener.COLLECTION);
JacksonDBCollection<Listener, String> col = JacksonDBCollection.wrap(
rawCol, Listener.class, String.class);
for (Listener l : col.find()) {
mListeners.put(l.deviceToken, l);
// add all registrations
for (String ident : l.identityExchanges) {
HashSet<String> listeners = mNotifiers.get(ident);
if (listeners == null) {
listeners = new HashSet<String>();
mNotifiers.put(ident, listeners);
}
listeners.add(l.deviceToken);
}
}
}
@POST
@Path("register")
@Produces("application/json")
public String register(Listener l) throws IOException {
boolean needs_update = true;
synchronized (mNotifiers) {
System.out.println(new Date() + "Registering device: "
+ l.deviceToken + " for identities "
+ Arrays.toString(l.identityExchanges.toArray()));
// clear pending message count on registration (e.g. amqp connected
// to drain messages)
// TODO: this is not really right if the client fails to download
// all messages
// before disconnecting
synchronized (mCounts) {
BadgeData bd = mCounts.get(l.deviceToken);
if (bd == null) {
bd = new BadgeData();
mCounts.put(l.deviceToken, bd);
}
if (l.localUnread != null)
bd.local = l.localUnread;
}
Listener existing = mListeners.get(l.deviceToken);
if (existing != null
&& existing.production == l.production
&& existing.identityExchanges.size() == l.identityExchanges
.size()) {
needs_update = false;
Iterator<String> a = existing.identityExchanges.iterator();
Iterator<String> b = l.identityExchanges.iterator();
while (a.hasNext()) {
String aa = a.next();
String bb = b.next();
if (!aa.equals(bb)) {
needs_update = true;
break;
}
}
}
if (!needs_update)
return "ok";
mListeners.put(l.deviceToken, l);
// TODO: set intersection to not wasteful tear up and down
if (existing != null) {
// remove all old registrations
for (String ident : existing.identityExchanges) {
HashSet<String> listeners = mNotifiers.get(ident);
assert (listeners != null);
listeners.remove(l.deviceToken);
if (listeners.size() == 0) {
amqpUnregister(ident);
mNotifiers.remove(ident);
}
}
}
// add all new registrations
for (String ident : l.identityExchanges) {
HashSet<String> listeners = mNotifiers.get(ident);
if (listeners == null) {
listeners = new HashSet<String>();
mNotifiers.put(ident, listeners);
amqpRegister(ident);
}
listeners.add(l.deviceToken);
}
}
DBCollection rawCol = Database.dbInstance().getCollection(
Listener.COLLECTION);
JacksonDBCollection<Listener, String> col = JacksonDBCollection.wrap(
rawCol, Listener.class, String.class);
Listener match = new Listener();
match.deviceToken = l.deviceToken;
col.update(match, l, true, false);
return "ok";
}
@POST
@Path("clearunread")
@Produces("application/json")
public String clearUnread(String deviceToken) throws IOException {
System.out.println(new Date() + "Clear unread " + deviceToken);
synchronized (mCounts) {
BadgeData bd = mCounts.get(deviceToken);
if (bd == null) {
bd = new BadgeData();
mCounts.put(deviceToken, bd);
}
bd.amqp = 0;
}
return "ok";
}
public static class ResetUnread {
public String deviceToken;
public int count;
public Boolean background;
}
@POST
@Path("resetunread")
@Produces("application/json")
public String resetUnread(ResetUnread ru) throws IOException {
System.out.println(new Date() + "reset unread " + ru.deviceToken
+ " to " + ru.count);
synchronized (mCounts) {
BadgeData bd = mCounts.get(ru.deviceToken);
if (bd == null) {
bd = new BadgeData();
mCounts.put(ru.deviceToken, bd);
}
if (ru.background == null || !ru.background) {
bd.last = null;
}
bd.local = ru.count;
}
return "ok";
}
void amqpRegister(final String identity) {
mJobs.add(new Runnable() {
@Override
public void run() {
try {
DeclareOk x = mPushThread.mIncomingChannel.queueDeclare();
System.out.println("listening " + identity);
mPushThread.mIncomingChannel.exchangeDeclare(identity,
"fanout", true);
mPushThread.mIncomingChannel.queueBind(x.getQueue(),
identity, "");
String consumerTag = mPushThread.mIncomingChannel
.basicConsume(x.getQueue(), true,
mPushThread.mConsumer);
synchronized (mNotifiers) {
mQueues.put(identity, x.getQueue());
mConsumers.put(consumerTag, identity);
}
} catch (Throwable t) {
throw new RuntimeException("failed to register", t);
}
}
});
}
void amqpUnregister(final String identity) {
mJobs.add(new Runnable() {
@Override
public void run() {
String queue = null;
synchronized (mNotifiers) {
queue = mQueues.get(identity);
// probably an error
if (queue == null)
return;
mQueues.remove(identity);
// TODO: update consumers
}
System.out.println("stop listening " + identity);
try {
mPushThread.mIncomingChannel.queueUnbind(queue, identity,
"");
} catch (Throwable t) {
throw new RuntimeException("removing queue dynamically", t);
}
}
});
}
@POST
@Path("unregister")
@Produces("application/json")
public String unregister(String deviceToken) throws IOException {
synchronized (mNotifiers) {
Listener existing = mListeners.get(deviceToken);
if (existing == null)
return "ok";
mListeners.remove(deviceToken);
synchronized (mCounts) {
mListeners.remove(deviceToken);
}
// remove all old registrations
for (String ident : existing.identityExchanges) {
HashSet<String> listeners = mNotifiers.get(ident);
assert (listeners != null);
listeners.remove(deviceToken);
if (listeners.size() == 0) {
amqpUnregister(ident);
mNotifiers.remove(ident);
}
}
}
DBCollection rawCol = Database.dbInstance().getCollection(
Listener.COLLECTION);
JacksonDBCollection<Listener, String> col = JacksonDBCollection.wrap(
rawCol, Listener.class, String.class);
Listener match = new Listener();
match.deviceToken = deviceToken;
col.remove(match);
return "ok";
}
}
| true | true | void amqp() throws Throwable {
final PushQueue dev_queue = Push.queue("push.p12", "pusubi", false,
1);
dev_queue.start();
final PushQueue prod_queue = Push.queue("pushprod.p12", "pusubi",
true, 1);
prod_queue.start();
for (;;) {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("bumblebee.musubi.us");
connectionFactory.setConnectionTimeout(30 * 1000);
connectionFactory.setRequestedHeartbeat(30);
Connection connection = connectionFactory.newConnection();
mIncomingChannel = connection.createChannel();
mConsumer = new DefaultConsumer(mIncomingChannel) {
@Override
public void handleDelivery(final String consumerTag,
final Envelope envelope,
final BasicProperties properties, final byte[] body)
throws IOException {
HashSet<String> threadDevices = new HashSet<String>();
synchronized (mNotifiers) {
String identity = mConsumers.get(consumerTag);
if (identity == null)
return;
HashSet<String> devices = mNotifiers.get(identity);
if (devices == null)
return;
threadDevices.addAll(devices);
}
Message m = null;
try {
m = mMapper.readValue(body, Message.class);
} catch (IOException e) {
new RuntimeException(
"Failed to parse BSON of outer message", e)
.printStackTrace();
return;
}
// don't notify for blind (profile/delete/like msgs)
if (m.l)
return;
String sender_exchange;
try {
sender_exchange = encodeAMQPname("ibeidentity-",
new IBHashedIdentity(m.s.i).at(0).identity_);
} catch (CorruptIdentity e) {
e.printStackTrace();
return;
}
Date now = new Date();
for (String device : threadDevices) {
Listener l;
synchronized (mNotifiers) {
l = mListeners.get(device);
}
// no self notify
if (l.identityExchanges.contains(sender_exchange))
continue;
int new_value = 0;
int amqp = 0;
int local = 0;
Date last;
synchronized (mCounts) {
BadgeData bd = mCounts.get(device);
if (bd == null) {
bd = new BadgeData();
mCounts.put(device, bd);
}
bd.amqp++;
amqp = bd.amqp;
local = bd.local;
new_value = bd.amqp + bd.local;
last = bd.last;
if (bd.last == null) {
bd.last = now;
} else if (bd.last != null
&& now.getTime() - bd.last.getTime() > 3 * 60 * 1000) {
bd.last = now;
last = null;
}
}
if (l.platform.equals("android")) {
com.google.android.gcm.server.Message message = new com.google.android.gcm.server.Message.Builder()
.addData("amqp", Integer.toString(amqp))
.build();
mGooglePushes.add(Pair.of(message, device));
} else {
try {
boolean production = l.production != null
&& l.production != false;
PushNotificationPayload payload = PushNotificationPayload
.complex();
try {
if (last == null) {
payload.addAlert("New message");
payload.addSound("default");
}
payload.addBadge(new_value);
payload.addCustomDictionary("local",
local);
payload.addCustomDictionary("amqp",
amqp);
} catch (JSONException e) {
// logic error, not runtime
e.printStackTrace();
System.exit(1);
}
if (!production)
dev_queue.add(payload, device);
else
prod_queue.add(payload, device);
} catch (InvalidDeviceTokenFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
System.out.println("doing registrations");
Set<String> notifiers = new HashSet<String>();
synchronized (mNotifiers) {
notifiers.addAll(mNotifiers.keySet());
}
for (String identity : notifiers) {
DeclareOk x = mIncomingChannel.queueDeclare();
System.out.println("listening " + identity);
mIncomingChannel.exchangeDeclare(identity, "fanout", true);
mIncomingChannel.queueBind(x.getQueue(), identity, "");
String consumerTag = mIncomingChannel.basicConsume(
x.getQueue(), true, mConsumer);
synchronized (mNotifiers) {
mQueues.put(identity, x.getQueue());
mConsumers.put(consumerTag, identity);
}
}
System.out.println("done registrations");
// TODO: don't do all the feedback stuff on one thread
long last = new Date().getTime();
for (;;) {
Runnable job = mJobs.poll(60, TimeUnit.SECONDS);
long current = new Date().getTime();
if (current - last > 60 * 1000) {
PushedNotifications ps = dev_queue
.getPushedNotifications();
for (PushedNotification p : ps) {
if (p.isSuccessful())
continue;
String invalidToken = p.getDevice().getToken();
System.err.println("unregistering invalid token "
+ invalidToken);
unregister(invalidToken);
/* Find out more about what the problem was */
Exception theProblem = p.getException();
theProblem.printStackTrace();
/*
* If the problem was an error-response packet
* returned by Apple, get it
*/
ResponsePacket theErrorResponse = p.getResponse();
if (theErrorResponse != null) {
System.out.println(theErrorResponse
.getMessage());
}
}
last = new Date().getTime();
List<Device> inactiveDevices = Push.feedback(
"push.p12", "pusubi", false);
for (Device d : inactiveDevices) {
String invalidToken = d.getToken();
System.err
.println("unregistering feedback failed token token "
+ invalidToken);
unregister(invalidToken);
}
}
if (job == null)
continue;
job.run();
}
}
}
| void amqp() throws Throwable {
final PushQueue dev_queue = Push.queue("push.p12", "pusubi", false,
1);
dev_queue.start();
final PushQueue prod_queue = Push.queue("pushprod.p12", "pusubi",
true, 1);
prod_queue.start();
for (;;) {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("bumblebee.musubi.us");
connectionFactory.setConnectionTimeout(30 * 1000);
connectionFactory.setRequestedHeartbeat(30);
Connection connection = connectionFactory.newConnection();
mIncomingChannel = connection.createChannel();
mConsumer = new DefaultConsumer(mIncomingChannel) {
@Override
public void handleDelivery(final String consumerTag,
final Envelope envelope,
final BasicProperties properties, final byte[] body)
throws IOException {
HashSet<String> threadDevices = new HashSet<String>();
synchronized (mNotifiers) {
String identity = mConsumers.get(consumerTag);
if (identity == null)
return;
HashSet<String> devices = mNotifiers.get(identity);
if (devices == null)
return;
threadDevices.addAll(devices);
}
Message m = null;
try {
m = mMapper.readValue(body, Message.class);
} catch (IOException e) {
new RuntimeException(
"Failed to parse BSON of outer message", e)
.printStackTrace();
return;
}
// don't notify for blind (profile/delete/like msgs)
if (m.l)
return;
String sender_exchange;
try {
sender_exchange = encodeAMQPname("ibeidentity-",
new IBHashedIdentity(m.s.i).at(0).identity_);
} catch (CorruptIdentity e) {
e.printStackTrace();
return;
}
Date now = new Date();
for (String device : threadDevices) {
Listener l;
synchronized (mNotifiers) {
l = mListeners.get(device);
}
// no self notify
if (l.identityExchanges.contains(sender_exchange))
continue;
int new_value = 0;
int amqp = 0;
int local = 0;
Date last;
synchronized (mCounts) {
BadgeData bd = mCounts.get(device);
if (bd == null) {
bd = new BadgeData();
mCounts.put(device, bd);
}
bd.amqp++;
amqp = bd.amqp;
local = bd.local;
new_value = bd.amqp + bd.local;
last = bd.last;
if (bd.last == null) {
bd.last = now;
} else if (bd.last != null
&& now.getTime() - bd.last.getTime() > 3 * 60 * 1000) {
bd.last = now;
last = null;
}
}
if (l.platform != null && l.platform.equals("android")) {
com.google.android.gcm.server.Message message = new com.google.android.gcm.server.Message.Builder()
.addData("amqp", Integer.toString(amqp))
.build();
mGooglePushes.add(Pair.of(message, device));
} else {
try {
boolean production = l.production != null
&& l.production != false;
PushNotificationPayload payload = PushNotificationPayload
.complex();
try {
if (last == null) {
payload.addAlert("New message");
payload.addSound("default");
}
payload.addBadge(new_value);
payload.addCustomDictionary("local",
local);
payload.addCustomDictionary("amqp",
amqp);
} catch (JSONException e) {
// logic error, not runtime
e.printStackTrace();
System.exit(1);
}
if (!production)
dev_queue.add(payload, device);
else
prod_queue.add(payload, device);
} catch (InvalidDeviceTokenFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
System.out.println("doing registrations");
Set<String> notifiers = new HashSet<String>();
synchronized (mNotifiers) {
notifiers.addAll(mNotifiers.keySet());
}
for (String identity : notifiers) {
DeclareOk x = mIncomingChannel.queueDeclare();
System.out.println("listening " + identity);
mIncomingChannel.exchangeDeclare(identity, "fanout", true);
mIncomingChannel.queueBind(x.getQueue(), identity, "");
String consumerTag = mIncomingChannel.basicConsume(
x.getQueue(), true, mConsumer);
synchronized (mNotifiers) {
mQueues.put(identity, x.getQueue());
mConsumers.put(consumerTag, identity);
}
}
System.out.println("done registrations");
// TODO: don't do all the feedback stuff on one thread
long last = new Date().getTime();
for (;;) {
Runnable job = mJobs.poll(60, TimeUnit.SECONDS);
long current = new Date().getTime();
if (current - last > 60 * 1000) {
PushedNotifications ps = dev_queue
.getPushedNotifications();
for (PushedNotification p : ps) {
if (p.isSuccessful())
continue;
String invalidToken = p.getDevice().getToken();
System.err.println("unregistering invalid token "
+ invalidToken);
unregister(invalidToken);
/* Find out more about what the problem was */
Exception theProblem = p.getException();
theProblem.printStackTrace();
/*
* If the problem was an error-response packet
* returned by Apple, get it
*/
ResponsePacket theErrorResponse = p.getResponse();
if (theErrorResponse != null) {
System.out.println(theErrorResponse
.getMessage());
}
}
last = new Date().getTime();
List<Device> inactiveDevices = Push.feedback(
"push.p12", "pusubi", false);
for (Device d : inactiveDevices) {
String invalidToken = d.getToken();
System.err
.println("unregistering feedback failed token token "
+ invalidToken);
unregister(invalidToken);
}
}
if (job == null)
continue;
job.run();
}
}
}
|
diff --git a/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/TaskDataManagerTest.java b/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/TaskDataManagerTest.java
index a41170803..f6eab43fe 100644
--- a/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/TaskDataManagerTest.java
+++ b/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/TaskDataManagerTest.java
@@ -1,317 +1,317 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 Mylar committers 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
*******************************************************************************/
package org.eclipse.mylar.tasks.tests;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.mylar.internal.tasks.core.RepositoryTaskHandleUtil;
import org.eclipse.mylar.internal.tasks.core.TaskDataManager;
import org.eclipse.mylar.tasks.core.RepositoryTaskAttribute;
import org.eclipse.mylar.tasks.core.RepositoryTaskData;
import org.eclipse.mylar.tasks.core.Task;
import org.eclipse.mylar.tasks.tests.connector.MockAttributeFactory;
import org.eclipse.mylar.tasks.tests.connector.MockRepositoryConnector;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
/**
* @author Rob Elves
*/
public class TaskDataManagerTest extends TestCase {
TaskDataManager offlineTaskDataManager;
@Override
protected void setUp() throws Exception {
super.setUp();
offlineTaskDataManager = TasksUiPlugin.getDefault().getTaskDataManager();
offlineTaskDataManager.clear();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
if (offlineTaskDataManager != null) {
offlineTaskDataManager.clear();
offlineTaskDataManager.save(true);
}
}
public void testAdd() throws CoreException {
RepositoryTaskData taskData = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
}
public void testSave() throws CoreException, IOException, ClassNotFoundException {
RepositoryTaskData taskData = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
RepositoryTaskAttribute attrib1 = new RepositoryTaskAttribute("key", "name", false);
- attrib1.setMetaDataValue("key1", "value1");
- attrib1.setMetaDataValue("key2", "value2");
+ attrib1.putMetaDataValue("key1", "value1");
+ attrib1.putMetaDataValue("key2", "value2");
taskData.addAttribute("key", attrib1);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
taskData = new RepositoryTaskData(new MockAttributeFactory(), MockRepositoryConnector.REPOSITORY_KIND,
MockRepositoryConnector.REPOSITORY_URL, "2", Task.DEFAULT_TASK_KIND);
RepositoryTaskAttribute attrib2 = new RepositoryTaskAttribute("key", "name", false);
- attrib2.setMetaDataValue("key3", "value3");
- attrib2.setMetaDataValue("key4", "value4");
+ attrib2.putMetaDataValue("key3", "value3");
+ attrib2.putMetaDataValue("key4", "value4");
taskData.addAttribute("key", attrib2);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "2"),
taskData);
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.save(true);
offlineTaskDataManager.clear();
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.readOfflineData();
RepositoryTaskData loaded1 = offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1"));
assertNotNull(loaded1);
RepositoryTaskAttribute atr = loaded1.getAttribute("key");
assertNotNull(atr);
assertEquals("value1", atr.getMetaDataValue("key1"));
assertEquals("value2", atr.getMetaDataValue("key2"));
RepositoryTaskData loaded2 = offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2"));
assertNotNull(loaded2);
RepositoryTaskAttribute atr2 = loaded2.getAttribute("key");
assertNotNull(atr2);
assertEquals("value3", atr2.getMetaDataValue("key3"));
assertEquals("value4", atr2.getMetaDataValue("key4"));
}
public void testGetNextOfflineBugId() throws IOException, ClassNotFoundException {
assertEquals("1", offlineTaskDataManager.getNewRepositoryTaskId());
assertEquals("2", offlineTaskDataManager.getNewRepositoryTaskId());
offlineTaskDataManager.save(true);
offlineTaskDataManager.clear();
offlineTaskDataManager.readOfflineData();
assertEquals("3", offlineTaskDataManager.getNewRepositoryTaskId());
}
public void testGetTaskData() throws CoreException, IOException, ClassNotFoundException {
RepositoryTaskData taskData = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
taskData.setNewComment("version 1");
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
taskData = new RepositoryTaskData(new MockAttributeFactory(), MockRepositoryConnector.REPOSITORY_KIND,
MockRepositoryConnector.REPOSITORY_URL, "1", Task.DEFAULT_TASK_KIND);
taskData.setNewComment("version 2");
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
offlineTaskDataManager.save(true);
offlineTaskDataManager.clear();
offlineTaskDataManager.readOfflineData();
assertEquals("version 2", offlineTaskDataManager.getRepositoryTaskData(
RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1")).getNewComment());
assertEquals("version 1", offlineTaskDataManager.getOldRepositoryTaskData(
RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1")).getNewComment());
}
public void testUniqueCopy() throws Exception {
RepositoryTaskData taskData = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
RepositoryTaskData taskData2 = offlineTaskDataManager.getEditableCopy(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1"));
assertNotNull(taskData2);
taskData2.setNewComment("test");
taskData = null;
taskData = offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1"));
assertFalse(taskData.getNewComment().equals("test"));
taskData = null;
taskData = offlineTaskDataManager.getOldRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1"));
assertFalse(taskData.getNewComment().equals("test"));
}
public void testRemoveRepositoryTaskData() throws CoreException, IOException, ClassNotFoundException {
RepositoryTaskData taskData = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
taskData = new RepositoryTaskData(new MockAttributeFactory(), MockRepositoryConnector.REPOSITORY_KIND,
MockRepositoryConnector.REPOSITORY_URL, "2", Task.DEFAULT_TASK_KIND);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "2"),
taskData);
offlineTaskDataManager.save(true);
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.remove(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "2"));
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.save(true);
offlineTaskDataManager.clear();
offlineTaskDataManager.readOfflineData();
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
}
public void testRemoveListOfRepositoryTaskData() throws CoreException, IOException, ClassNotFoundException {
RepositoryTaskData taskData1 = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData1);
RepositoryTaskData taskData2 = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "2",
Task.DEFAULT_TASK_KIND);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "2"),
taskData2);
offlineTaskDataManager.save(true);
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
ArrayList<String> list = new ArrayList<String>();
list.add(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"));
list.add(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "2"));
offlineTaskDataManager.remove(list);
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.save(true);
offlineTaskDataManager.clear();
offlineTaskDataManager.readOfflineData();
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
}
public void testEditing() {
RepositoryTaskData taskData = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNotNull(offlineTaskDataManager.getOldRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
RepositoryTaskData editData = offlineTaskDataManager.getEditableCopy(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1"));
assertNotNull(editData);
editData.setAttributeFactory(new MockAttributeFactory());
editData.setAttributeValue(RepositoryTaskAttribute.COMMENT_NEW, "new comment");
// for (RepositoryTaskAttribute attribute: editData.getAttributes()) {
// assertTrue(taskData.getAttribute(attribute.getID()).equals(attribute));
// }
Set<RepositoryTaskAttribute> attSave = new HashSet<RepositoryTaskAttribute>();
attSave.add(editData.getAttribute(RepositoryTaskAttribute.COMMENT_NEW));
offlineTaskDataManager.saveEdits(RepositoryTaskHandleUtil
.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"), attSave);
editData = null;
editData = offlineTaskDataManager.getEditableCopy(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1"));
assertNotNull(editData);
assertEquals("new comment", editData.getAttributeValue(RepositoryTaskAttribute.COMMENT_NEW));
}
// /** DND
// * As is will write 81481326 bytes.
// *
// * @throws Exception
// */
// public void testLargeDataSet() throws Exception {
// RepositoryTaskData taskData;
// for (int x = 1; x < 500; x++) {
// taskData = new RepositoryTaskData(new MockAttributeFactory(),
// MockRepositoryConnector.REPOSITORY_KIND,
// MockRepositoryConnector.REPOSITORY_URL, "" + x);
//
// for (int y = 1; y < 60; y++) {
// RepositoryTaskAttribute attribute = new RepositoryTaskAttribute("" + y,
// "" + y, false);
// for (int z = 1; z < 10; z++) {
// attribute.addOption("" + z, "" + z);
// attribute.addValue("" + z);
// }
// taskData.addAttribute("" + y, attribute);
// }
//
// for (int y = 1; y < 5; y++) {
// RepositoryOperation op = new RepositoryOperation("" + y, "" + y);
// taskData.addOperation(op);
// }
//
// try {
// for (int y = 1; y < 1000; y++) {
// TaskComment comment = new TaskComment(new MockAttributeFactory(), y);
// comment.setAttributeValue(RepositoryTaskAttribute.COMMENT_TEXT, "Testing
// \u05D0");
// taskData.addComment(comment);
// }
// } catch (StackOverflowError e) {
// e.printStackTrace();
// }
//
// // for(int y = 1; y < 1000; y++) {
// // RepositoryAttachment attachment = new
// // RepositoryAttachment(repository, new MockAttributeFactory());
// // taskData.addAttachment(attachment);
// // }
//
// offlineTaskDataManager.put(taskData);
// offlineTaskDataManager.put(taskData);
// }
// offlineTaskDataManager.save();
// File file =
// TasksUiPlugin.getDefault().getOfflineReportsFilePath().toFile();
// offlineTaskDataManager.clear();
// offlineTaskDataManager.readOfflineData();
// assertNotNull(offlineTaskDataManager.getOldTaskData(AbstractRepositoryTask.getHandle(
// MockRepositoryConnector.REPOSITORY_URL, 400)));
// }
}
| false | true | public void testSave() throws CoreException, IOException, ClassNotFoundException {
RepositoryTaskData taskData = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
RepositoryTaskAttribute attrib1 = new RepositoryTaskAttribute("key", "name", false);
attrib1.setMetaDataValue("key1", "value1");
attrib1.setMetaDataValue("key2", "value2");
taskData.addAttribute("key", attrib1);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
taskData = new RepositoryTaskData(new MockAttributeFactory(), MockRepositoryConnector.REPOSITORY_KIND,
MockRepositoryConnector.REPOSITORY_URL, "2", Task.DEFAULT_TASK_KIND);
RepositoryTaskAttribute attrib2 = new RepositoryTaskAttribute("key", "name", false);
attrib2.setMetaDataValue("key3", "value3");
attrib2.setMetaDataValue("key4", "value4");
taskData.addAttribute("key", attrib2);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "2"),
taskData);
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.save(true);
offlineTaskDataManager.clear();
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.readOfflineData();
RepositoryTaskData loaded1 = offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1"));
assertNotNull(loaded1);
RepositoryTaskAttribute atr = loaded1.getAttribute("key");
assertNotNull(atr);
assertEquals("value1", atr.getMetaDataValue("key1"));
assertEquals("value2", atr.getMetaDataValue("key2"));
RepositoryTaskData loaded2 = offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2"));
assertNotNull(loaded2);
RepositoryTaskAttribute atr2 = loaded2.getAttribute("key");
assertNotNull(atr2);
assertEquals("value3", atr2.getMetaDataValue("key3"));
assertEquals("value4", atr2.getMetaDataValue("key4"));
}
| public void testSave() throws CoreException, IOException, ClassNotFoundException {
RepositoryTaskData taskData = new RepositoryTaskData(new MockAttributeFactory(),
MockRepositoryConnector.REPOSITORY_KIND, MockRepositoryConnector.REPOSITORY_URL, "1",
Task.DEFAULT_TASK_KIND);
RepositoryTaskAttribute attrib1 = new RepositoryTaskAttribute("key", "name", false);
attrib1.putMetaDataValue("key1", "value1");
attrib1.putMetaDataValue("key2", "value2");
taskData.addAttribute("key", attrib1);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "1"),
taskData);
taskData = new RepositoryTaskData(new MockAttributeFactory(), MockRepositoryConnector.REPOSITORY_KIND,
MockRepositoryConnector.REPOSITORY_URL, "2", Task.DEFAULT_TASK_KIND);
RepositoryTaskAttribute attrib2 = new RepositoryTaskAttribute("key", "name", false);
attrib2.putMetaDataValue("key3", "value3");
attrib2.putMetaDataValue("key4", "value4");
taskData.addAttribute("key", attrib2);
offlineTaskDataManager.push(RepositoryTaskHandleUtil.getHandle(MockRepositoryConnector.REPOSITORY_URL, "2"),
taskData);
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNotNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.save(true);
offlineTaskDataManager.clear();
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1")));
assertNull(offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2")));
offlineTaskDataManager.readOfflineData();
RepositoryTaskData loaded1 = offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "1"));
assertNotNull(loaded1);
RepositoryTaskAttribute atr = loaded1.getAttribute("key");
assertNotNull(atr);
assertEquals("value1", atr.getMetaDataValue("key1"));
assertEquals("value2", atr.getMetaDataValue("key2"));
RepositoryTaskData loaded2 = offlineTaskDataManager.getRepositoryTaskData(RepositoryTaskHandleUtil.getHandle(
MockRepositoryConnector.REPOSITORY_URL, "2"));
assertNotNull(loaded2);
RepositoryTaskAttribute atr2 = loaded2.getAttribute("key");
assertNotNull(atr2);
assertEquals("value3", atr2.getMetaDataValue("key3"));
assertEquals("value4", atr2.getMetaDataValue("key4"));
}
|
diff --git a/KBDeX/src/kbdex/model/discourse/wordprocessing/KSimpleWordFinder.java b/KBDeX/src/kbdex/model/discourse/wordprocessing/KSimpleWordFinder.java
index fce1b13..c8742c2 100644
--- a/KBDeX/src/kbdex/model/discourse/wordprocessing/KSimpleWordFinder.java
+++ b/KBDeX/src/kbdex/model/discourse/wordprocessing/KSimpleWordFinder.java
@@ -1,104 +1,107 @@
/*
* KSimpleWordFinder.java
* Created on Jun 27, 2010
* Copyright(c) 2010 Yoshiaki Matsuzawa, Shizuoka University. All rights reserved.
*/
package kbdex.model.discourse.wordprocessing;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import kbdex.utils.KDictionary;
/*
* ・テスト用.Pajekとの比較によるverifyをするために使う
*/
public class KSimpleWordFinder implements IKWordFinder {
private boolean lowercaseCheck = false;
private boolean wordIncludingCheck = true;
private SortedMap<Integer, String> founds = new TreeMap<Integer, String>();
protected KSimpleWordFinder(boolean lowercaseCheck,
boolean wordIncludingCheck) {
this.lowercaseCheck = lowercaseCheck;
this.wordIncludingCheck = wordIncludingCheck;
}
public void parse(String text, KDictionary<String> keywords) {
if (lowercaseCheck) {
text = text.toLowerCase();
}
for (String word : keywords.getElements()) {
String currentText = text;
+ if (lowercaseCheck) {
+ word = word.toLowerCase();
+ }
while (true) {// 後ろから切っていくこと.前から切ると,indexがずれる.
int index = currentText.lastIndexOf(word);
if (index < 0) {
break;
}
// 包含しているwordでないか調べる(アルゴリズムがださいので変更すること)
if (wordIncludingCheck) {
if (index > 0) {// 最初でない
char c = text.charAt(index - 1);
if (!(c == ' ' /* || c == '.' */|| c == ',' || c == '?')) {// かつ,直前の文字がスペース,.じゃない->NG
// 7.29問題回避するため,ひとまず直前ピリオドは×
currentText = currentText.substring(0, index);
continue;
}
}
if (!text.endsWith(word)) {
char c = text.charAt(index + word.length());
if (!(c == ' ' || c == '.' || c == ',' || c == '?')) {
currentText = currentText.substring(0, index);
continue;
}
}
}
founds.put(index, word);
currentText = currentText.substring(0, index);
}
}
}
/*
* (non-Javadoc)
*
* @see kbdex.view.discourse.IKWordFinder#getFoundLocations()
*/
public List<Integer> getFoundLocations() {
return new ArrayList<Integer>(founds.keySet());
}
/*
* (non-Javadoc)
*
* @see kbdex.view.discourse.IKWordFinder#getWord(int)
*/
public String getFoundWord(int index) {
if (!founds.containsKey(index)) {
throw new RuntimeException();
}
return founds.get(index);
}
/*
* (non-Javadoc)
*
* @see kbdex.view.discourse.IKWordFinder#getFoundWords()
*/
public List<String> getFoundWords() {
return new ArrayList<String>(new HashSet<String>(founds.values()));
}
public String toString() {
return founds.toString();
}
}
| true | true | public void parse(String text, KDictionary<String> keywords) {
if (lowercaseCheck) {
text = text.toLowerCase();
}
for (String word : keywords.getElements()) {
String currentText = text;
while (true) {// 後ろから切っていくこと.前から切ると,indexがずれる.
int index = currentText.lastIndexOf(word);
if (index < 0) {
break;
}
// 包含しているwordでないか調べる(アルゴリズムがださいので変更すること)
if (wordIncludingCheck) {
if (index > 0) {// 最初でない
char c = text.charAt(index - 1);
if (!(c == ' ' /* || c == '.' */|| c == ',' || c == '?')) {// かつ,直前の文字がスペース,.じゃない->NG
// 7.29問題回避するため,ひとまず直前ピリオドは×
currentText = currentText.substring(0, index);
continue;
}
}
if (!text.endsWith(word)) {
char c = text.charAt(index + word.length());
if (!(c == ' ' || c == '.' || c == ',' || c == '?')) {
currentText = currentText.substring(0, index);
continue;
}
}
}
founds.put(index, word);
currentText = currentText.substring(0, index);
}
}
}
| public void parse(String text, KDictionary<String> keywords) {
if (lowercaseCheck) {
text = text.toLowerCase();
}
for (String word : keywords.getElements()) {
String currentText = text;
if (lowercaseCheck) {
word = word.toLowerCase();
}
while (true) {// 後ろから切っていくこと.前から切ると,indexがずれる.
int index = currentText.lastIndexOf(word);
if (index < 0) {
break;
}
// 包含しているwordでないか調べる(アルゴリズムがださいので変更すること)
if (wordIncludingCheck) {
if (index > 0) {// 最初でない
char c = text.charAt(index - 1);
if (!(c == ' ' /* || c == '.' */|| c == ',' || c == '?')) {// かつ,直前の文字がスペース,.じゃない->NG
// 7.29問題回避するため,ひとまず直前ピリオドは×
currentText = currentText.substring(0, index);
continue;
}
}
if (!text.endsWith(word)) {
char c = text.charAt(index + word.length());
if (!(c == ' ' || c == '.' || c == ',' || c == '?')) {
currentText = currentText.substring(0, index);
continue;
}
}
}
founds.put(index, word);
currentText = currentText.substring(0, index);
}
}
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index d76e0260..fc97832a 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1187 +1,1190 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.os.Process;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = true;
static final String TAG = "Launcher.Model";
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private Loader mLoader = new Loader();
private boolean mBeforeFirstLoad = true;
private WeakReference<Callbacks> mCallbacks;
private AllAppsList mAllAppsList = new AllAppsList();
public interface Callbacks {
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindPackageAdded(ArrayList<ApplicationInfo> apps);
public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps);
public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps);
}
LauncherModel(LauncherApplication app) {
mApp = app;
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
int cellX, int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
- info.title = c.getString(titleIndex);
+ if (itemType
+ != LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
+ info.title = c.getString(titleIndex);
+ }
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
| true | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
if (itemType
!= LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info.title = c.getString(titleIndex);
}
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
|
diff --git a/icy/main/Icy.java b/icy/main/Icy.java
index 2a7b328..c55fa30 100644
--- a/icy/main/Icy.java
+++ b/icy/main/Icy.java
@@ -1,1238 +1,1240 @@
/*
* Copyright 2010-2013 Institut Pasteur.
*
* This file is part of Icy.
*
* Icy 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.
*
* Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>.
*/
package icy.main;
import icy.action.ActionManager;
import icy.common.Version;
import icy.file.FileUtil;
import icy.file.Loader;
import icy.gui.dialog.ConfirmDialog;
import icy.gui.dialog.IdConfirmDialog;
import icy.gui.dialog.MessageDialog;
import icy.gui.frame.ExitFrame;
import icy.gui.frame.IcyExternalFrame;
import icy.gui.frame.SplashScreenFrame;
import icy.gui.frame.progress.AnnounceFrame;
import icy.gui.frame.progress.ToolTipFrame;
import icy.gui.main.MainFrame;
import icy.gui.main.MainInterface;
import icy.gui.main.MainInterfaceBatch;
import icy.gui.main.MainInterfaceGui;
import icy.gui.system.NewVersionFrame;
import icy.gui.util.LookAndFeelUtil;
import icy.imagej.ImageJPatcher;
import icy.math.UnitUtil;
import icy.network.NetworkUtil;
import icy.plugin.PluginInstaller;
import icy.plugin.PluginLauncher;
import icy.plugin.PluginLoader;
import icy.plugin.PluginUpdater;
import icy.preferences.ApplicationPreferences;
import icy.preferences.GeneralPreferences;
import icy.preferences.IcyPreferences;
import icy.preferences.PluginPreferences;
import icy.sequence.Sequence;
import icy.system.AppleUtil;
import icy.system.IcyExceptionHandler;
import icy.system.IcySecurityManager;
import icy.system.SingleInstanceCheck;
import icy.system.SystemUtil;
import icy.system.thread.ThreadUtil;
import icy.update.IcyUpdater;
import icy.util.StringUtil;
import icy.workspace.WorkspaceInstaller;
import icy.workspace.WorkspaceLoader;
import ij.ImageJ;
import java.awt.EventQueue;
import java.beans.PropertyVetoException;
import java.io.File;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import vtk.vtkNativeLibrary;
/**
* <br>
* ICY: Image Analysis Software <br>
* Institut Pasteur <br>
* Unite d analyse d images quantitative <br>
* 25,28 Rue du Docteur Roux <br>
* 75015 Paris - France
*
* @author Fabrice de Chaumont, Stephane Dallongeville
*/
public class Icy
{
public static final String LIB_PATH = "lib";
public static final int EXIT_FORCE_DELAY = 3000;
/**
* ICY Version
*/
public static Version version = new Version("1.5.4.2");
/**
* Main interface
*/
private static MainInterface mainInterface = null;
/**
* Unique instance checker
*/
static FileLock lock = null;
/**
* private splash for initial loading
*/
static SplashScreenFrame splashScreen = null;
/**
* VTK library loaded flag
*/
static boolean vtkLibraryLoaded = false;
/**
* ITK library loaded flag
*/
static boolean itkLibraryLoaded = false;
/**
* No splash screen flag (default = false)
*/
static boolean noSplash = false;
/**
* Exiting flag
*/
static boolean exiting = false;
/**
* Startup parameters
*/
static String[] args;
static String[] pluginArgs;
static String startupPlugin;
static String startupImage;
/**
* internals
*/
static ExitFrame exitFrame = null;
static Thread terminer = null;
/**
* @param args
* Received from the command line.
*/
public static void main(String[] args)
{
boolean headless = false;
try
{
System.out.println("Initializing...");
System.out.println();
// handle arguments (must be the first thing to do)
headless = handleAppArgs(args);
// force headless if we have a headless system
if (!headless && SystemUtil.isHeadLess())
headless = true;
// check if Icy is already running.
lock = SingleInstanceCheck.lock("icy");
if (lock == null)
{
// we always accept multi instance in headless mode
if (!headless)
{
// don't use the ConfirmDialog as headless is still false here
if (!ConfirmDialog.getBooleanReturnValue(JOptionPane.showConfirmDialog(null,
"Icy is already running on this computer. Start anyway ?", "Confirmation",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)))
{
System.out.println("Exiting...");
System.exit(0);
return;
}
}
}
if (!headless && !noSplash)
{
// prepare splashScreen (ok to create it here as we are not yet in substance laf)
splashScreen = new SplashScreenFrame();
// It's important to initialize AWT now (with InvokeNow(...) for instance) to avoid
// the JVM deadlock bug (id: 5104239). It happen when the AWT thread is initialized
// while others threads load some new library with ClassLoader.loadLibrary
// display splash NOW (don't use ThreadUtil as headless is still false here)
EventQueue.invokeAndWait(new Runnable()
{
@Override
public void run()
{
// display splash screen
splashScreen.setVisible(true);
}
});
}
// initialize preferences
IcyPreferences.init();
// initialize network (need preferences)
NetworkUtil.init();
// load plugins classes (need preferences init)
PluginLoader.reloadAsynch();
WorkspaceLoader.reloadAsynch();
// patches ImageJ classes
ImageJPatcher.applyPatches();
// build main interface
if (headless)
mainInterface = new MainInterfaceBatch();
else
mainInterface = new MainInterfaceGui();
}
catch (Throwable t)
{
// any error at this point is fatal
fatalError(t, headless);
}
if (!headless)
{
// do it on AWT thread NOW as this is what we want first
ThreadUtil.invokeNow(new Runnable()
{
@Override
public void run()
{
try
{
// init Look And Feel (need mainInterface instance)
LookAndFeelUtil.init();
// init need "mainInterface" variable to be initialized
getMainInterface().init();
}
catch (Throwable t)
{
// any error here is fatal
fatalError(t, false);
}
}
});
}
else
{
// simple main interface init
getMainInterface().init();
}
// splash screen initialized --> hide it
if (splashScreen != null)
{
// then do less important stuff later
ThreadUtil.invokeLater(new Runnable()
{
@Override
public void run()
{
// we can now hide splash as we have interface
splashScreen.dispose();
splashScreen = null;
}
});
}
// show general informations
System.out.println(SystemUtil.getJavaName() + " " + SystemUtil.getJavaVersion() + " ("
+ SystemUtil.getJavaArchDataModel() + " bit)");
System.out.println("Running on " + SystemUtil.getOSName() + " " + SystemUtil.getOSVersion() + " ("
+ SystemUtil.getOSArch() + ")");
System.out.println("Number of processors : " + SystemUtil.getAvailableProcessors());
System.out.println("System total memory : " + UnitUtil.getBytesString(SystemUtil.getTotalMemory()));
System.out.println("System available memory : " + UnitUtil.getBytesString(SystemUtil.getFreeMemory()));
System.out.println("Max java memory : " + UnitUtil.getBytesString(SystemUtil.getJavaMaxMemory()));
if (headless)
System.out.println("Headless mode.");
System.out.println();
// initialize OSX specific GUI stuff
if (!headless && SystemUtil.isMac())
AppleUtil.init();
// initialize security
IcySecurityManager.init();
// initialize exception handler
IcyExceptionHandler.init();
// initialize action manager
ActionManager.init();
// prepare native library files (need preferences init)
nativeLibrariesInit();
final long currentTime = new Date().getTime();
final long slice = 1000 * 60 * 12;
// check only once per 12 hours slice
if (currentTime > (GeneralPreferences.getLastUpdateCheckTime() + slice))
{
// check for core update
if (GeneralPreferences.getAutomaticUpdate())
IcyUpdater.checkUpdate(true);
// check for plugin update
if (PluginPreferences.getAutomaticUpdate())
PluginUpdater.checkUpdate(true);
// update last update check time
GeneralPreferences.setLastUpdateCheckTime(currentTime);
}
// changed version and not headless ?
if (!headless && !ApplicationPreferences.getVersion().equals(Icy.version))
{
// display the new version information
final String changeLog = Icy.getChangeLog();
// show the new version frame
if (!StringUtil.isEmpty(changeLog))
{
ThreadUtil.invokeNow(new Runnable()
{
@Override
public void run()
{
new NewVersionFrame(Icy.getChangeLog());
}
});
}
}
// update version info
ApplicationPreferences.setVersion(Icy.version);
// set LOCI debug level
loci.common.DebugTools.enableLogging("ERROR");
System.out.println();
System.out.println("Icy Version " + version + " started !");
System.out.println();
checkParameters();
// handle startup arguments
if (startupImage != null)
Icy.getMainInterface().addSequence(Loader.loadSequence(FileUtil.getGenericPath(startupImage), 0, false));
if (startupPlugin != null)
{
PluginLoader.waitWhileLoading();
PluginLauncher.start(startupPlugin);
}
// headless mode ?
if (headless)
{
// wait while updates are occurring...
while (PluginInstaller.isProcessing() || WorkspaceInstaller.isProcessing())
ThreadUtil.sleep(1);
// now we can exit
exit(false);
}
}
private static boolean handleAppArgs(String[] args)
{
final List<String> pluginArgs = new ArrayList<String>();
startupImage = null;
startupPlugin = null;
boolean execute = false;
boolean headless = false;
// save the base arguments
Icy.args = args;
for (String arg : args)
{
// store plugin arguments
if (startupPlugin != null)
pluginArgs.add(arg);
else if (execute)
startupPlugin = arg;
// special flag to disabled JCL (needed for development)
else if (arg.equalsIgnoreCase("--disableJCL") || arg.equalsIgnoreCase("-dJCL"))
PluginLoader.setJCLDisabled(true);
// headless mode
else if (arg.equalsIgnoreCase("--headless") || arg.equalsIgnoreCase("-hl"))
headless = true;
// disable splash-screen
else if (arg.equalsIgnoreCase("--nosplash") || arg.equalsIgnoreCase("-ns"))
noSplash = true;
// execute plugin
else if (arg.equalsIgnoreCase("--execute") || arg.equalsIgnoreCase("-x"))
execute = true;
// assume image name ?
else
startupImage = arg;
}
// save the plugin arguments
Icy.pluginArgs = pluginArgs.toArray(new String[pluginArgs.size()]);
return headless;
}
static void checkParameters()
{
// we verify that some parameters are incorrect
if ((ApplicationPreferences.getMaxMemoryMB() <= 128) && (ApplicationPreferences.getMaxMemoryMBLimit() > 128))
{
final String text = "Your maximum memory setting is low, you should increase it in preferences setting.";
if (Icy.getMainInterface().isHeadLess())
System.out.println(text);
else
MessageDialog.showDialog(text, MessageDialog.WARNING_MESSAGE);
}
else if (ApplicationPreferences.getMaxMemoryMB() < (ApplicationPreferences.getDefaultMemoryMB() / 2))
{
if (!Icy.getMainInterface().isHeadLess())
{
new ToolTipFrame(
"<html><b>Tip:</b> you can increase your maximum memory in preferences setting.</html>", 15,
"maxMemoryTip");
}
}
}
static void fatalError(Throwable t, boolean headless)
{
// hide splashScreen if needed
if ((splashScreen != null) && (splashScreen.isVisible()))
splashScreen.dispose();
// show error in console
IcyExceptionHandler.showErrorMessage(t, true);
// and show error in dialog if not headless
if (!headless)
{
JOptionPane.showMessageDialog(null, IcyExceptionHandler.getErrorMessage(t, true), "Fatal error",
JOptionPane.ERROR_MESSAGE);
}
// exit with error code 1
System.exit(1);
}
/**
* Restart application with user confirmation
*/
public static void confirmRestart()
{
confirmRestart(null);
}
/**
* Restart application with user confirmation (custom message)
*/
public static void confirmRestart(String message)
{
final String mess;
if (StringUtil.isEmpty(message))
mess = "Application need to be restarted so changes can take effet. Do it now ?";
else
mess = message;
if (ConfirmDialog.confirm(mess))
// restart application now
exit(true);
}
/**
* Show announcement to restart application
*/
public static void announceRestart()
{
announceRestart(null);
}
/**
* Show announcement to restart application (custom message)
*/
public static void announceRestart(String message)
{
final String mess;
if (StringUtil.isEmpty(message))
mess = "Application need to be restarted so changes can take effet.";
else
mess = message;
if (Icy.getMainInterface().isHeadLess())
{
// just display this message
System.out.println(mess);
}
else
{
new AnnounceFrame(mess, "Restart Now", new Runnable()
{
@Override
public void run()
{
// restart application now
exit(true);
}
}, 20);
}
}
/**
* Returns <code>true</code> if application can exit.<br>
* Shows a confirmation dialog if setting requires it or if it's unsafe to exit now.
*/
public static boolean canExit(boolean showConfirm)
{
// we first check if externals listeners allow existing
if (!getMainInterface().canExitExternal())
return false;
// headless mode --> allow exit
if (Icy.getMainInterface().isHeadLess())
return true;
// PluginInstaller or WorkspaceInstaller not running
final boolean safeExit = (!PluginInstaller.isProcessing()) && (!WorkspaceInstaller.isProcessing());
// not safe, need confirmation
if (!safeExit)
{
if (!ConfirmDialog.confirm("Quit the application",
"Some processes are not yet completed, are you sure you want to quit ?",
ConfirmDialog.YES_NO_CANCEL_OPTION))
return false;
return true;
}
else if (showConfirm && GeneralPreferences.getExitConfirm())
{
// we need user confirmation
if (!IdConfirmDialog.confirm("Quit the application ?", GeneralPreferences.ID_CONFIRM_EXIT))
return false;
return true;
}
return true;
}
/**
* exit
*/
public static boolean exit(final boolean restart)
{
// check we can exit application
if (!canExit(!restart))
return false;
// already existing
if (exiting && terminer.isAlive())
{
// set focus on exit frame
if (exitFrame != null)
exitFrame.requestFocus();
// return true;
return true;
}
// we don't want to be in EDT here and avoid BG runner
// as we test for BG runner completion
terminer = new Thread(new Runnable()
{
@Override
public void run()
{
// mark the application as exiting
exiting = true;
System.out.println("Exiting...");
final ImageJ ij = Icy.getMainInterface().getImageJ();
// clean ImageJ exit
if (ij != null)
ij.quit();
// get main frame
final MainFrame mainFrame = Icy.getMainInterface().getMainFrame();
// disconnect from chat (not needed but preferred)
if (mainFrame != null)
mainFrame.getChat().disconnect("Icy closed");
// close all icyFrames (force wait completion)
ThreadUtil.invokeNow(new Runnable()
{
@Override
public void run()
{
// for (IcyFrame frame : IcyFrame.getAllFrames())
// frame.close();
// close all JInternalFrames
final JDesktopPane desktopPane = Icy.getMainInterface().getDesktopPane();
if (desktopPane != null)
{
for (JInternalFrame frame : desktopPane.getAllFrames())
{
// if (frame instanceof IcyInternalFrame)
// {
// final IcyInternalFrame iFrame = (IcyInternalFrame) frame;
// if (!iFrame.isClosed())
// iFrame.close(true);
// if (iFrame.getDefaultCloseOperation() !=
// WindowConstants.DISPOSE_ON_CLOSE)
// iFrame.dispose();
// }
// else
// {
try
{
frame.setClosed(true);
}
catch (PropertyVetoException e)
{
// if (frame.getDefaultCloseOperation() !=
// WindowConstants.DISPOSE_ON_CLOSE)
frame.dispose();
}
// }
}
}
// then close all external frames except main frame
for (JFrame frame : Icy.getMainInterface().getExternalFrames())
{
if (frame != mainFrame)
{
if (frame instanceof IcyExternalFrame)
{
final IcyExternalFrame iFrame = (IcyExternalFrame) frame;
iFrame.close();
if (iFrame.getDefaultCloseOperation() != WindowConstants.DISPOSE_ON_CLOSE)
iFrame.dispose();
}
else
frame.dispose();
}
}
}
});
// stop daemon plugin
PluginLoader.stopDaemons();
// shutdown background processor after frame close
ThreadUtil.shutdown();
// headless mode
if (Icy.getMainInterface().isHeadLess())
{
// final long start = System.currentTimeMillis();
// // wait 10s max for background processors completed theirs tasks
// while (!ThreadUtil.isShutdownAndTerminated() && ((System.currentTimeMillis()
// - start) < 10 * 1000))
// ThreadUtil.sleep(1);
// wait for background processors completed theirs tasks
while (!ThreadUtil.isShutdownAndTerminated())
ThreadUtil.sleep(1);
}
else
{
// need to create the exit frame in EDT
ThreadUtil.invokeNow(new Runnable()
{
@Override
public void run()
{
// create and display the exit frame
exitFrame = new ExitFrame(EXIT_FORCE_DELAY);
}
});
// wait that background processors completed theirs tasks
while (!ThreadUtil.isShutdownAndTerminated() && !exitFrame.isForced())
ThreadUtil.sleep(1);
// can close the exit frame now
exitFrame.dispose();
}
// finally close the main frame
if (mainFrame != null)
mainFrame.dispose();
// save preferences
IcyPreferences.save();
// clean up native library files
// unPrepareNativeLibraries();
if (lock != null)
SingleInstanceCheck.release(lock);
final boolean doUpdate = IcyUpdater.getWantUpdate();
// launch updater if needed
if (doUpdate || restart)
IcyUpdater.launchUpdater(doUpdate, restart);
// good exit
System.exit(0);
}
});
terminer.setName("Icy Terminer");
terminer.start();
return true;
}
/**
* @param force
* @deprecated use <code>exit(boolean)</code> instead
*/
@Deprecated
public static boolean exit(final boolean restart, boolean force)
{
return exit(restart);
}
/**
* Return true is VTK library loaded.
*/
public static boolean isVtkLibraryLoaded()
{
return vtkLibraryLoaded;
}
/**
* Return true is VTK library loaded.
*/
public static boolean isItkLibraryLoaded()
{
return itkLibraryLoaded;
}
/**
* @deprecated Use {@link MainInterface#isHeadLess()} instead.
*/
@Deprecated
public static boolean isHeadLess()
{
return getMainInterface().isHeadLess();
}
/**
* Return true is the application is currently exiting.
*/
public static boolean isExiting()
{
return exiting;
}
/**
* Return the main Icy interface.
*/
public static MainInterface getMainInterface()
{
// batch mode
if (mainInterface == null)
mainInterface = new MainInterfaceBatch();
return mainInterface;
}
/**
* Returns the command line arguments
*/
public static String[] getCommandLineArgs()
{
return args;
}
/**
* Returns the command line arguments
*/
public static String[] getCommandLinePluginArgs()
{
return pluginArgs;
}
/**
* Return content of the <code>CHANGELOG.txt</code> file
*/
public static String getChangeLog()
{
if (FileUtil.exists("CHANGELOG.txt"))
return new String(FileUtil.load("CHANGELOG.txt", false));
return "";
}
/**
* Return content of the <code>COPYING.txt</code> file
*/
public static String getLicense()
{
if (FileUtil.exists("COPYING.txt"))
return new String(FileUtil.load("COPYING.txt", false));
return "";
}
/**
* Return content of the <code>README.txt</code> file
*/
public static String getReadMe()
{
if (FileUtil.exists("README.txt"))
return new String(FileUtil.load("README.txt", false));
return "";
}
/**
* @deprecated Uses <code>Icy.getMainInterface().addSequence(Sequence)</code> instead.
*/
@Deprecated
public static void addSequence(final Sequence sequence)
{
Icy.getMainInterface().addSequence(sequence);
}
static void nativeLibrariesInit()
{
final String lastOs = ApplicationPreferences.getOs();
final String os = SystemUtil.getOSArchIdString();
final boolean osChanged = !StringUtil.equals(lastOs, os);
// build the local native library path
final String libPath = LIB_PATH + FileUtil.separator + os;
final File libFile = new File(libPath);
// get all files in local native library path
final File[] files = FileUtil.getFiles(libFile, null, true, true, false);
final ArrayList<String> directories = new ArrayList<String>();
// add base local native library path to user library paths
directories.add(libFile.getAbsolutePath());
// add base temporary native library path to user library paths
directories.add(SystemUtil.getTempLibraryDirectory());
for (File f : files)
{
if (f.isDirectory())
{
// add all directories to user library paths
final String filePath = f.getAbsolutePath();
if (!directories.contains(filePath))
directories.add(filePath);
}
}
// add lib folder for unix system
if (SystemUtil.isUnix())
{
directories.add("/lib");
directories.add("/usr/lib");
if (SystemUtil.is64bits())
{
directories.add("/lib64");
directories.add("/lib/x86_64");
directories.add("/lib/x86_64-linux-gnu");
directories.add("/usr/lib64");
directories.add("/usr/lib/x86_64");
directories.add("/usr/lib/x86_64-linux-gnu");
}
else
{
directories.add("/lib/x86");
directories.add("/lib/x86-linux-gnu");
directories.add("/usr/lib/x86");
directories.add("/usr/lib/x86-linux-gnu");
}
}
if (!SystemUtil.addToJavaLibraryPath(directories.toArray(new String[directories.size()])))
System.err.println("Native libraries may won't load correctly.");
// save os change
if (osChanged)
ApplicationPreferences.setOs(os);
// load native libraries
loadVtkLibrary(libPath);
// loadItkLibrary(libPath);
// disable native lib support for JAI as we don't provide them (for the moment)
SystemUtil.setProperty("com.sun.media.jai.disableMediaLib", "true");
}
private static void loadVtkLibrary(String libPath)
{
final String vtkLibPath = libPath + FileUtil.separator + "vtk";
// we load it directly from inner lib path if possible
System.setProperty("vtk.lib.dir", vtkLibPath);
vtkLibraryLoaded = false;
try
{
// if (SystemUtil.isUnix())
// {
// vtkNativeLibrary.LoadAllNativeLibraries();
//
// // assume VTK loaded if at least 1 native library is loaded
// for (vtkNativeLibrary lib : vtkNativeLibrary.values())
// if (lib.IsLoaded())
// vtkLibraryLoaded = true;
// }
// else
{
loadLibrary(vtkLibPath, "vtkalglib");
loadLibrary(vtkLibPath, "vtkexpat");
loadLibrary(vtkLibPath, "vtkDICOMParser");
loadLibrary(vtkLibPath, "vtkjpeg");
loadLibrary(vtkLibPath, "vtkjsoncpp");
loadLibrary(vtkLibPath, "vtkzlib");
- loadLibrary(vtkLibPath, "vtkoggtheora");
+ loadLibrary(vtkLibPath, "vtkoggtheora", false);
loadLibrary(vtkLibPath, "vtkverdict");
loadLibrary(vtkLibPath, "vtkpng");
loadLibrary(vtkLibPath, "vtkgl2ps");
loadLibrary(vtkLibPath, "vtktiff");
loadLibrary(vtkLibPath, "vtklibxml2");
loadLibrary(vtkLibPath, "vtkproj4");
loadLibrary(vtkLibPath, "vtksys");
loadLibrary(vtkLibPath, "vtkfreetype");
loadLibrary(vtkLibPath, "vtkmetaio");
loadLibrary(vtkLibPath, "vtkftgl");
loadLibrary(vtkLibPath, "vtkCommonCore");
loadLibrary(vtkLibPath, "vtkWrappingJava");
loadLibrary(vtkLibPath, "vtkCommonSystem");
loadLibrary(vtkLibPath, "vtkCommonMath");
loadLibrary(vtkLibPath, "vtkCommonMisc");
loadLibrary(vtkLibPath, "vtkCommonTransforms");
if (SystemUtil.isMac())
{
loadLibrary(vtkLibPath, "vtkhdf5.1.8.5");
loadLibrary(vtkLibPath, "vtkhdf5_hl.1.8.5");
}
else
{
loadLibrary(vtkLibPath, "vtkhdf5");
loadLibrary(vtkLibPath, "vtkhdf5_hl");
}
loadLibrary(vtkLibPath, "vtkNetCDF");
loadLibrary(vtkLibPath, "vtkNetCDF_cxx");
loadLibrary(vtkLibPath, "vtkCommonDataModel");
loadLibrary(vtkLibPath, "vtkCommonColor");
loadLibrary(vtkLibPath, "vtkCommonComputationalGeometry");
loadLibrary(vtkLibPath, "vtkCommonExecutionModel");
loadLibrary(vtkLibPath, "vtkexoIIc");
loadLibrary(vtkLibPath, "vtkFiltersVerdict");
loadLibrary(vtkLibPath, "vtkFiltersProgrammable");
loadLibrary(vtkLibPath, "vtkImagingMath");
loadLibrary(vtkLibPath, "vtkIOCore");
loadLibrary(vtkLibPath, "vtkIOEnSight");
loadLibrary(vtkLibPath, "vtkIOVideo");
loadLibrary(vtkLibPath, "vtkIOLegacy");
loadLibrary(vtkLibPath, "vtkIONetCDF");
loadLibrary(vtkLibPath, "vtkIOXMLParser");
loadLibrary(vtkLibPath, "vtkIOXML");
loadLibrary(vtkLibPath, "vtkIOImage");
if (SystemUtil.isMac() || SystemUtil.isUnix())
loadLibrary(vtkLibPath, "vtksqlite");
loadLibrary(vtkLibPath, "vtkIOSQL");
loadLibrary(vtkLibPath, "vtkIOMovie");
loadLibrary(vtkLibPath, "vtkParallelCore");
loadLibrary(vtkLibPath, "vtkImagingCore");
loadLibrary(vtkLibPath, "vtkFiltersCore");
loadLibrary(vtkLibPath, "vtkImagingColor");
loadLibrary(vtkLibPath, "vtkImagingFourier");
loadLibrary(vtkLibPath, "vtkImagingSources");
loadLibrary(vtkLibPath, "vtkImagingHybrid");
loadLibrary(vtkLibPath, "vtkImagingStatistics");
loadLibrary(vtkLibPath, "vtkIOGeometry");
loadLibrary(vtkLibPath, "vtkIOPLY");
loadLibrary(vtkLibPath, "vtkFiltersSelection");
loadLibrary(vtkLibPath, "vtkImagingGeneral");
loadLibrary(vtkLibPath, "vtkImagingStencil");
loadLibrary(vtkLibPath, "vtkImagingMorphological");
loadLibrary(vtkLibPath, "vtkFiltersGeometry");
loadLibrary(vtkLibPath, "vtkFiltersStatistics");
loadLibrary(vtkLibPath, "vtkFiltersImaging");
loadLibrary(vtkLibPath, "vtkIOLSDyna");
loadLibrary(vtkLibPath, "vtkFiltersGeneral");
loadLibrary(vtkLibPath, "vtkFiltersHyperTree");
loadLibrary(vtkLibPath, "vtkFiltersSMP");
loadLibrary(vtkLibPath, "vtkFiltersTexture");
loadLibrary(vtkLibPath, "vtkFiltersAMR");
loadLibrary(vtkLibPath, "vtkFiltersExtraction");
loadLibrary(vtkLibPath, "vtkFiltersSources");
loadLibrary(vtkLibPath, "vtkIOExodus");
loadLibrary(vtkLibPath, "vtkFiltersGeneric");
loadLibrary(vtkLibPath, "vtkFiltersModeling");
loadLibrary(vtkLibPath, "vtkIOAMR");
loadLibrary(vtkLibPath, "vtkFiltersFlowPaths");
loadLibrary(vtkLibPath, "vtkInfovisCore");
loadLibrary(vtkLibPath, "vtkIOInfovis");
loadLibrary(vtkLibPath, "vtkInfovisLayout");
loadLibrary(vtkLibPath, "vtkRenderingCore");
loadLibrary(vtkLibPath, "vtkRenderingLOD");
loadLibrary(vtkLibPath, "vtkRenderingImage");
loadLibrary(vtkLibPath, "vtkRenderingFreeType");
loadLibrary(vtkLibPath, "vtkDomainsChemistry");
loadLibrary(vtkLibPath, "vtkInteractionStyle");
loadLibrary(vtkLibPath, "vtkIOImport");
loadLibrary(vtkLibPath, "vtkRenderingAnnotation");
loadLibrary(vtkLibPath, "vtkRenderingLabel");
loadLibrary(vtkLibPath, "vtkFiltersHybrid");
loadLibrary(vtkLibPath, "vtkFiltersParallel");
loadLibrary(vtkLibPath, "vtkFiltersParallelImaging");
loadLibrary(vtkLibPath, "vtkIOMINC");
loadLibrary(vtkLibPath, "vtkIOParallel");
loadLibrary(vtkLibPath, "vtkRenderingVolume");
- loadLibrary(vtkLibPath, "vtkRenderingVolumeAMR");
+ loadLibrary(vtkLibPath, "vtkRenderingVolumeAMR", false);
loadLibrary(vtkLibPath, "vtkInteractionWidgets");
loadLibrary(vtkLibPath, "vtkInteractionImage");
loadLibrary(vtkLibPath, "vtkViewsCore");
loadLibrary(vtkLibPath, "vtkRenderingOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingLIC");
loadLibrary(vtkLibPath, "vtkRenderingVolumeOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingContext2D");
+ loadLibrary(vtkLibPath, "vtkRenderingContextOpenGL", false);
loadLibrary(vtkLibPath, "vtkRenderingGL2PS");
loadLibrary(vtkLibPath, "vtkViewsContext2D");
loadLibrary(vtkLibPath, "vtkGeovisCore");
loadLibrary(vtkLibPath, "vtkIOExport");
loadLibrary(vtkLibPath, "vtkChartsCore");
loadLibrary(vtkLibPath, "vtkViewsInfovis");
- loadLibrary(vtkLibPath, "vtkViewsGeovis");
+ loadLibrary(vtkLibPath, "vtkViewsGeovis", false);
// JAVA wrapper
loadLibrary(vtkLibPath, "vtkCommonCoreJava");
loadLibrary(vtkLibPath, "vtkCommonSystemJava");
loadLibrary(vtkLibPath, "vtkCommonMathJava");
loadLibrary(vtkLibPath, "vtkCommonMiscJava");
loadLibrary(vtkLibPath, "vtkCommonTransformsJava");
loadLibrary(vtkLibPath, "vtkCommonDataModelJava");
loadLibrary(vtkLibPath, "vtkCommonColorJava");
loadLibrary(vtkLibPath, "vtkCommonComputationalGeometryJava");
loadLibrary(vtkLibPath, "vtkCommonExecutionModelJava");
loadLibrary(vtkLibPath, "vtkFiltersVerdictJava");
loadLibrary(vtkLibPath, "vtkFiltersProgrammableJava");
loadLibrary(vtkLibPath, "vtkImagingMathJava");
loadLibrary(vtkLibPath, "vtkIOCoreJava");
loadLibrary(vtkLibPath, "vtkIOEnSightJava");
loadLibrary(vtkLibPath, "vtkIOVideoJava");
loadLibrary(vtkLibPath, "vtkIOLegacyJava");
loadLibrary(vtkLibPath, "vtkIONetCDFJava");
loadLibrary(vtkLibPath, "vtkIOXMLParserJava");
loadLibrary(vtkLibPath, "vtkIOXMLJava");
loadLibrary(vtkLibPath, "vtkIOImageJava");
loadLibrary(vtkLibPath, "vtkIOSQLJava");
loadLibrary(vtkLibPath, "vtkIOMovieJava");
loadLibrary(vtkLibPath, "vtkParallelCoreJava");
loadLibrary(vtkLibPath, "vtkImagingCoreJava");
loadLibrary(vtkLibPath, "vtkFiltersCoreJava");
loadLibrary(vtkLibPath, "vtkImagingColorJava");
loadLibrary(vtkLibPath, "vtkImagingFourierJava");
loadLibrary(vtkLibPath, "vtkImagingSourcesJava");
loadLibrary(vtkLibPath, "vtkImagingHybridJava");
loadLibrary(vtkLibPath, "vtkImagingStatisticsJava");
loadLibrary(vtkLibPath, "vtkIOGeometryJava");
loadLibrary(vtkLibPath, "vtkIOPLYJava");
loadLibrary(vtkLibPath, "vtkFiltersSelectionJava");
loadLibrary(vtkLibPath, "vtkImagingGeneralJava");
loadLibrary(vtkLibPath, "vtkImagingStencilJava");
loadLibrary(vtkLibPath, "vtkImagingMorphologicalJava");
loadLibrary(vtkLibPath, "vtkFiltersGeometryJava");
loadLibrary(vtkLibPath, "vtkFiltersStatisticsJava");
loadLibrary(vtkLibPath, "vtkFiltersImagingJava");
loadLibrary(vtkLibPath, "vtkIOLSDynaJava");
loadLibrary(vtkLibPath, "vtkFiltersGeneralJava");
loadLibrary(vtkLibPath, "vtkFiltersHyperTreeJava");
loadLibrary(vtkLibPath, "vtkFiltersSMPJava");
loadLibrary(vtkLibPath, "vtkFiltersTextureJava");
loadLibrary(vtkLibPath, "vtkFiltersAMRJava");
loadLibrary(vtkLibPath, "vtkFiltersExtractionJava");
loadLibrary(vtkLibPath, "vtkFiltersSourcesJava");
loadLibrary(vtkLibPath, "vtkIOExodusJava");
loadLibrary(vtkLibPath, "vtkFiltersGenericJava");
loadLibrary(vtkLibPath, "vtkFiltersModelingJava");
loadLibrary(vtkLibPath, "vtkIOAMRJava");
loadLibrary(vtkLibPath, "vtkFiltersFlowPathsJava");
loadLibrary(vtkLibPath, "vtkInfovisCoreJava");
loadLibrary(vtkLibPath, "vtkIOInfovisJava");
loadLibrary(vtkLibPath, "vtkInfovisLayoutJava");
loadLibrary(vtkLibPath, "vtkRenderingCoreJava");
loadLibrary(vtkLibPath, "vtkRenderingLODJava");
loadLibrary(vtkLibPath, "vtkRenderingImageJava");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeJava");
loadLibrary(vtkLibPath, "vtkDomainsChemistryJava");
loadLibrary(vtkLibPath, "vtkInteractionStyleJava");
loadLibrary(vtkLibPath, "vtkIOImportJava");
loadLibrary(vtkLibPath, "vtkRenderingAnnotationJava");
loadLibrary(vtkLibPath, "vtkRenderingLabelJava");
loadLibrary(vtkLibPath, "vtkFiltersHybridJava");
loadLibrary(vtkLibPath, "vtkFiltersParallelJava");
loadLibrary(vtkLibPath, "vtkFiltersParallelImagingJava");
loadLibrary(vtkLibPath, "vtkIOMINCJava");
loadLibrary(vtkLibPath, "vtkIOParallelJava");
loadLibrary(vtkLibPath, "vtkRenderingVolumeJava");
- loadLibrary(vtkLibPath, "vtkRenderingVolumeAMRJava");
+ loadLibrary(vtkLibPath, "vtkRenderingVolumeAMRJava", false);
loadLibrary(vtkLibPath, "vtkInteractionWidgetsJava");
loadLibrary(vtkLibPath, "vtkInteractionImageJava");
loadLibrary(vtkLibPath, "vtkViewsCoreJava");
loadLibrary(vtkLibPath, "vtkRenderingOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingLICJava");
loadLibrary(vtkLibPath, "vtkRenderingVolumeOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingContext2DJava");
+ loadLibrary(vtkLibPath, "vtkRenderingContextOpenGLJava", false);
loadLibrary(vtkLibPath, "vtkRenderingGL2PSJava");
loadLibrary(vtkLibPath, "vtkViewsContext2DJava");
loadLibrary(vtkLibPath, "vtkGeovisCoreJava");
loadLibrary(vtkLibPath, "vtkIOExportJava");
loadLibrary(vtkLibPath, "vtkChartsCoreJava");
loadLibrary(vtkLibPath, "vtkViewsInfovisJava");
- loadLibrary(vtkLibPath, "vtkViewsGeovisJava");
+ loadLibrary(vtkLibPath, "vtkViewsGeovisJava", false);
// VTK library successfully loaded
vtkLibraryLoaded = true;
}
// redirect vtk error log to file
vtkNativeLibrary.DisableOutputWindow(new File("vtk.log"));
}
catch (Throwable e)
{
System.out.println(e);
}
if (vtkLibraryLoaded)
System.out.println("VTK library successfully loaded...");
else
System.out.println("Cannot load VTK library...");
}
private static void loadItkLibrary(String osDir)
{
final String itkLibDir = osDir + FileUtil.separator + "itk";
try
{
loadLibrary(itkLibDir, "SimpleITKJava", true);
System.out.println("SimpleITK library successfully loaded...");
itkLibraryLoaded = true;
}
catch (Throwable e)
{
System.out.println("Cannot load SimpleITK library...");
}
}
private static void loadLibrary(String dir, String name, boolean mandatory, boolean showLog)
{
if (mandatory)
SystemUtil.loadLibrary(dir, name);
else
{
try
{
SystemUtil.loadLibrary(dir, name);
}
catch (Throwable e)
{
if (showLog)
System.out.println("cannot load " + name + ", skipping...");
}
}
}
private static void loadLibrary(String dir, String name, boolean mandatory)
{
loadLibrary(dir, name, mandatory, false);
}
private static void loadLibrary(String dir, String name)
{
loadLibrary(dir, name, true, false);
}
static void nativeLibrariesShutdown()
{
// build the native local library path
final String path = LIB_PATH + FileUtil.separator + SystemUtil.getOSArchIdString();
// get file list (we don't want hidden files if any)
File[] libraryFiles = FileUtil.getFiles(new File(path), null, true, false, false);
// remove previous copied files
for (File libraryFile : libraryFiles)
{
// get file in root directory
final File file = new File(libraryFile.getName());
// invoke delete on exit if the file exists
if (file.exists())
file.deleteOnExit();
}
// get file list from temporary native library path
libraryFiles = FileUtil.getFiles(new File(SystemUtil.getTempLibraryDirectory()), null, true, false, false);
// remove previous copied files
for (File libraryFile : libraryFiles)
{
// delete file
if (!FileUtil.delete(libraryFile, false))
libraryFile.deleteOnExit();
}
}
}
| false | true | private static void loadVtkLibrary(String libPath)
{
final String vtkLibPath = libPath + FileUtil.separator + "vtk";
// we load it directly from inner lib path if possible
System.setProperty("vtk.lib.dir", vtkLibPath);
vtkLibraryLoaded = false;
try
{
// if (SystemUtil.isUnix())
// {
// vtkNativeLibrary.LoadAllNativeLibraries();
//
// // assume VTK loaded if at least 1 native library is loaded
// for (vtkNativeLibrary lib : vtkNativeLibrary.values())
// if (lib.IsLoaded())
// vtkLibraryLoaded = true;
// }
// else
{
loadLibrary(vtkLibPath, "vtkalglib");
loadLibrary(vtkLibPath, "vtkexpat");
loadLibrary(vtkLibPath, "vtkDICOMParser");
loadLibrary(vtkLibPath, "vtkjpeg");
loadLibrary(vtkLibPath, "vtkjsoncpp");
loadLibrary(vtkLibPath, "vtkzlib");
loadLibrary(vtkLibPath, "vtkoggtheora");
loadLibrary(vtkLibPath, "vtkverdict");
loadLibrary(vtkLibPath, "vtkpng");
loadLibrary(vtkLibPath, "vtkgl2ps");
loadLibrary(vtkLibPath, "vtktiff");
loadLibrary(vtkLibPath, "vtklibxml2");
loadLibrary(vtkLibPath, "vtkproj4");
loadLibrary(vtkLibPath, "vtksys");
loadLibrary(vtkLibPath, "vtkfreetype");
loadLibrary(vtkLibPath, "vtkmetaio");
loadLibrary(vtkLibPath, "vtkftgl");
loadLibrary(vtkLibPath, "vtkCommonCore");
loadLibrary(vtkLibPath, "vtkWrappingJava");
loadLibrary(vtkLibPath, "vtkCommonSystem");
loadLibrary(vtkLibPath, "vtkCommonMath");
loadLibrary(vtkLibPath, "vtkCommonMisc");
loadLibrary(vtkLibPath, "vtkCommonTransforms");
if (SystemUtil.isMac())
{
loadLibrary(vtkLibPath, "vtkhdf5.1.8.5");
loadLibrary(vtkLibPath, "vtkhdf5_hl.1.8.5");
}
else
{
loadLibrary(vtkLibPath, "vtkhdf5");
loadLibrary(vtkLibPath, "vtkhdf5_hl");
}
loadLibrary(vtkLibPath, "vtkNetCDF");
loadLibrary(vtkLibPath, "vtkNetCDF_cxx");
loadLibrary(vtkLibPath, "vtkCommonDataModel");
loadLibrary(vtkLibPath, "vtkCommonColor");
loadLibrary(vtkLibPath, "vtkCommonComputationalGeometry");
loadLibrary(vtkLibPath, "vtkCommonExecutionModel");
loadLibrary(vtkLibPath, "vtkexoIIc");
loadLibrary(vtkLibPath, "vtkFiltersVerdict");
loadLibrary(vtkLibPath, "vtkFiltersProgrammable");
loadLibrary(vtkLibPath, "vtkImagingMath");
loadLibrary(vtkLibPath, "vtkIOCore");
loadLibrary(vtkLibPath, "vtkIOEnSight");
loadLibrary(vtkLibPath, "vtkIOVideo");
loadLibrary(vtkLibPath, "vtkIOLegacy");
loadLibrary(vtkLibPath, "vtkIONetCDF");
loadLibrary(vtkLibPath, "vtkIOXMLParser");
loadLibrary(vtkLibPath, "vtkIOXML");
loadLibrary(vtkLibPath, "vtkIOImage");
if (SystemUtil.isMac() || SystemUtil.isUnix())
loadLibrary(vtkLibPath, "vtksqlite");
loadLibrary(vtkLibPath, "vtkIOSQL");
loadLibrary(vtkLibPath, "vtkIOMovie");
loadLibrary(vtkLibPath, "vtkParallelCore");
loadLibrary(vtkLibPath, "vtkImagingCore");
loadLibrary(vtkLibPath, "vtkFiltersCore");
loadLibrary(vtkLibPath, "vtkImagingColor");
loadLibrary(vtkLibPath, "vtkImagingFourier");
loadLibrary(vtkLibPath, "vtkImagingSources");
loadLibrary(vtkLibPath, "vtkImagingHybrid");
loadLibrary(vtkLibPath, "vtkImagingStatistics");
loadLibrary(vtkLibPath, "vtkIOGeometry");
loadLibrary(vtkLibPath, "vtkIOPLY");
loadLibrary(vtkLibPath, "vtkFiltersSelection");
loadLibrary(vtkLibPath, "vtkImagingGeneral");
loadLibrary(vtkLibPath, "vtkImagingStencil");
loadLibrary(vtkLibPath, "vtkImagingMorphological");
loadLibrary(vtkLibPath, "vtkFiltersGeometry");
loadLibrary(vtkLibPath, "vtkFiltersStatistics");
loadLibrary(vtkLibPath, "vtkFiltersImaging");
loadLibrary(vtkLibPath, "vtkIOLSDyna");
loadLibrary(vtkLibPath, "vtkFiltersGeneral");
loadLibrary(vtkLibPath, "vtkFiltersHyperTree");
loadLibrary(vtkLibPath, "vtkFiltersSMP");
loadLibrary(vtkLibPath, "vtkFiltersTexture");
loadLibrary(vtkLibPath, "vtkFiltersAMR");
loadLibrary(vtkLibPath, "vtkFiltersExtraction");
loadLibrary(vtkLibPath, "vtkFiltersSources");
loadLibrary(vtkLibPath, "vtkIOExodus");
loadLibrary(vtkLibPath, "vtkFiltersGeneric");
loadLibrary(vtkLibPath, "vtkFiltersModeling");
loadLibrary(vtkLibPath, "vtkIOAMR");
loadLibrary(vtkLibPath, "vtkFiltersFlowPaths");
loadLibrary(vtkLibPath, "vtkInfovisCore");
loadLibrary(vtkLibPath, "vtkIOInfovis");
loadLibrary(vtkLibPath, "vtkInfovisLayout");
loadLibrary(vtkLibPath, "vtkRenderingCore");
loadLibrary(vtkLibPath, "vtkRenderingLOD");
loadLibrary(vtkLibPath, "vtkRenderingImage");
loadLibrary(vtkLibPath, "vtkRenderingFreeType");
loadLibrary(vtkLibPath, "vtkDomainsChemistry");
loadLibrary(vtkLibPath, "vtkInteractionStyle");
loadLibrary(vtkLibPath, "vtkIOImport");
loadLibrary(vtkLibPath, "vtkRenderingAnnotation");
loadLibrary(vtkLibPath, "vtkRenderingLabel");
loadLibrary(vtkLibPath, "vtkFiltersHybrid");
loadLibrary(vtkLibPath, "vtkFiltersParallel");
loadLibrary(vtkLibPath, "vtkFiltersParallelImaging");
loadLibrary(vtkLibPath, "vtkIOMINC");
loadLibrary(vtkLibPath, "vtkIOParallel");
loadLibrary(vtkLibPath, "vtkRenderingVolume");
loadLibrary(vtkLibPath, "vtkRenderingVolumeAMR");
loadLibrary(vtkLibPath, "vtkInteractionWidgets");
loadLibrary(vtkLibPath, "vtkInteractionImage");
loadLibrary(vtkLibPath, "vtkViewsCore");
loadLibrary(vtkLibPath, "vtkRenderingOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingLIC");
loadLibrary(vtkLibPath, "vtkRenderingVolumeOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingContext2D");
loadLibrary(vtkLibPath, "vtkRenderingGL2PS");
loadLibrary(vtkLibPath, "vtkViewsContext2D");
loadLibrary(vtkLibPath, "vtkGeovisCore");
loadLibrary(vtkLibPath, "vtkIOExport");
loadLibrary(vtkLibPath, "vtkChartsCore");
loadLibrary(vtkLibPath, "vtkViewsInfovis");
loadLibrary(vtkLibPath, "vtkViewsGeovis");
// JAVA wrapper
loadLibrary(vtkLibPath, "vtkCommonCoreJava");
loadLibrary(vtkLibPath, "vtkCommonSystemJava");
loadLibrary(vtkLibPath, "vtkCommonMathJava");
loadLibrary(vtkLibPath, "vtkCommonMiscJava");
loadLibrary(vtkLibPath, "vtkCommonTransformsJava");
loadLibrary(vtkLibPath, "vtkCommonDataModelJava");
loadLibrary(vtkLibPath, "vtkCommonColorJava");
loadLibrary(vtkLibPath, "vtkCommonComputationalGeometryJava");
loadLibrary(vtkLibPath, "vtkCommonExecutionModelJava");
loadLibrary(vtkLibPath, "vtkFiltersVerdictJava");
loadLibrary(vtkLibPath, "vtkFiltersProgrammableJava");
loadLibrary(vtkLibPath, "vtkImagingMathJava");
loadLibrary(vtkLibPath, "vtkIOCoreJava");
loadLibrary(vtkLibPath, "vtkIOEnSightJava");
loadLibrary(vtkLibPath, "vtkIOVideoJava");
loadLibrary(vtkLibPath, "vtkIOLegacyJava");
loadLibrary(vtkLibPath, "vtkIONetCDFJava");
loadLibrary(vtkLibPath, "vtkIOXMLParserJava");
loadLibrary(vtkLibPath, "vtkIOXMLJava");
loadLibrary(vtkLibPath, "vtkIOImageJava");
loadLibrary(vtkLibPath, "vtkIOSQLJava");
loadLibrary(vtkLibPath, "vtkIOMovieJava");
loadLibrary(vtkLibPath, "vtkParallelCoreJava");
loadLibrary(vtkLibPath, "vtkImagingCoreJava");
loadLibrary(vtkLibPath, "vtkFiltersCoreJava");
loadLibrary(vtkLibPath, "vtkImagingColorJava");
loadLibrary(vtkLibPath, "vtkImagingFourierJava");
loadLibrary(vtkLibPath, "vtkImagingSourcesJava");
loadLibrary(vtkLibPath, "vtkImagingHybridJava");
loadLibrary(vtkLibPath, "vtkImagingStatisticsJava");
loadLibrary(vtkLibPath, "vtkIOGeometryJava");
loadLibrary(vtkLibPath, "vtkIOPLYJava");
loadLibrary(vtkLibPath, "vtkFiltersSelectionJava");
loadLibrary(vtkLibPath, "vtkImagingGeneralJava");
loadLibrary(vtkLibPath, "vtkImagingStencilJava");
loadLibrary(vtkLibPath, "vtkImagingMorphologicalJava");
loadLibrary(vtkLibPath, "vtkFiltersGeometryJava");
loadLibrary(vtkLibPath, "vtkFiltersStatisticsJava");
loadLibrary(vtkLibPath, "vtkFiltersImagingJava");
loadLibrary(vtkLibPath, "vtkIOLSDynaJava");
loadLibrary(vtkLibPath, "vtkFiltersGeneralJava");
loadLibrary(vtkLibPath, "vtkFiltersHyperTreeJava");
loadLibrary(vtkLibPath, "vtkFiltersSMPJava");
loadLibrary(vtkLibPath, "vtkFiltersTextureJava");
loadLibrary(vtkLibPath, "vtkFiltersAMRJava");
loadLibrary(vtkLibPath, "vtkFiltersExtractionJava");
loadLibrary(vtkLibPath, "vtkFiltersSourcesJava");
loadLibrary(vtkLibPath, "vtkIOExodusJava");
loadLibrary(vtkLibPath, "vtkFiltersGenericJava");
loadLibrary(vtkLibPath, "vtkFiltersModelingJava");
loadLibrary(vtkLibPath, "vtkIOAMRJava");
loadLibrary(vtkLibPath, "vtkFiltersFlowPathsJava");
loadLibrary(vtkLibPath, "vtkInfovisCoreJava");
loadLibrary(vtkLibPath, "vtkIOInfovisJava");
loadLibrary(vtkLibPath, "vtkInfovisLayoutJava");
loadLibrary(vtkLibPath, "vtkRenderingCoreJava");
loadLibrary(vtkLibPath, "vtkRenderingLODJava");
loadLibrary(vtkLibPath, "vtkRenderingImageJava");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeJava");
loadLibrary(vtkLibPath, "vtkDomainsChemistryJava");
loadLibrary(vtkLibPath, "vtkInteractionStyleJava");
loadLibrary(vtkLibPath, "vtkIOImportJava");
loadLibrary(vtkLibPath, "vtkRenderingAnnotationJava");
loadLibrary(vtkLibPath, "vtkRenderingLabelJava");
loadLibrary(vtkLibPath, "vtkFiltersHybridJava");
loadLibrary(vtkLibPath, "vtkFiltersParallelJava");
loadLibrary(vtkLibPath, "vtkFiltersParallelImagingJava");
loadLibrary(vtkLibPath, "vtkIOMINCJava");
loadLibrary(vtkLibPath, "vtkIOParallelJava");
loadLibrary(vtkLibPath, "vtkRenderingVolumeJava");
loadLibrary(vtkLibPath, "vtkRenderingVolumeAMRJava");
loadLibrary(vtkLibPath, "vtkInteractionWidgetsJava");
loadLibrary(vtkLibPath, "vtkInteractionImageJava");
loadLibrary(vtkLibPath, "vtkViewsCoreJava");
loadLibrary(vtkLibPath, "vtkRenderingOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingLICJava");
loadLibrary(vtkLibPath, "vtkRenderingVolumeOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingContext2DJava");
loadLibrary(vtkLibPath, "vtkRenderingGL2PSJava");
loadLibrary(vtkLibPath, "vtkViewsContext2DJava");
loadLibrary(vtkLibPath, "vtkGeovisCoreJava");
loadLibrary(vtkLibPath, "vtkIOExportJava");
loadLibrary(vtkLibPath, "vtkChartsCoreJava");
loadLibrary(vtkLibPath, "vtkViewsInfovisJava");
loadLibrary(vtkLibPath, "vtkViewsGeovisJava");
// VTK library successfully loaded
vtkLibraryLoaded = true;
}
// redirect vtk error log to file
vtkNativeLibrary.DisableOutputWindow(new File("vtk.log"));
}
catch (Throwable e)
{
System.out.println(e);
}
if (vtkLibraryLoaded)
System.out.println("VTK library successfully loaded...");
else
System.out.println("Cannot load VTK library...");
}
| private static void loadVtkLibrary(String libPath)
{
final String vtkLibPath = libPath + FileUtil.separator + "vtk";
// we load it directly from inner lib path if possible
System.setProperty("vtk.lib.dir", vtkLibPath);
vtkLibraryLoaded = false;
try
{
// if (SystemUtil.isUnix())
// {
// vtkNativeLibrary.LoadAllNativeLibraries();
//
// // assume VTK loaded if at least 1 native library is loaded
// for (vtkNativeLibrary lib : vtkNativeLibrary.values())
// if (lib.IsLoaded())
// vtkLibraryLoaded = true;
// }
// else
{
loadLibrary(vtkLibPath, "vtkalglib");
loadLibrary(vtkLibPath, "vtkexpat");
loadLibrary(vtkLibPath, "vtkDICOMParser");
loadLibrary(vtkLibPath, "vtkjpeg");
loadLibrary(vtkLibPath, "vtkjsoncpp");
loadLibrary(vtkLibPath, "vtkzlib");
loadLibrary(vtkLibPath, "vtkoggtheora", false);
loadLibrary(vtkLibPath, "vtkverdict");
loadLibrary(vtkLibPath, "vtkpng");
loadLibrary(vtkLibPath, "vtkgl2ps");
loadLibrary(vtkLibPath, "vtktiff");
loadLibrary(vtkLibPath, "vtklibxml2");
loadLibrary(vtkLibPath, "vtkproj4");
loadLibrary(vtkLibPath, "vtksys");
loadLibrary(vtkLibPath, "vtkfreetype");
loadLibrary(vtkLibPath, "vtkmetaio");
loadLibrary(vtkLibPath, "vtkftgl");
loadLibrary(vtkLibPath, "vtkCommonCore");
loadLibrary(vtkLibPath, "vtkWrappingJava");
loadLibrary(vtkLibPath, "vtkCommonSystem");
loadLibrary(vtkLibPath, "vtkCommonMath");
loadLibrary(vtkLibPath, "vtkCommonMisc");
loadLibrary(vtkLibPath, "vtkCommonTransforms");
if (SystemUtil.isMac())
{
loadLibrary(vtkLibPath, "vtkhdf5.1.8.5");
loadLibrary(vtkLibPath, "vtkhdf5_hl.1.8.5");
}
else
{
loadLibrary(vtkLibPath, "vtkhdf5");
loadLibrary(vtkLibPath, "vtkhdf5_hl");
}
loadLibrary(vtkLibPath, "vtkNetCDF");
loadLibrary(vtkLibPath, "vtkNetCDF_cxx");
loadLibrary(vtkLibPath, "vtkCommonDataModel");
loadLibrary(vtkLibPath, "vtkCommonColor");
loadLibrary(vtkLibPath, "vtkCommonComputationalGeometry");
loadLibrary(vtkLibPath, "vtkCommonExecutionModel");
loadLibrary(vtkLibPath, "vtkexoIIc");
loadLibrary(vtkLibPath, "vtkFiltersVerdict");
loadLibrary(vtkLibPath, "vtkFiltersProgrammable");
loadLibrary(vtkLibPath, "vtkImagingMath");
loadLibrary(vtkLibPath, "vtkIOCore");
loadLibrary(vtkLibPath, "vtkIOEnSight");
loadLibrary(vtkLibPath, "vtkIOVideo");
loadLibrary(vtkLibPath, "vtkIOLegacy");
loadLibrary(vtkLibPath, "vtkIONetCDF");
loadLibrary(vtkLibPath, "vtkIOXMLParser");
loadLibrary(vtkLibPath, "vtkIOXML");
loadLibrary(vtkLibPath, "vtkIOImage");
if (SystemUtil.isMac() || SystemUtil.isUnix())
loadLibrary(vtkLibPath, "vtksqlite");
loadLibrary(vtkLibPath, "vtkIOSQL");
loadLibrary(vtkLibPath, "vtkIOMovie");
loadLibrary(vtkLibPath, "vtkParallelCore");
loadLibrary(vtkLibPath, "vtkImagingCore");
loadLibrary(vtkLibPath, "vtkFiltersCore");
loadLibrary(vtkLibPath, "vtkImagingColor");
loadLibrary(vtkLibPath, "vtkImagingFourier");
loadLibrary(vtkLibPath, "vtkImagingSources");
loadLibrary(vtkLibPath, "vtkImagingHybrid");
loadLibrary(vtkLibPath, "vtkImagingStatistics");
loadLibrary(vtkLibPath, "vtkIOGeometry");
loadLibrary(vtkLibPath, "vtkIOPLY");
loadLibrary(vtkLibPath, "vtkFiltersSelection");
loadLibrary(vtkLibPath, "vtkImagingGeneral");
loadLibrary(vtkLibPath, "vtkImagingStencil");
loadLibrary(vtkLibPath, "vtkImagingMorphological");
loadLibrary(vtkLibPath, "vtkFiltersGeometry");
loadLibrary(vtkLibPath, "vtkFiltersStatistics");
loadLibrary(vtkLibPath, "vtkFiltersImaging");
loadLibrary(vtkLibPath, "vtkIOLSDyna");
loadLibrary(vtkLibPath, "vtkFiltersGeneral");
loadLibrary(vtkLibPath, "vtkFiltersHyperTree");
loadLibrary(vtkLibPath, "vtkFiltersSMP");
loadLibrary(vtkLibPath, "vtkFiltersTexture");
loadLibrary(vtkLibPath, "vtkFiltersAMR");
loadLibrary(vtkLibPath, "vtkFiltersExtraction");
loadLibrary(vtkLibPath, "vtkFiltersSources");
loadLibrary(vtkLibPath, "vtkIOExodus");
loadLibrary(vtkLibPath, "vtkFiltersGeneric");
loadLibrary(vtkLibPath, "vtkFiltersModeling");
loadLibrary(vtkLibPath, "vtkIOAMR");
loadLibrary(vtkLibPath, "vtkFiltersFlowPaths");
loadLibrary(vtkLibPath, "vtkInfovisCore");
loadLibrary(vtkLibPath, "vtkIOInfovis");
loadLibrary(vtkLibPath, "vtkInfovisLayout");
loadLibrary(vtkLibPath, "vtkRenderingCore");
loadLibrary(vtkLibPath, "vtkRenderingLOD");
loadLibrary(vtkLibPath, "vtkRenderingImage");
loadLibrary(vtkLibPath, "vtkRenderingFreeType");
loadLibrary(vtkLibPath, "vtkDomainsChemistry");
loadLibrary(vtkLibPath, "vtkInteractionStyle");
loadLibrary(vtkLibPath, "vtkIOImport");
loadLibrary(vtkLibPath, "vtkRenderingAnnotation");
loadLibrary(vtkLibPath, "vtkRenderingLabel");
loadLibrary(vtkLibPath, "vtkFiltersHybrid");
loadLibrary(vtkLibPath, "vtkFiltersParallel");
loadLibrary(vtkLibPath, "vtkFiltersParallelImaging");
loadLibrary(vtkLibPath, "vtkIOMINC");
loadLibrary(vtkLibPath, "vtkIOParallel");
loadLibrary(vtkLibPath, "vtkRenderingVolume");
loadLibrary(vtkLibPath, "vtkRenderingVolumeAMR", false);
loadLibrary(vtkLibPath, "vtkInteractionWidgets");
loadLibrary(vtkLibPath, "vtkInteractionImage");
loadLibrary(vtkLibPath, "vtkViewsCore");
loadLibrary(vtkLibPath, "vtkRenderingOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingLIC");
loadLibrary(vtkLibPath, "vtkRenderingVolumeOpenGL");
loadLibrary(vtkLibPath, "vtkRenderingContext2D");
loadLibrary(vtkLibPath, "vtkRenderingContextOpenGL", false);
loadLibrary(vtkLibPath, "vtkRenderingGL2PS");
loadLibrary(vtkLibPath, "vtkViewsContext2D");
loadLibrary(vtkLibPath, "vtkGeovisCore");
loadLibrary(vtkLibPath, "vtkIOExport");
loadLibrary(vtkLibPath, "vtkChartsCore");
loadLibrary(vtkLibPath, "vtkViewsInfovis");
loadLibrary(vtkLibPath, "vtkViewsGeovis", false);
// JAVA wrapper
loadLibrary(vtkLibPath, "vtkCommonCoreJava");
loadLibrary(vtkLibPath, "vtkCommonSystemJava");
loadLibrary(vtkLibPath, "vtkCommonMathJava");
loadLibrary(vtkLibPath, "vtkCommonMiscJava");
loadLibrary(vtkLibPath, "vtkCommonTransformsJava");
loadLibrary(vtkLibPath, "vtkCommonDataModelJava");
loadLibrary(vtkLibPath, "vtkCommonColorJava");
loadLibrary(vtkLibPath, "vtkCommonComputationalGeometryJava");
loadLibrary(vtkLibPath, "vtkCommonExecutionModelJava");
loadLibrary(vtkLibPath, "vtkFiltersVerdictJava");
loadLibrary(vtkLibPath, "vtkFiltersProgrammableJava");
loadLibrary(vtkLibPath, "vtkImagingMathJava");
loadLibrary(vtkLibPath, "vtkIOCoreJava");
loadLibrary(vtkLibPath, "vtkIOEnSightJava");
loadLibrary(vtkLibPath, "vtkIOVideoJava");
loadLibrary(vtkLibPath, "vtkIOLegacyJava");
loadLibrary(vtkLibPath, "vtkIONetCDFJava");
loadLibrary(vtkLibPath, "vtkIOXMLParserJava");
loadLibrary(vtkLibPath, "vtkIOXMLJava");
loadLibrary(vtkLibPath, "vtkIOImageJava");
loadLibrary(vtkLibPath, "vtkIOSQLJava");
loadLibrary(vtkLibPath, "vtkIOMovieJava");
loadLibrary(vtkLibPath, "vtkParallelCoreJava");
loadLibrary(vtkLibPath, "vtkImagingCoreJava");
loadLibrary(vtkLibPath, "vtkFiltersCoreJava");
loadLibrary(vtkLibPath, "vtkImagingColorJava");
loadLibrary(vtkLibPath, "vtkImagingFourierJava");
loadLibrary(vtkLibPath, "vtkImagingSourcesJava");
loadLibrary(vtkLibPath, "vtkImagingHybridJava");
loadLibrary(vtkLibPath, "vtkImagingStatisticsJava");
loadLibrary(vtkLibPath, "vtkIOGeometryJava");
loadLibrary(vtkLibPath, "vtkIOPLYJava");
loadLibrary(vtkLibPath, "vtkFiltersSelectionJava");
loadLibrary(vtkLibPath, "vtkImagingGeneralJava");
loadLibrary(vtkLibPath, "vtkImagingStencilJava");
loadLibrary(vtkLibPath, "vtkImagingMorphologicalJava");
loadLibrary(vtkLibPath, "vtkFiltersGeometryJava");
loadLibrary(vtkLibPath, "vtkFiltersStatisticsJava");
loadLibrary(vtkLibPath, "vtkFiltersImagingJava");
loadLibrary(vtkLibPath, "vtkIOLSDynaJava");
loadLibrary(vtkLibPath, "vtkFiltersGeneralJava");
loadLibrary(vtkLibPath, "vtkFiltersHyperTreeJava");
loadLibrary(vtkLibPath, "vtkFiltersSMPJava");
loadLibrary(vtkLibPath, "vtkFiltersTextureJava");
loadLibrary(vtkLibPath, "vtkFiltersAMRJava");
loadLibrary(vtkLibPath, "vtkFiltersExtractionJava");
loadLibrary(vtkLibPath, "vtkFiltersSourcesJava");
loadLibrary(vtkLibPath, "vtkIOExodusJava");
loadLibrary(vtkLibPath, "vtkFiltersGenericJava");
loadLibrary(vtkLibPath, "vtkFiltersModelingJava");
loadLibrary(vtkLibPath, "vtkIOAMRJava");
loadLibrary(vtkLibPath, "vtkFiltersFlowPathsJava");
loadLibrary(vtkLibPath, "vtkInfovisCoreJava");
loadLibrary(vtkLibPath, "vtkIOInfovisJava");
loadLibrary(vtkLibPath, "vtkInfovisLayoutJava");
loadLibrary(vtkLibPath, "vtkRenderingCoreJava");
loadLibrary(vtkLibPath, "vtkRenderingLODJava");
loadLibrary(vtkLibPath, "vtkRenderingImageJava");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeJava");
loadLibrary(vtkLibPath, "vtkDomainsChemistryJava");
loadLibrary(vtkLibPath, "vtkInteractionStyleJava");
loadLibrary(vtkLibPath, "vtkIOImportJava");
loadLibrary(vtkLibPath, "vtkRenderingAnnotationJava");
loadLibrary(vtkLibPath, "vtkRenderingLabelJava");
loadLibrary(vtkLibPath, "vtkFiltersHybridJava");
loadLibrary(vtkLibPath, "vtkFiltersParallelJava");
loadLibrary(vtkLibPath, "vtkFiltersParallelImagingJava");
loadLibrary(vtkLibPath, "vtkIOMINCJava");
loadLibrary(vtkLibPath, "vtkIOParallelJava");
loadLibrary(vtkLibPath, "vtkRenderingVolumeJava");
loadLibrary(vtkLibPath, "vtkRenderingVolumeAMRJava", false);
loadLibrary(vtkLibPath, "vtkInteractionWidgetsJava");
loadLibrary(vtkLibPath, "vtkInteractionImageJava");
loadLibrary(vtkLibPath, "vtkViewsCoreJava");
loadLibrary(vtkLibPath, "vtkRenderingOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingFreeTypeOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingLICJava");
loadLibrary(vtkLibPath, "vtkRenderingVolumeOpenGLJava");
loadLibrary(vtkLibPath, "vtkRenderingContext2DJava");
loadLibrary(vtkLibPath, "vtkRenderingContextOpenGLJava", false);
loadLibrary(vtkLibPath, "vtkRenderingGL2PSJava");
loadLibrary(vtkLibPath, "vtkViewsContext2DJava");
loadLibrary(vtkLibPath, "vtkGeovisCoreJava");
loadLibrary(vtkLibPath, "vtkIOExportJava");
loadLibrary(vtkLibPath, "vtkChartsCoreJava");
loadLibrary(vtkLibPath, "vtkViewsInfovisJava");
loadLibrary(vtkLibPath, "vtkViewsGeovisJava", false);
// VTK library successfully loaded
vtkLibraryLoaded = true;
}
// redirect vtk error log to file
vtkNativeLibrary.DisableOutputWindow(new File("vtk.log"));
}
catch (Throwable e)
{
System.out.println(e);
}
if (vtkLibraryLoaded)
System.out.println("VTK library successfully loaded...");
else
System.out.println("Cannot load VTK library...");
}
|
diff --git a/Caustk/src-core/com/teotigraphix/caustk/node/effect/EffectsChannel.java b/Caustk/src-core/com/teotigraphix/caustk/node/effect/EffectsChannel.java
index b0c08ec2..293567ce 100644
--- a/Caustk/src-core/com/teotigraphix/caustk/node/effect/EffectsChannel.java
+++ b/Caustk/src-core/com/teotigraphix/caustk/node/effect/EffectsChannel.java
@@ -1,232 +1,236 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2013 Michael Schmalle - Teoti Graphix, LLC
//
// 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
//
// Author: Michael Schmalle, Principal Architect
// mschmalle at teotigraphix dot com
////////////////////////////////////////////////////////////////////////////////
package com.teotigraphix.caustk.node.effect;
import java.util.HashMap;
import com.esotericsoftware.kryo.serializers.TaggedFieldSerializer.Tag;
import com.teotigraphix.caustk.core.CausticException;
import com.teotigraphix.caustk.core.osc.EffectsRackMessage;
import com.teotigraphix.caustk.core.osc.EffectsRackMessage.EffectsRackControl;
import com.teotigraphix.caustk.core.osc.IOSCControl;
import com.teotigraphix.caustk.node.NodeBase;
import com.teotigraphix.caustk.node.NodeBaseEvents.NodeEvent;
import com.teotigraphix.caustk.node.machine.MachineComponent;
import com.teotigraphix.caustk.node.machine.MachineNode;
import com.teotigraphix.caustk.node.master.MasterNode;
/**
* The effect channel node, currently holds 2 slots.
*
* @author Michael Schmalle
* @since 1.0
* @see MachineNode#getEffects()
*/
public class EffectsChannel extends MachineComponent {
// If machineIndex is -1, this is the master effect channel
private static final int NUM_SLOTS = 2;
//--------------------------------------------------------------------------
// Serialized API
//--------------------------------------------------------------------------
@Tag(100)
private HashMap<Integer, EffectNode> slots = new HashMap<Integer, EffectNode>();
@Tag(101)
private MasterNode masterNode;
//--------------------------------------------------------------------------
// Public API :: Properties
//--------------------------------------------------------------------------
//----------------------------------
// slots
//----------------------------------
/**
* Returns whether the effects channel contains en {@link EffectNode} at the
* specified slot.
*
* @param slot The slot index (0,1).
*/
public boolean containsEffect(int slot) {
return slots.containsKey(slot);
}
/**
* Returns an {@link EffectNode} at the specified slot or <code>null</code>.
*
* @param slot The slot index (0,1).
*/
public EffectNode getEfffect(int slot) {
return slots.get(slot);
}
//--------------------------------------------------------------------------
// Constructors
//--------------------------------------------------------------------------
/**
* Serialization
*/
public EffectsChannel() {
}
public EffectsChannel(MachineNode machineNode) {
super(machineNode);
}
public EffectsChannel(MasterNode masterNode) {
super(null);
this.masterNode = masterNode;
}
//--------------------------------------------------------------------------
// Public API :: Methods
//--------------------------------------------------------------------------
/**
* Creates a {@link EffectNode} in the {@link #getEffects()} channel and
* returns the new instance.
*
* @param slot The effect slot (0,1).
* @param effectType The {@link EffectType}.
* @return The new {@link EffectNode}.
* @throws CausticException Effect channel contains effect at slot
* @see EffectsChannelNodeCreateEvent
*/
@SuppressWarnings("unchecked")
public <T extends EffectNode> T createEffect(int slot, EffectType effectType)
throws CausticException {
if (containsEffect(slot))
throw new CausticException("Effect channel contains effect at slot: " + slot);
EffectNode effectNode = getFactory().createEffect(getMachineNode(), slot, effectType);
EffectsRackMessage.CREATE.send(getRack(), effectNode.getMachineIndex(),
effectNode.getSlot(), effectNode.getType().getValue());
set(effectNode);
post(new EffectsChannelNodeCreateEvent(this, EffectsRackControl.Create, effectNode));
return (T)effectNode;
}
public void updateEffects(EffectNode effect1, EffectNode effect2) {
if (effect1 != null) {
slots.put(0, effect1);
EffectsRackMessage.CREATE.send(getRack(), effect1.getMachineIndex(), effect1.getSlot(),
effect1.getType().getValue());
effect1.update();
}
if (effect2 != null) {
slots.put(1, effect2);
EffectsRackMessage.CREATE.send(getRack(), effect2.getMachineIndex(), effect2.getSlot(),
effect2.getType().getValue());
effect2.update();
}
}
//--------------------------------------------------------------------------
// Overridden Protected :: Methods
//--------------------------------------------------------------------------
@Override
protected void createComponents() {
}
@Override
protected void destroyComponents() {
}
@Override
protected void updateComponents() {
for (int i = 0; i < NUM_SLOTS; i++) {
if (containsEffect(i)) {
EffectNode effectNode = getEfffect(i);
EffectsRackMessage.CREATE.send(getRack(), effectNode.getMachineIndex(),
effectNode.getSlot(), effectNode.getType().getValue());
effectNode.update();
}
}
}
@Override
protected void restoreComponents() {
- for (int i = 0; i < NUM_SLOTS; i++) {
- EffectType type = EffectType.fromInt((int)EffectsRackMessage.TYPE.send(getRack(),
- getMachineIndex(), i));
- if (type != null) {
- EffectNode effect;
- try {
- effect = createEffect(i, type);
- effect.restore();
- } catch (CausticException e) {
- getLogger().err("EffectsChannelNode", e.getMessage());
+ if (getMachineNode() != null) {
+ for (int i = 0; i < NUM_SLOTS; i++) {
+ EffectType type = EffectType.fromInt((int)EffectsRackMessage.TYPE.send(getRack(),
+ getMachineIndex(), i));
+ if (type != null) {
+ EffectNode effect;
+ try {
+ effect = createEffect(i, type);
+ effect.restore();
+ } catch (CausticException e) {
+ getLogger().err("EffectsChannelNode", e.getMessage());
+ }
}
}
+ } else if (masterNode != null) {
+ // XXX Implement MasterNode effects restore
}
}
//--------------------------------------------------------------------------
// Private :: Methods
//--------------------------------------------------------------------------
private void set(EffectNode effectNode) {
slots.put(effectNode.getSlot(), effectNode);
}
//--------------------------------------------------------------------------
// Events
//--------------------------------------------------------------------------
/**
* Base event for the {@link EffectsChannel}.
*
* @author Michael Schmalle
* @since 1.0
*/
public static class EffectsChannelNodeEvent extends NodeEvent {
public EffectsChannelNodeEvent(NodeBase target, IOSCControl control) {
super(target, control);
}
}
/**
* @author Michael Schmalle
* @since 1.0
* @see EffectsChannel#createEffect(int, EffectType)
*/
public static class EffectsChannelNodeCreateEvent extends NodeEvent {
private EffectNode effectNode;
public EffectNode getEffectNode() {
return effectNode;
}
public EffectsChannelNodeCreateEvent(NodeBase target, IOSCControl control,
EffectNode effectNode) {
super(target, control);
this.effectNode = effectNode;
}
}
}
| false | true | protected void restoreComponents() {
for (int i = 0; i < NUM_SLOTS; i++) {
EffectType type = EffectType.fromInt((int)EffectsRackMessage.TYPE.send(getRack(),
getMachineIndex(), i));
if (type != null) {
EffectNode effect;
try {
effect = createEffect(i, type);
effect.restore();
} catch (CausticException e) {
getLogger().err("EffectsChannelNode", e.getMessage());
}
}
}
}
| protected void restoreComponents() {
if (getMachineNode() != null) {
for (int i = 0; i < NUM_SLOTS; i++) {
EffectType type = EffectType.fromInt((int)EffectsRackMessage.TYPE.send(getRack(),
getMachineIndex(), i));
if (type != null) {
EffectNode effect;
try {
effect = createEffect(i, type);
effect.restore();
} catch (CausticException e) {
getLogger().err("EffectsChannelNode", e.getMessage());
}
}
}
} else if (masterNode != null) {
// XXX Implement MasterNode effects restore
}
}
|
diff --git a/org.eclipse.mylyn.trac.core/src/org/eclipse/mylyn/internal/trac/core/TracTaskDataHandler.java b/org.eclipse.mylyn.trac.core/src/org/eclipse/mylyn/internal/trac/core/TracTaskDataHandler.java
index 4c118883c..4b3108290 100644
--- a/org.eclipse.mylyn.trac.core/src/org/eclipse/mylyn/internal/trac/core/TracTaskDataHandler.java
+++ b/org.eclipse.mylyn.trac.core/src/org/eclipse/mylyn/internal/trac/core/TracTaskDataHandler.java
@@ -1,608 +1,612 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers 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
*******************************************************************************/
package org.eclipse.mylyn.internal.trac.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.mylyn.commons.net.Policy;
import org.eclipse.mylyn.internal.trac.core.client.ITracClient;
import org.eclipse.mylyn.internal.trac.core.client.InvalidTicketException;
import org.eclipse.mylyn.internal.trac.core.model.TracAttachment;
import org.eclipse.mylyn.internal.trac.core.model.TracComment;
import org.eclipse.mylyn.internal.trac.core.model.TracTicket;
import org.eclipse.mylyn.internal.trac.core.model.TracTicketField;
import org.eclipse.mylyn.internal.trac.core.model.TracTicket.Key;
import org.eclipse.mylyn.internal.trac.core.util.TracUtil;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskMapping;
import org.eclipse.mylyn.tasks.core.RepositoryResponse;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.RepositoryResponse.ResponseKind;
import org.eclipse.mylyn.tasks.core.data.AbstractTaskDataHandler;
import org.eclipse.mylyn.tasks.core.data.TaskAttachmentMapper;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
import org.eclipse.mylyn.tasks.core.data.TaskAttributeMetaData;
import org.eclipse.mylyn.tasks.core.data.TaskCommentMapper;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskMapper;
import org.eclipse.mylyn.tasks.core.data.TaskOperation;
/**
* @author Steffen Pingel
*/
public class TracTaskDataHandler extends AbstractTaskDataHandler {
private static final String TASK_DATA_VERSION = "2";
public static final String ATTRIBUTE_BLOCKED_BY = "blockedby";
public static final String ATTRIBUTE_BLOCKING = "blocking";
private static final String CC_DELIMETER = ", ";
private static final String TRAC_KEY = "tracKey";
private final TracRepositoryConnector connector;
public TracTaskDataHandler(TracRepositoryConnector connector) {
this.connector = connector;
}
public TaskData getTaskData(TaskRepository repository, String taskId, IProgressMonitor monitor)
throws CoreException {
monitor = Policy.monitorFor(monitor);
try {
monitor.beginTask("Task Download", IProgressMonitor.UNKNOWN);
return downloadTaskData(repository, TracRepositoryConnector.getTicketId(taskId), monitor);
} finally {
monitor.done();
}
}
public TaskData downloadTaskData(TaskRepository repository, int taskId, IProgressMonitor monitor)
throws CoreException {
ITracClient client = connector.getClientManager().getTracClient(repository);
TracTicket ticket;
try {
client.updateAttributes(monitor, false);
ticket = client.getTicket(taskId, monitor);
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
// TODO catch TracException
throw new CoreException(TracCorePlugin.toStatus(e, repository));
}
return createTaskDataFromTicket(client, repository, ticket, monitor);
}
public TaskData createTaskDataFromTicket(ITracClient client, TaskRepository repository, TracTicket ticket,
IProgressMonitor monitor) throws CoreException {
TaskData taskData = new TaskData(getAttributeMapper(repository), TracCorePlugin.CONNECTOR_KIND,
repository.getRepositoryUrl(), ticket.getId() + "");
taskData.setVersion(TASK_DATA_VERSION);
try {
if (!TracRepositoryConnector.hasRichEditor(repository)) {
createDefaultAttributes(taskData, client, true);
Set<TaskAttribute> changedAttributes = updateTaskData(repository, taskData, ticket);
// remove attributes that were not set, i.e. were not received from the server
List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(taskData.getRoot()
.getAttributes()
.values());
for (TaskAttribute attribute : attributes) {
if (!changedAttributes.contains(attribute) && !TracAttributeMapper.isInternalAttribute(attribute)) {
taskData.getRoot().removeAttribute(attribute.getId());
}
}
taskData.setPartial(true);
} else {
createDefaultAttributes(taskData, client, true);
updateTaskData(repository, taskData, ticket);
}
return taskData;
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
// TODO catch TracException
throw new CoreException(TracCorePlugin.toStatus(e, repository));
}
}
public static Set<TaskAttribute> updateTaskData(TaskRepository repository, TaskData data, TracTicket ticket) {
Set<TaskAttribute> changedAttributes = new HashSet<TaskAttribute>();
Date lastChanged = ticket.getLastChanged();
if (lastChanged != null) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(TracAttribute.CHANGE_TIME.getTracKey());
taskAttribute.setValue(TracUtil.toTracTime(lastChanged) + "");
changedAttributes.add(taskAttribute);
}
if (ticket.getCreated() != null) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(TracAttribute.TIME.getTracKey());
taskAttribute.setValue(TracUtil.toTracTime(ticket.getCreated()) + "");
changedAttributes.add(taskAttribute);
}
Map<String, String> valueByKey = ticket.getValues();
for (String key : valueByKey.keySet()) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(key);
- if (Key.CC.getKey().equals(key)) {
- StringTokenizer t = new StringTokenizer(valueByKey.get(key), CC_DELIMETER);
- while (t.hasMoreTokens()) {
- taskAttribute.addValue(t.nextToken());
+ if (taskAttribute != null) {
+ if (Key.CC.getKey().equals(key)) {
+ StringTokenizer t = new StringTokenizer(valueByKey.get(key), CC_DELIMETER);
+ while (t.hasMoreTokens()) {
+ taskAttribute.addValue(t.nextToken());
+ }
+ } else {
+ taskAttribute.setValue(valueByKey.get(key));
}
+ changedAttributes.add(taskAttribute);
} else {
- taskAttribute.setValue(valueByKey.get(key));
+ // TODO log missing attribute?
}
- changedAttributes.add(taskAttribute);
}
TracComment[] comments = ticket.getComments();
if (comments != null) {
int count = 1;
for (int i = 0; i < comments.length; i++) {
if (!"comment".equals(comments[i].getField()) || "".equals(comments[i].getNewValue())) {
continue;
}
TaskCommentMapper mapper = new TaskCommentMapper();
mapper.setAuthor(repository.createPerson(comments[i].getAuthor()));
mapper.setCreationDate(comments[i].getCreated());
mapper.setText(comments[i].getNewValue());
// TODO mapper.setUrl();
mapper.setNumber(count);
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_COMMENT + count);
mapper.applyTo(attribute);
count++;
}
}
TracAttachment[] attachments = ticket.getAttachments();
if (attachments != null) {
for (int i = 0; i < attachments.length; i++) {
TaskAttachmentMapper mapper = new TaskAttachmentMapper();
mapper.setAuthor(repository.createPerson(attachments[i].getAuthor()));
mapper.setDescription(attachments[i].getDescription());
mapper.setFileName(attachments[i].getFilename());
mapper.setLength((long) attachments[i].getSize());
if (attachments[i].getCreated() != null) {
if (lastChanged == null || attachments[i].getCreated().after(lastChanged)) {
lastChanged = attachments[i].getCreated();
}
mapper.setCreationDate(attachments[i].getCreated());
}
mapper.setUrl(repository.getRepositoryUrl() + ITracClient.TICKET_ATTACHMENT_URL + ticket.getId() + "/"
+ TracUtil.encode(attachments[i].getFilename()));
mapper.setAttachmentId(i + "");
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_ATTACHMENT + (i + 1));
mapper.applyTo(attribute);
}
}
String[] actions = ticket.getActions();
if (actions != null) {
// add operations in a defined order
List<String> actionList = new ArrayList<String>(Arrays.asList(actions));
addOperation(repository, data, ticket, actionList, "leave");
addOperation(repository, data, ticket, actionList, "accept");
addOperation(repository, data, ticket, actionList, "resolve");
addOperation(repository, data, ticket, actionList, "reopen");
}
return changedAttributes;
}
private static void addOperation(TaskRepository repository, TaskData data, TracTicket ticket, List<String> actions,
String action) {
if (!actions.remove(action)) {
return;
}
String label = null;
if ("leave".equals(action)) {
// TODO provide better label for Leave action
//label = "Leave as " + data.getStatus() + " " + data.getResolution();
label = "Leave";
} else if ("accept".equals(action)) {
label = "Accept";
} else if ("resolve".equals(action)) {
label = "Resolve as";
} else if ("reopen".equals(action)) {
label = "Reopen";
}
if (label != null) {
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_OPERATION + action);
TaskOperation.applyTo(attribute, action, label);
if ("resolve".equals(action)) {
attribute.getMetaData().putValue(TaskAttribute.META_ASSOCIATED_ATTRIBUTE_ID,
TracAttribute.RESOLUTION.getTracKey());
}
}
}
public static void createDefaultAttributes(TaskData data, ITracClient client, boolean existingTask) {
data.setVersion(TASK_DATA_VERSION);
createAttribute(data, TracAttribute.SUMMARY);
createAttribute(data, TracAttribute.DESCRIPTION);
if (existingTask) {
createAttribute(data, TracAttribute.TIME);
createAttribute(data, TracAttribute.CHANGE_TIME);
createAttribute(data, TracAttribute.STATUS, client.getTicketStatus());
createAttribute(data, TracAttribute.RESOLUTION, client.getTicketResolutions());
}
createAttribute(data, TracAttribute.COMPONENT, client.getComponents());
createAttribute(data, TracAttribute.VERSION, client.getVersions(), true);
createAttribute(data, TracAttribute.PRIORITY, client.getPriorities());
createAttribute(data, TracAttribute.SEVERITY, client.getSeverities());
createAttribute(data, TracAttribute.MILESTONE, client.getMilestones(), true);
createAttribute(data, TracAttribute.TYPE, client.getTicketTypes());
createAttribute(data, TracAttribute.KEYWORDS);
TracTicketField[] fields = client.getTicketFields();
if (fields != null) {
for (TracTicketField field : fields) {
if (field.isCustom()) {
createAttribute(data, field);
}
}
}
// people
createAttribute(data, TracAttribute.OWNER);
if (existingTask) {
createAttribute(data, TracAttribute.REPORTER);
}
createAttribute(data, TracAttribute.CC);
if (existingTask) {
data.getRoot().createAttribute(TracAttributeMapper.NEW_CC).getMetaData().setType(
TaskAttribute.TYPE_SHORT_TEXT).setReadOnly(false);
data.getRoot().createAttribute(TracAttributeMapper.REMOVE_CC);
data.getRoot().createAttribute(TaskAttribute.COMMENT_NEW).getMetaData().setType(
TaskAttribute.TYPE_LONG_RICH_TEXT).setReadOnly(false);
}
// operations
data.getRoot().createAttribute(TaskAttribute.OPERATION).getMetaData().setType(TaskAttribute.TYPE_OPERATION);
}
private static void createAttribute(TaskData data, TracTicketField field) {
TaskAttribute attr = data.getRoot().createAttribute(field.getName());
TaskAttributeMetaData metaData = attr.getMetaData();
metaData.defaults();
metaData.setLabel(field.getLabel());
metaData.setKind(TaskAttribute.KIND_DEFAULT);
metaData.setReadOnly(false);
metaData.putValue(TRAC_KEY, field.getName());
if (field.getType() == TracTicketField.Type.CHECKBOX) {
// attr.addOption("True", "1");
// attr.addOption("False", "0");
metaData.setType(TaskAttribute.TYPE_BOOLEAN);
attr.putOption("1", "1");
attr.putOption("0", "0");
if (field.getDefaultValue() != null) {
attr.setValue(field.getDefaultValue());
}
} else if (field.getType() == TracTicketField.Type.SELECT || field.getType() == TracTicketField.Type.RADIO) {
metaData.setType(TaskAttribute.TYPE_SINGLE_SELECT);
String[] values = field.getOptions();
if (values != null && values.length > 0) {
if (field.isOptional()) {
attr.putOption("", "");
}
for (String value : values) {
attr.putOption(value, value);
}
if (field.getDefaultValue() != null) {
try {
int index = Integer.parseInt(field.getDefaultValue());
if (index > 0 && index < values.length) {
attr.setValue(values[index]);
}
} catch (NumberFormatException e) {
for (String value : values) {
if (field.getDefaultValue().equals(value.toString())) {
attr.setValue(value);
break;
}
}
}
}
}
} else if (field.getType() == TracTicketField.Type.TEXTAREA) {
metaData.setType(TaskAttribute.TYPE_LONG_TEXT);
if (field.getDefaultValue() != null) {
attr.setValue(field.getDefaultValue());
}
} else {
metaData.setType(TaskAttribute.TYPE_SHORT_TEXT);
if (field.getDefaultValue() != null) {
attr.setValue(field.getDefaultValue());
}
}
}
private static TaskAttribute createAttribute(TaskData data, TracAttribute tracAttribute) {
TaskAttribute attr = data.getRoot().createAttribute(tracAttribute.getTracKey());
TaskAttributeMetaData metaData = attr.getMetaData();
metaData.setType(tracAttribute.getType());
metaData.setKind(tracAttribute.getKind());
metaData.setLabel(tracAttribute.toString());
metaData.setReadOnly(tracAttribute.isReadOnly());
metaData.putValue(TRAC_KEY, tracAttribute.getTracKey());
return attr;
}
private static TaskAttribute createAttribute(TaskData data, TracAttribute tracAttribute, Object[] values,
boolean allowEmtpy) {
TaskAttribute attr = createAttribute(data, tracAttribute);
if (values != null && values.length > 0) {
if (allowEmtpy) {
attr.putOption("", "");
}
for (Object value : values) {
attr.putOption(value.toString(), value.toString());
}
} else {
attr.getMetaData().setReadOnly(true);
}
return attr;
}
private static TaskAttribute createAttribute(TaskData data, TracAttribute tracAttribute, Object[] values) {
return createAttribute(data, tracAttribute, values, false);
}
@Override
public RepositoryResponse postTaskData(TaskRepository repository, TaskData taskData,
Set<TaskAttribute> oldAttributes, IProgressMonitor monitor) throws CoreException {
try {
TracTicket ticket = TracTaskDataHandler.getTracTicket(repository, taskData);
ITracClient server = connector.getClientManager().getTracClient(repository);
if (taskData.isNew()) {
int id = server.createTicket(ticket, monitor);
return new RepositoryResponse(ResponseKind.TASK_CREATED, id + "");
} else {
String newComment = "";
TaskAttribute newCommentAttribute = taskData.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW);
if (newCommentAttribute != null) {
newComment = newCommentAttribute.getValue();
}
server.updateTicket(ticket, newComment, monitor);
return new RepositoryResponse(ResponseKind.TASK_UPDATED, ticket.getId() + "");
}
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
// TODO catch TracException
throw new CoreException(TracCorePlugin.toStatus(e, repository));
}
}
@Override
public boolean initializeTaskData(TaskRepository repository, TaskData data, ITaskMapping initializationData,
IProgressMonitor monitor) throws CoreException {
try {
ITracClient client = connector.getClientManager().getTracClient(repository);
client.updateAttributes(monitor, false);
createDefaultAttributes(data, client, false);
return true;
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
// TODO catch TracException
throw new CoreException(TracCorePlugin.toStatus(e, repository));
}
}
@Override
public boolean initializeSubTaskData(TaskRepository repository, TaskData taskData, TaskData parentTaskData,
IProgressMonitor monitor) throws CoreException {
initializeTaskData(repository, taskData, null, monitor);
TaskAttribute blockingAttribute = taskData.getRoot().getMappedAttribute(ATTRIBUTE_BLOCKING);
if (blockingAttribute == null) {
throw new CoreException(new RepositoryStatus(repository, IStatus.ERROR, TracCorePlugin.ID_PLUGIN,
RepositoryStatus.ERROR_REPOSITORY, "The repository does not support subtasks"));
}
TaskMapper mapper = new TaskMapper(taskData);
mapper.merge(new TaskMapper(parentTaskData));
mapper.setDescription("");
mapper.setSummary("");
blockingAttribute.setValue(parentTaskData.getTaskId());
TaskAttribute blockedByAttribute = taskData.getRoot().getMappedAttribute(ATTRIBUTE_BLOCKED_BY);
if (blockedByAttribute != null) {
blockedByAttribute.clearValues();
}
return true;
}
@Override
public boolean canInitializeSubTaskData(TaskRepository taskRepository, ITask task) {
return Boolean.parseBoolean(task.getAttribute(TracRepositoryConnector.TASK_KEY_SUPPORTS_SUBTASKS));
}
// /**
// * Updates attributes of <code>taskData</code> from <code>ticket</code>.
// */
// public void updateTaskDataFromTicket(TaskData taskData, TracTicket ticket, ITracClient client) {
// DefaultTaskSchema schema = new DefaultTaskSchema(taskData);
// if (ticket.getValue(Key.SUMMARY) != null) {
// schema.setSummary(ticket.getValue(Key.SUMMARY));
// }
//
// if (TracRepositoryConnector.isCompleted(ticket.getValue(Key.STATUS))) {
// schema.setCompletionDate(ticket.getLastChanged());
// } else {
// schema.setCompletionDate(null);
// }
//
// String priority = ticket.getValue(Key.PRIORITY);
// TracPriority[] tracPriorities = client.getPriorities();
// schema.setPriority(TracRepositoryConnector.getTaskPriority(priority, tracPriorities));
//
// if (ticket.getValue(Key.TYPE) != null) {
// TaskKind taskKind = TracRepositoryConnector.TaskKind.fromType(ticket.getValue(Key.TYPE));
// schema.setTaskKind((taskKind != null) ? taskKind.toString() : ticket.getValue(Key.TYPE));
// }
//
// if (ticket.getCreated() != null) {
// schema.setCreationDate(ticket.getCreated());
// }
//
// if (ticket.getCustomValue(TracTaskDataHandler.ATTRIBUTE_BLOCKING) != null) {
// taskData.addAttribute(ATTRIBUTE_BLOCKED_BY, new TaskAttribute(ATTRIBUTE_BLOCKED_BY, "Blocked by", true));
// }
// }
@Override
public TaskAttributeMapper getAttributeMapper(TaskRepository taskRepository) {
return new TracAttributeMapper(taskRepository);
}
public boolean supportsSubtasks(TaskData taskData) {
return taskData.getRoot().getAttribute(ATTRIBUTE_BLOCKED_BY) != null;
}
public static TracTicket getTracTicket(TaskRepository repository, TaskData data) throws InvalidTicketException,
CoreException {
TracTicket ticket = (data.isNew()) ? new TracTicket() : new TracTicket(
TracRepositoryConnector.getTicketId(data.getTaskId()));
Collection<TaskAttribute> attributes = data.getRoot().getAttributes().values();
for (TaskAttribute attribute : attributes) {
if (TracAttributeMapper.isInternalAttribute(attribute)) {
// ignore
} else if (!attribute.getMetaData().isReadOnly()) {
ticket.putValue(attribute.getId(), attribute.getValue());
}
}
// set cc value
StringBuilder sb = new StringBuilder();
List<String> removeValues = TracRepositoryConnector.getAttributeValues(data, TracAttributeMapper.REMOVE_CC);
List<String> values = TracRepositoryConnector.getAttributeValues(data, TaskAttribute.USER_CC);
for (String user : values) {
if (!removeValues.contains(user)) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(user);
}
}
if (TracRepositoryConnector.getAttributeValue(data, TracAttributeMapper.NEW_CC).length() > 0) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(TracRepositoryConnector.getAttributeValue(data, TracAttributeMapper.NEW_CC));
}
if (Boolean.TRUE.equals(TracRepositoryConnector.getAttributeValue(data, TaskAttribute.ADD_SELF_CC))) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(repository.getUserName());
}
ticket.putBuiltinValue(Key.CC, sb.toString());
ticket.putValue("owner", TracRepositoryConnector.getAttributeValue(data, TaskAttribute.USER_ASSIGNED));
TaskAttribute operationAttribute = data.getRoot().getMappedAttribute(TaskAttribute.OPERATION);
if (operationAttribute != null) {
TaskOperation operation = TaskOperation.createFrom(operationAttribute);
String action = operation.getOperationId();
if (!"leave".equals(action)) {
if ("accept".equals(action)) {
ticket.putValue("status", TracRepositoryConnector.TaskStatus.ASSIGNED.toStatusString());
} else if ("resolve".equals(action)) {
ticket.putValue("status", TracRepositoryConnector.TaskStatus.CLOSED.toStatusString());
ticket.putValue("resolution", TracRepositoryConnector.getAttributeValue(data,
TaskAttribute.RESOLUTION));
} else if ("reopen".equals(action)) {
ticket.putValue("status", TracRepositoryConnector.TaskStatus.REOPENED.toStatusString());
ticket.putValue("resolution", "");
} else if ("reassign".equals(action)) {
ticket.putValue("status", TracRepositoryConnector.TaskStatus.NEW.toStatusString());
}
}
}
return ticket;
}
@Override
public void migrateTaskData(TaskRepository taskRepository, TaskData taskData) {
int version = 0;
if (taskData.getVersion() != null) {
try {
version = Integer.parseInt(taskData.getVersion());
} catch (NumberFormatException e) {
// ignore
}
}
if (version < 1) {
TaskAttribute root = taskData.getRoot();
List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(root.getAttributes().values());
for (TaskAttribute attribute : attributes) {
if (TaskAttribute.TYPE_OPERATION.equals(attribute.getMetaData().getType())
&& "reassign".equals(attribute.getValue())) {
root.removeAttribute(attribute.getId());
} else if (TaskAttribute.OPERATION.equals(attribute.getId())) {
attribute.getMetaData().setType(TaskAttribute.TYPE_OPERATION);
} else if (TracAttributeMapper.NEW_CC.equals(attribute.getId())) {
attribute.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT).setReadOnly(false);
} else {
TracAttribute tracAttribute = TracAttribute.getByTracKey(attribute.getId());
if (tracAttribute != null) {
attribute.getMetaData().setType(tracAttribute.getType());
attribute.getMetaData().setKind(tracAttribute.getKind());
attribute.getMetaData().setReadOnly(tracAttribute.isReadOnly());
}
}
}
if (root.getAttribute(TracAttributeMapper.REMOVE_CC) == null) {
root.createAttribute(TracAttributeMapper.REMOVE_CC);
}
if (root.getAttribute(TaskAttribute.COMMENT_NEW) == null) {
root.createAttribute(TaskAttribute.COMMENT_NEW)
.getMetaData()
.setType(TaskAttribute.TYPE_LONG_RICH_TEXT)
.setReadOnly(false);
}
}
if (version < 2) {
List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(taskData.getRoot().getAttributes().values());
for (TaskAttribute attribute : attributes) {
if (!TracAttributeMapper.isInternalAttribute(attribute)) {
TaskAttributeMetaData metaData = attribute.getMetaData();
metaData.putValue(TRAC_KEY, attribute.getId());
if (metaData.getType() == null) {
metaData.setType(TaskAttribute.TYPE_SHORT_TEXT);
}
}
}
taskData.setVersion(TASK_DATA_VERSION);
}
}
}
| false | true | public static Set<TaskAttribute> updateTaskData(TaskRepository repository, TaskData data, TracTicket ticket) {
Set<TaskAttribute> changedAttributes = new HashSet<TaskAttribute>();
Date lastChanged = ticket.getLastChanged();
if (lastChanged != null) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(TracAttribute.CHANGE_TIME.getTracKey());
taskAttribute.setValue(TracUtil.toTracTime(lastChanged) + "");
changedAttributes.add(taskAttribute);
}
if (ticket.getCreated() != null) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(TracAttribute.TIME.getTracKey());
taskAttribute.setValue(TracUtil.toTracTime(ticket.getCreated()) + "");
changedAttributes.add(taskAttribute);
}
Map<String, String> valueByKey = ticket.getValues();
for (String key : valueByKey.keySet()) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(key);
if (Key.CC.getKey().equals(key)) {
StringTokenizer t = new StringTokenizer(valueByKey.get(key), CC_DELIMETER);
while (t.hasMoreTokens()) {
taskAttribute.addValue(t.nextToken());
}
} else {
taskAttribute.setValue(valueByKey.get(key));
}
changedAttributes.add(taskAttribute);
}
TracComment[] comments = ticket.getComments();
if (comments != null) {
int count = 1;
for (int i = 0; i < comments.length; i++) {
if (!"comment".equals(comments[i].getField()) || "".equals(comments[i].getNewValue())) {
continue;
}
TaskCommentMapper mapper = new TaskCommentMapper();
mapper.setAuthor(repository.createPerson(comments[i].getAuthor()));
mapper.setCreationDate(comments[i].getCreated());
mapper.setText(comments[i].getNewValue());
// TODO mapper.setUrl();
mapper.setNumber(count);
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_COMMENT + count);
mapper.applyTo(attribute);
count++;
}
}
TracAttachment[] attachments = ticket.getAttachments();
if (attachments != null) {
for (int i = 0; i < attachments.length; i++) {
TaskAttachmentMapper mapper = new TaskAttachmentMapper();
mapper.setAuthor(repository.createPerson(attachments[i].getAuthor()));
mapper.setDescription(attachments[i].getDescription());
mapper.setFileName(attachments[i].getFilename());
mapper.setLength((long) attachments[i].getSize());
if (attachments[i].getCreated() != null) {
if (lastChanged == null || attachments[i].getCreated().after(lastChanged)) {
lastChanged = attachments[i].getCreated();
}
mapper.setCreationDate(attachments[i].getCreated());
}
mapper.setUrl(repository.getRepositoryUrl() + ITracClient.TICKET_ATTACHMENT_URL + ticket.getId() + "/"
+ TracUtil.encode(attachments[i].getFilename()));
mapper.setAttachmentId(i + "");
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_ATTACHMENT + (i + 1));
mapper.applyTo(attribute);
}
}
String[] actions = ticket.getActions();
if (actions != null) {
// add operations in a defined order
List<String> actionList = new ArrayList<String>(Arrays.asList(actions));
addOperation(repository, data, ticket, actionList, "leave");
addOperation(repository, data, ticket, actionList, "accept");
addOperation(repository, data, ticket, actionList, "resolve");
addOperation(repository, data, ticket, actionList, "reopen");
}
return changedAttributes;
}
| public static Set<TaskAttribute> updateTaskData(TaskRepository repository, TaskData data, TracTicket ticket) {
Set<TaskAttribute> changedAttributes = new HashSet<TaskAttribute>();
Date lastChanged = ticket.getLastChanged();
if (lastChanged != null) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(TracAttribute.CHANGE_TIME.getTracKey());
taskAttribute.setValue(TracUtil.toTracTime(lastChanged) + "");
changedAttributes.add(taskAttribute);
}
if (ticket.getCreated() != null) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(TracAttribute.TIME.getTracKey());
taskAttribute.setValue(TracUtil.toTracTime(ticket.getCreated()) + "");
changedAttributes.add(taskAttribute);
}
Map<String, String> valueByKey = ticket.getValues();
for (String key : valueByKey.keySet()) {
TaskAttribute taskAttribute = data.getRoot().getAttribute(key);
if (taskAttribute != null) {
if (Key.CC.getKey().equals(key)) {
StringTokenizer t = new StringTokenizer(valueByKey.get(key), CC_DELIMETER);
while (t.hasMoreTokens()) {
taskAttribute.addValue(t.nextToken());
}
} else {
taskAttribute.setValue(valueByKey.get(key));
}
changedAttributes.add(taskAttribute);
} else {
// TODO log missing attribute?
}
}
TracComment[] comments = ticket.getComments();
if (comments != null) {
int count = 1;
for (int i = 0; i < comments.length; i++) {
if (!"comment".equals(comments[i].getField()) || "".equals(comments[i].getNewValue())) {
continue;
}
TaskCommentMapper mapper = new TaskCommentMapper();
mapper.setAuthor(repository.createPerson(comments[i].getAuthor()));
mapper.setCreationDate(comments[i].getCreated());
mapper.setText(comments[i].getNewValue());
// TODO mapper.setUrl();
mapper.setNumber(count);
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_COMMENT + count);
mapper.applyTo(attribute);
count++;
}
}
TracAttachment[] attachments = ticket.getAttachments();
if (attachments != null) {
for (int i = 0; i < attachments.length; i++) {
TaskAttachmentMapper mapper = new TaskAttachmentMapper();
mapper.setAuthor(repository.createPerson(attachments[i].getAuthor()));
mapper.setDescription(attachments[i].getDescription());
mapper.setFileName(attachments[i].getFilename());
mapper.setLength((long) attachments[i].getSize());
if (attachments[i].getCreated() != null) {
if (lastChanged == null || attachments[i].getCreated().after(lastChanged)) {
lastChanged = attachments[i].getCreated();
}
mapper.setCreationDate(attachments[i].getCreated());
}
mapper.setUrl(repository.getRepositoryUrl() + ITracClient.TICKET_ATTACHMENT_URL + ticket.getId() + "/"
+ TracUtil.encode(attachments[i].getFilename()));
mapper.setAttachmentId(i + "");
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_ATTACHMENT + (i + 1));
mapper.applyTo(attribute);
}
}
String[] actions = ticket.getActions();
if (actions != null) {
// add operations in a defined order
List<String> actionList = new ArrayList<String>(Arrays.asList(actions));
addOperation(repository, data, ticket, actionList, "leave");
addOperation(repository, data, ticket, actionList, "accept");
addOperation(repository, data, ticket, actionList, "resolve");
addOperation(repository, data, ticket, actionList, "reopen");
}
return changedAttributes;
}
|
diff --git a/EditeurDeTexte/src/model/classes/Line.java b/EditeurDeTexte/src/model/classes/Line.java
index 334cc17..ab5a861 100644
--- a/EditeurDeTexte/src/model/classes/Line.java
+++ b/EditeurDeTexte/src/model/classes/Line.java
@@ -1,184 +1,184 @@
package model.classes;
import java.util.Observable;
import java.util.Observer;
import model.interfaces.ILine;
/**
* 10 oct. 2012 - EditeurDeTexte.
* @author Simon Devineau & Pierre Reliquet Ecole des Mines de Nantes Major in
* Computer and Information System Engineering Line.java
*/
class Line extends Observable implements ILine {
/**
* The representation of the line as a StringBuffer to avoid creating a new
* string each time that a char is added.
*/
private StringBuilder _Line;
/**
* The variable to store the variable location inside the line.
*/
private boolean _IsCurrent;
/**
* Default constructor which creates an empty line
*/
Line() {
_Line = new StringBuilder();
Cursor.instance().setCurrentLine(this);
this.addObserver(Cursor.instance());
}
/**
* The constructor to create a line using the CharSequence as starting text.
* @param sequence
* , the CharSequence which contains the basis.
*/
Line(CharSequence sequence) {
this();
addUnderCursor(sequence);
}
@Override
public void addUnderCursor(CharSequence insertion) {
// TODO vérifier si c'est _CursorLocation ou _CursorLocation+1
if (hasCursor()
&& Cursor.instance().getCurrentPosition() < _Line.length()) {
_Line.insert(Cursor.instance().getCurrentPosition(), insertion);
Cursor.instance()
.setCurrentPosition(
Cursor.instance().getCurrentPosition()
+ insertion.length());
setChanged();
notifyObservers();
}
else if (hasCursor()
&& Cursor.instance().getCurrentPosition() >= _Line.length()) {
_Line.insert(_Line.length(), insertion);
Cursor.instance().setCurrentPosition(
_Line.length() + insertion.length());
}
}
@Override
public void append(CharSequence content) {
if (hasCursor()) {
_Line.append(content);
Cursor.instance().setCurrentPosition(
Cursor.instance().getCurrentPosition() + content.length());
this.setChanged();
this.notifyObservers();
}
}
@Override
public void deleteUnderCursor() {
if (hasCursor()) {
_Line.deleteCharAt(Cursor.instance().getCurrentPosition());
this.setChanged();
this.notifyObservers();
}
}
@Override
public boolean hasCursor() {
return _IsCurrent;
}
@Override
public void replaceUnderCursor(CharSequence replacement) {
if (hasCursor()) {
// TODO vérifier les index
// Copying the start of the line (before the cursor)
StringBuilder tmp = new StringBuilder(_Line.substring(0, Cursor
.instance().getCurrentPosition()));
// Adding the replacement
tmp.append(replacement);
// TODO vérifier les index
// Calculating the new cursor location
int newCursorLocation = Cursor.instance().getCurrentPosition()
+ replacement.length();
// If the line is longer than the new cursor location we need
// to append the rest of the line
if (_Line.length() > newCursorLocation) {
tmp.append(_Line.substring(newCursorLocation));
}
// We store the new variables.
_Line = tmp;
Cursor.instance().setCurrentPosition(newCursorLocation);
this.setChanged();
this.notifyObservers();
}
}
@Override
public synchronized void addObserver(Observer o) {
super.addObserver(o);
}
@Override
public int length() {
return _Line.length();
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder toReturn = new StringBuilder();
int index = 0;
// If the line has the cursor, this one has to be added to the line
if (this.hasCursor()) {
// FBefore adding the cursor, we get all the char placed before this
// one
while (index < Cursor.instance().getCurrentPosition() - 1
&& index < _Line.length()) {
toReturn.append(_Line.charAt(index));
index++;
}
// If there is no char before the cursor, the line is empty, we add
// an "_" to display a fake cursor
if (_Line.length() == 0) {
toReturn.append("<span style=\"background-color:red;text-decoration:blink;\">"
+ "_" + "</span>");
}
// If there are chars before we place the cursor on the
// corresponding char and complete the line
else {
if (index < _Line.length() || index == 0) {
toReturn.append("<span style=\"text-decoration:underline;background-color:red;text-decoration:blink;\">"
+ _Line.charAt(index) + "</span>");
}
else {
toReturn.append("<span style=\"text-decoration:underline;background-color:red;text-decoration:blink;\">"
- + _Line.charAt(_Line.length()) + "</span>");
+ + _Line.charAt(_Line.length() - 1) + "</span>");
}
index++;
while (index < _Line.length()) {
toReturn.append(_Line.charAt(index));
index++;
}
}
}
else {
toReturn = _Line;
}
return toReturn.toString();
}
/*
*//**
* @see model.interfaces.ILine#hasCursor()
*/
/*
* @Override public boolean hasCursor() { //TODO equals or ==, plutot == car
* on veut que ca soit la meme case m�moire return
* Cursor.getCursorInstance().getCurrentLine().equals(this); }
*/
@Override
public void setCurrent(boolean isCurrent) {
_IsCurrent = isCurrent;
}
}
| true | true | public String toString() {
StringBuilder toReturn = new StringBuilder();
int index = 0;
// If the line has the cursor, this one has to be added to the line
if (this.hasCursor()) {
// FBefore adding the cursor, we get all the char placed before this
// one
while (index < Cursor.instance().getCurrentPosition() - 1
&& index < _Line.length()) {
toReturn.append(_Line.charAt(index));
index++;
}
// If there is no char before the cursor, the line is empty, we add
// an "_" to display a fake cursor
if (_Line.length() == 0) {
toReturn.append("<span style=\"background-color:red;text-decoration:blink;\">"
+ "_" + "</span>");
}
// If there are chars before we place the cursor on the
// corresponding char and complete the line
else {
if (index < _Line.length() || index == 0) {
toReturn.append("<span style=\"text-decoration:underline;background-color:red;text-decoration:blink;\">"
+ _Line.charAt(index) + "</span>");
}
else {
toReturn.append("<span style=\"text-decoration:underline;background-color:red;text-decoration:blink;\">"
+ _Line.charAt(_Line.length()) + "</span>");
}
index++;
while (index < _Line.length()) {
toReturn.append(_Line.charAt(index));
index++;
}
}
}
else {
toReturn = _Line;
}
return toReturn.toString();
}
| public String toString() {
StringBuilder toReturn = new StringBuilder();
int index = 0;
// If the line has the cursor, this one has to be added to the line
if (this.hasCursor()) {
// FBefore adding the cursor, we get all the char placed before this
// one
while (index < Cursor.instance().getCurrentPosition() - 1
&& index < _Line.length()) {
toReturn.append(_Line.charAt(index));
index++;
}
// If there is no char before the cursor, the line is empty, we add
// an "_" to display a fake cursor
if (_Line.length() == 0) {
toReturn.append("<span style=\"background-color:red;text-decoration:blink;\">"
+ "_" + "</span>");
}
// If there are chars before we place the cursor on the
// corresponding char and complete the line
else {
if (index < _Line.length() || index == 0) {
toReturn.append("<span style=\"text-decoration:underline;background-color:red;text-decoration:blink;\">"
+ _Line.charAt(index) + "</span>");
}
else {
toReturn.append("<span style=\"text-decoration:underline;background-color:red;text-decoration:blink;\">"
+ _Line.charAt(_Line.length() - 1) + "</span>");
}
index++;
while (index < _Line.length()) {
toReturn.append(_Line.charAt(index));
index++;
}
}
}
else {
toReturn = _Line;
}
return toReturn.toString();
}
|
diff --git a/components/patient-update-listeners/src/main/java/edu/toronto/cs/phenotips/listeners/FreePhenotypeCategoryUpdater.java b/components/patient-update-listeners/src/main/java/edu/toronto/cs/phenotips/listeners/FreePhenotypeCategoryUpdater.java
index 5ac415844..bdd6cffc9 100644
--- a/components/patient-update-listeners/src/main/java/edu/toronto/cs/phenotips/listeners/FreePhenotypeCategoryUpdater.java
+++ b/components/patient-update-listeners/src/main/java/edu/toronto/cs/phenotips/listeners/FreePhenotypeCategoryUpdater.java
@@ -1,192 +1,192 @@
/*
* 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 edu.toronto.cs.phenotips.listeners;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.bridge.event.DocumentCreatingEvent;
import org.xwiki.bridge.event.DocumentUpdatingEvent;
import org.xwiki.component.annotation.Component;
import org.xwiki.container.Container;
import org.xwiki.container.servlet.ServletRequest;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.event.Event;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.classes.BaseClass;
/**
* Store the target category specified for free text phenotypes.
*
* @version $Id$
*/
@Component
@Named("phenotype-category-updater")
@Singleton
public class FreePhenotypeCategoryUpdater implements EventListener
{
/** The name of the space where the PhenoTips classes are. */
private static final String PHENOTIPS_CODE_SPACE = "PhenoTips";
/** The name of the class where the mapping between phenotypes and categories is stored. */
private static final EntityReference CATEGORY_CLASS_REFERENCE = new EntityReference("PhenotypeCategoryClass",
EntityType.DOCUMENT, new EntityReference(PHENOTIPS_CODE_SPACE, EntityType.SPACE));
/** The name of the mapping class property where the phenotype property name is stored. */
private static final String NAME_PROPETY_NAME = "target_property_name";
/** The name of the mapping class property where the phenotype value is stored. */
private static final String VALUE_PROPETY_NAME = "target_property_value";
/** The name of the mapping class property where the target category is stored. */
private static final String CATEGORY_PROPETY_NAME = "target_property_category";
/** Needed for getting access to the request. */
@Inject
private Container container;
@Override
public String getName()
{
return "phenotype-category-updater";
}
@Override
public List<Event> getEvents()
{
// The list of events this listener listens to
return Arrays.<Event> asList(new DocumentCreatingEvent(), new DocumentUpdatingEvent());
}
@Override
public void onEvent(Event event, Object source, Object data)
{
XWikiContext context = (XWikiContext) data;
XWikiDocument doc = (XWikiDocument) source;
BaseObject patientRecordObj =
doc.getXObject(new DocumentReference(doc.getDocumentReference().getRoot().getName(), PHENOTIPS_CODE_SPACE,
"PatientClass"));
if (patientRecordObj == null) {
return;
}
BaseClass patientRecordClass = patientRecordObj.getXClass(context);
for (String targetPropertyName : patientRecordClass.getPropertyList()) {
if (!targetPropertyName.contains("phenotype")) {
continue;
}
for (String phenotype : (List<String>) patientRecordObj.getListValue(targetPropertyName)) {
if (!phenotype.matches("HP:[0-9]+")) {
List<String> category =
- getParameter(targetPropertyName + "__" + phenotype.replaceAll("[^a-z0-9_]+", "_")
+ getParameter(targetPropertyName + "__" + phenotype.replaceAll("[^a-zA-Z0-9_]+", "_")
+ "__category", patientRecordObj.getNumber());
if (category != null && !category.isEmpty()) {
storeCategory(phenotype, category, targetPropertyName, doc, context);
}
}
}
}
}
/**
* Store the category specified for a free-text phenotype in an object attached to the patient sheet.
*
* @param phenotype the free-text phenotype value found in the request
* @param category the specified category where the phenotype belongs
* @param targetPropertyName the name of the phenotype property where the {@code phenotype} was specified
* @param doc the patient sheet
* @param context the current execution context
*/
private void storeCategory(String phenotype, List<String> category, String targetPropertyName, XWikiDocument doc,
XWikiContext context)
{
BaseObject targetMappingObject = findCategoryObject(phenotype, targetPropertyName, doc, context);
targetMappingObject.setStringValue(NAME_PROPETY_NAME, targetPropertyName);
targetMappingObject.setStringValue(VALUE_PROPETY_NAME, phenotype);
targetMappingObject.setStringListValue(CATEGORY_PROPETY_NAME, category);
}
/**
* Find an XObject for storing the category for a phenotype. This method first searches for an existing object for
* that phenotype, which will be updated, or if one isn't found, then a new object will be created.
*
* @param phenotype the free-text phenotype value found in the request
* @param targetPropertyName the name of the phenotype property where the {@code phenotype} was specified
* @param doc the patient sheet
* @param context the current execution context
* @return the target XObject
*/
private BaseObject findCategoryObject(String phenotype, String targetPropertyName, XWikiDocument doc,
XWikiContext context)
{
BaseObject targetMappingObject = null;
try {
List<BaseObject> existingObjects = doc.getXObjects(CATEGORY_CLASS_REFERENCE);
if (existingObjects != null) {
for (BaseObject mappingObject : existingObjects) {
if (targetPropertyName.equals(mappingObject.getStringValue(NAME_PROPETY_NAME))
&& phenotype.equals(mappingObject.getStringValue(VALUE_PROPETY_NAME))) {
targetMappingObject = mappingObject;
break;
}
}
}
if (targetMappingObject == null) {
targetMappingObject =
doc.getXObject(CATEGORY_CLASS_REFERENCE, doc.createXObject(CATEGORY_CLASS_REFERENCE, context));
}
} catch (XWikiException ex) {
// Storage error, shouldn't happen
}
return targetMappingObject;
}
/**
* Read a property from the request.
*
* @param propertyName the name of the property as it would appear in the class, for example
* {@code age_of_onset_years}
* @param objectNumber the object's number
* @return the value sent in the request, {@code null} if the property is missing
*/
private List<String> getParameter(String propertyName, int objectNumber)
{
String parameterName = MessageFormat.format("PhenoTips.PatientClass_{0}_{1}", objectNumber, propertyName);
String[] parameters =
((ServletRequest) this.container.getRequest()).getHttpServletRequest().getParameterValues(parameterName);
if (parameters == null) {
return null;
}
return Arrays.asList(parameters);
}
}
| true | true | public void onEvent(Event event, Object source, Object data)
{
XWikiContext context = (XWikiContext) data;
XWikiDocument doc = (XWikiDocument) source;
BaseObject patientRecordObj =
doc.getXObject(new DocumentReference(doc.getDocumentReference().getRoot().getName(), PHENOTIPS_CODE_SPACE,
"PatientClass"));
if (patientRecordObj == null) {
return;
}
BaseClass patientRecordClass = patientRecordObj.getXClass(context);
for (String targetPropertyName : patientRecordClass.getPropertyList()) {
if (!targetPropertyName.contains("phenotype")) {
continue;
}
for (String phenotype : (List<String>) patientRecordObj.getListValue(targetPropertyName)) {
if (!phenotype.matches("HP:[0-9]+")) {
List<String> category =
getParameter(targetPropertyName + "__" + phenotype.replaceAll("[^a-z0-9_]+", "_")
+ "__category", patientRecordObj.getNumber());
if (category != null && !category.isEmpty()) {
storeCategory(phenotype, category, targetPropertyName, doc, context);
}
}
}
}
}
| public void onEvent(Event event, Object source, Object data)
{
XWikiContext context = (XWikiContext) data;
XWikiDocument doc = (XWikiDocument) source;
BaseObject patientRecordObj =
doc.getXObject(new DocumentReference(doc.getDocumentReference().getRoot().getName(), PHENOTIPS_CODE_SPACE,
"PatientClass"));
if (patientRecordObj == null) {
return;
}
BaseClass patientRecordClass = patientRecordObj.getXClass(context);
for (String targetPropertyName : patientRecordClass.getPropertyList()) {
if (!targetPropertyName.contains("phenotype")) {
continue;
}
for (String phenotype : (List<String>) patientRecordObj.getListValue(targetPropertyName)) {
if (!phenotype.matches("HP:[0-9]+")) {
List<String> category =
getParameter(targetPropertyName + "__" + phenotype.replaceAll("[^a-zA-Z0-9_]+", "_")
+ "__category", patientRecordObj.getNumber());
if (category != null && !category.isEmpty()) {
storeCategory(phenotype, category, targetPropertyName, doc, context);
}
}
}
}
}
|
diff --git a/api/src/test/java/org/openmrs/api/context/ContextWithModuleTest.java b/api/src/test/java/org/openmrs/api/context/ContextWithModuleTest.java
index 994175a5..bce8c757 100644
--- a/api/src/test/java/org/openmrs/api/context/ContextWithModuleTest.java
+++ b/api/src/test/java/org/openmrs/api/context/ContextWithModuleTest.java
@@ -1,78 +1,78 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* 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.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.api.context;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openmrs.module.ModuleClassLoader;
import org.openmrs.module.ModuleConstants;
import org.openmrs.module.ModuleInteroperabilityTest;
import org.openmrs.module.ModuleUtil;
import org.openmrs.test.BaseContextSensitiveTest;
import org.openmrs.test.SkipBaseSetup;
import org.openmrs.test.Verifies;
/**
* This test class is meant just for testing the {@link Context#loadClass(String)} method. This
* method needs to have a module loaded for it to test correctly, so it is put into a separate class
* The module is stolen/copied from the {@link ModuleInteroperabilityTest}
*
* @see ContextTest
*/
public class ContextWithModuleTest extends BaseContextSensitiveTest {
@Before
public void startupBeforeEachTest() throws Exception {
ModuleUtil.startup(getRuntimeProperties());
}
@After
public void cleanupAfterEachTest() throws Exception {
ModuleUtil.shutdown();
}
/**
* This class file uses the atd and dss modules to test the compatibility
*
* @see org.openmrs.test.BaseContextSensitiveTest#getRuntimeProperties()
*/
public Properties getRuntimeProperties() {
Properties props = super.getRuntimeProperties();
// NOTE! This module is modified heavily from the original atd modules.
// the "/lib" folder has been emptied to compact the size.
// the "/metadata/sqldiff.xml" file has been deleted in order to load the modules into hsql.
// (the sql tables are built from hibernate mapping files automatically in unit tests)
props.setProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD,
- "org/openmrs/module/include/logic-0.2.omod org/openmrs/api/context/include/dssmodule-1.44.omod");
+ "org/openmrs/module/include/logic-0.2.omod org/openmrs/module/include/dssmodule-1.44.omod");
return props;
}
/**
* @see {@link Context#loadClass(String)}
*/
@Test
@SkipBaseSetup
@Verifies(value = "should load class with the OpenmrsClassLoader", method = "loadClass(String)")
public void loadClass_shouldLoadClassWithOpenmrsClassLoader() throws Exception {
Class<?> c = Context.loadClass("org.openmrs.module.dssmodule.DssService");
Assert.assertTrue("Should be loaded by OpenmrsClassLoader", c.getClassLoader() instanceof ModuleClassLoader);
}
}
| true | true | public Properties getRuntimeProperties() {
Properties props = super.getRuntimeProperties();
// NOTE! This module is modified heavily from the original atd modules.
// the "/lib" folder has been emptied to compact the size.
// the "/metadata/sqldiff.xml" file has been deleted in order to load the modules into hsql.
// (the sql tables are built from hibernate mapping files automatically in unit tests)
props.setProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD,
"org/openmrs/module/include/logic-0.2.omod org/openmrs/api/context/include/dssmodule-1.44.omod");
return props;
}
| public Properties getRuntimeProperties() {
Properties props = super.getRuntimeProperties();
// NOTE! This module is modified heavily from the original atd modules.
// the "/lib" folder has been emptied to compact the size.
// the "/metadata/sqldiff.xml" file has been deleted in order to load the modules into hsql.
// (the sql tables are built from hibernate mapping files automatically in unit tests)
props.setProperty(ModuleConstants.RUNTIMEPROPERTY_MODULE_LIST_TO_LOAD,
"org/openmrs/module/include/logic-0.2.omod org/openmrs/module/include/dssmodule-1.44.omod");
return props;
}
|
diff --git a/gamelib/test/testgame/tests/LongTaskTest.java b/gamelib/test/testgame/tests/LongTaskTest.java
index fb06838..5064166 100644
--- a/gamelib/test/testgame/tests/LongTaskTest.java
+++ b/gamelib/test/testgame/tests/LongTaskTest.java
@@ -1,113 +1,113 @@
/*******************************************************************************
* Copyright (c) 2012 Emanuele Tamponi.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Emanuele Tamponi - initial API and implementation
******************************************************************************/
package testgame.tests;
import static org.junit.Assert.*;
import game.core.LongTask;
import game.core.LongTask.LongTaskUpdate;
import java.util.Observable;
import java.util.Observer;
import org.junit.Test;
public class LongTaskTest {
private static class LongTaskImplB extends LongTask {
@Override
protected Object execute(Object... params) {
try {
Thread.sleep(100);
updateStatus(0.2, "LongTaskImplB slept for 1 seconds");
Thread.sleep(100);
updateStatus(0.4, "LongTaskImplB slept for 2 seconds");
Thread.sleep(100);
updateStatus(0.6, "LongTaskImplB slept for 3 seconds");
Thread.sleep(100);
updateStatus(0.8, "LongTaskImplB slept for 4 seconds");
Thread.sleep(100);
updateStatus(1.0, "LongTaskImplB slept for 5 seconds");
} catch (InterruptedException e) {}
return null;
}
@Override
public String getTaskDescription() {
return "test task B";
}
}
private static class LongTaskImplA extends LongTask {
@Override
protected Object execute(Object... params) {
try {
Thread.sleep(100);
updateStatus(0.1, "slept for 1 seconds");
Thread.sleep(100);
updateStatus(0.2, "slept for 2 seconds");
Thread.sleep(100);
updateStatus(0.3, "slept for 3 seconds");
LongTask other = new LongTaskImplB();
other.setOption("name", "OtherTask");
startAnotherTaskAndWait(0.8, other);
Thread.sleep(100);
updateStatus(1.0, "slept for a lot of seconds");
} catch (InterruptedException e) {}
return null;
}
public Object startTest() {
return startTask();
}
@Override
public String getTaskDescription() {
return "test task A";
}
}
@Test
public void test() {
LongTaskImplA task = new LongTaskImplA();
task.addObserver(new Observer() {
private int count = 0;
@Override
public void update(Observable o, Object m) {
if (m instanceof LongTaskUpdate) {
LongTask observed = (LongTask)o;
System.out.println(String.format("%6.2f%% of %s: %s", observed.getCurrentPercent()*100, observed, observed.getCurrentMessage()));
if (count == 0)
assertEquals("start task test task A", observed.getCurrentMessage());
else if (count > 0 && count < 4)
assertEquals("slept for " + count + " seconds", observed.getCurrentMessage());
else if (count == 4)
assertEquals("start task test task B", observed.getCurrentMessage());
else if (count > 4 && count < 10)
assertEquals("LongTaskImplB slept for " + (count-4) + " seconds", observed.getCurrentMessage());
else if (count == 10)
- assertEquals("task finished", observed.getCurrentMessage());
+ assertEquals("task finished (test task B)", observed.getCurrentMessage());
else if (count == 11)
assertEquals("slept for a lot of seconds", observed.getCurrentMessage());
else
- assertEquals("task finished", observed.getCurrentMessage());
+ assertEquals("task finished (test task A)", observed.getCurrentMessage());
count++;
}
}
});
task.startTest();
}
}
| false | true | public void test() {
LongTaskImplA task = new LongTaskImplA();
task.addObserver(new Observer() {
private int count = 0;
@Override
public void update(Observable o, Object m) {
if (m instanceof LongTaskUpdate) {
LongTask observed = (LongTask)o;
System.out.println(String.format("%6.2f%% of %s: %s", observed.getCurrentPercent()*100, observed, observed.getCurrentMessage()));
if (count == 0)
assertEquals("start task test task A", observed.getCurrentMessage());
else if (count > 0 && count < 4)
assertEquals("slept for " + count + " seconds", observed.getCurrentMessage());
else if (count == 4)
assertEquals("start task test task B", observed.getCurrentMessage());
else if (count > 4 && count < 10)
assertEquals("LongTaskImplB slept for " + (count-4) + " seconds", observed.getCurrentMessage());
else if (count == 10)
assertEquals("task finished", observed.getCurrentMessage());
else if (count == 11)
assertEquals("slept for a lot of seconds", observed.getCurrentMessage());
else
assertEquals("task finished", observed.getCurrentMessage());
count++;
}
}
});
task.startTest();
}
| public void test() {
LongTaskImplA task = new LongTaskImplA();
task.addObserver(new Observer() {
private int count = 0;
@Override
public void update(Observable o, Object m) {
if (m instanceof LongTaskUpdate) {
LongTask observed = (LongTask)o;
System.out.println(String.format("%6.2f%% of %s: %s", observed.getCurrentPercent()*100, observed, observed.getCurrentMessage()));
if (count == 0)
assertEquals("start task test task A", observed.getCurrentMessage());
else if (count > 0 && count < 4)
assertEquals("slept for " + count + " seconds", observed.getCurrentMessage());
else if (count == 4)
assertEquals("start task test task B", observed.getCurrentMessage());
else if (count > 4 && count < 10)
assertEquals("LongTaskImplB slept for " + (count-4) + " seconds", observed.getCurrentMessage());
else if (count == 10)
assertEquals("task finished (test task B)", observed.getCurrentMessage());
else if (count == 11)
assertEquals("slept for a lot of seconds", observed.getCurrentMessage());
else
assertEquals("task finished (test task A)", observed.getCurrentMessage());
count++;
}
}
});
task.startTest();
}
|
diff --git a/demo/src/java/main/org/uncommons/maths/demo/GaussianDistribution.java b/demo/src/java/main/org/uncommons/maths/demo/GaussianDistribution.java
index a0664f7..302799a 100644
--- a/demo/src/java/main/org/uncommons/maths/demo/GaussianDistribution.java
+++ b/demo/src/java/main/org/uncommons/maths/demo/GaussianDistribution.java
@@ -1,95 +1,95 @@
// ============================================================================
// Copyright 2006, 2007 Daniel W. Dyer
//
// 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.uncommons.maths.demo;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.uncommons.maths.random.GaussianGenerator;
/**
* @author Daniel Dyer
*/
class GaussianDistribution extends ProbabilityDistribution
{
private final double mean;
private final double standardDeviation;
public GaussianDistribution(double mean, double standardDeviation)
{
this.mean = mean;
this.standardDeviation = standardDeviation;
}
protected GaussianGenerator createValueGenerator(Random rng)
{
return new GaussianGenerator(mean, standardDeviation, rng);
}
public Map<Double, Double> getExpectedValues()
{
Map<Double, Double> values = new HashMap<Double, Double>();
double p;
- double x = mean;
+ double x = 0;
do
{
- p = getExpectedProbability(x);
- values.put(x, p);
- values.put(-x, p);
- x += (3 * standardDeviation / 10); // 99.7% of values are within 3 standard deviations.
+ p = getExpectedProbability(mean + x);
+ values.put(mean + x, p);
+ values.put(mean - x, p);
+ x += (3 * standardDeviation / 10); // 99.7% of values are within 3 standard deviations of the mean.
} while (p > 0.001);
return values;
}
/**
* This is the probability density function for the Gaussian
* distribution.
*/
private double getExpectedProbability(double x)
{
double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2));
double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2)));
return y * Math.exp(z);
}
public double getExpectedMean()
{
return mean;
}
public double getExpectedStandardDeviation()
{
return standardDeviation;
}
public String getDescription()
{
return "Gaussian Distribution (\u03bc = " + mean + ", \u03c3 = " + standardDeviation +")";
}
public boolean isDiscrete()
{
return false;
}
}
| false | true | public Map<Double, Double> getExpectedValues()
{
Map<Double, Double> values = new HashMap<Double, Double>();
double p;
double x = mean;
do
{
p = getExpectedProbability(x);
values.put(x, p);
values.put(-x, p);
x += (3 * standardDeviation / 10); // 99.7% of values are within 3 standard deviations.
} while (p > 0.001);
return values;
}
| public Map<Double, Double> getExpectedValues()
{
Map<Double, Double> values = new HashMap<Double, Double>();
double p;
double x = 0;
do
{
p = getExpectedProbability(mean + x);
values.put(mean + x, p);
values.put(mean - x, p);
x += (3 * standardDeviation / 10); // 99.7% of values are within 3 standard deviations of the mean.
} while (p > 0.001);
return values;
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dNPC.java b/src/main/java/net/aufdemrand/denizen/objects/dNPC.java
index eb23aff3e..a64b1e676 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dNPC.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dNPC.java
@@ -1,592 +1,592 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.flags.FlagManager;
import net.aufdemrand.denizen.npc.dNPCRegistry;
import net.aufdemrand.denizen.npc.traits.*;
import net.aufdemrand.denizen.scripts.commands.npc.EngageCommand;
import net.aufdemrand.denizen.scripts.containers.core.InteractScriptContainer;
import net.aufdemrand.denizen.scripts.containers.core.InteractScriptHelper;
import net.aufdemrand.denizen.scripts.triggers.AbstractTrigger;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.tags.core.NPCTags;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.ai.Navigator;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.trait.trait.Owner;
import net.citizensnpcs.trait.Anchors;
import net.citizensnpcs.util.Anchor;
import net.minecraft.server.v1_6_R3.EntityLiving;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_6_R3.entity.CraftLivingEntity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class dNPC implements dObject {
public static dNPC mirrorCitizensNPC(NPC npc) {
if (dNPCRegistry.denizenNPCs.containsKey(npc.getId())) return dNPCRegistry.denizenNPCs.get(npc.getId());
else return new dNPC(npc);
}
@ObjectFetcher("n")
public static dNPC valueOf(String string) {
if (string == null) return null;
////////
// Match NPC id
string = string.toUpperCase().replace("N@", "");
NPC npc;
if (aH.matchesInteger(string)) {
if (dNPCRegistry.denizenNPCs.containsKey(aH.getIntegerFrom(string)))
return dNPCRegistry.denizenNPCs.get(aH.getIntegerFrom(string));
npc = CitizensAPI.getNPCRegistry().getById(aH.getIntegerFrom(string));
if (npc != null) return new dNPC(npc);
}
////////
// Match NPC name
else {
for (NPC test : CitizensAPI.getNPCRegistry()) {
if (test.getName().equalsIgnoreCase(string)) {
return new dNPC(test);
}
}
}
return null;
}
public static boolean matches(String string) {
string = string.toUpperCase().replace("N@", "");
NPC npc;
if (aH.matchesInteger(string)) {
npc = CitizensAPI.getNPCRegistry().getById(aH.getIntegerFrom(string));
if (npc != null) return true;
}
else {
for (NPC test : CitizensAPI.getNPCRegistry()) {
if (test.getName().equalsIgnoreCase(string)) {
return true;
}
}
}
return false;
}
public boolean isValid() {
return getCitizen() != null;
}
private int npcid = -1;
private final org.bukkit.Location locationCache = new org.bukkit.Location(null, 0, 0, 0);
public dNPC(NPC citizensNPC) {
if (citizensNPC != null)
this.npcid = citizensNPC.getId();
if (npcid >= 0 && !dNPCRegistry.denizenNPCs.containsKey(npcid))
dNPCRegistry.denizenNPCs.put(npcid, this);
}
public EntityLiving getHandle() {
return ((CraftLivingEntity) getEntity()).getHandle();
}
public NPC getCitizen() {
NPC npc = CitizensAPI.getNPCRegistry().getById(npcid);
if (npc == null)
dB.log("Uh oh! Denizen has encountered a NPE while trying to fetch a NPC. Has this NPC been removed?");
return npc;
}
public LivingEntity getEntity() {
try {
return getCitizen().getBukkitEntity();
} catch (NullPointerException e) {
dB.log("Uh oh! Denizen has encountered a NPE while trying to fetch a NPC entity. Has this NPC been removed?");
return null;
}
}
public dEntity getDenizenEntity() {
try {
return new dEntity(getCitizen().getBukkitEntity());
} catch (NullPointerException e) {
dB.log("Uh oh! Denizen has encountered a NPE while trying to fetch a NPC entity. Has this NPC been removed?");
return null;
}
}
public EntityType getEntityType() {
return getCitizen().getBukkitEntity().getType();
}
public Navigator getNavigator() {
return getCitizen().getNavigator();
}
public int getId() {
return getCitizen().getId();
}
public String getName() {
return getCitizen().getName();
}
public InteractScriptContainer getInteractScript(dPlayer player, Class<? extends AbstractTrigger> triggerType) {
return InteractScriptHelper.getInteractScript(this, player, triggerType);
}
public InteractScriptContainer getInteractScriptQuietly(dPlayer player, Class<? extends AbstractTrigger> triggerType) {
boolean db = dB.debugMode;
dB.debugMode = false;
InteractScriptContainer script = InteractScriptHelper.getInteractScript(this, player, triggerType);
dB.debugMode = db;
return script;
}
public void destroy() {
getCitizen().destroy();
}
public dLocation getLocation() {
if (isSpawned()) return
new dLocation(getCitizen().getBukkitEntity().getLocation(locationCache));
else return null;
}
public dLocation getEyeLocation() {
if (isSpawned()) return
new dLocation(getCitizen().getBukkitEntity().getEyeLocation());
else return null;
}
public World getWorld() {
if (isSpawned()) return getEntity().getWorld();
else return null;
}
@Override
public String toString() {
return getCitizen().getName() + "/" + getCitizen().getId();
}
public boolean isEngaged() {
return EngageCommand.getEngaged(getCitizen());
}
public boolean isSpawned() {
return getCitizen().isSpawned();
}
public boolean isVulnerable() {
return true;
}
public String getOwner() {
return getCitizen().getTrait(Owner.class).getOwner();
}
public AssignmentTrait getAssignmentTrait() {
if (!getCitizen().hasTrait(AssignmentTrait.class))
getCitizen().addTrait(AssignmentTrait.class);
return getCitizen().getTrait(AssignmentTrait.class);
}
public NicknameTrait getNicknameTrait() {
if (!getCitizen().hasTrait(NicknameTrait.class))
getCitizen().addTrait(NicknameTrait.class);
return getCitizen().getTrait(NicknameTrait.class);
}
public HealthTrait getHealthTrait() {
if (!getCitizen().hasTrait(HealthTrait.class))
getCitizen().addTrait(HealthTrait.class);
return getCitizen().getTrait(HealthTrait.class);
}
public TriggerTrait getTriggerTrait() {
if (!getCitizen().hasTrait(TriggerTrait.class))
getCitizen().addTrait(TriggerTrait.class);
return getCitizen().getTrait(TriggerTrait.class);
}
public void action(String actionName, dPlayer player, Map<String, dObject> context) {
if (getCitizen() != null)
{
if (getCitizen().hasTrait(AssignmentTrait.class))
DenizenAPI.getCurrentInstance().getNPCRegistry()
.getActionHandler().doAction(
actionName,
this,
player,
getAssignmentTrait().getAssignment(),
context);
}
}
public void action(String actionName, dPlayer player) {
action(actionName, player, null);
}
private String prefix = "npc";
@Override
public String getPrefix() {
return prefix;
}
@Override
public String debug() {
return (prefix + "='<A>" + identify() + "<G>' ");
}
@Override
public boolean isUnique() {
return true;
}
@Override
public String getObjectType() {
return "NPC";
}
@Override
public String identify() {
return "n@" + npcid;
}
@Override
public dNPC setPrefix(String prefix) {
return this;
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
// <--[tag]
// @attribute <npc.name.nickname>
// @returns Element
// @description
// returns the NPC's display name.
// -->
if (attribute.startsWith("name.nickname"))
return new Element(getCitizen().hasTrait(NicknameTrait.class) ? getCitizen().getTrait(NicknameTrait.class)
.getNickname() : getName()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.name>
// @returns Element
// @description
// returns the name of the NPC.
// -->
if (attribute.startsWith("name"))
return new Element(ChatColor.stripColor(getName()))
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.list_traits>
// @returns dList
// @description
// Returns a list of all of the NPC's traits.
// -->
if (attribute.startsWith("list_traits")) {
List<String> list = new ArrayList<String>();
for (Trait trait : getCitizen().getTraits())
list.add(trait.getName());
return new dList(list).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.has_trait[<trait>]>
// @returns Element(boolean)
// @description
// Returns whether the NPC has a specified trait.
// -->
if (attribute.startsWith("has_trait")) {
if (attribute.hasContext(1)) {
Class<? extends Trait> trait = CitizensAPI.getTraitFactory().getTraitClass(attribute.getContext(1));
if (trait != null)
return new Element(getCitizen().hasTrait(trait))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <npc.anchor.list>
// @returns dList
// @description
// returns a list of anchor names currently assigned to the NPC.
// -->
if (attribute.startsWith("anchor.list")
|| attribute.startsWith("anchors.list")) {
List<String> list = new ArrayList<String>();
for (Anchor anchor : getCitizen().getTrait(Anchors.class).getAnchors())
list.add(anchor.getName());
return new dList(list).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <npc.has_anchors>
// @returns Element(boolean)
// @description
// returns whether the NPC has anchors assigned.
// -->
if (attribute.startsWith("has_anchors")) {
return (new Element(getCitizen().getTrait(Anchors.class).getAnchors().size() > 0))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.anchor[name]>
// @returns dLocation
// @description
// returns the location associated with the specified anchor, or null if it doesn't exist.
// -->
if (attribute.startsWith("anchor")) {
if (attribute.hasContext(1)
&& getCitizen().getTrait(Anchors.class).getAnchor(attribute.getContext(1)) != null)
return new dLocation(getCitizen().getTrait(Anchors.class)
.getAnchor(attribute.getContext(1)).getLocation())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.flag[flag_name]>
// @returns Flag dList
// @description
// returns the specified flag from the NPC.
// -->
if (attribute.startsWith("flag")) {
String flag_name;
if (attribute.hasContext(1)) flag_name = attribute.getContext(1);
else return "null";
attribute.fulfill(1);
if (attribute.startsWith("is_expired")
|| attribute.startsWith("isexpired"))
return new Element(!FlagManager.npcHasFlag(this, flag_name))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("size") && !FlagManager.npcHasFlag(this, flag_name))
return new Element(0).getAttribute(attribute.fulfill(1));
if (FlagManager.npcHasFlag(this, flag_name))
return new dList(DenizenAPI.getCurrentInstance().flagManager()
.getNPCFlag(getId(), flag_name))
.getAttribute(attribute);
else return "null";
}
// <--[tag]
// @attribute <npc.constant[constant_name]>
// @returns Element
// @description
// returns the specified constant from the NPC.
// -->
if (attribute.startsWith("constant")) {
String constant_name;
if (attribute.hasContext(1)) {
if (getCitizen().hasTrait(ConstantsTrait.class)
&& getCitizen().getTrait(ConstantsTrait.class).getConstant(attribute.getContext(1)) != null) {
return new Element(getCitizen().getTrait(ConstantsTrait.class)
.getConstant(attribute.getContext(1))).getAttribute(attribute.fulfill(1));
}
else {
return "null";
}
}
}
// <--[tag]
// @attribute <npc.id>
// @returns Element(number)
// @description
// returns the NPC's ID number.
// -->
if (attribute.startsWith("id"))
return new Element(getId()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.owner>
// @returns Element
// @description
// returns the owner of the NPC.
// -->
if (attribute.startsWith("owner"))
return new Element(getOwner()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.inventory>
// @returns dInventory
// @description
// Returns the dInventory of the NPC.
// -->
if (attribute.startsWith("inventory"))
return new dInventory(getEntity()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.is_spawned>
// @returns Element(boolean)
// @description
// returns whether the NPC is spawned.
// -->
if (attribute.startsWith("is_spawned"))
return new Element(isSpawned()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.location.previous_location>
// @returns dLocation
// @description
// returns the NPC's previous navigated location.
// -->
if (attribute.startsWith("location.previous_location"))
return (NPCTags.previousLocations.containsKey(getId())
? NPCTags.previousLocations.get(getId()).getAttribute(attribute.fulfill(2))
: "null");
// <--[tag]
// @attribute <npc.script>
// @returns dScript
// @description
// returns the NPC's assigned script.
// -->
if (attribute.startsWith("script")) {
NPC citizen = getCitizen();
if (!citizen.hasTrait(AssignmentTrait.class) || !citizen.getTrait(AssignmentTrait.class).hasAssignment()) {
return "null";
}
else {
return new Element(citizen.getTrait(AssignmentTrait.class).getAssignment().getName())
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <npc.navigator.is_navigating>
// @returns Element(boolean)
// @description
// returns whether the NPC is currently navigating.
// -->
if (attribute.startsWith("navigator.is_navigating"))
return new Element(getNavigator().isNavigating()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.speed>
// @returns Element(number)
// @description
// returns the current speed of the NPC.
// -->
if (attribute.startsWith("navigator.speed"))
return new Element(getNavigator().getLocalParameters().speed())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.range>
// @returns Element(number)
// @description
// returns the maximum pathfinding range.
// -->
if (attribute.startsWith("navigator.range"))
return new Element(getNavigator().getLocalParameters().range())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.attack_strategy>
// @returns Element
// @description
// returns the NPC's attack strategy.
// -->
if (attribute.startsWith("navigator.attack_strategy"))
return new Element(getNavigator().getLocalParameters().attackStrategy().toString())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.speed_modifier>
// @returns Element(number)
// @description
// returns the NPC movement speed modifier.
// -->
if (attribute.startsWith("navigator.speed_modifier"))
return new Element(getNavigator().getLocalParameters().speedModifier())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.base_speed>
// @returns Element(number)
// @description
// returns the base navigation speed.
// -->
if (attribute.startsWith("navigator.base_speed"))
return new Element(getNavigator().getLocalParameters().baseSpeed())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.avoid_water>
// @returns Element(boolean)
// @description
// returns whether the NPC will avoid water.
// -->
if (attribute.startsWith("navigator.avoid_water"))
return new Element(getNavigator().getLocalParameters().avoidWater())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_location>
// @returns dLocation
// @description
// returns the location the NPC is curently navigating towards.
// -->
if (attribute.startsWith("navigator.target_location"))
return (getNavigator().getTargetAsLocation() != null
? new dLocation(getNavigator().getTargetAsLocation()).getAttribute(attribute.fulfill(2))
: "null");
// <--[tag]
// @attribute <npc.navigator.is_fighting>
// @returns Element(boolean)
// @description
// returns whether the NPC is in combat.
// -->
if (attribute.startsWith("navigator.is_fighting"))
- return new Element(getNavigator().getEntityTarget().isAggressive())
+ return new Element(getNavigator().getEntityTarget() != null && getNavigator().getEntityTarget().isAggressive())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_type>
// @returns Element
// @description
// returns the entity type of the target.
// -->
if (attribute.startsWith("navigator.target_type"))
- return new Element(getNavigator().getTargetType().toString())
+ return new Element(getNavigator().getTargetType() == null ? "null": getNavigator().getTargetType().toString())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_entity>
// @returns dEntity
// @description
// returns the entity being targeted.
// -->
if (attribute.startsWith("navigator.target_entity"))
- return (getNavigator().getEntityTarget().getTarget() != null
+ return (getNavigator().getEntityTarget() != null && getNavigator().getEntityTarget().getTarget() != null
? new dEntity(getNavigator().getEntityTarget().getTarget()).getAttribute(attribute.fulfill(2))
: "null");
return (getEntity() != null
? new dEntity(getCitizen()).getAttribute(attribute)
: new Element(identify()).getAttribute(attribute));
}
}
| false | true | public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
// <--[tag]
// @attribute <npc.name.nickname>
// @returns Element
// @description
// returns the NPC's display name.
// -->
if (attribute.startsWith("name.nickname"))
return new Element(getCitizen().hasTrait(NicknameTrait.class) ? getCitizen().getTrait(NicknameTrait.class)
.getNickname() : getName()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.name>
// @returns Element
// @description
// returns the name of the NPC.
// -->
if (attribute.startsWith("name"))
return new Element(ChatColor.stripColor(getName()))
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.list_traits>
// @returns dList
// @description
// Returns a list of all of the NPC's traits.
// -->
if (attribute.startsWith("list_traits")) {
List<String> list = new ArrayList<String>();
for (Trait trait : getCitizen().getTraits())
list.add(trait.getName());
return new dList(list).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.has_trait[<trait>]>
// @returns Element(boolean)
// @description
// Returns whether the NPC has a specified trait.
// -->
if (attribute.startsWith("has_trait")) {
if (attribute.hasContext(1)) {
Class<? extends Trait> trait = CitizensAPI.getTraitFactory().getTraitClass(attribute.getContext(1));
if (trait != null)
return new Element(getCitizen().hasTrait(trait))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <npc.anchor.list>
// @returns dList
// @description
// returns a list of anchor names currently assigned to the NPC.
// -->
if (attribute.startsWith("anchor.list")
|| attribute.startsWith("anchors.list")) {
List<String> list = new ArrayList<String>();
for (Anchor anchor : getCitizen().getTrait(Anchors.class).getAnchors())
list.add(anchor.getName());
return new dList(list).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <npc.has_anchors>
// @returns Element(boolean)
// @description
// returns whether the NPC has anchors assigned.
// -->
if (attribute.startsWith("has_anchors")) {
return (new Element(getCitizen().getTrait(Anchors.class).getAnchors().size() > 0))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.anchor[name]>
// @returns dLocation
// @description
// returns the location associated with the specified anchor, or null if it doesn't exist.
// -->
if (attribute.startsWith("anchor")) {
if (attribute.hasContext(1)
&& getCitizen().getTrait(Anchors.class).getAnchor(attribute.getContext(1)) != null)
return new dLocation(getCitizen().getTrait(Anchors.class)
.getAnchor(attribute.getContext(1)).getLocation())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.flag[flag_name]>
// @returns Flag dList
// @description
// returns the specified flag from the NPC.
// -->
if (attribute.startsWith("flag")) {
String flag_name;
if (attribute.hasContext(1)) flag_name = attribute.getContext(1);
else return "null";
attribute.fulfill(1);
if (attribute.startsWith("is_expired")
|| attribute.startsWith("isexpired"))
return new Element(!FlagManager.npcHasFlag(this, flag_name))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("size") && !FlagManager.npcHasFlag(this, flag_name))
return new Element(0).getAttribute(attribute.fulfill(1));
if (FlagManager.npcHasFlag(this, flag_name))
return new dList(DenizenAPI.getCurrentInstance().flagManager()
.getNPCFlag(getId(), flag_name))
.getAttribute(attribute);
else return "null";
}
// <--[tag]
// @attribute <npc.constant[constant_name]>
// @returns Element
// @description
// returns the specified constant from the NPC.
// -->
if (attribute.startsWith("constant")) {
String constant_name;
if (attribute.hasContext(1)) {
if (getCitizen().hasTrait(ConstantsTrait.class)
&& getCitizen().getTrait(ConstantsTrait.class).getConstant(attribute.getContext(1)) != null) {
return new Element(getCitizen().getTrait(ConstantsTrait.class)
.getConstant(attribute.getContext(1))).getAttribute(attribute.fulfill(1));
}
else {
return "null";
}
}
}
// <--[tag]
// @attribute <npc.id>
// @returns Element(number)
// @description
// returns the NPC's ID number.
// -->
if (attribute.startsWith("id"))
return new Element(getId()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.owner>
// @returns Element
// @description
// returns the owner of the NPC.
// -->
if (attribute.startsWith("owner"))
return new Element(getOwner()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.inventory>
// @returns dInventory
// @description
// Returns the dInventory of the NPC.
// -->
if (attribute.startsWith("inventory"))
return new dInventory(getEntity()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.is_spawned>
// @returns Element(boolean)
// @description
// returns whether the NPC is spawned.
// -->
if (attribute.startsWith("is_spawned"))
return new Element(isSpawned()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.location.previous_location>
// @returns dLocation
// @description
// returns the NPC's previous navigated location.
// -->
if (attribute.startsWith("location.previous_location"))
return (NPCTags.previousLocations.containsKey(getId())
? NPCTags.previousLocations.get(getId()).getAttribute(attribute.fulfill(2))
: "null");
// <--[tag]
// @attribute <npc.script>
// @returns dScript
// @description
// returns the NPC's assigned script.
// -->
if (attribute.startsWith("script")) {
NPC citizen = getCitizen();
if (!citizen.hasTrait(AssignmentTrait.class) || !citizen.getTrait(AssignmentTrait.class).hasAssignment()) {
return "null";
}
else {
return new Element(citizen.getTrait(AssignmentTrait.class).getAssignment().getName())
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <npc.navigator.is_navigating>
// @returns Element(boolean)
// @description
// returns whether the NPC is currently navigating.
// -->
if (attribute.startsWith("navigator.is_navigating"))
return new Element(getNavigator().isNavigating()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.speed>
// @returns Element(number)
// @description
// returns the current speed of the NPC.
// -->
if (attribute.startsWith("navigator.speed"))
return new Element(getNavigator().getLocalParameters().speed())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.range>
// @returns Element(number)
// @description
// returns the maximum pathfinding range.
// -->
if (attribute.startsWith("navigator.range"))
return new Element(getNavigator().getLocalParameters().range())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.attack_strategy>
// @returns Element
// @description
// returns the NPC's attack strategy.
// -->
if (attribute.startsWith("navigator.attack_strategy"))
return new Element(getNavigator().getLocalParameters().attackStrategy().toString())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.speed_modifier>
// @returns Element(number)
// @description
// returns the NPC movement speed modifier.
// -->
if (attribute.startsWith("navigator.speed_modifier"))
return new Element(getNavigator().getLocalParameters().speedModifier())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.base_speed>
// @returns Element(number)
// @description
// returns the base navigation speed.
// -->
if (attribute.startsWith("navigator.base_speed"))
return new Element(getNavigator().getLocalParameters().baseSpeed())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.avoid_water>
// @returns Element(boolean)
// @description
// returns whether the NPC will avoid water.
// -->
if (attribute.startsWith("navigator.avoid_water"))
return new Element(getNavigator().getLocalParameters().avoidWater())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_location>
// @returns dLocation
// @description
// returns the location the NPC is curently navigating towards.
// -->
if (attribute.startsWith("navigator.target_location"))
return (getNavigator().getTargetAsLocation() != null
? new dLocation(getNavigator().getTargetAsLocation()).getAttribute(attribute.fulfill(2))
: "null");
// <--[tag]
// @attribute <npc.navigator.is_fighting>
// @returns Element(boolean)
// @description
// returns whether the NPC is in combat.
// -->
if (attribute.startsWith("navigator.is_fighting"))
return new Element(getNavigator().getEntityTarget().isAggressive())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_type>
// @returns Element
// @description
// returns the entity type of the target.
// -->
if (attribute.startsWith("navigator.target_type"))
return new Element(getNavigator().getTargetType().toString())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_entity>
// @returns dEntity
// @description
// returns the entity being targeted.
// -->
if (attribute.startsWith("navigator.target_entity"))
return (getNavigator().getEntityTarget().getTarget() != null
? new dEntity(getNavigator().getEntityTarget().getTarget()).getAttribute(attribute.fulfill(2))
: "null");
return (getEntity() != null
? new dEntity(getCitizen()).getAttribute(attribute)
: new Element(identify()).getAttribute(attribute));
}
| public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
// <--[tag]
// @attribute <npc.name.nickname>
// @returns Element
// @description
// returns the NPC's display name.
// -->
if (attribute.startsWith("name.nickname"))
return new Element(getCitizen().hasTrait(NicknameTrait.class) ? getCitizen().getTrait(NicknameTrait.class)
.getNickname() : getName()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.name>
// @returns Element
// @description
// returns the name of the NPC.
// -->
if (attribute.startsWith("name"))
return new Element(ChatColor.stripColor(getName()))
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.list_traits>
// @returns dList
// @description
// Returns a list of all of the NPC's traits.
// -->
if (attribute.startsWith("list_traits")) {
List<String> list = new ArrayList<String>();
for (Trait trait : getCitizen().getTraits())
list.add(trait.getName());
return new dList(list).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.has_trait[<trait>]>
// @returns Element(boolean)
// @description
// Returns whether the NPC has a specified trait.
// -->
if (attribute.startsWith("has_trait")) {
if (attribute.hasContext(1)) {
Class<? extends Trait> trait = CitizensAPI.getTraitFactory().getTraitClass(attribute.getContext(1));
if (trait != null)
return new Element(getCitizen().hasTrait(trait))
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <npc.anchor.list>
// @returns dList
// @description
// returns a list of anchor names currently assigned to the NPC.
// -->
if (attribute.startsWith("anchor.list")
|| attribute.startsWith("anchors.list")) {
List<String> list = new ArrayList<String>();
for (Anchor anchor : getCitizen().getTrait(Anchors.class).getAnchors())
list.add(anchor.getName());
return new dList(list).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <npc.has_anchors>
// @returns Element(boolean)
// @description
// returns whether the NPC has anchors assigned.
// -->
if (attribute.startsWith("has_anchors")) {
return (new Element(getCitizen().getTrait(Anchors.class).getAnchors().size() > 0))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.anchor[name]>
// @returns dLocation
// @description
// returns the location associated with the specified anchor, or null if it doesn't exist.
// -->
if (attribute.startsWith("anchor")) {
if (attribute.hasContext(1)
&& getCitizen().getTrait(Anchors.class).getAnchor(attribute.getContext(1)) != null)
return new dLocation(getCitizen().getTrait(Anchors.class)
.getAnchor(attribute.getContext(1)).getLocation())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <npc.flag[flag_name]>
// @returns Flag dList
// @description
// returns the specified flag from the NPC.
// -->
if (attribute.startsWith("flag")) {
String flag_name;
if (attribute.hasContext(1)) flag_name = attribute.getContext(1);
else return "null";
attribute.fulfill(1);
if (attribute.startsWith("is_expired")
|| attribute.startsWith("isexpired"))
return new Element(!FlagManager.npcHasFlag(this, flag_name))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("size") && !FlagManager.npcHasFlag(this, flag_name))
return new Element(0).getAttribute(attribute.fulfill(1));
if (FlagManager.npcHasFlag(this, flag_name))
return new dList(DenizenAPI.getCurrentInstance().flagManager()
.getNPCFlag(getId(), flag_name))
.getAttribute(attribute);
else return "null";
}
// <--[tag]
// @attribute <npc.constant[constant_name]>
// @returns Element
// @description
// returns the specified constant from the NPC.
// -->
if (attribute.startsWith("constant")) {
String constant_name;
if (attribute.hasContext(1)) {
if (getCitizen().hasTrait(ConstantsTrait.class)
&& getCitizen().getTrait(ConstantsTrait.class).getConstant(attribute.getContext(1)) != null) {
return new Element(getCitizen().getTrait(ConstantsTrait.class)
.getConstant(attribute.getContext(1))).getAttribute(attribute.fulfill(1));
}
else {
return "null";
}
}
}
// <--[tag]
// @attribute <npc.id>
// @returns Element(number)
// @description
// returns the NPC's ID number.
// -->
if (attribute.startsWith("id"))
return new Element(getId()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.owner>
// @returns Element
// @description
// returns the owner of the NPC.
// -->
if (attribute.startsWith("owner"))
return new Element(getOwner()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.inventory>
// @returns dInventory
// @description
// Returns the dInventory of the NPC.
// -->
if (attribute.startsWith("inventory"))
return new dInventory(getEntity()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.is_spawned>
// @returns Element(boolean)
// @description
// returns whether the NPC is spawned.
// -->
if (attribute.startsWith("is_spawned"))
return new Element(isSpawned()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <npc.location.previous_location>
// @returns dLocation
// @description
// returns the NPC's previous navigated location.
// -->
if (attribute.startsWith("location.previous_location"))
return (NPCTags.previousLocations.containsKey(getId())
? NPCTags.previousLocations.get(getId()).getAttribute(attribute.fulfill(2))
: "null");
// <--[tag]
// @attribute <npc.script>
// @returns dScript
// @description
// returns the NPC's assigned script.
// -->
if (attribute.startsWith("script")) {
NPC citizen = getCitizen();
if (!citizen.hasTrait(AssignmentTrait.class) || !citizen.getTrait(AssignmentTrait.class).hasAssignment()) {
return "null";
}
else {
return new Element(citizen.getTrait(AssignmentTrait.class).getAssignment().getName())
.getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <npc.navigator.is_navigating>
// @returns Element(boolean)
// @description
// returns whether the NPC is currently navigating.
// -->
if (attribute.startsWith("navigator.is_navigating"))
return new Element(getNavigator().isNavigating()).getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.speed>
// @returns Element(number)
// @description
// returns the current speed of the NPC.
// -->
if (attribute.startsWith("navigator.speed"))
return new Element(getNavigator().getLocalParameters().speed())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.range>
// @returns Element(number)
// @description
// returns the maximum pathfinding range.
// -->
if (attribute.startsWith("navigator.range"))
return new Element(getNavigator().getLocalParameters().range())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.attack_strategy>
// @returns Element
// @description
// returns the NPC's attack strategy.
// -->
if (attribute.startsWith("navigator.attack_strategy"))
return new Element(getNavigator().getLocalParameters().attackStrategy().toString())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.speed_modifier>
// @returns Element(number)
// @description
// returns the NPC movement speed modifier.
// -->
if (attribute.startsWith("navigator.speed_modifier"))
return new Element(getNavigator().getLocalParameters().speedModifier())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.base_speed>
// @returns Element(number)
// @description
// returns the base navigation speed.
// -->
if (attribute.startsWith("navigator.base_speed"))
return new Element(getNavigator().getLocalParameters().baseSpeed())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.avoid_water>
// @returns Element(boolean)
// @description
// returns whether the NPC will avoid water.
// -->
if (attribute.startsWith("navigator.avoid_water"))
return new Element(getNavigator().getLocalParameters().avoidWater())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_location>
// @returns dLocation
// @description
// returns the location the NPC is curently navigating towards.
// -->
if (attribute.startsWith("navigator.target_location"))
return (getNavigator().getTargetAsLocation() != null
? new dLocation(getNavigator().getTargetAsLocation()).getAttribute(attribute.fulfill(2))
: "null");
// <--[tag]
// @attribute <npc.navigator.is_fighting>
// @returns Element(boolean)
// @description
// returns whether the NPC is in combat.
// -->
if (attribute.startsWith("navigator.is_fighting"))
return new Element(getNavigator().getEntityTarget() != null && getNavigator().getEntityTarget().isAggressive())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_type>
// @returns Element
// @description
// returns the entity type of the target.
// -->
if (attribute.startsWith("navigator.target_type"))
return new Element(getNavigator().getTargetType() == null ? "null": getNavigator().getTargetType().toString())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <npc.navigator.target_entity>
// @returns dEntity
// @description
// returns the entity being targeted.
// -->
if (attribute.startsWith("navigator.target_entity"))
return (getNavigator().getEntityTarget() != null && getNavigator().getEntityTarget().getTarget() != null
? new dEntity(getNavigator().getEntityTarget().getTarget()).getAttribute(attribute.fulfill(2))
: "null");
return (getEntity() != null
? new dEntity(getCitizen()).getAttribute(attribute)
: new Element(identify()).getAttribute(attribute));
}
|
diff --git a/lc-user-tools/src/main/java/org/esa/cci/lc/io/LcBinWriter.java b/lc-user-tools/src/main/java/org/esa/cci/lc/io/LcBinWriter.java
index 3686578..dd37cbc 100644
--- a/lc-user-tools/src/main/java/org/esa/cci/lc/io/LcBinWriter.java
+++ b/lc-user-tools/src/main/java/org/esa/cci/lc/io/LcBinWriter.java
@@ -1,246 +1,246 @@
package org.esa.cci.lc.io;
import org.esa.beam.binning.Aggregator;
import org.esa.beam.binning.BinningContext;
import org.esa.beam.binning.PlanetaryGrid;
import org.esa.beam.binning.TemporalBin;
import org.esa.beam.binning.WritableVector;
import org.esa.beam.binning.operator.BinWriter;
import org.esa.beam.binning.support.PlateCarreeGrid;
import org.esa.beam.binning.support.RegularGaussianGrid;
import org.esa.beam.dataio.netcdf.nc.NFileWriteable;
import org.esa.beam.dataio.netcdf.nc.NVariable;
import org.esa.beam.dataio.netcdf.nc.NWritableFactory;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.util.io.FileUtils;
import org.esa.beam.util.logging.BeamLogManager;
import org.geotools.geometry.jts.ReferencedEnvelope;
import ucar.ma2.DataType;
import java.awt.Dimension;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* @author Marco Peters
*/
public class LcBinWriter implements BinWriter {
private static final float FILL_VALUE = Float.NaN;
private final Map<String, String> lcProperties;
private Logger logger;
private String targetFilePath;
private BinningContext binningContext;
private PlanetaryGrid planetaryGrid;
private ReferencedEnvelope region;
public LcBinWriter(Map<String, String> lcProperties, ReferencedEnvelope region) {
this.lcProperties = lcProperties;
logger = BeamLogManager.getSystemLogger();
this.region = region;
}
@Override
public void setBinningContext(BinningContext binningContext) {
this.binningContext = binningContext;
if (region != null) {
this.planetaryGrid = new RegionalPlanetaryGrid(binningContext.getPlanetaryGrid(), region);
} else {
this.planetaryGrid = binningContext.getPlanetaryGrid();
}
}
@Override
public void write(Map<String, String> metadataProperties, List<TemporalBin> temporalBins) throws IOException {
NFileWriteable writeable = NWritableFactory.create(targetFilePath, "netcdf4");
try {
int sceneWidth = planetaryGrid.getNumCols(0);
int sceneHeight = planetaryGrid.getNumRows();
writeable.addDimension("lat", sceneHeight);
writeable.addDimension("lon", sceneWidth);
Dimension tileSize = new Dimension(128, 128);
addGlobalAttributes(writeable);
CoordinateEncoder coordinateEncoder = createCoordinateEncoder();
coordinateEncoder.addCoordVars(writeable);
ArrayList<NVariable> variables = addFeatureVariables(writeable, tileSize);
writeable.create();
fillVariables(temporalBins, variables, sceneWidth, sceneHeight);
coordinateEncoder.fillCoordinateVars(writeable);
} catch (Throwable e) {
e.printStackTrace();
} finally {
writeable.close();
}
}
private CoordinateEncoder createCoordinateEncoder() {
if (planetaryGrid instanceof PlateCarreeGrid || planetaryGrid instanceof RegularGaussianGrid || planetaryGrid instanceof RegionalPlanetaryGrid) {
return new RegularCoordinateEncoder(planetaryGrid);
} else {
throw new IllegalStateException("Unknown planetary grid");
}
}
@Override
public void setTargetFileTemplatePath(String targetFileTemplatePath) {
targetFilePath = FileUtils.ensureExtension(targetFileTemplatePath, ".nc");
}
@Override
public String getTargetFilePath() {
return targetFilePath;
}
@Override
public void setLogger(Logger logger) {
this.logger = logger;
}
private void addGlobalAttributes(NFileWriteable writeable) throws IOException {
String aggregationType = String.valueOf(lcProperties.remove("aggregationType"));
writeable.addGlobalAttribute("title", String.format("ESA CCI Land Cover %s Aggregated", aggregationType));
writeable.addGlobalAttribute("summary",
"This dataset contains the global ESA CCI land cover products " +
"which are spatially aggregated by the lc-user-tool.");
String spatialResolution = lcProperties.remove("spatialResolution");
String temporalResolution = lcProperties.remove("temporalResolution");
String version = lcProperties.remove("version");
addTypeAndIdAttribute(aggregationType, spatialResolution, temporalResolution, version, writeable);
LcWriterUtils.addGenericGlobalAttributes(writeable);
LcWriterUtils.addSpecificGlobalAttributes(lcProperties.remove("spatialResolutionDegrees"),
spatialResolution,
lcProperties.remove("temporalCoverageYears"),
temporalResolution,
lcProperties.remove("startTime"),
lcProperties.remove("endTime"),
version,
lcProperties.remove("latMax"),
lcProperties.remove("latMin"),
lcProperties.remove("lonMin"),
lcProperties.remove("lonMax"),
writeable);
// LC specific way of metadata provision
for (Map.Entry<String, String> lcPropEentry : lcProperties.entrySet()) {
writeable.addGlobalAttribute(lcPropEentry.getKey(), lcPropEentry.getValue());
}
}
private void addTypeAndIdAttribute(String aggregationType, String spatialResolution, String temporalResolution, String version,
NFileWriteable writeable) throws IOException {
String typeString;
String idString;
if (aggregationType.equals("Map")) {
String epoch = lcProperties.remove("epoch");
typeString = String.format("ESACCI-LC-L4-LCCS-Map-%sm-P%sY-%s", spatialResolution, temporalResolution, "aggregated");
idString = String.format("%s-%s-v%s", typeString, epoch, version);
} else {
String condition = lcProperties.remove("condition");
String startYear = lcProperties.remove("startYear");
String endYear = lcProperties.remove("endYear");
String startDate = lcProperties.remove("startDate");
typeString = String.format("ESACCI-LC-L4-%s-Cond-%sm-P%sD-%s", condition, spatialResolution, temporalResolution, "aggregated");
idString = String.format("%s-%s-%s-%s-v%s", typeString, startYear, endYear, startDate, version);
}
writeable.addGlobalAttribute("type", typeString);
writeable.addGlobalAttribute("id", idString);
}
private ArrayList<NVariable> addFeatureVariables(NFileWriteable writeable, Dimension tileSize) throws IOException {
final int aggregatorCount = binningContext.getBinManager().getAggregatorCount();
final ArrayList<NVariable> featureVars = new ArrayList<NVariable>(60);
for (int i = 0; i < aggregatorCount; i++) {
final Aggregator aggregator = binningContext.getBinManager().getAggregator(i);
final String[] featureNames = aggregator.getOutputFeatureNames();
for (String featureName : featureNames) {
final NVariable featureVar = writeable.addVariable(featureName, DataType.FLOAT, tileSize, writeable.getDimensions());
featureVar.addAttribute("_FillValue", FILL_VALUE);
featureVars.add(featureVar);
}
}
return featureVars;
}
private void fillVariables(List<TemporalBin> temporalBins, ArrayList<NVariable> variables, int sceneWidth, int sceneHeight) throws IOException {
final Iterator<TemporalBin> iterator = temporalBins.iterator();
ProductData.Float[] dataLines = new ProductData.Float[variables.size()];
initDataLines(variables, sceneWidth, dataLines);
int lineY = 0;
- int hundredthHeight = sceneHeight / 100;
+ int hundredthHeight = Math.max(sceneHeight / 100, sceneHeight);
int binX;
int binY;
while (iterator.hasNext()) {
final TemporalBin temporalBin = iterator.next();
long binIndex = temporalBin.getIndex();
if (planetaryGrid instanceof RegionalPlanetaryGrid) {
final RegionalPlanetaryGrid regionalGrid = (RegionalPlanetaryGrid) planetaryGrid;
if (!regionalGrid.isBinIndexInRegionalGrid(binIndex)) {
continue;
}
int baseGridWidth = regionalGrid.getGlobalGrid().getNumCols(0);
binX = (int) (binIndex % baseGridWidth);
binY = (int) (binIndex / baseGridWidth);
binX = binX - regionalGrid.getColumnOffset();
binY = binY - regionalGrid.getRowOffset();
} else {
binX = (int) (binIndex % sceneWidth);
binY = (int) (binIndex / sceneWidth);
}
final WritableVector resultVector = temporalBin.toVector();
if (binY != lineY) {
lineY = writeDataLine(variables, sceneWidth, dataLines, lineY);
lineY = writeEmptyLines(variables, sceneWidth, dataLines, lineY, binY);
if (lineY % hundredthHeight == 0) {
logger.info(String.format("Line %d of %d done", lineY, sceneHeight));
}
}
for (int i = 0; i < variables.size(); i++) {
dataLines[i].setElemFloatAt(binX, resultVector.get(i));
}
}
lineY = writeDataLine(variables, sceneWidth, dataLines, lineY);
writeEmptyLines(variables, sceneWidth, dataLines, lineY, sceneHeight);
}
private int writeEmptyLines(ArrayList<NVariable> variables, int sceneWidth, ProductData.Float[] dataLines, int lastY, int y) throws IOException {
initDataLines(variables, sceneWidth, dataLines);
for (; lastY < y; lastY++) {
writeDataLine(variables, sceneWidth, dataLines, lastY);
}
return lastY;
}
private int writeDataLine(ArrayList<NVariable> variables, int sceneWidth, ProductData.Float[] dataLines, int y) throws IOException {
for (int i = 0; i < variables.size(); i++) {
NVariable variable = variables.get(i);
variable.write(0, y, sceneWidth, 1, false, dataLines[i]);
}
return y + 1;
}
private void initDataLines(ArrayList<NVariable> variables, int sceneWidth, ProductData.Float[] dataLines) {
for (int i = 0; i < variables.size(); i++) {
if (dataLines[i] != null) {
Arrays.fill(dataLines[i].getArray(), FILL_VALUE);
} else {
float[] line = new float[sceneWidth];
Arrays.fill(line, FILL_VALUE);
dataLines[i] = new ProductData.Float(line);
}
}
}
}
| true | true | private void fillVariables(List<TemporalBin> temporalBins, ArrayList<NVariable> variables, int sceneWidth, int sceneHeight) throws IOException {
final Iterator<TemporalBin> iterator = temporalBins.iterator();
ProductData.Float[] dataLines = new ProductData.Float[variables.size()];
initDataLines(variables, sceneWidth, dataLines);
int lineY = 0;
int hundredthHeight = sceneHeight / 100;
int binX;
int binY;
while (iterator.hasNext()) {
final TemporalBin temporalBin = iterator.next();
long binIndex = temporalBin.getIndex();
if (planetaryGrid instanceof RegionalPlanetaryGrid) {
final RegionalPlanetaryGrid regionalGrid = (RegionalPlanetaryGrid) planetaryGrid;
if (!regionalGrid.isBinIndexInRegionalGrid(binIndex)) {
continue;
}
int baseGridWidth = regionalGrid.getGlobalGrid().getNumCols(0);
binX = (int) (binIndex % baseGridWidth);
binY = (int) (binIndex / baseGridWidth);
binX = binX - regionalGrid.getColumnOffset();
binY = binY - regionalGrid.getRowOffset();
} else {
binX = (int) (binIndex % sceneWidth);
binY = (int) (binIndex / sceneWidth);
}
final WritableVector resultVector = temporalBin.toVector();
if (binY != lineY) {
lineY = writeDataLine(variables, sceneWidth, dataLines, lineY);
lineY = writeEmptyLines(variables, sceneWidth, dataLines, lineY, binY);
if (lineY % hundredthHeight == 0) {
logger.info(String.format("Line %d of %d done", lineY, sceneHeight));
}
}
for (int i = 0; i < variables.size(); i++) {
dataLines[i].setElemFloatAt(binX, resultVector.get(i));
}
}
lineY = writeDataLine(variables, sceneWidth, dataLines, lineY);
writeEmptyLines(variables, sceneWidth, dataLines, lineY, sceneHeight);
}
| private void fillVariables(List<TemporalBin> temporalBins, ArrayList<NVariable> variables, int sceneWidth, int sceneHeight) throws IOException {
final Iterator<TemporalBin> iterator = temporalBins.iterator();
ProductData.Float[] dataLines = new ProductData.Float[variables.size()];
initDataLines(variables, sceneWidth, dataLines);
int lineY = 0;
int hundredthHeight = Math.max(sceneHeight / 100, sceneHeight);
int binX;
int binY;
while (iterator.hasNext()) {
final TemporalBin temporalBin = iterator.next();
long binIndex = temporalBin.getIndex();
if (planetaryGrid instanceof RegionalPlanetaryGrid) {
final RegionalPlanetaryGrid regionalGrid = (RegionalPlanetaryGrid) planetaryGrid;
if (!regionalGrid.isBinIndexInRegionalGrid(binIndex)) {
continue;
}
int baseGridWidth = regionalGrid.getGlobalGrid().getNumCols(0);
binX = (int) (binIndex % baseGridWidth);
binY = (int) (binIndex / baseGridWidth);
binX = binX - regionalGrid.getColumnOffset();
binY = binY - regionalGrid.getRowOffset();
} else {
binX = (int) (binIndex % sceneWidth);
binY = (int) (binIndex / sceneWidth);
}
final WritableVector resultVector = temporalBin.toVector();
if (binY != lineY) {
lineY = writeDataLine(variables, sceneWidth, dataLines, lineY);
lineY = writeEmptyLines(variables, sceneWidth, dataLines, lineY, binY);
if (lineY % hundredthHeight == 0) {
logger.info(String.format("Line %d of %d done", lineY, sceneHeight));
}
}
for (int i = 0; i < variables.size(); i++) {
dataLines[i].setElemFloatAt(binX, resultVector.get(i));
}
}
lineY = writeDataLine(variables, sceneWidth, dataLines, lineY);
writeEmptyLines(variables, sceneWidth, dataLines, lineY, sceneHeight);
}
|
diff --git a/src/physics/GJKSimplex.java b/src/physics/GJKSimplex.java
index 89879ab..31f391c 100644
--- a/src/physics/GJKSimplex.java
+++ b/src/physics/GJKSimplex.java
@@ -1,251 +1,251 @@
package physics;
import java.util.List;
import math.Vector3;
import math.Supportable;
// http://mollyrocket.com/forums/viewtopic.php?t=245
public class GJKSimplex{
static boolean containsOrigin(List<Vector3> simplex) {
// If we don't have 4 points, then we can't enclose the origin in R3
if(simplex.size() < 4)
return false;
Vector3 a = simplex.get(3);
Vector3 b = simplex.get(2);
Vector3 c = simplex.get(1);
Vector3 d = simplex.get(0);
// Compute all the edges we will use first, to avoid computing the same edge twice.
Vector3 ac = c.minus(a);
Vector3 ab = b.minus(a);
Vector3 bc = c.minus(b);
Vector3 bd = d.minus(b);
Vector3 ad = d.minus(a);
Vector3 ba = ab.negate();
Vector3 ao = a.negate();
Vector3 bo = b.negate();
/* We need to find the normals of all the faces
* of a tetrahedron
*
* Tetrahedron net (unfolded)
* A-----------------B-----------------A
* \ / \ /
* \ / \ /
* \ AC x AB / \ AB x AD /
* \ / \ /
* \ / \ /
* \ / BC x BD \ /
* \ / \ /
* \ / \ /
* C-----------------D
* \ /
* \ /
* \ AD x AC /
* \ /
* \ /
* \ /
* \ /
* \ /
* A
*/
Vector3 abc = ac.cross(ab);
Vector3 bcd = bc.cross(bd);
Vector3 adb = ab.cross(ad);
Vector3 acd = ad.cross(ac);
/*
* We don't know which way our sides are described, so we could have an inside out
* tetrahedron.
*
* So we multiple two dot products, the first tells us which way the normal is facing
* and the second tells us which way the origin is from that face, if they are the same
* sign then the origin and the vertex opposite that face are in the same direction.
*
* Since we just want to know if they are the same sign we multiple the two dot products
* together and see if the product is positive.
*
* For the origin to be within the tetrahedron, it must be on the inside of all four faces.
*/
return
(abc.dotProduct(ad) * abc.dotProduct(ao) > 0.0f) &&
(bcd.dotProduct(ba) * bcd.dotProduct(bo) > 0.0f) &&
(adb.dotProduct(ac) * adb.dotProduct(ao) > 0.0f) &&
(acd.dotProduct(ab) * acd.dotProduct(ao) > 0.0f);
}
/**
* update the simplex and the new direction
*/
static public Vector3 findSimplex(List<Vector3> simplex){
switch(simplex.size()){
case 2:
return findLineSimplex(simplex);
case 3:
return findTriangleSimplex(simplex);
default:
return findTetrahedronSimplex(simplex);
}
}
static public Vector3 findLineSimplex(List<Vector3> simplex){
Vector3 newDirection;
//A is the point added last to the simplex
Vector3 a = simplex.get(1);
Vector3 b = simplex.get(0);
Vector3 ab = b.minus(a);
Vector3 ao = Vector3.ORIGIN.minus(a);
if (ab.sameDirection(ao)) {
// The new direction is perpendicular to AB pointing to the origin
newDirection = ab.cross(ao).cross(ab);
} else {
newDirection = ao;
}
return newDirection;
}
static public Vector3 findTriangleSimplex(List<Vector3> simplex){
Vector3 newDirection;
//A is the point added last to the simplex
Vector3 a = simplex.get(2);
Vector3 b = simplex.get(1);
Vector3 c = simplex.get(0);
Vector3 ao = Vector3.ORIGIN.minus(a);
// The AB edge
Vector3 ab = b.minus(a);
// the AC edge
Vector3 ac = c.minus(a);
// The normal to the triangle
Vector3 abc = ab.cross(ac);
if (abc.cross(ac).sameDirection(ao)) {
// The origin is above
if (ac.sameDirection(ao)) {
simplex.clear();
simplex.add(a);
simplex.add(c);
newDirection = ac.cross(ao).cross(ac);
}
else
if (ab.sameDirection(ao)) {
simplex.clear();
simplex.add(a);
simplex.add(b);
newDirection = ab.cross(ao).cross(ab);
}
else {
simplex.clear();
simplex.add(a);
newDirection = ao;
}
}
else {
// The origin is below
if (ab.cross(abc).sameDirection(ao)) {
if (ab.sameDirection(ao)) {
simplex.clear();
simplex.add(a);
simplex.add(b);
newDirection = ab.cross(ao).cross(ab);
}
else {
simplex.clear();
simplex.add(a);
newDirection = ao;
}
}
else {
if (abc.sameDirection(ao)) {
//the simplex stays A, B, C
newDirection = abc;
}
else {
simplex.clear();
simplex.add(a);
simplex.add(c);
simplex.add(b);
newDirection = abc.negate();
}
}
}
return newDirection;
}
static public Vector3 findTetrahedronSimplex(List<Vector3> simplex){
Vector3 newDirection;
//A is the point added last to the simplex
Vector3 a = simplex.get(3);
Vector3 b = simplex.get(2);
Vector3 c = simplex.get(1);
Vector3 d = simplex.get(0);
Vector3 ao = a.negate();
Vector3 ab = b.minus(a);
Vector3 ac = c.minus(a);
Vector3 ad = d.minus(a);
Vector3 abc = ab.cross(ac);
Vector3 acd = ac.cross(ad);
Vector3 adb = ad.cross(ab);
//the side (positive or negative) of B, C and D relative to the planes of ACD, ADB and ABC respectively
int BsideOnACD = acd.dotProduct(ab) > 0.0f ? 1 : 0;
int CsideOnADB = adb.dotProduct(ac) > 0.0f ? 1 : 0;
int DsideOnABC = abc.dotProduct(ad) > 0.0f ? 1 : 0;
//whether the origin is on the same side of ACD/ADB/ABC as B, C and D respectively
boolean ABsameAsOrigin = (acd.dotProduct(ao) > 0.0f ? 1 : 0) == BsideOnACD;
boolean ACsameAsOrigin = (adb.dotProduct(ao) > 0.0f ? 1 : 0) == CsideOnADB;
//if the origin is not on the side of B relative to ACD
if (!ABsameAsOrigin) {
//B is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(b);
//the new direction is on the other side of ACD, relative to B
newDirection = acd.times(-BsideOnACD);
}
//if the origin is not on the side of C relative to ADB
else if (!ACsameAsOrigin) {
//C is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(c);
//the new direction is on the other side of ADB, relative to C
newDirection = adb.times(-CsideOnADB);
}
//if the origin is not on the side of D relative to ABC
else //if (!ADsameAsOrigin) {
//D is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(d);
//the new direction is on the other side of ABC, relative to D
newDirection = abc.times(-DsideOnABC);
//go on with the triangle case
//TODO: maybe we should restrict the depth of the recursion, just like we restricted the number of iterations in BodiesIntersect?
return findTriangleSimplex(simplex);
}
static Vector3 getSupport(Supportable lhs, Supportable rhs, Vector3 direction) {
return lhs.getFarthestPointInDirection(direction).minus(rhs.getFarthestPointInDirection(direction.negate()));
}
static public boolean isColliding(math.Supportable lhs, math.Supportable rhs){
List<Vector3> simplex = new java.util.ArrayList<Vector3>();
Vector3 support = getSupport(lhs,rhs,Vector3.UNIT_X);
simplex.add(support);
Vector3 direction = support.negate();
// If A is in the same direction as we were heading, then we haven't crossed the origin,
// so that means we can't get to the origin
- while((support = getSupport(lhs,rhs,direction)).dotProduct(direction) < 0){
+ while((support = getSupport(lhs,rhs,direction)).sameDirection(direction)){
simplex.add(support);
direction = findSimplex(simplex);
// If the simplex has enclosed the origin then the two objects are colliding
if(direction.equals(Vector3.ZERO) || containsOrigin(simplex))
return true;
}
return false;
}
}
| true | true | static public Vector3 findTetrahedronSimplex(List<Vector3> simplex){
Vector3 newDirection;
//A is the point added last to the simplex
Vector3 a = simplex.get(3);
Vector3 b = simplex.get(2);
Vector3 c = simplex.get(1);
Vector3 d = simplex.get(0);
Vector3 ao = a.negate();
Vector3 ab = b.minus(a);
Vector3 ac = c.minus(a);
Vector3 ad = d.minus(a);
Vector3 abc = ab.cross(ac);
Vector3 acd = ac.cross(ad);
Vector3 adb = ad.cross(ab);
//the side (positive or negative) of B, C and D relative to the planes of ACD, ADB and ABC respectively
int BsideOnACD = acd.dotProduct(ab) > 0.0f ? 1 : 0;
int CsideOnADB = adb.dotProduct(ac) > 0.0f ? 1 : 0;
int DsideOnABC = abc.dotProduct(ad) > 0.0f ? 1 : 0;
//whether the origin is on the same side of ACD/ADB/ABC as B, C and D respectively
boolean ABsameAsOrigin = (acd.dotProduct(ao) > 0.0f ? 1 : 0) == BsideOnACD;
boolean ACsameAsOrigin = (adb.dotProduct(ao) > 0.0f ? 1 : 0) == CsideOnADB;
//if the origin is not on the side of B relative to ACD
if (!ABsameAsOrigin) {
//B is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(b);
//the new direction is on the other side of ACD, relative to B
newDirection = acd.times(-BsideOnACD);
}
//if the origin is not on the side of C relative to ADB
else if (!ACsameAsOrigin) {
//C is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(c);
//the new direction is on the other side of ADB, relative to C
newDirection = adb.times(-CsideOnADB);
}
//if the origin is not on the side of D relative to ABC
else //if (!ADsameAsOrigin) {
//D is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(d);
//the new direction is on the other side of ABC, relative to D
newDirection = abc.times(-DsideOnABC);
//go on with the triangle case
//TODO: maybe we should restrict the depth of the recursion, just like we restricted the number of iterations in BodiesIntersect?
return findTriangleSimplex(simplex);
}
static Vector3 getSupport(Supportable lhs, Supportable rhs, Vector3 direction) {
return lhs.getFarthestPointInDirection(direction).minus(rhs.getFarthestPointInDirection(direction.negate()));
}
static public boolean isColliding(math.Supportable lhs, math.Supportable rhs){
List<Vector3> simplex = new java.util.ArrayList<Vector3>();
Vector3 support = getSupport(lhs,rhs,Vector3.UNIT_X);
simplex.add(support);
Vector3 direction = support.negate();
// If A is in the same direction as we were heading, then we haven't crossed the origin,
// so that means we can't get to the origin
while((support = getSupport(lhs,rhs,direction)).dotProduct(direction) < 0){
simplex.add(support);
direction = findSimplex(simplex);
// If the simplex has enclosed the origin then the two objects are colliding
if(direction.equals(Vector3.ZERO) || containsOrigin(simplex))
return true;
}
return false;
}
}
| static public Vector3 findTetrahedronSimplex(List<Vector3> simplex){
Vector3 newDirection;
//A is the point added last to the simplex
Vector3 a = simplex.get(3);
Vector3 b = simplex.get(2);
Vector3 c = simplex.get(1);
Vector3 d = simplex.get(0);
Vector3 ao = a.negate();
Vector3 ab = b.minus(a);
Vector3 ac = c.minus(a);
Vector3 ad = d.minus(a);
Vector3 abc = ab.cross(ac);
Vector3 acd = ac.cross(ad);
Vector3 adb = ad.cross(ab);
//the side (positive or negative) of B, C and D relative to the planes of ACD, ADB and ABC respectively
int BsideOnACD = acd.dotProduct(ab) > 0.0f ? 1 : 0;
int CsideOnADB = adb.dotProduct(ac) > 0.0f ? 1 : 0;
int DsideOnABC = abc.dotProduct(ad) > 0.0f ? 1 : 0;
//whether the origin is on the same side of ACD/ADB/ABC as B, C and D respectively
boolean ABsameAsOrigin = (acd.dotProduct(ao) > 0.0f ? 1 : 0) == BsideOnACD;
boolean ACsameAsOrigin = (adb.dotProduct(ao) > 0.0f ? 1 : 0) == CsideOnADB;
//if the origin is not on the side of B relative to ACD
if (!ABsameAsOrigin) {
//B is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(b);
//the new direction is on the other side of ACD, relative to B
newDirection = acd.times(-BsideOnACD);
}
//if the origin is not on the side of C relative to ADB
else if (!ACsameAsOrigin) {
//C is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(c);
//the new direction is on the other side of ADB, relative to C
newDirection = adb.times(-CsideOnADB);
}
//if the origin is not on the side of D relative to ABC
else //if (!ADsameAsOrigin) {
//D is farthest from the origin among all of the tetrahedron's points, so remove it from the list and go on with the triangle case
simplex.remove(d);
//the new direction is on the other side of ABC, relative to D
newDirection = abc.times(-DsideOnABC);
//go on with the triangle case
//TODO: maybe we should restrict the depth of the recursion, just like we restricted the number of iterations in BodiesIntersect?
return findTriangleSimplex(simplex);
}
static Vector3 getSupport(Supportable lhs, Supportable rhs, Vector3 direction) {
return lhs.getFarthestPointInDirection(direction).minus(rhs.getFarthestPointInDirection(direction.negate()));
}
static public boolean isColliding(math.Supportable lhs, math.Supportable rhs){
List<Vector3> simplex = new java.util.ArrayList<Vector3>();
Vector3 support = getSupport(lhs,rhs,Vector3.UNIT_X);
simplex.add(support);
Vector3 direction = support.negate();
// If A is in the same direction as we were heading, then we haven't crossed the origin,
// so that means we can't get to the origin
while((support = getSupport(lhs,rhs,direction)).sameDirection(direction)){
simplex.add(support);
direction = findSimplex(simplex);
// If the simplex has enclosed the origin then the two objects are colliding
if(direction.equals(Vector3.ZERO) || containsOrigin(simplex))
return true;
}
return false;
}
}
|
diff --git a/src/main/java/org/urbancode/terraform/tasks/aws/InstanceTask.java b/src/main/java/org/urbancode/terraform/tasks/aws/InstanceTask.java
index 9676bfd..4dcf25e 100644
--- a/src/main/java/org/urbancode/terraform/tasks/aws/InstanceTask.java
+++ b/src/main/java/org/urbancode/terraform/tasks/aws/InstanceTask.java
@@ -1,574 +1,574 @@
package org.urbancode.terraform.tasks.aws;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;
import org.urbancode.terraform.tasks.EnvironmentCreationException;
import org.urbancode.terraform.tasks.EnvironmentDestructionException;
import org.urbancode.terraform.tasks.aws.helpers.AWSHelper;
import org.urbancode.terraform.tasks.common.Task;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.BlockDeviceMapping;
import com.amazonaws.services.ec2.model.GroupIdentifier;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancing;
public class InstanceTask extends Task {
//**********************************************************************************************
// CLASS
//**********************************************************************************************
final static private Logger log = Logger.getLogger(InstanceTask.class);
//**********************************************************************************************
// INSTANCE
//**********************************************************************************************
private AmazonEC2 ec2Client;
private AmazonElasticLoadBalancing elbClient;
private AWSHelper helper;
protected ContextAWS context;
private boolean elasticIp;
private String name;
private String instanceId;
private String amiId;
private String subnetName;
private String subnetId;
private String elasticIpAllocId;
private String elasticIpAddress;
private String keyRef;
private String sizeType;
private String userData;
private String loadBalancer;
private String privateIp;
// default values
private int count = 1;
private int priority = 1;
private BootActionsTask bootActions;
private PostCreateActionsTask pca;
private List<SecurityGroupRefTask> secRefs = new ArrayList<SecurityGroupRefTask>();
private List<EbsTask> ebsVolumes = new ArrayList<EbsTask>();
//----------------------------------------------------------------------------------------------
public InstanceTask(ContextAWS context) {
this.context = context;
helper = context.getAWSHelper();
}
//----------------------------------------------------------------------------------------------
public void setPrivateIp(String privateIp) {
this.privateIp = privateIp;
}
//----------------------------------------------------------------------------------------------
public void setLoadBalancer(String loadBalancer) {
this.loadBalancer = loadBalancer;
}
//----------------------------------------------------------------------------------------------
public void setPriority(int priority) {
this.priority = priority;
}
//----------------------------------------------------------------------------------------------
public void setCount(int count) {
this.count = count;
}
//----------------------------------------------------------------------------------------------
public void setPrivateKeyRef(String keyRef) {
this.keyRef = keyRef;
}
//----------------------------------------------------------------------------------------------
public void setImageSize(String sizeType) {
this.sizeType = sizeType;
}
//----------------------------------------------------------------------------------------------
public void setName(String name) {
this.name = name;
}
//----------------------------------------------------------------------------------------------
public void setId(String id) {
this.instanceId = id;
}
//----------------------------------------------------------------------------------------------
public void setAmiId(String id) {
this.amiId = id;
}
//----------------------------------------------------------------------------------------------
public void setSubnetName(String name) {
this.subnetName = name;
}
//----------------------------------------------------------------------------------------------
public void setSubnetId(String id) {
this.subnetId = id;
}
//----------------------------------------------------------------------------------------------
public void setElasticIpAddress(String elasticIpAddress) {
this.elasticIpAddress = elasticIpAddress;
}
//----------------------------------------------------------------------------------------------
public void setElasticIp(boolean elasticIp) {
this.elasticIp = elasticIp;
}
//----------------------------------------------------------------------------------------------
public void setElasticIpAllocId(String id) {
this.elasticIpAllocId = id;
}
//----------------------------------------------------------------------------------------------
public String getPrivateIp() {
return privateIp;
}
//----------------------------------------------------------------------------------------------
public String getLoadBalancer() {
return loadBalancer;
}
//----------------------------------------------------------------------------------------------
public int getPriority() {
return priority;
}
//----------------------------------------------------------------------------------------------
public int getCount() {
return count;
}
//----------------------------------------------------------------------------------------------
public String getId() {
return instanceId;
}
//----------------------------------------------------------------------------------------------
public String getImageSize() {
return sizeType;
}
//----------------------------------------------------------------------------------------------
public String getPrivateKeyRef() {
return keyRef;
}
//----------------------------------------------------------------------------------------------
public String getName() {
return name;
}
//----------------------------------------------------------------------------------------------
public BootActionsTask getBootActions() {
return bootActions;
}
//----------------------------------------------------------------------------------------------
public PostCreateActionsTask getPostCreateActions() {
return pca;
}
//----------------------------------------------------------------------------------------------
public List<SecurityGroupRefTask> getSecurityGroupRefs() {
return Collections.unmodifiableList(secRefs);
}
//----------------------------------------------------------------------------------------------
public List<EbsTask> getEbsVolumes() {
return Collections.unmodifiableList(ebsVolumes);
}
//----------------------------------------------------------------------------------------------
public String getAmiId() {
return amiId;
}
//----------------------------------------------------------------------------------------------
public String getSubnetId() {
return subnetId;
}
//----------------------------------------------------------------------------------------------
public String getSubnetName() {
return subnetName;
}
//----------------------------------------------------------------------------------------------
public boolean getElasticIp() {
return elasticIp;
}
//----------------------------------------------------------------------------------------------
public String getElasticIpAllocId() {
return elasticIpAllocId;
}
//----------------------------------------------------------------------------------------------
public String getElasticIpAddress() {
return elasticIpAddress;
}
//----------------------------------------------------------------------------------------------
public EbsTask createEbs() {
EbsTask ebs = new EbsTask(context);
ebsVolumes.add(ebs);
return ebs;
}
//----------------------------------------------------------------------------------------------
public BootActionsTask createBootActions() {
this.bootActions = new BootActionsTask(context);
return bootActions;
}
//----------------------------------------------------------------------------------------------
public PostCreateActionsTask createPostCreateActions() {
this.pca = new PostCreateActionsTask(context);
return pca;
}
//----------------------------------------------------------------------------------------------
public SecurityGroupRefTask createSecurityGroupRef() {
SecurityGroupRefTask sec = new SecurityGroupRefTask(context);
secRefs.add(sec);
return sec;
}
//----------------------------------------------------------------------------------------------
private boolean verifyElasticIp(Instance instance) {
boolean result = false;
boolean hasEIP = instance.getPublicIpAddress() != null;
if (elasticIp == hasEIP) {
if (elasticIp == true) {
if (instance.getPublicIpAddress().equals(elasticIpAddress)) {
result = true;
}
}
else {
result = true;
}
}
return result;
}
//----------------------------------------------------------------------------------------------
private boolean verifyKeyPair(Instance instance) {
boolean result = false;
String keyName = context.getKeyByName(keyRef);
if (instance.getKeyName() != null && keyName != null) {
if (instance.getKeyName().equals(keyName)) {
result = true;
}
}
return result;
}
//----------------------------------------------------------------------------------------------
private boolean verifySize(Instance instance) {
boolean result = false;
String size = context.getSizeByName(sizeType);
if (instance.getInstanceType() != null && size != null) {
if (instance.getInstanceType().equals(size)) {
result = true;
}
}
return result;
}
//----------------------------------------------------------------------------------------------
private boolean verifySecurityGroups(Instance instance) throws Exception {
boolean result = false;
List<String> expectedIds = new ArrayList<String>();
for (SecurityGroupRefTask group : getSecurityGroupRefs()) {
expectedIds.add(group.fetchSecurityGroup().getId());
}
List<String> foundIds = new ArrayList<String>();
List<GroupIdentifier> gids = instance.getSecurityGroups();
if (gids != null && !gids.isEmpty()) {
for (GroupIdentifier gid : gids) {
foundIds.add(gid.getGroupId());
}
}
return result;
}
//----------------------------------------------------------------------------------------------
public boolean verify() throws Exception {
// will return false if the id is null
boolean result = false;
if (instanceId != null) {
if (ec2Client == null) {
ec2Client = context.getEC2Client();
}
List<String> id = new ArrayList<String>();
id.add(instanceId);
List<Instance> instances = helper.describeInstances(id, ec2Client);
if (instances != null && !instances.isEmpty()) {
for (Instance instance : instances) {
if (instance.getImageId().equals(amiId)) {
String subId = ((EnvironmentTaskAWS)context.getEnvironment()).getVpc().findSubnetForName(subnetName).getId();
if (instance.getSubnetId() != null && instance.getSubnetId().equals(subId)) {
if (verifyElasticIp(instance)) {
if (verifyKeyPair(instance)) {
if (verifySize(instance)) {
if (verifySecurityGroups(instance)) {
result = true;
}
}
}
}
}
}
}
}
}
return result;
}
//----------------------------------------------------------------------------------------------
@Override
public void create()
throws Exception {
log.debug("InstanceAWS: create()");
boolean verified = false;
context.setProperty("server.name", name); // update server.name prop
if (ec2Client == null) {
ec2Client = context.getEC2Client();
}
if (elbClient == null) {
elbClient = context.getELBClient();
}
try {
if (instanceId != null) {
verified = verify();
}
log.debug("Setting up Boot Actions");
if (getBootActions() != null) {
getBootActions().create();
userData = getBootActions().getUserData();
userData = context.resolve(userData);
}
log.info("Instance is being launched with following user-data script:\n\n" + userData);
String keyPair = keyRef;
String size = context.getSizeByName(sizeType.toLowerCase());
if (!verified) {
setId(null);
log.info("Creating Instance...");
// add security groups
List<String> groupIds = new ArrayList<String>();
for (SecurityGroupRefTask ref : getSecurityGroupRefs()) {
groupIds.add(ref.fetchSecurityGroup().getId());
}
// do Ebs
List<BlockDeviceMapping> blockMaps = new ArrayList<BlockDeviceMapping>();
if (ebsVolumes != null) {
for (EbsTask ebs : ebsVolumes) {
ebs.create();
blockMaps.add(ebs.getBlockDeviceMapping());
}
}
// set the instanceId
instanceId = helper.launchAmi(amiId, subnetId, keyPair, size, userData, groupIds, blockMaps, ec2Client);
// wait for instance to start and pass status checks
helper.waitForState(instanceId, "running", 8, ec2Client);
helper.waitForStatus(instanceId, "ok", 8, ec2Client);
// name Instances
String serverName = context.getEnvironment().getName() + "-" + name;
helper.tagInstance(instanceId, "Name", serverName, ec2Client);
// give instance elastic ip
if (elasticIp) {
setElasticIpAllocId(helper.requestElasticIp(ec2Client));
setElasticIpAddress(helper.assignElasticIp(instanceId, elasticIpAllocId, ec2Client));
context.setProperty(getName() + ".public.ip", getElasticIpAddress());
}
// set private ip
privateIp = helper.getPrivateIp(instanceId, ec2Client);
context.setProperty(getName() + ".private.ip", getPrivateIp());
// register with LB
List<String> tmp = new ArrayList<String>();
tmp.add(instanceId);
if (loadBalancer != null && !"".equals(loadBalancer)) {
helper.updateInstancesOnLoadBalancer(loadBalancer, tmp, true, elbClient);
}
// do PostCreateActions
if (pca != null) {
if (elasticIpAddress != null && !elasticIpAddress.isEmpty()) {
pca.setHost(elasticIpAddress);
}
else {
log.warn("Trying to do PostCreateActions on instance with no public ip!"
+ "\nName: " + name
+ "\nId: " + instanceId);
}
if (keyPair != null && !keyPair.isEmpty()) {
- String basePath = "/home/ncc/.ec2";
+ String basePath = System.getProperty("user.home") + File.separator + ".terraform";
String keyPairPath = basePath + File.separator + keyPair + ".pem";
pca.setIdFile(keyPairPath);
}
else {
log.warn("Trying to do PostCreateActions on instance with no ssh key!"
+ "\nName: " + name
+ "\nId: " + instanceId);
}
pca.create();
}
}
}
catch (Exception e) {
log.error("Did not start instance " + name + " completely");
throw new EnvironmentCreationException("Failed to create Instance " + name, e);
}
finally {
ec2Client = null;
elbClient = null;
}
}
//----------------------------------------------------------------------------------------------
@Override
public void destroy()
throws Exception {
if (ec2Client == null) {
ec2Client = context.getEC2Client();
}
if (elbClient == null) {
elbClient = context.getELBClient();
}
try {
log.info("Shutting down instance " + getId());
List<String> instanceIds = new ArrayList<String>();
instanceIds.add(instanceId);
if (loadBalancer != null && !"".equals(loadBalancer)) {
helper.updateInstancesOnLoadBalancer(loadBalancer, instanceIds, false, elbClient);
}
if (elasticIpAllocId != null) {
String assocId = helper.getAssociationIdForAllocationId(elasticIpAllocId, ec2Client);
helper.disassociateElasticIp(assocId, ec2Client);
helper.releaseElasticIp(getElasticIpAllocId(), ec2Client);
}
helper.terminateInstances(instanceIds, ec2Client);
helper.waitForState(getId(), "terminated", 8, ec2Client);
for (SecurityGroupRefTask group : secRefs) {
group.destroy();
}
// clear all attributes
setId(null);
setSubnetId(null);
setElasticIpAllocId(null);
setElasticIpAddress(null);
}
catch (Exception e) {
log.error("Did not destroy instance " + name + " completely");
throw new EnvironmentDestructionException("Failed to destroy instance " + name, e);
}
finally {
ec2Client = null;
elbClient = null;
log.info("Instance Destroyed.");
}
}
//----------------------------------------------------------------------------------------------
@Override
public InstanceTask clone() {
InstanceTask result = new InstanceTask(context);
// this takes up more memory than needed???
result.setAmiId(amiId);
result.setElasticIp(elasticIp);
result.setImageSize(sizeType);
result.setName(name);
result.setPrivateKeyRef(keyRef);
result.setSubnetName(subnetName);
// post create actions task
BootActionsTask pcat = result.createBootActions();
if (getPostCreateActions() != null) {
if (getBootActions().getShell() != null) {
pcat.setShell(getBootActions().getShell());
}
if (getBootActions().getScript() != null) {
for (PostCreateSubTask script : getBootActions().getScript()) {
ScriptTask scriptTask = (ScriptTask) script;
ScriptTask nScript = pcat.createScript();
nScript.setCmds(script.getCmds());
nScript.setShell(scriptTask.getShell());
nScript.setUrl(scriptTask.getUrl());
for (ParamTask param : scriptTask.getParams()) {
ParamTask nParam = nScript.createParam();
nParam.setValue(param.getValue());
}
}
}
}
// sec group refs
if (getSecurityGroupRefs() != null) {
for (SecurityGroupRefTask secGroup : getSecurityGroupRefs()) {
SecurityGroupRefTask nSecGroup = result.createSecurityGroupRef();
nSecGroup.setSecurityGroupName(secGroup.getSecurityGroupName());
}
}
// ebsVolumes
if (getEbsVolumes() != null) {
for (EbsTask ebs : getEbsVolumes()) {
EbsTask nEbs = result.createEbs();
nEbs.setVolumeSize(ebs.getVolumeSize());
nEbs.setVolumeId(ebs.getVolumeId());
nEbs.setSnapshotId(ebs.getSnapshotId());
nEbs.setPersist(ebs.getPersist());
nEbs.setName(ebs.getName());
nEbs.setDeviceName(ebs.getDeviceName());
}
}
return result;
}
}
| true | true | public void create()
throws Exception {
log.debug("InstanceAWS: create()");
boolean verified = false;
context.setProperty("server.name", name); // update server.name prop
if (ec2Client == null) {
ec2Client = context.getEC2Client();
}
if (elbClient == null) {
elbClient = context.getELBClient();
}
try {
if (instanceId != null) {
verified = verify();
}
log.debug("Setting up Boot Actions");
if (getBootActions() != null) {
getBootActions().create();
userData = getBootActions().getUserData();
userData = context.resolve(userData);
}
log.info("Instance is being launched with following user-data script:\n\n" + userData);
String keyPair = keyRef;
String size = context.getSizeByName(sizeType.toLowerCase());
if (!verified) {
setId(null);
log.info("Creating Instance...");
// add security groups
List<String> groupIds = new ArrayList<String>();
for (SecurityGroupRefTask ref : getSecurityGroupRefs()) {
groupIds.add(ref.fetchSecurityGroup().getId());
}
// do Ebs
List<BlockDeviceMapping> blockMaps = new ArrayList<BlockDeviceMapping>();
if (ebsVolumes != null) {
for (EbsTask ebs : ebsVolumes) {
ebs.create();
blockMaps.add(ebs.getBlockDeviceMapping());
}
}
// set the instanceId
instanceId = helper.launchAmi(amiId, subnetId, keyPair, size, userData, groupIds, blockMaps, ec2Client);
// wait for instance to start and pass status checks
helper.waitForState(instanceId, "running", 8, ec2Client);
helper.waitForStatus(instanceId, "ok", 8, ec2Client);
// name Instances
String serverName = context.getEnvironment().getName() + "-" + name;
helper.tagInstance(instanceId, "Name", serverName, ec2Client);
// give instance elastic ip
if (elasticIp) {
setElasticIpAllocId(helper.requestElasticIp(ec2Client));
setElasticIpAddress(helper.assignElasticIp(instanceId, elasticIpAllocId, ec2Client));
context.setProperty(getName() + ".public.ip", getElasticIpAddress());
}
// set private ip
privateIp = helper.getPrivateIp(instanceId, ec2Client);
context.setProperty(getName() + ".private.ip", getPrivateIp());
// register with LB
List<String> tmp = new ArrayList<String>();
tmp.add(instanceId);
if (loadBalancer != null && !"".equals(loadBalancer)) {
helper.updateInstancesOnLoadBalancer(loadBalancer, tmp, true, elbClient);
}
// do PostCreateActions
if (pca != null) {
if (elasticIpAddress != null && !elasticIpAddress.isEmpty()) {
pca.setHost(elasticIpAddress);
}
else {
log.warn("Trying to do PostCreateActions on instance with no public ip!"
+ "\nName: " + name
+ "\nId: " + instanceId);
}
if (keyPair != null && !keyPair.isEmpty()) {
String basePath = "/home/ncc/.ec2";
String keyPairPath = basePath + File.separator + keyPair + ".pem";
pca.setIdFile(keyPairPath);
}
else {
log.warn("Trying to do PostCreateActions on instance with no ssh key!"
+ "\nName: " + name
+ "\nId: " + instanceId);
}
pca.create();
}
}
}
catch (Exception e) {
log.error("Did not start instance " + name + " completely");
throw new EnvironmentCreationException("Failed to create Instance " + name, e);
}
finally {
ec2Client = null;
elbClient = null;
}
}
| public void create()
throws Exception {
log.debug("InstanceAWS: create()");
boolean verified = false;
context.setProperty("server.name", name); // update server.name prop
if (ec2Client == null) {
ec2Client = context.getEC2Client();
}
if (elbClient == null) {
elbClient = context.getELBClient();
}
try {
if (instanceId != null) {
verified = verify();
}
log.debug("Setting up Boot Actions");
if (getBootActions() != null) {
getBootActions().create();
userData = getBootActions().getUserData();
userData = context.resolve(userData);
}
log.info("Instance is being launched with following user-data script:\n\n" + userData);
String keyPair = keyRef;
String size = context.getSizeByName(sizeType.toLowerCase());
if (!verified) {
setId(null);
log.info("Creating Instance...");
// add security groups
List<String> groupIds = new ArrayList<String>();
for (SecurityGroupRefTask ref : getSecurityGroupRefs()) {
groupIds.add(ref.fetchSecurityGroup().getId());
}
// do Ebs
List<BlockDeviceMapping> blockMaps = new ArrayList<BlockDeviceMapping>();
if (ebsVolumes != null) {
for (EbsTask ebs : ebsVolumes) {
ebs.create();
blockMaps.add(ebs.getBlockDeviceMapping());
}
}
// set the instanceId
instanceId = helper.launchAmi(amiId, subnetId, keyPair, size, userData, groupIds, blockMaps, ec2Client);
// wait for instance to start and pass status checks
helper.waitForState(instanceId, "running", 8, ec2Client);
helper.waitForStatus(instanceId, "ok", 8, ec2Client);
// name Instances
String serverName = context.getEnvironment().getName() + "-" + name;
helper.tagInstance(instanceId, "Name", serverName, ec2Client);
// give instance elastic ip
if (elasticIp) {
setElasticIpAllocId(helper.requestElasticIp(ec2Client));
setElasticIpAddress(helper.assignElasticIp(instanceId, elasticIpAllocId, ec2Client));
context.setProperty(getName() + ".public.ip", getElasticIpAddress());
}
// set private ip
privateIp = helper.getPrivateIp(instanceId, ec2Client);
context.setProperty(getName() + ".private.ip", getPrivateIp());
// register with LB
List<String> tmp = new ArrayList<String>();
tmp.add(instanceId);
if (loadBalancer != null && !"".equals(loadBalancer)) {
helper.updateInstancesOnLoadBalancer(loadBalancer, tmp, true, elbClient);
}
// do PostCreateActions
if (pca != null) {
if (elasticIpAddress != null && !elasticIpAddress.isEmpty()) {
pca.setHost(elasticIpAddress);
}
else {
log.warn("Trying to do PostCreateActions on instance with no public ip!"
+ "\nName: " + name
+ "\nId: " + instanceId);
}
if (keyPair != null && !keyPair.isEmpty()) {
String basePath = System.getProperty("user.home") + File.separator + ".terraform";
String keyPairPath = basePath + File.separator + keyPair + ".pem";
pca.setIdFile(keyPairPath);
}
else {
log.warn("Trying to do PostCreateActions on instance with no ssh key!"
+ "\nName: " + name
+ "\nId: " + instanceId);
}
pca.create();
}
}
}
catch (Exception e) {
log.error("Did not start instance " + name + " completely");
throw new EnvironmentCreationException("Failed to create Instance " + name, e);
}
finally {
ec2Client = null;
elbClient = null;
}
}
|
diff --git a/src/de/caluga/morphium/Morphium.java b/src/de/caluga/morphium/Morphium.java
index eb7973f1..5df32345 100644
--- a/src/de/caluga/morphium/Morphium.java
+++ b/src/de/caluga/morphium/Morphium.java
@@ -1,2343 +1,2343 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.caluga.morphium;
import com.mongodb.*;
import de.caluga.morphium.annotations.*;
import de.caluga.morphium.annotations.ReadPreference;
import de.caluga.morphium.annotations.caching.Cache;
import de.caluga.morphium.annotations.caching.NoCache;
import de.caluga.morphium.annotations.lifecycle.*;
import de.caluga.morphium.annotations.security.NoProtection;
import de.caluga.morphium.cache.CacheElement;
import de.caluga.morphium.cache.CacheHousekeeper;
import de.caluga.morphium.replicaset.ConfNode;
import de.caluga.morphium.replicaset.ReplicaSetConf;
import de.caluga.morphium.replicaset.ReplicaSetNode;
import de.caluga.morphium.secure.MongoSecurityException;
import de.caluga.morphium.secure.MongoSecurityManager;
import de.caluga.morphium.secure.Permission;
import net.sf.cglib.proxy.Enhancer;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* This is the single access point for accessing MongoDB. This should
*
* @author stephan
*/
public final class Morphium {
/**
* singleton is usually not a good idea in j2ee-Context, but as we did it on
* several places in the Application it's the easiest way Usage:
* <code>
* MorphiumConfig cfg=new MorphiumConfig("testdb",false,false,10,5000,2500);
* cfg.addAddress("localhost",27017);
* Morphium.config=cfg;
* Morphium l=Morphium.get();
* if (l==null) {
* System.out.println("Error establishing connection!");
* System.exit(1);
* }
* </code>
*
* @see MorphiumConfig
*/
private final static Logger logger = Logger.getLogger(Morphium.class);
private MorphiumConfig config;
private Mongo mongo;
private DB database;
private ThreadPoolExecutor writers = new ThreadPoolExecutor(10, 50,
10000L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
//Cache by Type, query String -> CacheElement (contains list etc)
private Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cache;
private Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idCache;
private final Map<StatisticKeys, StatisticValue> stats;
private Map<Class<?>, Map<Class<? extends Annotation>, Method>> lifeCycleMethods;
/**
* String Representing current user - needs to be set by Application
*/
private String currentUser;
private CacheHousekeeper cacheHousekeeper;
private Vector<MorphiumStorageListener> listeners;
private Vector<ProfilingListener> profilingListeners;
private Vector<Thread> privileged;
private Vector<ShutdownListener> shutDownListeners;
public MorphiumConfig getConfig() {
return config;
}
// private boolean securityEnabled = false;
/**
* init the MongoDbLayer. Uses Morphium-Configuration Object for Configuration.
* Needs to be set before use or RuntimeException is thrown!
* all logging is done in INFO level
*
* @see MorphiumConfig
*/
public Morphium(MorphiumConfig cfg) {
if (cfg == null) {
throw new RuntimeException("Please specify configuration!");
}
config = cfg;
privileged = new Vector<Thread>();
shutDownListeners = new Vector<ShutdownListener>();
listeners = new Vector<MorphiumStorageListener>();
profilingListeners = new Vector<ProfilingListener>();
cache = new Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>();
idCache = new Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>>();
stats = new Hashtable<StatisticKeys, StatisticValue>();
lifeCycleMethods = new Hashtable<Class<?>, Map<Class<? extends Annotation>, Method>>();
for (StatisticKeys k : StatisticKeys.values()) {
stats.put(k, new StatisticValue());
}
//dummyUser.setGroupIds();
MongoOptions o = new MongoOptions();
o.autoConnectRetry = true;
o.fsync = true;
o.socketTimeout = config.getSocketTimeout();
o.connectTimeout = config.getConnectionTimeout();
o.connectionsPerHost = config.getMaxConnections();
o.socketKeepAlive = config.isSocketKeepAlive();
o.threadsAllowedToBlockForConnectionMultiplier = 5;
o.safe = false;
writers.setCorePoolSize(config.getMaxConnections() / 2);
writers.setMaximumPoolSize(config.getMaxConnections());
if (config.getAdr().isEmpty()) {
throw new RuntimeException("Error - no server address specified!");
}
switch (config.getMode()) {
case REPLICASET:
if (config.getAdr().size() < 2) {
throw new RuntimeException("at least 2 Server Adresses needed for MongoDB in ReplicaSet Mode!");
}
mongo = new Mongo(config.getAdr(), o);
break;
case PAIRED:
throw new RuntimeException("PAIRED Mode not available anymore!!!!");
// if (config.getAdr().size() != 2) {
// morphia = null;
// dataStore = null;
// throw new RuntimeException("2 Server Adresses needed for MongoDB in Paired Mode!");
// }
//
// morphium = new Mongo(config.getAdr().get(0), config.getAdr().get(1), o);
// break;
case SINGLE:
default:
if (config.getAdr().size() > 1) {
// Logger.getLogger(Morphium.class.getName()).warning("WARNING: ignoring additional server Adresses only using 1st!");
}
mongo = new Mongo(config.getAdr().get(0), o);
break;
}
database = mongo.getDB(config.getDatabase());
if (config.isSlaveOk()) {
mongo.setReadPreference(com.mongodb.ReadPreference.SECONDARY);
}
if (config.getMongoLogin() != null) {
if (!database.authenticate(config.getMongoLogin(), config.getMongoPassword().toCharArray())) {
throw new RuntimeException("Authentication failed!");
}
}
// int cnt = database.getCollection("system.indexes").find().count(); //test connection
if (config.getConfigManager() == null) {
config.setConfigManager(new ConfigManagerImpl());
}
config.getConfigManager().setMorphium(this);
cacheHousekeeper = new CacheHousekeeper(this, 5000, config.getGlobalCacheValidTime());
cacheHousekeeper.start();
config.getConfigManager().startCleanupThread();
if (config.getMapper() == null) {
config.setMapper(new ObjectMapperImpl(this));
} else {
config.getMapper().setMorphium(this);
}
logger.info("Initialization successful...");
}
public void addListener(MorphiumStorageListener lst) {
listeners.add(lst);
}
public void removeListener(MorphiumStorageListener lst) {
listeners.remove(lst);
}
public Mongo getMongo() {
return mongo;
}
public DB getDatabase() {
return database;
}
public ConfigManager getConfigManager() {
return config.getConfigManager();
}
/**
* search for objects similar to template concerning all given fields.
* If no fields are specified, all NON Null-Fields are taken into account
* if specified, field might also be null
*
* @param template
* @param fields
* @param <T>
* @return
*/
public <T> List<T> findByTemplate(T template, String... fields) {
Class cls = template.getClass();
List<String> flds = new ArrayList<String>();
if (fields.length > 0) {
flds.addAll(Arrays.asList(fields));
} else {
flds = getFields(cls);
}
Query<T> q = createQueryFor(cls);
for (String f : flds) {
try {
q.f(f).eq(getValue(template, f));
} catch (Exception e) {
logger.error("Could not read field " + f + " of object " + cls.getName());
}
}
return q.asList();
}
public void unset(Object toSet, Enum field) {
unset(toSet, field.name());
}
/**
* can be called for autmatic index ensurance. Attention: might cause heavy load on mongo
* will be called automatically if a new collection is created
*
* @param type
*/
public void ensureIndicesFor(Class type) {
if (isAnnotationPresentInHierarchy(type, Index.class)) {
//type must be marked as to be indexed
List<Annotation> lst = getAllAnnotationsFromHierachy(type, Index.class);
for (Annotation a : lst) {
Index i = (Index) a;
if (i.value().length > 0) {
for (String idx : i.value()) {
String[] idxStr = idx.replaceAll(" +", "").split(",");
ensureIndex(type, idxStr);
}
}
}
List<String> flds = config.getMapper().getFields(type, Index.class);
if (flds != null && flds.size() > 0) {
for (String f : flds) {
Index i = config.getMapper().getField(type, f).getAnnotation(Index.class);
if (i.decrement()) {
ensureIndex(type, "-" + f);
} else {
ensureIndex(type, f);
}
}
}
}
}
/**
* Un-setting a value in an existing mongo collection entry - no reading necessary. Object is altered in place
* db.collection.update({"_id":toSet.id},{$unset:{field:1}}
* <b>attention</b>: this alteres the given object toSet in a similar way
*
* @param toSet: object to set the value in (or better - the corresponding entry in mongo)
* @param field: field to remove from document
*/
public void unset(Object toSet, String field) {
if (toSet == null) throw new RuntimeException("Cannot update null!");
if (getId(toSet) == null) {
logger.info("just storing object as it is new...");
store(toSet);
}
Class cls = toSet.getClass();
firePreUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.UNSET);
String coll = config.getMapper().getCollectionName(cls);
BasicDBObject query = new BasicDBObject();
query.put("_id", getId(toSet));
Field f = getField(cls, field);
if (f == null) {
throw new RuntimeException("Unknown field: " + field);
}
String fieldName = getFieldName(cls, field);
BasicDBObject update = new BasicDBObject("$unset", new BasicDBObject(fieldName, 1));
WriteConcern wc = getWriteConcernForClass(toSet.getClass());
if (!database.collectionExists(coll)) {
ensureIndicesFor(cls);
}
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(coll).update(query, update);
} else {
database.getCollection(coll).update(query, update, false, false, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(toSet.getClass(), update, dur, false, WriteAccessType.SINGLE_UPDATE);
clearCacheIfNecessary(cls);
try {
f.set(toSet, null);
} catch (IllegalAccessException e) {
//May happen, if null is not allowed for example
}
firePostUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.UNSET);
}
private void clearCacheIfNecessary(Class cls) {
Cache c = getAnnotationFromHierarchy(cls, Cache.class); //cls.getAnnotation(Cache.class);
if (c != null) {
if (c.clearOnWrite()) {
clearCachefor(cls);
}
}
}
private DBObject simplifyQueryObject(DBObject q) {
if (q.keySet().size() == 1 && q.get("$and") != null) {
BasicDBObject ret = new BasicDBObject();
BasicDBList lst = (BasicDBList) q.get("$and");
for (Object o : lst) {
if (o instanceof DBObject) {
ret.putAll(((DBObject) o));
} else if (o instanceof Map) {
ret.putAll(((Map) o));
} else {
//something we cannot handle
return q;
}
}
return ret;
}
return q;
}
public void set(Query<?> query, Enum field, Object val) {
set(query, field.name(), val);
}
public void set(Query<?> query, String field, Object val) {
set(query, field, val, false, false);
}
public void setEnum(Query<?> query, Map<Enum, Object> values, boolean insertIfNotExist, boolean multiple) {
HashMap<String, Object> toSet = new HashMap<String, Object>();
for (Map.Entry<Enum, Object> est : values.entrySet()) {
toSet.put(est.getKey().name(), values.get(est.getValue()));
}
set(query, toSet, insertIfNotExist, multiple);
}
public void push(Query<?> query, Enum field, Object value) {
pushPull(true, query, field.name(), value, false, true);
}
public void pull(Query<?> query, Enum field, Object value) {
pushPull(false, query, field.name(), value, false, true);
}
public void push(Query<?> query, String field, Object value) {
pushPull(true, query, field, value, false, true);
}
public void pull(Query<?> query, String field, Object value) {
pushPull(false, query, field, value, false, true);
}
public void push(Query<?> query, Enum field, Object value, boolean insertIfNotExist, boolean multiple) {
pushPull(true, query, field.name(), value, insertIfNotExist, multiple);
}
public void pull(Query<?> query, Enum field, Object value, boolean insertIfNotExist, boolean multiple) {
pushPull(false, query, field.name(), value, insertIfNotExist, multiple);
}
public void pushAll(Query<?> query, Enum field, List<Object> value, boolean insertIfNotExist, boolean multiple) {
pushPullAll(true, query, field.name(), value, insertIfNotExist, multiple);
}
public void pullAll(Query<?> query, Enum field, List<Object> value, boolean insertIfNotExist, boolean multiple) {
pushPullAll(false, query, field.name(), value, insertIfNotExist, multiple);
}
public void push(Query<?> query, String field, Object value, boolean insertIfNotExist, boolean multiple) {
pushPull(true, query, field, value, insertIfNotExist, multiple);
}
public void pull(Query<?> query, String field, Object value, boolean insertIfNotExist, boolean multiple) {
pushPull(false, query, field, value, insertIfNotExist, multiple);
}
public void pushAll(Query<?> query, String field, List<Object> value, boolean insertIfNotExist, boolean multiple) {
pushPullAll(true, query, field, value, insertIfNotExist, multiple);
}
public void pullAll(Query<?> query, String field, List<Object> value, boolean insertIfNotExist, boolean multiple) {
pushPull(false, query, field, value, insertIfNotExist, multiple);
}
private void pushPull(boolean push, Query<?> query, String field, Object value, boolean insertIfNotExist, boolean multiple) {
Class<?> cls = query.getType();
firePreUpdateEvent(getRealClass(cls), push ? MorphiumStorageListener.UpdateTypes.PUSH : MorphiumStorageListener.UpdateTypes.PULL);
String coll = config.getMapper().getCollectionName(cls);
DBObject qobj = query.toQueryObject();
if (insertIfNotExist) {
qobj = simplifyQueryObject(qobj);
}
field = config.getMapper().getFieldName(cls, field);
BasicDBObject set = new BasicDBObject(field, value);
BasicDBObject update = new BasicDBObject(push ? "$push" : "$pull", set);
pushIt(push, insertIfNotExist, multiple, cls, coll, qobj, update);
}
private void pushIt(boolean push, boolean insertIfNotExist, boolean multiple, Class<?> cls, String coll, DBObject qobj, BasicDBObject update) {
if (!database.collectionExists(coll) && insertIfNotExist) {
ensureIndicesFor(cls);
}
WriteConcern wc = getWriteConcernForClass(cls);
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(coll).update(qobj, update, insertIfNotExist, multiple);
} else {
database.getCollection(coll).update(qobj, update, insertIfNotExist, multiple, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, update, dur, insertIfNotExist, multiple ? WriteAccessType.BULK_UPDATE : WriteAccessType.SINGLE_UPDATE);
clearCacheIfNecessary(cls);
firePostUpdateEvent(getRealClass(cls), push ? MorphiumStorageListener.UpdateTypes.PUSH : MorphiumStorageListener.UpdateTypes.PULL);
}
private void pushPullAll(boolean push, Query<?> query, String field, List<Object> value, boolean insertIfNotExist, boolean multiple) {
Class<?> cls = query.getType();
String coll = config.getMapper().getCollectionName(cls);
firePreUpdateEvent(getRealClass(cls), push ? MorphiumStorageListener.UpdateTypes.PUSH : MorphiumStorageListener.UpdateTypes.PULL);
BasicDBList dbl = new BasicDBList();
dbl.addAll(value);
DBObject qobj = query.toQueryObject();
if (insertIfNotExist) {
qobj = simplifyQueryObject(qobj);
}
field = config.getMapper().getFieldName(cls, field);
BasicDBObject set = new BasicDBObject(field, value);
BasicDBObject update = new BasicDBObject(push ? "$pushAll" : "$pullAll", set);
pushIt(push, insertIfNotExist, multiple, cls, coll, qobj, update);
}
/**
* will change an entry in mongodb-collection corresponding to given class object
* if query is too complex, upsert might not work!
* Upsert should consist of single and-queries, which will be used to generate the object to create, unless
* it already exists. look at Mongodb-query documentation as well
*
* @param query - query to specify which objects should be set
* @param values - map fieldName->Value, which values are to be set!
* @param insertIfNotExist - insert, if it does not exist (query needs to be simple!)
* @param multiple - update several documents, if false, only first hit will be updated
*/
public void set(Query<?> query, Map<String, Object> values, boolean insertIfNotExist, boolean multiple) {
Class<?> cls = query.getType();
String coll = config.getMapper().getCollectionName(cls);
firePreUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.SET);
BasicDBObject toSet = new BasicDBObject();
for (Map.Entry<String, Object> ef : values.entrySet()) {
String fieldName = getFieldName(cls, ef.getKey());
toSet.put(fieldName, ef.getValue());
}
DBObject qobj = query.toQueryObject();
if (insertIfNotExist) {
qobj = simplifyQueryObject(qobj);
}
if (insertIfNotExist && !database.collectionExists(coll)) {
ensureIndicesFor(cls);
}
BasicDBObject update = new BasicDBObject("$set", toSet);
WriteConcern wc = getWriteConcernForClass(cls);
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(coll).update(qobj, update, insertIfNotExist, multiple);
} else {
database.getCollection(coll).update(qobj, update, insertIfNotExist, multiple, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, update, dur, insertIfNotExist, multiple ? WriteAccessType.BULK_UPDATE : WriteAccessType.SINGLE_UPDATE);
clearCacheIfNecessary(cls);
firePostUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.SET);
}
/**
* will change an entry in mongodb-collection corresponding to given class object
* if query is too complex, upsert might not work!
* Upsert should consist of single and-queries, which will be used to generate the object to create, unless
* it already exists. look at Mongodb-query documentation as well
*
* @param query - query to specify which objects should be set
* @param field - field to set
* @param val - value to set
* @param insertIfNotExist - insert, if it does not exist (query needs to be simple!)
* @param multiple - update several documents, if false, only first hit will be updated
*/
public void set(Query<?> query, String field, Object val, boolean insertIfNotExist, boolean multiple) {
Map<String, Object> map = new HashMap<String, Object>();
map.put(field, val);
set(query, map, insertIfNotExist, multiple);
}
public void dec(Query<?> query, Enum field, int amount, boolean insertIfNotExist, boolean multiple) {
dec(query, field.name(), amount, insertIfNotExist, multiple);
}
public void dec(Query<?> query, String field, int amount, boolean insertIfNotExist, boolean multiple) {
inc(query, field, -amount, insertIfNotExist, multiple);
}
public void dec(Query<?> query, String field, int amount) {
inc(query, field, -amount, false, false);
}
public void dec(Query<?> query, Enum field, int amount) {
inc(query, field, -amount, false, false);
}
public void inc(Query<?> query, String field, int amount) {
inc(query, field, amount, false, false);
}
public void inc(Query<?> query, Enum field, int amount) {
inc(query, field, amount, false, false);
}
public void inc(Query<?> query, Enum field, int amount, boolean insertIfNotExist, boolean multiple) {
inc(query, field.name(), amount, insertIfNotExist, multiple);
}
public void inc(Query<?> query, String field, int amount, boolean insertIfNotExist, boolean multiple) {
Class<?> cls = query.getType();
firePreUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.INC);
String coll = config.getMapper().getCollectionName(cls);
String fieldName = getFieldName(cls, field);
BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject(fieldName, amount));
DBObject qobj = query.toQueryObject();
if (insertIfNotExist) {
qobj = simplifyQueryObject(qobj);
}
if (insertIfNotExist && !database.collectionExists(coll)) {
ensureIndicesFor(cls);
}
WriteConcern wc = getWriteConcernForClass(cls);
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(coll).update(qobj, update, insertIfNotExist, multiple);
} else {
database.getCollection(coll).update(qobj, update, insertIfNotExist, multiple, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, update, dur, insertIfNotExist, multiple ? WriteAccessType.BULK_UPDATE : WriteAccessType.SINGLE_UPDATE);
clearCacheIfNecessary(cls);
firePostUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.INC);
}
public void set(Object toSet, Enum field, Object value) {
set(toSet, field.name(), value);
}
/**
* setting a value in an existing mongo collection entry - no reading necessary. Object is altered in place
* db.collection.update({"_id":toSet.id},{$set:{field:value}}
* <b>attention</b>: this alteres the given object toSet in a similar way
*
* @param toSet: object to set the value in (or better - the corresponding entry in mongo)
* @param field: the field to change
* @param value: the value to set
*/
public void set(Object toSet, String field, Object value) {
if (toSet == null) throw new RuntimeException("Cannot update null!");
if (getId(toSet) == null) {
logger.info("just storing object as it is new...");
storeNoCache(toSet);
}
Class cls = toSet.getClass();
firePreUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.SET);
String coll = config.getMapper().getCollectionName(cls);
BasicDBObject query = new BasicDBObject();
query.put("_id", getId(toSet));
Field f = getField(cls, field);
if (f == null) {
throw new RuntimeException("Unknown field: " + field);
}
String fieldName = getFieldName(cls, field);
BasicDBObject update = new BasicDBObject("$set", new BasicDBObject(fieldName, value));
WriteConcern wc = getWriteConcernForClass(toSet.getClass());
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(coll).update(query, update);
} else {
database.getCollection(coll).update(query, update, false, false, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, update, dur, false, WriteAccessType.SINGLE_UPDATE);
clearCacheIfNecessary(cls);
try {
f.set(toSet, value);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
firePostUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.SET);
}
/**
* decreasing a value of a given object
* calles <code>inc(toDec,field,-amount);</code>
*/
public void dec(Object toDec, String field, int amount) {
inc(toDec, field, -amount);
}
/**
* Increases a value in an existing mongo collection entry - no reading necessary. Object is altered in place
* db.collection.update({"_id":toInc.id},{$inc:{field:amount}}
* <b>attention</b>: this alteres the given object toSet in a similar way
*
* @param toInc: object to set the value in (or better - the corresponding entry in mongo)
* @param field: the field to change
* @param amount: the value to set
*/
public void inc(Object toInc, String field, int amount) {
if (toInc == null) throw new RuntimeException("Cannot update null!");
if (getId(toInc) == null) {
logger.info("just storing object as it is new...");
storeNoCache(toInc);
}
Class cls = toInc.getClass();
firePreUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.INC);
String coll = config.getMapper().getCollectionName(cls);
BasicDBObject query = new BasicDBObject();
query.put("_id", getId(toInc));
Field f = getField(cls, field);
if (f == null) {
throw new RuntimeException("Unknown field: " + field);
}
String fieldName = getFieldName(cls, field);
BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject(fieldName, amount));
WriteConcern wc = getWriteConcernForClass(toInc.getClass());
if (wc == null) {
database.getCollection(coll).update(query, update);
} else {
database.getCollection(coll).update(query, update, false, false, wc);
}
clearCacheIfNecessary(cls);
//TODO: check inf necessary
if (f.getType().equals(Integer.class) || f.getType().equals(int.class)) {
try {
f.set(toInc, ((Integer) f.get(toInc)) + (int) amount);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} else if (f.getType().equals(Double.class) || f.getType().equals(double.class)) {
try {
f.set(toInc, ((Double) f.get(toInc)) + amount);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} else if (f.getType().equals(Float.class) || f.getType().equals(float.class)) {
try {
f.set(toInc, ((Float) f.get(toInc)) + (float) amount);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} else if (f.getType().equals(Long.class) || f.getType().equals(long.class)) {
try {
f.set(toInc, ((Long) f.get(toInc)) + (long) amount);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} else {
logger.error("Could not set increased value - unsupported type " + cls.getName());
}
firePostUpdateEvent(getRealClass(cls), MorphiumStorageListener.UpdateTypes.INC);
}
public void setIdCache(Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> c) {
idCache = c;
}
/**
* adds some list of objects to the cache manually...
* is being used internally, and should be used with care
*
* @param k - Key, usually the mongodb query string
* @param type - class type
* @param ret - list of results
* @param <T> - Type of record
*/
public <T extends Object> void addToCache(String k, Class<? extends Object> type, List<T> ret) {
if (k == null) {
return;
}
if (ret != null) {
//copy from idCache
Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idCacheClone = cloneIdCache();
for (T record : ret) {
if (idCacheClone.get(type) == null) {
idCacheClone.put(type, new Hashtable<ObjectId, Object>());
}
idCacheClone.get(type).put(config.getMapper().getId(record), record);
}
setIdCache(idCacheClone);
}
CacheElement e = new CacheElement(ret);
e.setLru(System.currentTimeMillis());
Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cl = (Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>) cache.clone();
if (cl.get(type) == null) {
cl.put(type, new Hashtable<String, CacheElement>());
}
cl.get(type).put(k, e);
//atomar execution of this operand - no synchronization needed
cache = cl;
}
protected void setPrivilegedThread(Thread thr) {
}
protected void inc(StatisticKeys k) {
stats.get(k).inc();
}
public String toJsonString(Object o) {
return config.getMapper().marshall(o).toString();
}
public int writeBufferCount() {
return writers.getQueue().size();
}
public String getCacheKey(DBObject qo, Map<String, Integer> sort, int skip, int limit) {
StringBuffer b = new StringBuffer();
b.append(qo.toString());
b.append(" l:");
b.append(limit);
b.append(" s:");
b.append(skip);
if (sort != null) {
b.append(" sort:");
b.append(new BasicDBObject(sort).toString());
}
return b.toString();
}
/**
* create unique cache key for queries, also honoring skip & limit and sorting
*
* @param q
* @return
*/
public String getCacheKey(Query q) {
return getCacheKey(q.toQueryObject(), q.getOrder(), q.getSkip(), q.getLimit());
}
private void storeNoCacheUsingFields(Object ent, String... fields) {
ObjectId id = getId(ent);
if (ent == null) return;
if (id == null) {
//new object - update not working
logger.warn("trying to partially update new object - storing it in full!");
storeNoCache(ent);
return;
}
firePreStoreEvent(ent, false);
inc(StatisticKeys.WRITES);
DBObject find = new BasicDBObject();
find.put("_id", id);
DBObject update = new BasicDBObject();
for (String f : fields) {
try {
Object value = getValue(ent, f);
if (isAnnotationPresentInHierarchy(value.getClass(), Entity.class)) {
value = config.getMapper().marshall(value);
}
update.put(f, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Class<?> type = getRealClass(ent.getClass());
StoreLastChange t = getAnnotationFromHierarchy(type, StoreLastChange.class); //(StoreLastChange) type.getAnnotation(StoreLastChange.class);
if (t != null) {
List<String> lst = config.getMapper().getFields(ent.getClass(), LastChange.class);
long now = System.currentTimeMillis();
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(ent, now);
} catch (IllegalAccessException e) {
logger.error("Could not set modification time", e);
}
}
update.put(ctf, now);
}
lst = config.getMapper().getFields(ent.getClass(), LastChangeBy.class);
if (lst != null && lst.size() != 0) {
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(ent, config.getSecurityMgr().getCurrentUserId());
} catch (IllegalAccessException e) {
logger.error("Could not set changed by", e);
}
}
update.put(ctf, config.getSecurityMgr().getCurrentUserId());
}
}
}
update = new BasicDBObject("$set", update);
WriteConcern wc = getWriteConcernForClass(type);
long start = System.currentTimeMillis();
if (wc != null) {
database.getCollection(config.getMapper().getCollectionName(ent.getClass())).update(find, update, false, false, wc);
} else {
database.getCollection(config.getMapper().getCollectionName(ent.getClass())).update(find, update, false, false);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(ent.getClass(), update, dur, false, WriteAccessType.SINGLE_UPDATE);
clearCacheIfNecessary(getRealClass(ent.getClass()));
firePostStoreEvent(ent, false);
}
/**
* updating an enty in DB without sending the whole entity
* only transfers the fields to be changed / set
*
* @param ent
* @param fields
*/
public void updateUsingFields(final Object ent, final String... fields) {
if (ent == null) return;
if (fields.length == 0) return; //not doing an update - no change
if (!isAnnotationPresentInHierarchy(ent.getClass(), NoProtection.class)) {
if (getId(ent) == null) {
if (accessDenied(ent, Permission.INSERT)) {
throw new SecurityException("Insert of new Object denied!");
}
} else {
if (accessDenied(ent, Permission.UPDATE)) {
throw new SecurityException("Update of Object denied!");
}
}
}
if (isAnnotationPresentInHierarchy(ent.getClass(), NoCache.class)) {
storeNoCacheUsingFields(ent, fields);
return;
}
Cache cc = getAnnotationFromHierarchy(ent.getClass(), Cache.class); //ent.getClass().getAnnotation(Cache.class);
if (cc != null) {
if (cc.writeCache()) {
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCacheUsingFields(ent, fields);
}
});
inc(StatisticKeys.WRITES_CACHED);
} else {
storeNoCacheUsingFields(ent, fields);
}
} else {
storeNoCacheUsingFields(ent, fields);
}
}
public List<Annotation> getAllAnnotationsFromHierachy(Class<?> cls, Class<? extends Annotation>... anCls) {
cls = getRealClass(cls);
List<Annotation> ret = new ArrayList<Annotation>();
Class<?> z = cls;
while (!z.equals(Object.class)) {
if (z.getAnnotations() != null && z.getAnnotations().length != 0) {
if (anCls.length == 0) {
ret.addAll(Arrays.asList(z.getAnnotations()));
} else {
for (Annotation a : z.getAnnotations()) {
for (Class<? extends Annotation> ac : anCls) {
if (a.annotationType().equals(ac)) {
ret.add(a);
}
}
}
}
}
z = z.getSuperclass();
if (z == null) break;
}
return ret;
}
/**
* returns annotations, even if in class hierarchy or
* lazyloading proxy
*
* @param cls
* @return
*/
public <T extends Annotation> T getAnnotationFromHierarchy(Class<?> cls, Class<T> anCls) {
cls = getRealClass(cls);
if (cls.isAnnotationPresent(anCls)) {
return cls.getAnnotation(anCls);
}
//class hierarchy?
Class<?> z = cls;
while (!z.equals(Object.class)) {
if (z.isAnnotationPresent(anCls)) {
return z.getAnnotation(anCls);
}
z = z.getSuperclass();
if (z == null) break;
}
return null;
}
private Class<?> getRealClass(Class<?> cls) {
return config.getMapper().getRealClass(cls);
}
private <T> T getRealObject(T o) {
return config.getMapper().getRealObject(o);
}
public <T extends Annotation> boolean isAnnotationPresentInHierarchy(Class<?> cls, Class<T> anCls) {
return getAnnotationFromHierarchy(cls, anCls) != null;
}
public void callLifecycleMethod(Class<? extends Annotation> type, Object on) {
if (on == null) return;
//No synchronized block - might cause the methods to be put twice into the
//hashtabel - but for performance reasons, it's ok...
Class<?> cls = on.getClass();
//No Lifecycle annotation - no method calling
if (!isAnnotationPresentInHierarchy(cls, Lifecycle.class)) {//cls.isAnnotationPresent(Lifecycle.class)) {
return;
}
//Already stored - should not change during runtime
if (lifeCycleMethods.get(cls) != null) {
if (lifeCycleMethods.get(cls).get(type) != null) {
try {
lifeCycleMethods.get(cls).get(type).invoke(on);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
return;
}
Map<Class<? extends Annotation>, Method> methods = new HashMap<Class<? extends Annotation>, Method>();
//Methods must be public
for (Method m : cls.getMethods()) {
for (Annotation a : m.getAnnotations()) {
methods.put(a.annotationType(), m);
}
}
lifeCycleMethods.put(cls, methods);
if (methods.get(type) != null) {
try {
methods.get(type).invoke(on);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
/**
* careful this actually changes the parameter o!
*
* @param o
* @param <T>
* @return
*/
public <T> T reread(T o) {
if (o == null) throw new RuntimeException("Cannot re read null!");
ObjectId id = getId(o);
if (id == null) {
return null;
}
DBCollection col = database.getCollection(getConfig().getMapper().getCollectionName(o.getClass()));
BasicDBObject srch = new BasicDBObject("_id", id);
DBCursor crs = col.find(srch).limit(1);
if (crs.hasNext()) {
DBObject dbo = crs.next();
Object fromDb = getConfig().getMapper().unmarshall(o.getClass(), dbo);
List<String> flds = getFields(o.getClass());
for (String f : flds) {
Field fld = getConfig().getMapper().getField(o.getClass(), f);
if (java.lang.reflect.Modifier.isStatic(fld.getModifiers())) {
continue;
}
try {
fld.set(o, fld.get(fromDb));
} catch (IllegalAccessException e) {
logger.error("Could not set Value: " + fld);
}
}
} else {
logger.info("Did not find object with id " + id);
return null;
}
return o;
}
private void firePreStoreEvent(Object o, boolean isNew) {
if (o == null) return;
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preStore(o, isNew);
}
callLifecycleMethod(PreStore.class, o);
}
private void firePostStoreEvent(Object o, boolean isNew) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postStore(o, isNew);
}
callLifecycleMethod(PostStore.class, o);
//existing object => store last Access, if needed
}
private void firePreDropEvent(Class cls) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preDrop(cls);
}
}
private void firePostDropEvent(Class cls) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postDrop(cls);
}
}
private void firePostUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) {
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postUpdate(cls, t);
}
}
private void firePreUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) {
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preUpdate(cls, t);
}
}
private void firePostRemoveEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postRemove(o);
}
callLifecycleMethod(PostRemove.class, o);
}
private void firePostRemoveEvent(Query q) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postRemove(q);
}
//TODO: FIX - Cannot call lifecycle method here
}
private void firePreRemoveEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preDelete(o);
}
callLifecycleMethod(PreRemove.class, o);
}
private void firePreRemoveEvent(Query q) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preRemove(q);
}
//TODO: Fix - cannot call lifecycle method
}
// private void firePreListStoreEvent(List records, Map<Object,Boolean> isNew) {
// //Avoid concurrent modification exception
// List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
// for (MorphiumStorageListener l : lst) {
// l.preListStore(records,isNew);
// }
// for (Object o : records) {
// callLifecycleMethod(PreStore.class, o);
// }
// }
// private void firePostListStoreEvent(List records, Map<Object,Boolean> isNew) {
// //Avoid concurrent modification exception
// List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
// for (MorphiumStorageListener l : lst) {
// l.postListStore(records,isNew);
// }
// for (Object o : records) {
// callLifecycleMethod(PostStore.class, o);
// }
//
// }
/**
* will be called by query after unmarshalling
*
* @param o
*/
protected void firePostLoadEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postLoad(o);
}
callLifecycleMethod(PostLoad.class, o);
}
public void storeNoCache(Object o) {
long start = System.currentTimeMillis();
Class type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, Entity.class)) {
throw new RuntimeException("Not an entity! Storing not possible!");
}
inc(StatisticKeys.WRITES);
ObjectId id = config.getMapper().getId(o);
if (isAnnotationPresentInHierarchy(type, PartialUpdate.class)) {
if ((o instanceof PartiallyUpdateable)) {
updateUsingFields(o, ((PartiallyUpdateable) o).getAlteredFields().toArray(new String[((PartiallyUpdateable) o).getAlteredFields().size()]));
((PartiallyUpdateable) o).clearAlteredFields();
return;
}
}
o = getRealObject(o);
if (o == null) {
logger.warn("Illegal Reference? - cannot store Lazy-Loaded / Partial Update Proxy without delegate!");
return;
}
boolean isNew = id == null;
firePreStoreEvent(o, isNew);
long dur = System.currentTimeMillis() - start;
DBObject marshall = config.getMapper().marshall(o);
if (isNew) {
//new object - need to store creation time
if (isAnnotationPresentInHierarchy(type, StoreCreationTime.class)) {
List<String> lst = config.getMapper().getFields(type, CreationTime.class);
if (lst == null || lst.size() == 0) {
logger.error("Unable to store creation time as @CreationTime is missing");
} else {
long now = System.currentTimeMillis();
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, now);
} catch (IllegalAccessException e) {
logger.error("Could not set creation time", e);
}
}
marshall.put(ctf, now);
}
}
lst = config.getMapper().getFields(type, CreatedBy.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, config.getSecurityMgr().getCurrentUserId());
} catch (IllegalAccessException e) {
logger.error("Could not set created by", e);
}
}
marshall.put(ctf, config.getSecurityMgr().getCurrentUserId());
}
}
}
}
if (isAnnotationPresentInHierarchy(type, StoreLastChange.class)) {
List<String> lst = config.getMapper().getFields(type, LastChange.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
long now = System.currentTimeMillis();
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, now);
} catch (IllegalAccessException e) {
logger.error("Could not set modification time", e);
}
}
marshall.put(ctf, now);
}
} else {
logger.warn("Could not store last change - @LastChange missing!");
}
lst = config.getMapper().getFields(type, LastChangeBy.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, config.getSecurityMgr().getCurrentUserId());
} catch (IllegalAccessException e) {
logger.error("Could not set changed by", e);
}
}
marshall.put(ctf, config.getSecurityMgr().getCurrentUserId());
}
}
}
String coll = config.getMapper().getCollectionName(type);
if (!database.collectionExists(coll)) {
if (logger.isDebugEnabled())
logger.debug("Collection does not exist - ensuring indices");
ensureIndicesFor(type);
}
WriteConcern wc = getWriteConcernForClass(type);
if (wc != null) {
database.getCollection(coll).save(marshall, wc);
} else {
database.getCollection(coll).save(marshall);
}
dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(o.getClass(), marshall, dur, true, WriteAccessType.SINGLE_INSERT);
if (logger.isDebugEnabled()) {
String n = "";
if (isNew) {
n = "NEW ";
}
logger.debug(n + "stored " + type.getSimpleName() + " after " + dur + " ms length:" + marshall.toString().length());
}
if (isNew) {
List<String> flds = config.getMapper().getFields(o.getClass(), Id.class);
if (flds == null) {
throw new RuntimeException("Object does not have an ID field!");
}
try {
//Setting new ID (if object was new created) to Entity
getField(o.getClass(), flds.get(0)).set(o, marshall.get("_id"));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
Cache ch = getAnnotationFromHierarchy(o.getClass(), Cache.class);
if (ch != null) {
if (ch.clearOnWrite()) {
clearCachefor(o.getClass());
}
}
firePostStoreEvent(o, isNew);
}
/**
* same as retReplicaSetStatus(false);
*
* @return
*/
public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus() {
return getReplicaSetStatus(false);
}
/**
* get the current replicaset status - issues the replSetGetStatus command to mongo
* if full==true, also the configuration is read. This method is called with full==false for every write in
* case a Replicaset is configured to find out the current number of active nodes
*
* @param full
* @return
*/
public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus(boolean full) {
if (config.getMode().equals(MongoDbMode.REPLICASET)) {
try {
CommandResult res = getMongo().getDB("admin").command("replSetGetStatus");
de.caluga.morphium.replicaset.ReplicaSetStatus status = getConfig().getMapper().unmarshall(de.caluga.morphium.replicaset.ReplicaSetStatus.class, res);
if (full) {
DBCursor rpl = getMongo().getDB("local").getCollection("system.replset").find();
DBObject stat = rpl.next(); //should only be one, i think
ReplicaSetConf cfg = getConfig().getMapper().unmarshall(ReplicaSetConf.class, stat);
List<Object> mem = cfg.getMemberList();
List<ConfNode> cmembers = new ArrayList<ConfNode>();
for (Object o : mem) {
DBObject dbo = (DBObject) o;
ConfNode cn = getConfig().getMapper().unmarshall(ConfNode.class, dbo);
cmembers.add(cn);
}
cfg.setMembers(cmembers);
status.setConfig(cfg);
}
//de-referencing list
List lst = status.getMembers();
List<ReplicaSetNode> members = new ArrayList<ReplicaSetNode>();
for (Object l : lst) {
DBObject o = (DBObject) l;
ReplicaSetNode n = getConfig().getMapper().unmarshall(ReplicaSetNode.class, o);
members.add(n);
}
status.setMembers(members);
return status;
} catch (Exception e) {
logger.error("Could not get Replicaset status", e);
}
}
return null;
}
public boolean isReplicaSet() {
return config.getMode().equals(MongoDbMode.REPLICASET);
}
public WriteConcern getWriteConcernForClass(Class<?> cls) {
WriteSafety safety = getAnnotationFromHierarchy(cls, WriteSafety.class); // cls.getAnnotation(WriteSafety.class);
if (safety == null) return null;
boolean fsync = safety.waitForSync();
boolean j = safety.waitForJournalCommit();
if (j && fsync) {
fsync = false;
}
int w = safety.level().getValue();
if (!isReplicaSet() && w > 1) {
w = 1;
}
int timeout = safety.timeout();
if (isReplicaSet() && w > 2) {
de.caluga.morphium.replicaset.ReplicaSetStatus s = getReplicaSetStatus();
if (s == null || s.getActiveNodes() == 0) {
logger.warn("ReplicaSet status is null or no node active! Assuming default write concern");
return null;
}
int activeNodes = s.getActiveNodes();
if (timeout == 0) {
if (getConfig().getConnectionTimeout() == 0) {
if (logger.isDebugEnabled())
logger.debug("Not waiting for all slaves withoug timeout - unfortunately no connection timeout set in config - setting to 10s, Type: " + cls.getSimpleName());
timeout = 10000;
} else {
if (logger.isDebugEnabled())
logger.debug("Not waiting for all slaves without timeout - could cause deadlock. Setting to connectionTimeout value, Type: " + cls.getSimpleName());
timeout = getConfig().getConnectionTimeout();
}
}
//Wait for all active slaves
w = activeNodes;
}
// if (w==0) {
// return WriteConcern.NONE;
// }
// if(w==1) {
// return WriteConcern.FSYNC_SAFE;
// }
// if (w==2) {
// return WriteConcern.JOURNAL_SAFE;
// }
// if (w==3) {
// return WriteConcern.REPLICAS_SAFE;
// }
return new WriteConcern(w, timeout, fsync, j);
}
public void addProfilingListener(ProfilingListener l) {
profilingListeners.add(l);
}
public void removeProfilingListener(ProfilingListener l) {
profilingListeners.remove(l);
}
private void fireProfilingWriteEvent(Class type, Object data, long time, boolean isNew, WriteAccessType wt) {
for (ProfilingListener l : profilingListeners) {
try {
l.writeAccess(type, data, time, isNew, wt);
} catch (Throwable e) {
logger.error("Error during profiling: ", e);
}
}
}
public void fireProfilingReadEvent(Query q, long time, ReadAccessType t) {
for (ProfilingListener l : profilingListeners) {
try {
l.readAccess(q, time, t);
} catch (Throwable e) {
logger.error("Error during profiling", e);
}
}
}
public void storeNoCacheList(List lst) {
if (!lst.isEmpty()) {
HashMap<Class, List<Object>> sorted = new HashMap<Class, List<Object>>();
HashMap<Object, Boolean> isNew = new HashMap<Object, Boolean>();
for (Object o : lst) {
Class type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, Entity.class)) {
logger.error("Not an entity! Storing not possible! Even not in list!");
continue;
}
inc(StatisticKeys.WRITES);
ObjectId id = config.getMapper().getId(o);
if (isAnnotationPresentInHierarchy(type, PartialUpdate.class)) {
//not part of list, acutally...
if ((o instanceof PartiallyUpdateable)) {
updateUsingFields(o, ((PartiallyUpdateable) o).getAlteredFields().toArray(new String[((PartiallyUpdateable) o).getAlteredFields().size()]));
((PartiallyUpdateable) o).clearAlteredFields();
continue;
}
}
o = getRealObject(o);
if (o == null) {
logger.warn("Illegal Reference? - cannot store Lazy-Loaded / Partial Update Proxy without delegate!");
return;
}
if (sorted.get(o.getClass()) == null) {
sorted.put(o.getClass(), new ArrayList<Object>());
}
sorted.get(o.getClass()).add(o);
if (getId(o) == null) {
isNew.put(o, true);
} else {
isNew.put(o, false);
}
firePreStoreEvent(o, isNew.get(o));
}
// firePreListStoreEvent(lst,isNew);
for (Map.Entry<Class, List<Object>> es : sorted.entrySet()) {
Class c = es.getKey();
ArrayList<DBObject> dbLst = new ArrayList<DBObject>();
//bulk insert... check if something already exists
WriteConcern wc = getWriteConcernForClass(c);
DBCollection collection = database.getCollection(getConfig().getMapper().getCollectionName(c));
for (Object record : es.getValue()) {
DBObject marshall = config.getMapper().marshall(record);
if (isNew.get(record)) {
dbLst.add(marshall);
} else {
//single update
long start = System.currentTimeMillis();
if (wc == null) {
collection.save(marshall);
} else {
collection.save(marshall, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(c, marshall, dur, false, WriteAccessType.SINGLE_INSERT);
firePostStoreEvent(record, isNew.get(record));
}
}
long start = System.currentTimeMillis();
if (wc == null) {
collection.insert(dbLst);
} else {
collection.insert(dbLst, wc);
}
long dur = System.currentTimeMillis() - start;
//bulk insert
fireProfilingWriteEvent(c, dbLst, dur, true, WriteAccessType.BULK_INSERT);
for (Object record : es.getValue()) {
if (isNew.get(record)) {
firePostStoreEvent(record, isNew.get(record));
}
}
}
// firePostListStoreEvent(lst,isNew);
}
}
protected boolean isCached(Class<? extends Object> type, String k) {
Cache c = getAnnotationFromHierarchy(type, Cache.class); ///type.getAnnotation(Cache.class);
if (c != null) {
if (!c.readCache()) return false;
} else {
return false;
}
return cache.get(type) != null && cache.get(type).get(k) != null && cache.get(type).get(k).getFound() != null;
}
/**
* return object by from cache. Cache key usually is the string-representation of the search
* query.toQueryObject()
*
* @param type
* @param k
* @param <T>
* @return
*/
public <T> List<T> getFromCache(Class<T> type, String k) {
if (cache.get(type) == null || cache.get(type).get(k) == null) return null;
final CacheElement cacheElement = cache.get(type).get(k);
cacheElement.setLru(System.currentTimeMillis());
return cacheElement.getFound();
}
public Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cloneCache() {
return (Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>) cache.clone();
}
public Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> cloneIdCache() {
return (Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>>) idCache.clone();
}
/**
* issues a delete command - no lifecycle methods calles, no drop, keeps all indexec this way
*
* @param cls
*/
public void clearCollection(Class<? extends Object> cls) {
delete(createQueryFor(cls));
}
/**
* clears every single object in collection - reads ALL objects to do so
* this way Lifecycle methods can be called!
*
* @param cls
*/
public void deleteCollectionItems(Class<? extends Object> cls) {
if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) {
try {
if (accessDenied(cls.newInstance(), Permission.DROP)) {
throw new SecurityException("Drop of Collection denied!");
}
} catch (InstantiationException ex) {
Logger.getLogger(Morphium.class).error(ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Morphium.class).error(ex);
}
}
inc(StatisticKeys.WRITES);
List<? extends Object> lst = readAll(cls);
for (Object r : lst) {
deleteObject(r);
}
clearCacheIfNecessary(cls);
}
/**
* return a list of all elements stored in morphium for this type
*
* @param cls - type to search for, needs to be an Property
* @param <T> - Type
* @return - list of all elements stored
*/
public <T> List<T> readAll(Class<T> cls) {
inc(StatisticKeys.READS);
Query<T> qu;
qu = createQueryFor(cls);
return qu.asList();
}
public <T> Query<T> createQueryFor(Class<T> type) {
return new QueryImpl<T>(this, type, config.getMapper());
}
public <T> List<T> find(Query<T> q) {
return q.asList();
}
private <T> T getFromIDCache(Class<T> type, ObjectId id) {
if (idCache.get(type) != null) {
return (T) idCache.get(type).get(id);
}
return null;
}
public List<Object> distinct(Enum key, Class c) {
return distinct(key.name(), c);
}
/**
* returns a distinct list of values of the given collection
* Attention: these values are not unmarshalled, you might get MongoDBObjects
*/
public List<Object> distinct(Enum key, Query q) {
return distinct(key.name(), q);
}
/**
* returns a distinct list of values of the given collection
* Attention: these values are not unmarshalled, you might get MongoDBObjects
*/
public List<Object> distinct(String key, Query q) {
return database.getCollection(config.getMapper().getCollectionName(q.getType())).distinct(key, q.toQueryObject());
}
public List<Object> distinct(String key, Class cls) {
DBCollection collection = database.getCollection(config.getMapper().getCollectionName(cls));
setReadPreference(collection, cls);
return collection.distinct(key, new BasicDBObject());
}
private void setReadPreference(DBCollection c, Class type) {
ReadPreference pr = getAnnotationFromHierarchy(type, ReadPreference.class);
if (pr != null) {
if (pr.equals(ReadPreferenceLevel.MASTER_ONLY)) {
c.setReadPreference(com.mongodb.ReadPreference.PRIMARY);
} else {
c.setReadPreference(com.mongodb.ReadPreference.SECONDARY);
}
} else {
c.setReadPreference(null);
}
}
public DBObject group(Query q, Map<String, Object> initial, String jsReduce, String jsFinalize, String... keys) {
BasicDBObject k = new BasicDBObject();
BasicDBObject ini = new BasicDBObject();
ini.putAll(initial);
for (String ks : keys) {
if (ks.startsWith("-")) {
k.append(ks.substring(1), "false");
} else if (ks.startsWith("+")) {
k.append(ks.substring(1), "true");
} else {
k.append(ks, "true");
}
}
if (!jsReduce.trim().startsWith("function(")) {
jsReduce = "function (obj,data) { " + jsReduce + " }";
}
if (jsFinalize == null) {
jsFinalize = "";
}
if (!jsFinalize.trim().startsWith("function(")) {
jsFinalize = "function (data) {" + jsFinalize + "}";
}
GroupCommand cmd = new GroupCommand(database.getCollection(config.getMapper().getCollectionName(q.getType())),
k, q.toQueryObject(), ini, jsReduce, jsFinalize);
return database.getCollection(config.getMapper().getCollectionName(q.getType())).group(cmd);
}
public <T> T findById(Class<T> type, ObjectId id) {
T ret = getFromIDCache(type, id);
if (ret != null) return ret;
List<String> ls = config.getMapper().getFields(type, Id.class);
if (ls.size() == 0) throw new RuntimeException("Cannot find by ID on non-Entity");
return (T) createQueryFor(type).f(ls.get(0)).eq(id).get();
}
// /**
// * returns a list of all elements for the given type, matching the given query
// * @param qu - the query to search
// * @param <T> - type of the elementyx
// * @return - list of elements matching query
// */
// public <T> List<T> readAll(Query<T> qu) {
// inc(StatisticKeys.READS);
// if (qu.getEntityClass().isAnnotationPresent(Cache.class)) {
// if (isCached(qu.getEntityClass(), qu.toString())) {
// inc(StatisticKeys.CHITS);
// return getFromCache(qu.getEntityClass(), qu.toString());
// } else {
// inc(StatisticKeys.CMISS);
// }
// }
// List<T> lst = qu.asList();
// addToCache(qu.toString()+" / l:"+((QueryImpl)qu).getLimit()+" o:"+((QueryImpl)qu).getOffset(), qu.getEntityClass(), lst);
// return lst;
//
// }
/**
* does not set values in DB only in the entity
*
* @param toSetValueIn
*/
public void setValueIn(Object toSetValueIn, String fld, Object value) {
config.getMapper().setValue(toSetValueIn, value, fld);
}
public void setValueIn(Object toSetValueIn, Enum fld, Object value) {
config.getMapper().setValue(toSetValueIn, value, fld.name());
}
public Object getValueOf(Object toGetValueFrom, String fld) {
return config.getMapper().getValue(toGetValueFrom, fld);
}
public Object getValueOf(Object toGetValueFrom, Enum fld) {
return config.getMapper().getValue(toGetValueFrom, fld.name());
}
@SuppressWarnings("unchecked")
public <T> List<T> findByField(Class<T> cls, String fld, Object val) {
Query<T> q = createQueryFor(cls);
q = q.f(fld).eq(val);
return q.asList();
// return createQueryFor(cls).field(fld).equal(val).asList();
}
public <T> List<T> findByField(Class<T> cls, Enum fld, Object val) {
Query<T> q = createQueryFor(cls);
q = q.f(fld).eq(val);
return q.asList();
// return createQueryFor(cls).field(fld).equal(val).asList();
}
/**
* deletes all objects matching the given query
*
* @param q
* @param <T>
*/
public <T> void delete(Query<T> q) {
firePreRemoveEvent(q);
WriteConcern wc = getWriteConcernForClass(q.getType());
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(config.getMapper().getCollectionName(q.getType())).remove(q.toQueryObject());
} else {
database.getCollection(config.getMapper().getCollectionName(q.getType())).remove(q.toQueryObject(), wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(q.getType(), q.toQueryObject(), dur, false, WriteAccessType.BULK_DELETE);
clearCacheIfNecessary(q.getType());
firePostRemoveEvent(q);
}
/**
* get a list of valid fields of a given record as they are in the MongoDB
* so, if you have a field Mapping, the mapped Property-name will be used
*
* @param cls
* @return
*/
public final List<String> getFields(Class cls) {
return config.getMapper().getFields(cls);
}
public final Class getTypeOfField(Class cls, String fld) {
Field f = getField(cls, fld);
if (f == null) return null;
return f.getType();
}
public boolean storesLastChange(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreLastChange.class);
}
public boolean storesLastAccess(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreLastAccess.class);
}
public boolean storesCreation(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreCreationTime.class);
}
private String getFieldName(Class cls, String fld) {
return config.getMapper().getFieldName(cls, fld);
}
/**
* extended logic: Fld may be, the java field name, the name of the specified value in Property-Annotation or
* the translated underscored lowercase name (mongoId => mongo_id)
*
* @param cls - class to search
* @param fld - field name
* @return field, if found, null else
*/
private Field getField(Class cls, String fld) {
return config.getMapper().getField(cls, fld);
}
public void setValue(Object in, String fld, Object val) {
config.getMapper().setValue(in, val, fld);
}
public Object getValue(Object o, String fld) {
return config.getMapper().getValue(o, fld);
}
public Long getLongValue(Object o, String fld) {
return (Long) getValue(o, fld);
}
public String getStringValue(Object o, String fld) {
return (String) getValue(o, fld);
}
public Date getDateValue(Object o, String fld) {
return (Date) getValue(o, fld);
}
public Double getDoubleValue(Object o, String fld) {
return (Double) getValue(o, fld);
}
/**
* Erase cache entries for the given type. is being called after every store
* depending on cache settings!
*
* @param cls
*/
public void clearCachefor(Class<? extends Object> cls) {
if (cache.get(cls) != null) {
cache.get(cls).clear();
}
if (idCache.get(cls) != null) {
idCache.get(cls).clear();
}
//clearCacheFor(cls);
}
public void storeInBackground(final Object lst) {
inc(StatisticKeys.WRITES_CACHED);
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCache(lst);
}
});
}
public void storeListInBackground(final List lst) {
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCacheList(lst);
}
});
}
public ObjectId getId(Object o) {
return config.getMapper().getId(o);
}
public void dropCollection(Class<? extends Object> cls) {
if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) {
try {
if (accessDenied(cls.newInstance(), Permission.DROP)) {
throw new SecurityException("Drop of Collection denied!");
}
} catch (InstantiationException ex) {
Logger.getLogger(Morphium.class.getName()).fatal(ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Morphium.class.getName()).fatal(ex);
}
}
-// if (config.getMode() == MongoDbMode.REPLICASET && config.getAdr().size() > 1) {
-// //replicaset
-// logger.warn("Cannot drop collection for class " + cls.getSimpleName() + " as we're in a clustered environment (Driver 2.8.0)");
-// clearCollection(cls);
-// return;
-// }
+ if (config.getMode() == MongoDbMode.REPLICASET && config.getAdr().size() > 1) {
+ //replicaset
+ logger.warn("Cannot drop collection for class " + cls.getSimpleName() + " as we're in a clustered environment (Driver 2.8.0)");
+ clearCollection(cls);
+ return;
+ }
if (isAnnotationPresentInHierarchy(cls, Entity.class)) {
firePreDropEvent(cls);
long start = System.currentTimeMillis();
// Entity entity = getAnnotationFromHierarchy(cls, Entity.class); //cls.getAnnotation(Entity.class);
database.getCollection(config.getMapper().getCollectionName(cls)).drop();
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, null, dur, false, WriteAccessType.DROP);
firePostDropEvent(cls);
} else {
throw new RuntimeException("No entity class: " + cls.getName());
}
}
public void ensureIndex(Class<?> cls, Map<String, Integer> index) {
List<String> fields = getFields(cls);
Map<String, Integer> idx = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> es : index.entrySet()) {
String k = es.getKey();
if (!fields.contains(k) && !fields.contains(config.getMapper().convertCamelCase(k))) {
throw new IllegalArgumentException("Field unknown for type " + cls.getSimpleName() + ": " + k);
}
String fn = config.getMapper().getFieldName(cls, k);
idx.put(fn, es.getValue());
}
long start = System.currentTimeMillis();
database.getCollection(config.getMapper().getCollectionName(cls)).ensureIndex(new BasicDBObject(idx));
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, new BasicDBObject(idx), dur, false, WriteAccessType.ENSURE_INDEX);
}
/**
* ensureIndex(CachedObject.class,"counter","-value");
* Similar to sorting
*
* @param cls
* @param fldStr
*/
public void ensureIndex(Class<?> cls, String... fldStr) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
for (String f : fldStr) {
int idx = 1;
if (f.startsWith("-")) {
idx = -1;
f = f.substring(1);
} else if (f.startsWith("+")) {
f = f.substring(1);
}
m.put(f, idx);
}
ensureIndex(cls, m);
}
public void ensureIndex(Class<?> cls, Enum... fldStr) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
for (Enum e : fldStr) {
String f = e.name();
m.put(f, 1);
}
ensureIndex(cls, m);
}
/**
* Stores a single Object. Clears the corresponding cache
*
* @param o - Object to store
*/
public void store(Object o) {
if (o instanceof List) {
throw new RuntimeException("Lists need to be stored with storeList");
}
Class<?> type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, NoProtection.class)) { //o.getClass().isAnnotationPresent(NoProtection.class)) {
if (getId(o) == null) {
if (accessDenied(o, Permission.INSERT)) {
throw new SecurityException("Insert of new Object denied!");
}
} else {
if (accessDenied(o, Permission.UPDATE)) {
throw new SecurityException("Update of Object denied!");
}
}
}
Cache cc = getAnnotationFromHierarchy(type, Cache.class);//o.getClass().getAnnotation(Cache.class);
if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class)) {
storeNoCache(o);
return;
}
final Object fo = o;
if (cc.writeCache()) {
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCache(fo);
}
});
inc(StatisticKeys.WRITES_CACHED);
} else {
storeNoCache(o);
}
}
public <T> void storeList(List<T> lst) {
//have to sort list - might have different objects
List<T> storeDirect = new ArrayList<T>();
List<T> storeInBg = new ArrayList<T>();
//checking permission - might take some time ;-(
for (T o : lst) {
if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) {
if (getId(o) == null) {
if (accessDenied(o, Permission.INSERT)) {
throw new SecurityException("Insert of new Object denied!");
}
} else {
if (accessDenied(o, Permission.UPDATE)) {
throw new SecurityException("Update of Object denied!");
}
}
}
Cache c = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class);
if (c != null && !isAnnotationPresentInHierarchy(o.getClass(), NoCache.class)) {
if (c.writeCache()) {
storeInBg.add(o);
} else {
storeDirect.add(o);
}
} else {
storeDirect.add(o);
}
}
storeListInBackground(storeInBg);
storeNoCacheList(storeDirect);
}
/**
* deletes a single object from morphium backend. Clears cache
*
* @param o
*/
public <T> void deleteObject(T o) {
o = getRealObject(o);
if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) {
if (accessDenied(o, Permission.DELETE)) {
throw new SecurityException("Deletion of Object denied!");
}
}
firePreRemoveEvent(o);
ObjectId id = config.getMapper().getId(o);
BasicDBObject db = new BasicDBObject();
db.append("_id", id);
WriteConcern wc = getWriteConcernForClass(o.getClass());
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(config.getMapper().getCollectionName(o.getClass())).remove(db);
} else {
database.getCollection(config.getMapper().getCollectionName(o.getClass())).remove(db, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(o.getClass(), o, dur, false, WriteAccessType.SINGLE_DELETE);
clearCachefor(o.getClass());
inc(StatisticKeys.WRITES);
firePostRemoveEvent(o);
}
public void resetCache() {
setCache(new Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>());
}
public void setCache(Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cache) {
this.cache = cache;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////
/////////////// Statistics
/////////
/////
///
public Map<String, Double> getStatistics() {
return new Statistics(this);
}
public void removeEntryFromCache(Class cls, ObjectId id) {
Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> c = cloneCache();
Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idc = cloneIdCache();
idc.get(cls).remove(id);
ArrayList<String> toRemove = new ArrayList<String>();
for (String key : c.get(cls).keySet()) {
for (Object el : c.get(cls).get(key).getFound()) {
ObjectId lid = config.getMapper().getId(el);
if (lid == null) {
logger.error("Null id in CACHE?");
toRemove.add(key);
}
if (lid.equals(id)) {
toRemove.add(key);
}
}
}
for (String k : toRemove) {
c.get(cls).remove(k);
}
setCache(c);
setIdCache(idc);
}
public Map<StatisticKeys, StatisticValue> getStats() {
return stats;
}
public void addShutdownListener(ShutdownListener l) {
shutDownListeners.add(l);
}
public void removeShutdownListener(ShutdownListener l) {
shutDownListeners.remove(l);
}
public void close() {
cacheHousekeeper.end();
for (ShutdownListener l : shutDownListeners) {
l.onShutdown(this);
}
try {
Thread.sleep(1000); //give it time to end ;-)
} catch (Exception e) {
logger.debug("Ignoring interrupted-exception");
}
if (cacheHousekeeper.isAlive()) {
cacheHousekeeper.interrupt();
}
database = null;
config = null;
mongo.close();
MorphiumSingleton.reset();
}
public String createCamelCase(String n) {
return config.getMapper().createCamelCase(n, false);
}
/**
* create a proxy object, implementing the ParitallyUpdateable Interface
* these objects will be updated in mongo by only changing altered fields
* <b>Attention:</b> the field name if determined by the setter name for now. That means, it does not honor the @Property-Annotation!!!
* To make sure, you take the correct field - use the UpdatingField-Annotation for the setters!
*
* @param o
* @param <T>
* @return
*/
public <T> T createPartiallyUpdateableEntity(T o) {
return (T) Enhancer.create(o.getClass(), new Class[]{PartiallyUpdateable.class, Serializable.class}, new PartiallyUpdateableProxy(this, o));
}
public <T> T createLazyLoadedEntity(Class<T> cls, ObjectId id) {
return (T) Enhancer.create(cls, new Class[]{Serializable.class}, new LazyDeReferencingProxy(this, cls, id));
}
protected <T> MongoField<T> createMongoField() {
try {
return (MongoField<T>) config.getFieldImplClass().newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public String getLastChangeField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastChange.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastChangeByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastChangeBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastAccessField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastAccess.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastAccessByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastAccessBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getCreationTimeField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null;
List<String> lst = config.getMapper().getFields(cls, CreationTime.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getCreatedByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null;
List<String> lst = config.getMapper().getFields(cls, CreatedBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
//////////////////////////////////////////////////////
////////// SecuritySettings
///////
/////
////
///
//
public MongoSecurityManager getSecurityManager() {
return config.getSecurityMgr();
}
/**
* temporarily switch off security settings - needed by SecurityManagers
*/
public void setPrivileged() {
privileged.add(Thread.currentThread());
}
public boolean checkAccess(String domain, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return true;
}
return getSecurityManager().checkAccess(domain, p);
}
public boolean accessDenied(Class<?> cls, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return false;
}
return !getSecurityManager().checkAccess(cls, p);
}
public boolean accessDenied(Object r, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return false;
}
return !getSecurityManager().checkAccess(config.getMapper().getRealObject(r), p);
}
}
| true | true | public void callLifecycleMethod(Class<? extends Annotation> type, Object on) {
if (on == null) return;
//No synchronized block - might cause the methods to be put twice into the
//hashtabel - but for performance reasons, it's ok...
Class<?> cls = on.getClass();
//No Lifecycle annotation - no method calling
if (!isAnnotationPresentInHierarchy(cls, Lifecycle.class)) {//cls.isAnnotationPresent(Lifecycle.class)) {
return;
}
//Already stored - should not change during runtime
if (lifeCycleMethods.get(cls) != null) {
if (lifeCycleMethods.get(cls).get(type) != null) {
try {
lifeCycleMethods.get(cls).get(type).invoke(on);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
return;
}
Map<Class<? extends Annotation>, Method> methods = new HashMap<Class<? extends Annotation>, Method>();
//Methods must be public
for (Method m : cls.getMethods()) {
for (Annotation a : m.getAnnotations()) {
methods.put(a.annotationType(), m);
}
}
lifeCycleMethods.put(cls, methods);
if (methods.get(type) != null) {
try {
methods.get(type).invoke(on);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
/**
* careful this actually changes the parameter o!
*
* @param o
* @param <T>
* @return
*/
public <T> T reread(T o) {
if (o == null) throw new RuntimeException("Cannot re read null!");
ObjectId id = getId(o);
if (id == null) {
return null;
}
DBCollection col = database.getCollection(getConfig().getMapper().getCollectionName(o.getClass()));
BasicDBObject srch = new BasicDBObject("_id", id);
DBCursor crs = col.find(srch).limit(1);
if (crs.hasNext()) {
DBObject dbo = crs.next();
Object fromDb = getConfig().getMapper().unmarshall(o.getClass(), dbo);
List<String> flds = getFields(o.getClass());
for (String f : flds) {
Field fld = getConfig().getMapper().getField(o.getClass(), f);
if (java.lang.reflect.Modifier.isStatic(fld.getModifiers())) {
continue;
}
try {
fld.set(o, fld.get(fromDb));
} catch (IllegalAccessException e) {
logger.error("Could not set Value: " + fld);
}
}
} else {
logger.info("Did not find object with id " + id);
return null;
}
return o;
}
private void firePreStoreEvent(Object o, boolean isNew) {
if (o == null) return;
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preStore(o, isNew);
}
callLifecycleMethod(PreStore.class, o);
}
private void firePostStoreEvent(Object o, boolean isNew) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postStore(o, isNew);
}
callLifecycleMethod(PostStore.class, o);
//existing object => store last Access, if needed
}
private void firePreDropEvent(Class cls) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preDrop(cls);
}
}
private void firePostDropEvent(Class cls) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postDrop(cls);
}
}
private void firePostUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) {
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postUpdate(cls, t);
}
}
private void firePreUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) {
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preUpdate(cls, t);
}
}
private void firePostRemoveEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postRemove(o);
}
callLifecycleMethod(PostRemove.class, o);
}
private void firePostRemoveEvent(Query q) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postRemove(q);
}
//TODO: FIX - Cannot call lifecycle method here
}
private void firePreRemoveEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preDelete(o);
}
callLifecycleMethod(PreRemove.class, o);
}
private void firePreRemoveEvent(Query q) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preRemove(q);
}
//TODO: Fix - cannot call lifecycle method
}
// private void firePreListStoreEvent(List records, Map<Object,Boolean> isNew) {
// //Avoid concurrent modification exception
// List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
// for (MorphiumStorageListener l : lst) {
// l.preListStore(records,isNew);
// }
// for (Object o : records) {
// callLifecycleMethod(PreStore.class, o);
// }
// }
// private void firePostListStoreEvent(List records, Map<Object,Boolean> isNew) {
// //Avoid concurrent modification exception
// List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
// for (MorphiumStorageListener l : lst) {
// l.postListStore(records,isNew);
// }
// for (Object o : records) {
// callLifecycleMethod(PostStore.class, o);
// }
//
// }
/**
* will be called by query after unmarshalling
*
* @param o
*/
protected void firePostLoadEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postLoad(o);
}
callLifecycleMethod(PostLoad.class, o);
}
public void storeNoCache(Object o) {
long start = System.currentTimeMillis();
Class type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, Entity.class)) {
throw new RuntimeException("Not an entity! Storing not possible!");
}
inc(StatisticKeys.WRITES);
ObjectId id = config.getMapper().getId(o);
if (isAnnotationPresentInHierarchy(type, PartialUpdate.class)) {
if ((o instanceof PartiallyUpdateable)) {
updateUsingFields(o, ((PartiallyUpdateable) o).getAlteredFields().toArray(new String[((PartiallyUpdateable) o).getAlteredFields().size()]));
((PartiallyUpdateable) o).clearAlteredFields();
return;
}
}
o = getRealObject(o);
if (o == null) {
logger.warn("Illegal Reference? - cannot store Lazy-Loaded / Partial Update Proxy without delegate!");
return;
}
boolean isNew = id == null;
firePreStoreEvent(o, isNew);
long dur = System.currentTimeMillis() - start;
DBObject marshall = config.getMapper().marshall(o);
if (isNew) {
//new object - need to store creation time
if (isAnnotationPresentInHierarchy(type, StoreCreationTime.class)) {
List<String> lst = config.getMapper().getFields(type, CreationTime.class);
if (lst == null || lst.size() == 0) {
logger.error("Unable to store creation time as @CreationTime is missing");
} else {
long now = System.currentTimeMillis();
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, now);
} catch (IllegalAccessException e) {
logger.error("Could not set creation time", e);
}
}
marshall.put(ctf, now);
}
}
lst = config.getMapper().getFields(type, CreatedBy.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, config.getSecurityMgr().getCurrentUserId());
} catch (IllegalAccessException e) {
logger.error("Could not set created by", e);
}
}
marshall.put(ctf, config.getSecurityMgr().getCurrentUserId());
}
}
}
}
if (isAnnotationPresentInHierarchy(type, StoreLastChange.class)) {
List<String> lst = config.getMapper().getFields(type, LastChange.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
long now = System.currentTimeMillis();
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, now);
} catch (IllegalAccessException e) {
logger.error("Could not set modification time", e);
}
}
marshall.put(ctf, now);
}
} else {
logger.warn("Could not store last change - @LastChange missing!");
}
lst = config.getMapper().getFields(type, LastChangeBy.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, config.getSecurityMgr().getCurrentUserId());
} catch (IllegalAccessException e) {
logger.error("Could not set changed by", e);
}
}
marshall.put(ctf, config.getSecurityMgr().getCurrentUserId());
}
}
}
String coll = config.getMapper().getCollectionName(type);
if (!database.collectionExists(coll)) {
if (logger.isDebugEnabled())
logger.debug("Collection does not exist - ensuring indices");
ensureIndicesFor(type);
}
WriteConcern wc = getWriteConcernForClass(type);
if (wc != null) {
database.getCollection(coll).save(marshall, wc);
} else {
database.getCollection(coll).save(marshall);
}
dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(o.getClass(), marshall, dur, true, WriteAccessType.SINGLE_INSERT);
if (logger.isDebugEnabled()) {
String n = "";
if (isNew) {
n = "NEW ";
}
logger.debug(n + "stored " + type.getSimpleName() + " after " + dur + " ms length:" + marshall.toString().length());
}
if (isNew) {
List<String> flds = config.getMapper().getFields(o.getClass(), Id.class);
if (flds == null) {
throw new RuntimeException("Object does not have an ID field!");
}
try {
//Setting new ID (if object was new created) to Entity
getField(o.getClass(), flds.get(0)).set(o, marshall.get("_id"));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
Cache ch = getAnnotationFromHierarchy(o.getClass(), Cache.class);
if (ch != null) {
if (ch.clearOnWrite()) {
clearCachefor(o.getClass());
}
}
firePostStoreEvent(o, isNew);
}
/**
* same as retReplicaSetStatus(false);
*
* @return
*/
public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus() {
return getReplicaSetStatus(false);
}
/**
* get the current replicaset status - issues the replSetGetStatus command to mongo
* if full==true, also the configuration is read. This method is called with full==false for every write in
* case a Replicaset is configured to find out the current number of active nodes
*
* @param full
* @return
*/
public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus(boolean full) {
if (config.getMode().equals(MongoDbMode.REPLICASET)) {
try {
CommandResult res = getMongo().getDB("admin").command("replSetGetStatus");
de.caluga.morphium.replicaset.ReplicaSetStatus status = getConfig().getMapper().unmarshall(de.caluga.morphium.replicaset.ReplicaSetStatus.class, res);
if (full) {
DBCursor rpl = getMongo().getDB("local").getCollection("system.replset").find();
DBObject stat = rpl.next(); //should only be one, i think
ReplicaSetConf cfg = getConfig().getMapper().unmarshall(ReplicaSetConf.class, stat);
List<Object> mem = cfg.getMemberList();
List<ConfNode> cmembers = new ArrayList<ConfNode>();
for (Object o : mem) {
DBObject dbo = (DBObject) o;
ConfNode cn = getConfig().getMapper().unmarshall(ConfNode.class, dbo);
cmembers.add(cn);
}
cfg.setMembers(cmembers);
status.setConfig(cfg);
}
//de-referencing list
List lst = status.getMembers();
List<ReplicaSetNode> members = new ArrayList<ReplicaSetNode>();
for (Object l : lst) {
DBObject o = (DBObject) l;
ReplicaSetNode n = getConfig().getMapper().unmarshall(ReplicaSetNode.class, o);
members.add(n);
}
status.setMembers(members);
return status;
} catch (Exception e) {
logger.error("Could not get Replicaset status", e);
}
}
return null;
}
public boolean isReplicaSet() {
return config.getMode().equals(MongoDbMode.REPLICASET);
}
public WriteConcern getWriteConcernForClass(Class<?> cls) {
WriteSafety safety = getAnnotationFromHierarchy(cls, WriteSafety.class); // cls.getAnnotation(WriteSafety.class);
if (safety == null) return null;
boolean fsync = safety.waitForSync();
boolean j = safety.waitForJournalCommit();
if (j && fsync) {
fsync = false;
}
int w = safety.level().getValue();
if (!isReplicaSet() && w > 1) {
w = 1;
}
int timeout = safety.timeout();
if (isReplicaSet() && w > 2) {
de.caluga.morphium.replicaset.ReplicaSetStatus s = getReplicaSetStatus();
if (s == null || s.getActiveNodes() == 0) {
logger.warn("ReplicaSet status is null or no node active! Assuming default write concern");
return null;
}
int activeNodes = s.getActiveNodes();
if (timeout == 0) {
if (getConfig().getConnectionTimeout() == 0) {
if (logger.isDebugEnabled())
logger.debug("Not waiting for all slaves withoug timeout - unfortunately no connection timeout set in config - setting to 10s, Type: " + cls.getSimpleName());
timeout = 10000;
} else {
if (logger.isDebugEnabled())
logger.debug("Not waiting for all slaves without timeout - could cause deadlock. Setting to connectionTimeout value, Type: " + cls.getSimpleName());
timeout = getConfig().getConnectionTimeout();
}
}
//Wait for all active slaves
w = activeNodes;
}
// if (w==0) {
// return WriteConcern.NONE;
// }
// if(w==1) {
// return WriteConcern.FSYNC_SAFE;
// }
// if (w==2) {
// return WriteConcern.JOURNAL_SAFE;
// }
// if (w==3) {
// return WriteConcern.REPLICAS_SAFE;
// }
return new WriteConcern(w, timeout, fsync, j);
}
public void addProfilingListener(ProfilingListener l) {
profilingListeners.add(l);
}
public void removeProfilingListener(ProfilingListener l) {
profilingListeners.remove(l);
}
private void fireProfilingWriteEvent(Class type, Object data, long time, boolean isNew, WriteAccessType wt) {
for (ProfilingListener l : profilingListeners) {
try {
l.writeAccess(type, data, time, isNew, wt);
} catch (Throwable e) {
logger.error("Error during profiling: ", e);
}
}
}
public void fireProfilingReadEvent(Query q, long time, ReadAccessType t) {
for (ProfilingListener l : profilingListeners) {
try {
l.readAccess(q, time, t);
} catch (Throwable e) {
logger.error("Error during profiling", e);
}
}
}
public void storeNoCacheList(List lst) {
if (!lst.isEmpty()) {
HashMap<Class, List<Object>> sorted = new HashMap<Class, List<Object>>();
HashMap<Object, Boolean> isNew = new HashMap<Object, Boolean>();
for (Object o : lst) {
Class type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, Entity.class)) {
logger.error("Not an entity! Storing not possible! Even not in list!");
continue;
}
inc(StatisticKeys.WRITES);
ObjectId id = config.getMapper().getId(o);
if (isAnnotationPresentInHierarchy(type, PartialUpdate.class)) {
//not part of list, acutally...
if ((o instanceof PartiallyUpdateable)) {
updateUsingFields(o, ((PartiallyUpdateable) o).getAlteredFields().toArray(new String[((PartiallyUpdateable) o).getAlteredFields().size()]));
((PartiallyUpdateable) o).clearAlteredFields();
continue;
}
}
o = getRealObject(o);
if (o == null) {
logger.warn("Illegal Reference? - cannot store Lazy-Loaded / Partial Update Proxy without delegate!");
return;
}
if (sorted.get(o.getClass()) == null) {
sorted.put(o.getClass(), new ArrayList<Object>());
}
sorted.get(o.getClass()).add(o);
if (getId(o) == null) {
isNew.put(o, true);
} else {
isNew.put(o, false);
}
firePreStoreEvent(o, isNew.get(o));
}
// firePreListStoreEvent(lst,isNew);
for (Map.Entry<Class, List<Object>> es : sorted.entrySet()) {
Class c = es.getKey();
ArrayList<DBObject> dbLst = new ArrayList<DBObject>();
//bulk insert... check if something already exists
WriteConcern wc = getWriteConcernForClass(c);
DBCollection collection = database.getCollection(getConfig().getMapper().getCollectionName(c));
for (Object record : es.getValue()) {
DBObject marshall = config.getMapper().marshall(record);
if (isNew.get(record)) {
dbLst.add(marshall);
} else {
//single update
long start = System.currentTimeMillis();
if (wc == null) {
collection.save(marshall);
} else {
collection.save(marshall, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(c, marshall, dur, false, WriteAccessType.SINGLE_INSERT);
firePostStoreEvent(record, isNew.get(record));
}
}
long start = System.currentTimeMillis();
if (wc == null) {
collection.insert(dbLst);
} else {
collection.insert(dbLst, wc);
}
long dur = System.currentTimeMillis() - start;
//bulk insert
fireProfilingWriteEvent(c, dbLst, dur, true, WriteAccessType.BULK_INSERT);
for (Object record : es.getValue()) {
if (isNew.get(record)) {
firePostStoreEvent(record, isNew.get(record));
}
}
}
// firePostListStoreEvent(lst,isNew);
}
}
protected boolean isCached(Class<? extends Object> type, String k) {
Cache c = getAnnotationFromHierarchy(type, Cache.class); ///type.getAnnotation(Cache.class);
if (c != null) {
if (!c.readCache()) return false;
} else {
return false;
}
return cache.get(type) != null && cache.get(type).get(k) != null && cache.get(type).get(k).getFound() != null;
}
/**
* return object by from cache. Cache key usually is the string-representation of the search
* query.toQueryObject()
*
* @param type
* @param k
* @param <T>
* @return
*/
public <T> List<T> getFromCache(Class<T> type, String k) {
if (cache.get(type) == null || cache.get(type).get(k) == null) return null;
final CacheElement cacheElement = cache.get(type).get(k);
cacheElement.setLru(System.currentTimeMillis());
return cacheElement.getFound();
}
public Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cloneCache() {
return (Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>) cache.clone();
}
public Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> cloneIdCache() {
return (Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>>) idCache.clone();
}
/**
* issues a delete command - no lifecycle methods calles, no drop, keeps all indexec this way
*
* @param cls
*/
public void clearCollection(Class<? extends Object> cls) {
delete(createQueryFor(cls));
}
/**
* clears every single object in collection - reads ALL objects to do so
* this way Lifecycle methods can be called!
*
* @param cls
*/
public void deleteCollectionItems(Class<? extends Object> cls) {
if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) {
try {
if (accessDenied(cls.newInstance(), Permission.DROP)) {
throw new SecurityException("Drop of Collection denied!");
}
} catch (InstantiationException ex) {
Logger.getLogger(Morphium.class).error(ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Morphium.class).error(ex);
}
}
inc(StatisticKeys.WRITES);
List<? extends Object> lst = readAll(cls);
for (Object r : lst) {
deleteObject(r);
}
clearCacheIfNecessary(cls);
}
/**
* return a list of all elements stored in morphium for this type
*
* @param cls - type to search for, needs to be an Property
* @param <T> - Type
* @return - list of all elements stored
*/
public <T> List<T> readAll(Class<T> cls) {
inc(StatisticKeys.READS);
Query<T> qu;
qu = createQueryFor(cls);
return qu.asList();
}
public <T> Query<T> createQueryFor(Class<T> type) {
return new QueryImpl<T>(this, type, config.getMapper());
}
public <T> List<T> find(Query<T> q) {
return q.asList();
}
private <T> T getFromIDCache(Class<T> type, ObjectId id) {
if (idCache.get(type) != null) {
return (T) idCache.get(type).get(id);
}
return null;
}
public List<Object> distinct(Enum key, Class c) {
return distinct(key.name(), c);
}
/**
* returns a distinct list of values of the given collection
* Attention: these values are not unmarshalled, you might get MongoDBObjects
*/
public List<Object> distinct(Enum key, Query q) {
return distinct(key.name(), q);
}
/**
* returns a distinct list of values of the given collection
* Attention: these values are not unmarshalled, you might get MongoDBObjects
*/
public List<Object> distinct(String key, Query q) {
return database.getCollection(config.getMapper().getCollectionName(q.getType())).distinct(key, q.toQueryObject());
}
public List<Object> distinct(String key, Class cls) {
DBCollection collection = database.getCollection(config.getMapper().getCollectionName(cls));
setReadPreference(collection, cls);
return collection.distinct(key, new BasicDBObject());
}
private void setReadPreference(DBCollection c, Class type) {
ReadPreference pr = getAnnotationFromHierarchy(type, ReadPreference.class);
if (pr != null) {
if (pr.equals(ReadPreferenceLevel.MASTER_ONLY)) {
c.setReadPreference(com.mongodb.ReadPreference.PRIMARY);
} else {
c.setReadPreference(com.mongodb.ReadPreference.SECONDARY);
}
} else {
c.setReadPreference(null);
}
}
public DBObject group(Query q, Map<String, Object> initial, String jsReduce, String jsFinalize, String... keys) {
BasicDBObject k = new BasicDBObject();
BasicDBObject ini = new BasicDBObject();
ini.putAll(initial);
for (String ks : keys) {
if (ks.startsWith("-")) {
k.append(ks.substring(1), "false");
} else if (ks.startsWith("+")) {
k.append(ks.substring(1), "true");
} else {
k.append(ks, "true");
}
}
if (!jsReduce.trim().startsWith("function(")) {
jsReduce = "function (obj,data) { " + jsReduce + " }";
}
if (jsFinalize == null) {
jsFinalize = "";
}
if (!jsFinalize.trim().startsWith("function(")) {
jsFinalize = "function (data) {" + jsFinalize + "}";
}
GroupCommand cmd = new GroupCommand(database.getCollection(config.getMapper().getCollectionName(q.getType())),
k, q.toQueryObject(), ini, jsReduce, jsFinalize);
return database.getCollection(config.getMapper().getCollectionName(q.getType())).group(cmd);
}
public <T> T findById(Class<T> type, ObjectId id) {
T ret = getFromIDCache(type, id);
if (ret != null) return ret;
List<String> ls = config.getMapper().getFields(type, Id.class);
if (ls.size() == 0) throw new RuntimeException("Cannot find by ID on non-Entity");
return (T) createQueryFor(type).f(ls.get(0)).eq(id).get();
}
// /**
// * returns a list of all elements for the given type, matching the given query
// * @param qu - the query to search
// * @param <T> - type of the elementyx
// * @return - list of elements matching query
// */
// public <T> List<T> readAll(Query<T> qu) {
// inc(StatisticKeys.READS);
// if (qu.getEntityClass().isAnnotationPresent(Cache.class)) {
// if (isCached(qu.getEntityClass(), qu.toString())) {
// inc(StatisticKeys.CHITS);
// return getFromCache(qu.getEntityClass(), qu.toString());
// } else {
// inc(StatisticKeys.CMISS);
// }
// }
// List<T> lst = qu.asList();
// addToCache(qu.toString()+" / l:"+((QueryImpl)qu).getLimit()+" o:"+((QueryImpl)qu).getOffset(), qu.getEntityClass(), lst);
// return lst;
//
// }
/**
* does not set values in DB only in the entity
*
* @param toSetValueIn
*/
public void setValueIn(Object toSetValueIn, String fld, Object value) {
config.getMapper().setValue(toSetValueIn, value, fld);
}
public void setValueIn(Object toSetValueIn, Enum fld, Object value) {
config.getMapper().setValue(toSetValueIn, value, fld.name());
}
public Object getValueOf(Object toGetValueFrom, String fld) {
return config.getMapper().getValue(toGetValueFrom, fld);
}
public Object getValueOf(Object toGetValueFrom, Enum fld) {
return config.getMapper().getValue(toGetValueFrom, fld.name());
}
@SuppressWarnings("unchecked")
public <T> List<T> findByField(Class<T> cls, String fld, Object val) {
Query<T> q = createQueryFor(cls);
q = q.f(fld).eq(val);
return q.asList();
// return createQueryFor(cls).field(fld).equal(val).asList();
}
public <T> List<T> findByField(Class<T> cls, Enum fld, Object val) {
Query<T> q = createQueryFor(cls);
q = q.f(fld).eq(val);
return q.asList();
// return createQueryFor(cls).field(fld).equal(val).asList();
}
/**
* deletes all objects matching the given query
*
* @param q
* @param <T>
*/
public <T> void delete(Query<T> q) {
firePreRemoveEvent(q);
WriteConcern wc = getWriteConcernForClass(q.getType());
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(config.getMapper().getCollectionName(q.getType())).remove(q.toQueryObject());
} else {
database.getCollection(config.getMapper().getCollectionName(q.getType())).remove(q.toQueryObject(), wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(q.getType(), q.toQueryObject(), dur, false, WriteAccessType.BULK_DELETE);
clearCacheIfNecessary(q.getType());
firePostRemoveEvent(q);
}
/**
* get a list of valid fields of a given record as they are in the MongoDB
* so, if you have a field Mapping, the mapped Property-name will be used
*
* @param cls
* @return
*/
public final List<String> getFields(Class cls) {
return config.getMapper().getFields(cls);
}
public final Class getTypeOfField(Class cls, String fld) {
Field f = getField(cls, fld);
if (f == null) return null;
return f.getType();
}
public boolean storesLastChange(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreLastChange.class);
}
public boolean storesLastAccess(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreLastAccess.class);
}
public boolean storesCreation(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreCreationTime.class);
}
private String getFieldName(Class cls, String fld) {
return config.getMapper().getFieldName(cls, fld);
}
/**
* extended logic: Fld may be, the java field name, the name of the specified value in Property-Annotation or
* the translated underscored lowercase name (mongoId => mongo_id)
*
* @param cls - class to search
* @param fld - field name
* @return field, if found, null else
*/
private Field getField(Class cls, String fld) {
return config.getMapper().getField(cls, fld);
}
public void setValue(Object in, String fld, Object val) {
config.getMapper().setValue(in, val, fld);
}
public Object getValue(Object o, String fld) {
return config.getMapper().getValue(o, fld);
}
public Long getLongValue(Object o, String fld) {
return (Long) getValue(o, fld);
}
public String getStringValue(Object o, String fld) {
return (String) getValue(o, fld);
}
public Date getDateValue(Object o, String fld) {
return (Date) getValue(o, fld);
}
public Double getDoubleValue(Object o, String fld) {
return (Double) getValue(o, fld);
}
/**
* Erase cache entries for the given type. is being called after every store
* depending on cache settings!
*
* @param cls
*/
public void clearCachefor(Class<? extends Object> cls) {
if (cache.get(cls) != null) {
cache.get(cls).clear();
}
if (idCache.get(cls) != null) {
idCache.get(cls).clear();
}
//clearCacheFor(cls);
}
public void storeInBackground(final Object lst) {
inc(StatisticKeys.WRITES_CACHED);
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCache(lst);
}
});
}
public void storeListInBackground(final List lst) {
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCacheList(lst);
}
});
}
public ObjectId getId(Object o) {
return config.getMapper().getId(o);
}
public void dropCollection(Class<? extends Object> cls) {
if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) {
try {
if (accessDenied(cls.newInstance(), Permission.DROP)) {
throw new SecurityException("Drop of Collection denied!");
}
} catch (InstantiationException ex) {
Logger.getLogger(Morphium.class.getName()).fatal(ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Morphium.class.getName()).fatal(ex);
}
}
// if (config.getMode() == MongoDbMode.REPLICASET && config.getAdr().size() > 1) {
// //replicaset
// logger.warn("Cannot drop collection for class " + cls.getSimpleName() + " as we're in a clustered environment (Driver 2.8.0)");
// clearCollection(cls);
// return;
// }
if (isAnnotationPresentInHierarchy(cls, Entity.class)) {
firePreDropEvent(cls);
long start = System.currentTimeMillis();
// Entity entity = getAnnotationFromHierarchy(cls, Entity.class); //cls.getAnnotation(Entity.class);
database.getCollection(config.getMapper().getCollectionName(cls)).drop();
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, null, dur, false, WriteAccessType.DROP);
firePostDropEvent(cls);
} else {
throw new RuntimeException("No entity class: " + cls.getName());
}
}
public void ensureIndex(Class<?> cls, Map<String, Integer> index) {
List<String> fields = getFields(cls);
Map<String, Integer> idx = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> es : index.entrySet()) {
String k = es.getKey();
if (!fields.contains(k) && !fields.contains(config.getMapper().convertCamelCase(k))) {
throw new IllegalArgumentException("Field unknown for type " + cls.getSimpleName() + ": " + k);
}
String fn = config.getMapper().getFieldName(cls, k);
idx.put(fn, es.getValue());
}
long start = System.currentTimeMillis();
database.getCollection(config.getMapper().getCollectionName(cls)).ensureIndex(new BasicDBObject(idx));
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, new BasicDBObject(idx), dur, false, WriteAccessType.ENSURE_INDEX);
}
/**
* ensureIndex(CachedObject.class,"counter","-value");
* Similar to sorting
*
* @param cls
* @param fldStr
*/
public void ensureIndex(Class<?> cls, String... fldStr) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
for (String f : fldStr) {
int idx = 1;
if (f.startsWith("-")) {
idx = -1;
f = f.substring(1);
} else if (f.startsWith("+")) {
f = f.substring(1);
}
m.put(f, idx);
}
ensureIndex(cls, m);
}
public void ensureIndex(Class<?> cls, Enum... fldStr) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
for (Enum e : fldStr) {
String f = e.name();
m.put(f, 1);
}
ensureIndex(cls, m);
}
/**
* Stores a single Object. Clears the corresponding cache
*
* @param o - Object to store
*/
public void store(Object o) {
if (o instanceof List) {
throw new RuntimeException("Lists need to be stored with storeList");
}
Class<?> type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, NoProtection.class)) { //o.getClass().isAnnotationPresent(NoProtection.class)) {
if (getId(o) == null) {
if (accessDenied(o, Permission.INSERT)) {
throw new SecurityException("Insert of new Object denied!");
}
} else {
if (accessDenied(o, Permission.UPDATE)) {
throw new SecurityException("Update of Object denied!");
}
}
}
Cache cc = getAnnotationFromHierarchy(type, Cache.class);//o.getClass().getAnnotation(Cache.class);
if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class)) {
storeNoCache(o);
return;
}
final Object fo = o;
if (cc.writeCache()) {
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCache(fo);
}
});
inc(StatisticKeys.WRITES_CACHED);
} else {
storeNoCache(o);
}
}
public <T> void storeList(List<T> lst) {
//have to sort list - might have different objects
List<T> storeDirect = new ArrayList<T>();
List<T> storeInBg = new ArrayList<T>();
//checking permission - might take some time ;-(
for (T o : lst) {
if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) {
if (getId(o) == null) {
if (accessDenied(o, Permission.INSERT)) {
throw new SecurityException("Insert of new Object denied!");
}
} else {
if (accessDenied(o, Permission.UPDATE)) {
throw new SecurityException("Update of Object denied!");
}
}
}
Cache c = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class);
if (c != null && !isAnnotationPresentInHierarchy(o.getClass(), NoCache.class)) {
if (c.writeCache()) {
storeInBg.add(o);
} else {
storeDirect.add(o);
}
} else {
storeDirect.add(o);
}
}
storeListInBackground(storeInBg);
storeNoCacheList(storeDirect);
}
/**
* deletes a single object from morphium backend. Clears cache
*
* @param o
*/
public <T> void deleteObject(T o) {
o = getRealObject(o);
if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) {
if (accessDenied(o, Permission.DELETE)) {
throw new SecurityException("Deletion of Object denied!");
}
}
firePreRemoveEvent(o);
ObjectId id = config.getMapper().getId(o);
BasicDBObject db = new BasicDBObject();
db.append("_id", id);
WriteConcern wc = getWriteConcernForClass(o.getClass());
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(config.getMapper().getCollectionName(o.getClass())).remove(db);
} else {
database.getCollection(config.getMapper().getCollectionName(o.getClass())).remove(db, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(o.getClass(), o, dur, false, WriteAccessType.SINGLE_DELETE);
clearCachefor(o.getClass());
inc(StatisticKeys.WRITES);
firePostRemoveEvent(o);
}
public void resetCache() {
setCache(new Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>());
}
public void setCache(Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cache) {
this.cache = cache;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////
/////////////// Statistics
/////////
/////
///
public Map<String, Double> getStatistics() {
return new Statistics(this);
}
public void removeEntryFromCache(Class cls, ObjectId id) {
Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> c = cloneCache();
Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idc = cloneIdCache();
idc.get(cls).remove(id);
ArrayList<String> toRemove = new ArrayList<String>();
for (String key : c.get(cls).keySet()) {
for (Object el : c.get(cls).get(key).getFound()) {
ObjectId lid = config.getMapper().getId(el);
if (lid == null) {
logger.error("Null id in CACHE?");
toRemove.add(key);
}
if (lid.equals(id)) {
toRemove.add(key);
}
}
}
for (String k : toRemove) {
c.get(cls).remove(k);
}
setCache(c);
setIdCache(idc);
}
public Map<StatisticKeys, StatisticValue> getStats() {
return stats;
}
public void addShutdownListener(ShutdownListener l) {
shutDownListeners.add(l);
}
public void removeShutdownListener(ShutdownListener l) {
shutDownListeners.remove(l);
}
public void close() {
cacheHousekeeper.end();
for (ShutdownListener l : shutDownListeners) {
l.onShutdown(this);
}
try {
Thread.sleep(1000); //give it time to end ;-)
} catch (Exception e) {
logger.debug("Ignoring interrupted-exception");
}
if (cacheHousekeeper.isAlive()) {
cacheHousekeeper.interrupt();
}
database = null;
config = null;
mongo.close();
MorphiumSingleton.reset();
}
public String createCamelCase(String n) {
return config.getMapper().createCamelCase(n, false);
}
/**
* create a proxy object, implementing the ParitallyUpdateable Interface
* these objects will be updated in mongo by only changing altered fields
* <b>Attention:</b> the field name if determined by the setter name for now. That means, it does not honor the @Property-Annotation!!!
* To make sure, you take the correct field - use the UpdatingField-Annotation for the setters!
*
* @param o
* @param <T>
* @return
*/
public <T> T createPartiallyUpdateableEntity(T o) {
return (T) Enhancer.create(o.getClass(), new Class[]{PartiallyUpdateable.class, Serializable.class}, new PartiallyUpdateableProxy(this, o));
}
public <T> T createLazyLoadedEntity(Class<T> cls, ObjectId id) {
return (T) Enhancer.create(cls, new Class[]{Serializable.class}, new LazyDeReferencingProxy(this, cls, id));
}
protected <T> MongoField<T> createMongoField() {
try {
return (MongoField<T>) config.getFieldImplClass().newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public String getLastChangeField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastChange.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastChangeByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastChangeBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastAccessField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastAccess.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastAccessByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastAccessBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getCreationTimeField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null;
List<String> lst = config.getMapper().getFields(cls, CreationTime.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getCreatedByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null;
List<String> lst = config.getMapper().getFields(cls, CreatedBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
//////////////////////////////////////////////////////
////////// SecuritySettings
///////
/////
////
///
//
public MongoSecurityManager getSecurityManager() {
return config.getSecurityMgr();
}
/**
* temporarily switch off security settings - needed by SecurityManagers
*/
public void setPrivileged() {
privileged.add(Thread.currentThread());
}
public boolean checkAccess(String domain, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return true;
}
return getSecurityManager().checkAccess(domain, p);
}
public boolean accessDenied(Class<?> cls, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return false;
}
return !getSecurityManager().checkAccess(cls, p);
}
public boolean accessDenied(Object r, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return false;
}
return !getSecurityManager().checkAccess(config.getMapper().getRealObject(r), p);
}
}
| public void callLifecycleMethod(Class<? extends Annotation> type, Object on) {
if (on == null) return;
//No synchronized block - might cause the methods to be put twice into the
//hashtabel - but for performance reasons, it's ok...
Class<?> cls = on.getClass();
//No Lifecycle annotation - no method calling
if (!isAnnotationPresentInHierarchy(cls, Lifecycle.class)) {//cls.isAnnotationPresent(Lifecycle.class)) {
return;
}
//Already stored - should not change during runtime
if (lifeCycleMethods.get(cls) != null) {
if (lifeCycleMethods.get(cls).get(type) != null) {
try {
lifeCycleMethods.get(cls).get(type).invoke(on);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
return;
}
Map<Class<? extends Annotation>, Method> methods = new HashMap<Class<? extends Annotation>, Method>();
//Methods must be public
for (Method m : cls.getMethods()) {
for (Annotation a : m.getAnnotations()) {
methods.put(a.annotationType(), m);
}
}
lifeCycleMethods.put(cls, methods);
if (methods.get(type) != null) {
try {
methods.get(type).invoke(on);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
/**
* careful this actually changes the parameter o!
*
* @param o
* @param <T>
* @return
*/
public <T> T reread(T o) {
if (o == null) throw new RuntimeException("Cannot re read null!");
ObjectId id = getId(o);
if (id == null) {
return null;
}
DBCollection col = database.getCollection(getConfig().getMapper().getCollectionName(o.getClass()));
BasicDBObject srch = new BasicDBObject("_id", id);
DBCursor crs = col.find(srch).limit(1);
if (crs.hasNext()) {
DBObject dbo = crs.next();
Object fromDb = getConfig().getMapper().unmarshall(o.getClass(), dbo);
List<String> flds = getFields(o.getClass());
for (String f : flds) {
Field fld = getConfig().getMapper().getField(o.getClass(), f);
if (java.lang.reflect.Modifier.isStatic(fld.getModifiers())) {
continue;
}
try {
fld.set(o, fld.get(fromDb));
} catch (IllegalAccessException e) {
logger.error("Could not set Value: " + fld);
}
}
} else {
logger.info("Did not find object with id " + id);
return null;
}
return o;
}
private void firePreStoreEvent(Object o, boolean isNew) {
if (o == null) return;
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preStore(o, isNew);
}
callLifecycleMethod(PreStore.class, o);
}
private void firePostStoreEvent(Object o, boolean isNew) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postStore(o, isNew);
}
callLifecycleMethod(PostStore.class, o);
//existing object => store last Access, if needed
}
private void firePreDropEvent(Class cls) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preDrop(cls);
}
}
private void firePostDropEvent(Class cls) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postDrop(cls);
}
}
private void firePostUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) {
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postUpdate(cls, t);
}
}
private void firePreUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) {
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preUpdate(cls, t);
}
}
private void firePostRemoveEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postRemove(o);
}
callLifecycleMethod(PostRemove.class, o);
}
private void firePostRemoveEvent(Query q) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postRemove(q);
}
//TODO: FIX - Cannot call lifecycle method here
}
private void firePreRemoveEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preDelete(o);
}
callLifecycleMethod(PreRemove.class, o);
}
private void firePreRemoveEvent(Query q) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.preRemove(q);
}
//TODO: Fix - cannot call lifecycle method
}
// private void firePreListStoreEvent(List records, Map<Object,Boolean> isNew) {
// //Avoid concurrent modification exception
// List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
// for (MorphiumStorageListener l : lst) {
// l.preListStore(records,isNew);
// }
// for (Object o : records) {
// callLifecycleMethod(PreStore.class, o);
// }
// }
// private void firePostListStoreEvent(List records, Map<Object,Boolean> isNew) {
// //Avoid concurrent modification exception
// List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
// for (MorphiumStorageListener l : lst) {
// l.postListStore(records,isNew);
// }
// for (Object o : records) {
// callLifecycleMethod(PostStore.class, o);
// }
//
// }
/**
* will be called by query after unmarshalling
*
* @param o
*/
protected void firePostLoadEvent(Object o) {
//Avoid concurrent modification exception
List<MorphiumStorageListener> lst = (List<MorphiumStorageListener>) listeners.clone();
for (MorphiumStorageListener l : lst) {
l.postLoad(o);
}
callLifecycleMethod(PostLoad.class, o);
}
public void storeNoCache(Object o) {
long start = System.currentTimeMillis();
Class type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, Entity.class)) {
throw new RuntimeException("Not an entity! Storing not possible!");
}
inc(StatisticKeys.WRITES);
ObjectId id = config.getMapper().getId(o);
if (isAnnotationPresentInHierarchy(type, PartialUpdate.class)) {
if ((o instanceof PartiallyUpdateable)) {
updateUsingFields(o, ((PartiallyUpdateable) o).getAlteredFields().toArray(new String[((PartiallyUpdateable) o).getAlteredFields().size()]));
((PartiallyUpdateable) o).clearAlteredFields();
return;
}
}
o = getRealObject(o);
if (o == null) {
logger.warn("Illegal Reference? - cannot store Lazy-Loaded / Partial Update Proxy without delegate!");
return;
}
boolean isNew = id == null;
firePreStoreEvent(o, isNew);
long dur = System.currentTimeMillis() - start;
DBObject marshall = config.getMapper().marshall(o);
if (isNew) {
//new object - need to store creation time
if (isAnnotationPresentInHierarchy(type, StoreCreationTime.class)) {
List<String> lst = config.getMapper().getFields(type, CreationTime.class);
if (lst == null || lst.size() == 0) {
logger.error("Unable to store creation time as @CreationTime is missing");
} else {
long now = System.currentTimeMillis();
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, now);
} catch (IllegalAccessException e) {
logger.error("Could not set creation time", e);
}
}
marshall.put(ctf, now);
}
}
lst = config.getMapper().getFields(type, CreatedBy.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, config.getSecurityMgr().getCurrentUserId());
} catch (IllegalAccessException e) {
logger.error("Could not set created by", e);
}
}
marshall.put(ctf, config.getSecurityMgr().getCurrentUserId());
}
}
}
}
if (isAnnotationPresentInHierarchy(type, StoreLastChange.class)) {
List<String> lst = config.getMapper().getFields(type, LastChange.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
long now = System.currentTimeMillis();
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, now);
} catch (IllegalAccessException e) {
logger.error("Could not set modification time", e);
}
}
marshall.put(ctf, now);
}
} else {
logger.warn("Could not store last change - @LastChange missing!");
}
lst = config.getMapper().getFields(type, LastChangeBy.class);
if (lst != null && lst.size() > 0) {
for (String ctf : lst) {
Field f = getField(type, ctf);
if (f != null) {
try {
f.set(o, config.getSecurityMgr().getCurrentUserId());
} catch (IllegalAccessException e) {
logger.error("Could not set changed by", e);
}
}
marshall.put(ctf, config.getSecurityMgr().getCurrentUserId());
}
}
}
String coll = config.getMapper().getCollectionName(type);
if (!database.collectionExists(coll)) {
if (logger.isDebugEnabled())
logger.debug("Collection does not exist - ensuring indices");
ensureIndicesFor(type);
}
WriteConcern wc = getWriteConcernForClass(type);
if (wc != null) {
database.getCollection(coll).save(marshall, wc);
} else {
database.getCollection(coll).save(marshall);
}
dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(o.getClass(), marshall, dur, true, WriteAccessType.SINGLE_INSERT);
if (logger.isDebugEnabled()) {
String n = "";
if (isNew) {
n = "NEW ";
}
logger.debug(n + "stored " + type.getSimpleName() + " after " + dur + " ms length:" + marshall.toString().length());
}
if (isNew) {
List<String> flds = config.getMapper().getFields(o.getClass(), Id.class);
if (flds == null) {
throw new RuntimeException("Object does not have an ID field!");
}
try {
//Setting new ID (if object was new created) to Entity
getField(o.getClass(), flds.get(0)).set(o, marshall.get("_id"));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
Cache ch = getAnnotationFromHierarchy(o.getClass(), Cache.class);
if (ch != null) {
if (ch.clearOnWrite()) {
clearCachefor(o.getClass());
}
}
firePostStoreEvent(o, isNew);
}
/**
* same as retReplicaSetStatus(false);
*
* @return
*/
public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus() {
return getReplicaSetStatus(false);
}
/**
* get the current replicaset status - issues the replSetGetStatus command to mongo
* if full==true, also the configuration is read. This method is called with full==false for every write in
* case a Replicaset is configured to find out the current number of active nodes
*
* @param full
* @return
*/
public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus(boolean full) {
if (config.getMode().equals(MongoDbMode.REPLICASET)) {
try {
CommandResult res = getMongo().getDB("admin").command("replSetGetStatus");
de.caluga.morphium.replicaset.ReplicaSetStatus status = getConfig().getMapper().unmarshall(de.caluga.morphium.replicaset.ReplicaSetStatus.class, res);
if (full) {
DBCursor rpl = getMongo().getDB("local").getCollection("system.replset").find();
DBObject stat = rpl.next(); //should only be one, i think
ReplicaSetConf cfg = getConfig().getMapper().unmarshall(ReplicaSetConf.class, stat);
List<Object> mem = cfg.getMemberList();
List<ConfNode> cmembers = new ArrayList<ConfNode>();
for (Object o : mem) {
DBObject dbo = (DBObject) o;
ConfNode cn = getConfig().getMapper().unmarshall(ConfNode.class, dbo);
cmembers.add(cn);
}
cfg.setMembers(cmembers);
status.setConfig(cfg);
}
//de-referencing list
List lst = status.getMembers();
List<ReplicaSetNode> members = new ArrayList<ReplicaSetNode>();
for (Object l : lst) {
DBObject o = (DBObject) l;
ReplicaSetNode n = getConfig().getMapper().unmarshall(ReplicaSetNode.class, o);
members.add(n);
}
status.setMembers(members);
return status;
} catch (Exception e) {
logger.error("Could not get Replicaset status", e);
}
}
return null;
}
public boolean isReplicaSet() {
return config.getMode().equals(MongoDbMode.REPLICASET);
}
public WriteConcern getWriteConcernForClass(Class<?> cls) {
WriteSafety safety = getAnnotationFromHierarchy(cls, WriteSafety.class); // cls.getAnnotation(WriteSafety.class);
if (safety == null) return null;
boolean fsync = safety.waitForSync();
boolean j = safety.waitForJournalCommit();
if (j && fsync) {
fsync = false;
}
int w = safety.level().getValue();
if (!isReplicaSet() && w > 1) {
w = 1;
}
int timeout = safety.timeout();
if (isReplicaSet() && w > 2) {
de.caluga.morphium.replicaset.ReplicaSetStatus s = getReplicaSetStatus();
if (s == null || s.getActiveNodes() == 0) {
logger.warn("ReplicaSet status is null or no node active! Assuming default write concern");
return null;
}
int activeNodes = s.getActiveNodes();
if (timeout == 0) {
if (getConfig().getConnectionTimeout() == 0) {
if (logger.isDebugEnabled())
logger.debug("Not waiting for all slaves withoug timeout - unfortunately no connection timeout set in config - setting to 10s, Type: " + cls.getSimpleName());
timeout = 10000;
} else {
if (logger.isDebugEnabled())
logger.debug("Not waiting for all slaves without timeout - could cause deadlock. Setting to connectionTimeout value, Type: " + cls.getSimpleName());
timeout = getConfig().getConnectionTimeout();
}
}
//Wait for all active slaves
w = activeNodes;
}
// if (w==0) {
// return WriteConcern.NONE;
// }
// if(w==1) {
// return WriteConcern.FSYNC_SAFE;
// }
// if (w==2) {
// return WriteConcern.JOURNAL_SAFE;
// }
// if (w==3) {
// return WriteConcern.REPLICAS_SAFE;
// }
return new WriteConcern(w, timeout, fsync, j);
}
public void addProfilingListener(ProfilingListener l) {
profilingListeners.add(l);
}
public void removeProfilingListener(ProfilingListener l) {
profilingListeners.remove(l);
}
private void fireProfilingWriteEvent(Class type, Object data, long time, boolean isNew, WriteAccessType wt) {
for (ProfilingListener l : profilingListeners) {
try {
l.writeAccess(type, data, time, isNew, wt);
} catch (Throwable e) {
logger.error("Error during profiling: ", e);
}
}
}
public void fireProfilingReadEvent(Query q, long time, ReadAccessType t) {
for (ProfilingListener l : profilingListeners) {
try {
l.readAccess(q, time, t);
} catch (Throwable e) {
logger.error("Error during profiling", e);
}
}
}
public void storeNoCacheList(List lst) {
if (!lst.isEmpty()) {
HashMap<Class, List<Object>> sorted = new HashMap<Class, List<Object>>();
HashMap<Object, Boolean> isNew = new HashMap<Object, Boolean>();
for (Object o : lst) {
Class type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, Entity.class)) {
logger.error("Not an entity! Storing not possible! Even not in list!");
continue;
}
inc(StatisticKeys.WRITES);
ObjectId id = config.getMapper().getId(o);
if (isAnnotationPresentInHierarchy(type, PartialUpdate.class)) {
//not part of list, acutally...
if ((o instanceof PartiallyUpdateable)) {
updateUsingFields(o, ((PartiallyUpdateable) o).getAlteredFields().toArray(new String[((PartiallyUpdateable) o).getAlteredFields().size()]));
((PartiallyUpdateable) o).clearAlteredFields();
continue;
}
}
o = getRealObject(o);
if (o == null) {
logger.warn("Illegal Reference? - cannot store Lazy-Loaded / Partial Update Proxy without delegate!");
return;
}
if (sorted.get(o.getClass()) == null) {
sorted.put(o.getClass(), new ArrayList<Object>());
}
sorted.get(o.getClass()).add(o);
if (getId(o) == null) {
isNew.put(o, true);
} else {
isNew.put(o, false);
}
firePreStoreEvent(o, isNew.get(o));
}
// firePreListStoreEvent(lst,isNew);
for (Map.Entry<Class, List<Object>> es : sorted.entrySet()) {
Class c = es.getKey();
ArrayList<DBObject> dbLst = new ArrayList<DBObject>();
//bulk insert... check if something already exists
WriteConcern wc = getWriteConcernForClass(c);
DBCollection collection = database.getCollection(getConfig().getMapper().getCollectionName(c));
for (Object record : es.getValue()) {
DBObject marshall = config.getMapper().marshall(record);
if (isNew.get(record)) {
dbLst.add(marshall);
} else {
//single update
long start = System.currentTimeMillis();
if (wc == null) {
collection.save(marshall);
} else {
collection.save(marshall, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(c, marshall, dur, false, WriteAccessType.SINGLE_INSERT);
firePostStoreEvent(record, isNew.get(record));
}
}
long start = System.currentTimeMillis();
if (wc == null) {
collection.insert(dbLst);
} else {
collection.insert(dbLst, wc);
}
long dur = System.currentTimeMillis() - start;
//bulk insert
fireProfilingWriteEvent(c, dbLst, dur, true, WriteAccessType.BULK_INSERT);
for (Object record : es.getValue()) {
if (isNew.get(record)) {
firePostStoreEvent(record, isNew.get(record));
}
}
}
// firePostListStoreEvent(lst,isNew);
}
}
protected boolean isCached(Class<? extends Object> type, String k) {
Cache c = getAnnotationFromHierarchy(type, Cache.class); ///type.getAnnotation(Cache.class);
if (c != null) {
if (!c.readCache()) return false;
} else {
return false;
}
return cache.get(type) != null && cache.get(type).get(k) != null && cache.get(type).get(k).getFound() != null;
}
/**
* return object by from cache. Cache key usually is the string-representation of the search
* query.toQueryObject()
*
* @param type
* @param k
* @param <T>
* @return
*/
public <T> List<T> getFromCache(Class<T> type, String k) {
if (cache.get(type) == null || cache.get(type).get(k) == null) return null;
final CacheElement cacheElement = cache.get(type).get(k);
cacheElement.setLru(System.currentTimeMillis());
return cacheElement.getFound();
}
public Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cloneCache() {
return (Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>) cache.clone();
}
public Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> cloneIdCache() {
return (Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>>) idCache.clone();
}
/**
* issues a delete command - no lifecycle methods calles, no drop, keeps all indexec this way
*
* @param cls
*/
public void clearCollection(Class<? extends Object> cls) {
delete(createQueryFor(cls));
}
/**
* clears every single object in collection - reads ALL objects to do so
* this way Lifecycle methods can be called!
*
* @param cls
*/
public void deleteCollectionItems(Class<? extends Object> cls) {
if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) {
try {
if (accessDenied(cls.newInstance(), Permission.DROP)) {
throw new SecurityException("Drop of Collection denied!");
}
} catch (InstantiationException ex) {
Logger.getLogger(Morphium.class).error(ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Morphium.class).error(ex);
}
}
inc(StatisticKeys.WRITES);
List<? extends Object> lst = readAll(cls);
for (Object r : lst) {
deleteObject(r);
}
clearCacheIfNecessary(cls);
}
/**
* return a list of all elements stored in morphium for this type
*
* @param cls - type to search for, needs to be an Property
* @param <T> - Type
* @return - list of all elements stored
*/
public <T> List<T> readAll(Class<T> cls) {
inc(StatisticKeys.READS);
Query<T> qu;
qu = createQueryFor(cls);
return qu.asList();
}
public <T> Query<T> createQueryFor(Class<T> type) {
return new QueryImpl<T>(this, type, config.getMapper());
}
public <T> List<T> find(Query<T> q) {
return q.asList();
}
private <T> T getFromIDCache(Class<T> type, ObjectId id) {
if (idCache.get(type) != null) {
return (T) idCache.get(type).get(id);
}
return null;
}
public List<Object> distinct(Enum key, Class c) {
return distinct(key.name(), c);
}
/**
* returns a distinct list of values of the given collection
* Attention: these values are not unmarshalled, you might get MongoDBObjects
*/
public List<Object> distinct(Enum key, Query q) {
return distinct(key.name(), q);
}
/**
* returns a distinct list of values of the given collection
* Attention: these values are not unmarshalled, you might get MongoDBObjects
*/
public List<Object> distinct(String key, Query q) {
return database.getCollection(config.getMapper().getCollectionName(q.getType())).distinct(key, q.toQueryObject());
}
public List<Object> distinct(String key, Class cls) {
DBCollection collection = database.getCollection(config.getMapper().getCollectionName(cls));
setReadPreference(collection, cls);
return collection.distinct(key, new BasicDBObject());
}
private void setReadPreference(DBCollection c, Class type) {
ReadPreference pr = getAnnotationFromHierarchy(type, ReadPreference.class);
if (pr != null) {
if (pr.equals(ReadPreferenceLevel.MASTER_ONLY)) {
c.setReadPreference(com.mongodb.ReadPreference.PRIMARY);
} else {
c.setReadPreference(com.mongodb.ReadPreference.SECONDARY);
}
} else {
c.setReadPreference(null);
}
}
public DBObject group(Query q, Map<String, Object> initial, String jsReduce, String jsFinalize, String... keys) {
BasicDBObject k = new BasicDBObject();
BasicDBObject ini = new BasicDBObject();
ini.putAll(initial);
for (String ks : keys) {
if (ks.startsWith("-")) {
k.append(ks.substring(1), "false");
} else if (ks.startsWith("+")) {
k.append(ks.substring(1), "true");
} else {
k.append(ks, "true");
}
}
if (!jsReduce.trim().startsWith("function(")) {
jsReduce = "function (obj,data) { " + jsReduce + " }";
}
if (jsFinalize == null) {
jsFinalize = "";
}
if (!jsFinalize.trim().startsWith("function(")) {
jsFinalize = "function (data) {" + jsFinalize + "}";
}
GroupCommand cmd = new GroupCommand(database.getCollection(config.getMapper().getCollectionName(q.getType())),
k, q.toQueryObject(), ini, jsReduce, jsFinalize);
return database.getCollection(config.getMapper().getCollectionName(q.getType())).group(cmd);
}
public <T> T findById(Class<T> type, ObjectId id) {
T ret = getFromIDCache(type, id);
if (ret != null) return ret;
List<String> ls = config.getMapper().getFields(type, Id.class);
if (ls.size() == 0) throw new RuntimeException("Cannot find by ID on non-Entity");
return (T) createQueryFor(type).f(ls.get(0)).eq(id).get();
}
// /**
// * returns a list of all elements for the given type, matching the given query
// * @param qu - the query to search
// * @param <T> - type of the elementyx
// * @return - list of elements matching query
// */
// public <T> List<T> readAll(Query<T> qu) {
// inc(StatisticKeys.READS);
// if (qu.getEntityClass().isAnnotationPresent(Cache.class)) {
// if (isCached(qu.getEntityClass(), qu.toString())) {
// inc(StatisticKeys.CHITS);
// return getFromCache(qu.getEntityClass(), qu.toString());
// } else {
// inc(StatisticKeys.CMISS);
// }
// }
// List<T> lst = qu.asList();
// addToCache(qu.toString()+" / l:"+((QueryImpl)qu).getLimit()+" o:"+((QueryImpl)qu).getOffset(), qu.getEntityClass(), lst);
// return lst;
//
// }
/**
* does not set values in DB only in the entity
*
* @param toSetValueIn
*/
public void setValueIn(Object toSetValueIn, String fld, Object value) {
config.getMapper().setValue(toSetValueIn, value, fld);
}
public void setValueIn(Object toSetValueIn, Enum fld, Object value) {
config.getMapper().setValue(toSetValueIn, value, fld.name());
}
public Object getValueOf(Object toGetValueFrom, String fld) {
return config.getMapper().getValue(toGetValueFrom, fld);
}
public Object getValueOf(Object toGetValueFrom, Enum fld) {
return config.getMapper().getValue(toGetValueFrom, fld.name());
}
@SuppressWarnings("unchecked")
public <T> List<T> findByField(Class<T> cls, String fld, Object val) {
Query<T> q = createQueryFor(cls);
q = q.f(fld).eq(val);
return q.asList();
// return createQueryFor(cls).field(fld).equal(val).asList();
}
public <T> List<T> findByField(Class<T> cls, Enum fld, Object val) {
Query<T> q = createQueryFor(cls);
q = q.f(fld).eq(val);
return q.asList();
// return createQueryFor(cls).field(fld).equal(val).asList();
}
/**
* deletes all objects matching the given query
*
* @param q
* @param <T>
*/
public <T> void delete(Query<T> q) {
firePreRemoveEvent(q);
WriteConcern wc = getWriteConcernForClass(q.getType());
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(config.getMapper().getCollectionName(q.getType())).remove(q.toQueryObject());
} else {
database.getCollection(config.getMapper().getCollectionName(q.getType())).remove(q.toQueryObject(), wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(q.getType(), q.toQueryObject(), dur, false, WriteAccessType.BULK_DELETE);
clearCacheIfNecessary(q.getType());
firePostRemoveEvent(q);
}
/**
* get a list of valid fields of a given record as they are in the MongoDB
* so, if you have a field Mapping, the mapped Property-name will be used
*
* @param cls
* @return
*/
public final List<String> getFields(Class cls) {
return config.getMapper().getFields(cls);
}
public final Class getTypeOfField(Class cls, String fld) {
Field f = getField(cls, fld);
if (f == null) return null;
return f.getType();
}
public boolean storesLastChange(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreLastChange.class);
}
public boolean storesLastAccess(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreLastAccess.class);
}
public boolean storesCreation(Class<? extends Object> cls) {
return isAnnotationPresentInHierarchy(cls, StoreCreationTime.class);
}
private String getFieldName(Class cls, String fld) {
return config.getMapper().getFieldName(cls, fld);
}
/**
* extended logic: Fld may be, the java field name, the name of the specified value in Property-Annotation or
* the translated underscored lowercase name (mongoId => mongo_id)
*
* @param cls - class to search
* @param fld - field name
* @return field, if found, null else
*/
private Field getField(Class cls, String fld) {
return config.getMapper().getField(cls, fld);
}
public void setValue(Object in, String fld, Object val) {
config.getMapper().setValue(in, val, fld);
}
public Object getValue(Object o, String fld) {
return config.getMapper().getValue(o, fld);
}
public Long getLongValue(Object o, String fld) {
return (Long) getValue(o, fld);
}
public String getStringValue(Object o, String fld) {
return (String) getValue(o, fld);
}
public Date getDateValue(Object o, String fld) {
return (Date) getValue(o, fld);
}
public Double getDoubleValue(Object o, String fld) {
return (Double) getValue(o, fld);
}
/**
* Erase cache entries for the given type. is being called after every store
* depending on cache settings!
*
* @param cls
*/
public void clearCachefor(Class<? extends Object> cls) {
if (cache.get(cls) != null) {
cache.get(cls).clear();
}
if (idCache.get(cls) != null) {
idCache.get(cls).clear();
}
//clearCacheFor(cls);
}
public void storeInBackground(final Object lst) {
inc(StatisticKeys.WRITES_CACHED);
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCache(lst);
}
});
}
public void storeListInBackground(final List lst) {
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCacheList(lst);
}
});
}
public ObjectId getId(Object o) {
return config.getMapper().getId(o);
}
public void dropCollection(Class<? extends Object> cls) {
if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) {
try {
if (accessDenied(cls.newInstance(), Permission.DROP)) {
throw new SecurityException("Drop of Collection denied!");
}
} catch (InstantiationException ex) {
Logger.getLogger(Morphium.class.getName()).fatal(ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Morphium.class.getName()).fatal(ex);
}
}
if (config.getMode() == MongoDbMode.REPLICASET && config.getAdr().size() > 1) {
//replicaset
logger.warn("Cannot drop collection for class " + cls.getSimpleName() + " as we're in a clustered environment (Driver 2.8.0)");
clearCollection(cls);
return;
}
if (isAnnotationPresentInHierarchy(cls, Entity.class)) {
firePreDropEvent(cls);
long start = System.currentTimeMillis();
// Entity entity = getAnnotationFromHierarchy(cls, Entity.class); //cls.getAnnotation(Entity.class);
database.getCollection(config.getMapper().getCollectionName(cls)).drop();
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, null, dur, false, WriteAccessType.DROP);
firePostDropEvent(cls);
} else {
throw new RuntimeException("No entity class: " + cls.getName());
}
}
public void ensureIndex(Class<?> cls, Map<String, Integer> index) {
List<String> fields = getFields(cls);
Map<String, Integer> idx = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> es : index.entrySet()) {
String k = es.getKey();
if (!fields.contains(k) && !fields.contains(config.getMapper().convertCamelCase(k))) {
throw new IllegalArgumentException("Field unknown for type " + cls.getSimpleName() + ": " + k);
}
String fn = config.getMapper().getFieldName(cls, k);
idx.put(fn, es.getValue());
}
long start = System.currentTimeMillis();
database.getCollection(config.getMapper().getCollectionName(cls)).ensureIndex(new BasicDBObject(idx));
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(cls, new BasicDBObject(idx), dur, false, WriteAccessType.ENSURE_INDEX);
}
/**
* ensureIndex(CachedObject.class,"counter","-value");
* Similar to sorting
*
* @param cls
* @param fldStr
*/
public void ensureIndex(Class<?> cls, String... fldStr) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
for (String f : fldStr) {
int idx = 1;
if (f.startsWith("-")) {
idx = -1;
f = f.substring(1);
} else if (f.startsWith("+")) {
f = f.substring(1);
}
m.put(f, idx);
}
ensureIndex(cls, m);
}
public void ensureIndex(Class<?> cls, Enum... fldStr) {
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
for (Enum e : fldStr) {
String f = e.name();
m.put(f, 1);
}
ensureIndex(cls, m);
}
/**
* Stores a single Object. Clears the corresponding cache
*
* @param o - Object to store
*/
public void store(Object o) {
if (o instanceof List) {
throw new RuntimeException("Lists need to be stored with storeList");
}
Class<?> type = getRealClass(o.getClass());
if (!isAnnotationPresentInHierarchy(type, NoProtection.class)) { //o.getClass().isAnnotationPresent(NoProtection.class)) {
if (getId(o) == null) {
if (accessDenied(o, Permission.INSERT)) {
throw new SecurityException("Insert of new Object denied!");
}
} else {
if (accessDenied(o, Permission.UPDATE)) {
throw new SecurityException("Update of Object denied!");
}
}
}
Cache cc = getAnnotationFromHierarchy(type, Cache.class);//o.getClass().getAnnotation(Cache.class);
if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class)) {
storeNoCache(o);
return;
}
final Object fo = o;
if (cc.writeCache()) {
writers.execute(new Runnable() {
@Override
public void run() {
storeNoCache(fo);
}
});
inc(StatisticKeys.WRITES_CACHED);
} else {
storeNoCache(o);
}
}
public <T> void storeList(List<T> lst) {
//have to sort list - might have different objects
List<T> storeDirect = new ArrayList<T>();
List<T> storeInBg = new ArrayList<T>();
//checking permission - might take some time ;-(
for (T o : lst) {
if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) {
if (getId(o) == null) {
if (accessDenied(o, Permission.INSERT)) {
throw new SecurityException("Insert of new Object denied!");
}
} else {
if (accessDenied(o, Permission.UPDATE)) {
throw new SecurityException("Update of Object denied!");
}
}
}
Cache c = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class);
if (c != null && !isAnnotationPresentInHierarchy(o.getClass(), NoCache.class)) {
if (c.writeCache()) {
storeInBg.add(o);
} else {
storeDirect.add(o);
}
} else {
storeDirect.add(o);
}
}
storeListInBackground(storeInBg);
storeNoCacheList(storeDirect);
}
/**
* deletes a single object from morphium backend. Clears cache
*
* @param o
*/
public <T> void deleteObject(T o) {
o = getRealObject(o);
if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) {
if (accessDenied(o, Permission.DELETE)) {
throw new SecurityException("Deletion of Object denied!");
}
}
firePreRemoveEvent(o);
ObjectId id = config.getMapper().getId(o);
BasicDBObject db = new BasicDBObject();
db.append("_id", id);
WriteConcern wc = getWriteConcernForClass(o.getClass());
long start = System.currentTimeMillis();
if (wc == null) {
database.getCollection(config.getMapper().getCollectionName(o.getClass())).remove(db);
} else {
database.getCollection(config.getMapper().getCollectionName(o.getClass())).remove(db, wc);
}
long dur = System.currentTimeMillis() - start;
fireProfilingWriteEvent(o.getClass(), o, dur, false, WriteAccessType.SINGLE_DELETE);
clearCachefor(o.getClass());
inc(StatisticKeys.WRITES);
firePostRemoveEvent(o);
}
public void resetCache() {
setCache(new Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>());
}
public void setCache(Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cache) {
this.cache = cache;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////
/////////////// Statistics
/////////
/////
///
public Map<String, Double> getStatistics() {
return new Statistics(this);
}
public void removeEntryFromCache(Class cls, ObjectId id) {
Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> c = cloneCache();
Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idc = cloneIdCache();
idc.get(cls).remove(id);
ArrayList<String> toRemove = new ArrayList<String>();
for (String key : c.get(cls).keySet()) {
for (Object el : c.get(cls).get(key).getFound()) {
ObjectId lid = config.getMapper().getId(el);
if (lid == null) {
logger.error("Null id in CACHE?");
toRemove.add(key);
}
if (lid.equals(id)) {
toRemove.add(key);
}
}
}
for (String k : toRemove) {
c.get(cls).remove(k);
}
setCache(c);
setIdCache(idc);
}
public Map<StatisticKeys, StatisticValue> getStats() {
return stats;
}
public void addShutdownListener(ShutdownListener l) {
shutDownListeners.add(l);
}
public void removeShutdownListener(ShutdownListener l) {
shutDownListeners.remove(l);
}
public void close() {
cacheHousekeeper.end();
for (ShutdownListener l : shutDownListeners) {
l.onShutdown(this);
}
try {
Thread.sleep(1000); //give it time to end ;-)
} catch (Exception e) {
logger.debug("Ignoring interrupted-exception");
}
if (cacheHousekeeper.isAlive()) {
cacheHousekeeper.interrupt();
}
database = null;
config = null;
mongo.close();
MorphiumSingleton.reset();
}
public String createCamelCase(String n) {
return config.getMapper().createCamelCase(n, false);
}
/**
* create a proxy object, implementing the ParitallyUpdateable Interface
* these objects will be updated in mongo by only changing altered fields
* <b>Attention:</b> the field name if determined by the setter name for now. That means, it does not honor the @Property-Annotation!!!
* To make sure, you take the correct field - use the UpdatingField-Annotation for the setters!
*
* @param o
* @param <T>
* @return
*/
public <T> T createPartiallyUpdateableEntity(T o) {
return (T) Enhancer.create(o.getClass(), new Class[]{PartiallyUpdateable.class, Serializable.class}, new PartiallyUpdateableProxy(this, o));
}
public <T> T createLazyLoadedEntity(Class<T> cls, ObjectId id) {
return (T) Enhancer.create(cls, new Class[]{Serializable.class}, new LazyDeReferencingProxy(this, cls, id));
}
protected <T> MongoField<T> createMongoField() {
try {
return (MongoField<T>) config.getFieldImplClass().newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public String getLastChangeField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastChange.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastChangeByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastChangeBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastAccessField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastAccess.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getLastAccessByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null;
List<String> lst = config.getMapper().getFields(cls, LastAccessBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getCreationTimeField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null;
List<String> lst = config.getMapper().getFields(cls, CreationTime.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
public String getCreatedByField(Class<?> cls) {
if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null;
List<String> lst = config.getMapper().getFields(cls, CreatedBy.class);
if (lst == null || lst.isEmpty()) return null;
return lst.get(0);
}
//////////////////////////////////////////////////////
////////// SecuritySettings
///////
/////
////
///
//
public MongoSecurityManager getSecurityManager() {
return config.getSecurityMgr();
}
/**
* temporarily switch off security settings - needed by SecurityManagers
*/
public void setPrivileged() {
privileged.add(Thread.currentThread());
}
public boolean checkAccess(String domain, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return true;
}
return getSecurityManager().checkAccess(domain, p);
}
public boolean accessDenied(Class<?> cls, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return false;
}
return !getSecurityManager().checkAccess(cls, p);
}
public boolean accessDenied(Object r, Permission p) throws MongoSecurityException {
if (privileged.contains(Thread.currentThread())) {
privileged.remove(Thread.currentThread());
return false;
}
return !getSecurityManager().checkAccess(config.getMapper().getRealObject(r), p);
}
}
|
diff --git a/common/rebelkeithy/mods/metallurgy/metals/MetallurgyMetals.java b/common/rebelkeithy/mods/metallurgy/metals/MetallurgyMetals.java
index d8c45cd..ff4b004 100644
--- a/common/rebelkeithy/mods/metallurgy/metals/MetallurgyMetals.java
+++ b/common/rebelkeithy/mods/metallurgy/metals/MetallurgyMetals.java
@@ -1,317 +1,317 @@
package rebelkeithy.mods.metallurgy.metals;
import java.io.File;
import java.io.IOException;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.src.ModLoader;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import rebelkeithy.mods.metallurgy.core.MetalInfoDatabase;
import rebelkeithy.mods.metallurgy.core.MetallurgyCore;
import rebelkeithy.mods.metallurgy.core.MetallurgyTabs;
import rebelkeithy.mods.metallurgy.core.metalsets.ISwordHitListener;
import rebelkeithy.mods.metallurgy.core.metalsets.MetalSet;
import rebelkeithy.mods.metallurgy.metals.utilityItems.ItemFertilizer;
import rebelkeithy.mods.metallurgy.metals.utilityItems.ItemIgniter;
import rebelkeithy.mods.metallurgy.metals.utilityItems.tnt.EntityLargeTNTPrimed;
import rebelkeithy.mods.metallurgy.metals.utilityItems.tnt.EntityMinersTNTPrimed;
import rebelkeithy.mods.metallurgy.metals.utilityItems.tnt.BlockLargeTNT;
import rebelkeithy.mods.metallurgy.metals.utilityItems.tnt.BlockMinersTNT;
import rebelkeithy.mods.particleregistry.ParticleRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod(modid="Metallurgy3Base", name="Metallurgy 3 Base", version="1.4.7-1.11.13-1a")
@NetworkMod(channels = {"MetallurgyBase"}, clientSideRequired = true, serverSideRequired = false)
public class MetallurgyMetals {
public static MetalSet baseSet;
public static MetalSet preciousSet;
public static MetalSet netherSet;
public static MetalSet fantasySet;
public static MetalSet enderSet;
public static MetalSet utilitySet;
public static MetallurgyTabs baseTab;
public static MetallurgyTabs preciousTab;
public static MetallurgyTabs netherTab;
public static MetallurgyTabs fantasyTab;
public static MetallurgyTabs enderTab;
public static MetallurgyTabs utilityTab;
public static Configuration baseConfig;
public static Configuration utilityConfig;
public static Configuration fantasyConfig;
//Vanilla Items
public static Item dustIron;
public static Item dustGold;
//Utility Items
public static Item magnesiumIgniter;
public static Item match;
public static Item fertilizer;
public static Item tar;
public static Block largeTNT;
public static Block minersTNT;
@SidedProxy(clientSide = "rebelkeithy.mods.metallurgy.metals.ClientProxy", serverSide = "rebelkeithy.mods.metallurgy.metals.CommonProxy")
public static CommonProxy proxy;
@Instance(value = "Metallurgy3Base")
public static MetallurgyMetals instance;
@PreInit
public void preInit(FMLPreInitializationEvent event)
{
baseConfig = initConfig("Base");
baseConfig.load();
utilityConfig = initConfig("Utility");
utilityConfig.load();
fantasyConfig = initConfig("Fantasy");
baseTab = new MetallurgyTabs("Metallurgy: Base");
preciousTab = new MetallurgyTabs("Metallurgy: Precious");
netherTab = new MetallurgyTabs("Metallurgy: Nether");
fantasyTab = new MetallurgyTabs("Metallurgy: Fantasy");
enderTab = new MetallurgyTabs("Metallurgy: Ender");
utilityTab = new MetallurgyTabs("Metallurgy: Utility");
LanguageRegistry.instance().addStringLocalization("itemGroup.Metallurgy: Base", "Metallurgy: Base");
LanguageRegistry.instance().addStringLocalization("itemGroup.Metallurgy: Precious", "Metallurgy: Precious");
LanguageRegistry.instance().addStringLocalization("itemGroup.Metallurgy: Nether", "Metallurgy: Nether");
LanguageRegistry.instance().addStringLocalization("itemGroup.Metallurgy: Fantasy", "Metallurgy: Fantasy");
LanguageRegistry.instance().addStringLocalization("itemGroup.Metallurgy: Utility", "Metallurgy: Utility");
LanguageRegistry.instance().addStringLocalization("itemGroup.Metallurgy: Ender", "Metallurgy: Ender");
//TODO
String filepath = event.getSourceFile().getAbsolutePath();
if(filepath.equals("C:\\Users\\Keithy\\Documents\\Metallurgy 3 1.5\\eclipse\\Metallurgy 3\\bin"))
{
filepath = MetallurgyCore.proxy.getMinecraftDir() + "/mods/Metallurgy.jar";
}
MetalInfoDatabase.readMetalDataFromJar("spreadsheet.csv", filepath);
MetalInfoDatabase.readItemDataFromJar(baseConfig, "Items.csv", filepath, utilityTab);
baseSet = new MetalSet("Base", MetalInfoDatabase.getSpreadsheetDataForSet("Base"), baseTab);
preciousSet = new MetalSet("Precious", MetalInfoDatabase.getSpreadsheetDataForSet("Precious"), preciousTab);
netherSet = new MetalSet("Nether", MetalInfoDatabase.getSpreadsheetDataForSet("Nether"), netherTab);
fantasySet = new MetalSet("Fantasy", MetalInfoDatabase.getSpreadsheetDataForSet("Fantasy"), fantasyTab);
enderSet = new MetalSet("Ender", MetalInfoDatabase.getSpreadsheetDataForSet("Ender"), enderTab);
utilitySet = new MetalSet("Utility", MetalInfoDatabase.getSpreadsheetDataForSet("Utility"), utilityTab);
}
@Init
public void Init(FMLInitializationEvent event)
{
//TODO add config for vanilla dusts
dustIron = new Item(5100).setUnlocalizedName("Metallurgy:Vanilla/IronDust").setCreativeTab(CreativeTabs.tabMaterials);
dustGold = new Item(5101).setUnlocalizedName("Metallurgy:Vanilla/GoldDust").setCreativeTab(CreativeTabs.tabMaterials);
LanguageRegistry.addName(dustIron, "Iron Dust");
LanguageRegistry.addName(dustGold, "Gold Dust");
OreDictionary.registerOre("dustIron", dustIron);
OreDictionary.registerOre("dustGold", dustGold);
Item debug = new ItemOreFinder(5102).setUnlocalizedName("stick").setCreativeTab(CreativeTabs.tabTools);
createUtilityItems();
utilityConfig.save();
ParticleRegistry.registerParticle("FantasyOre", EntityFantasyOreFX.class);
fantasySet.getOreInfo("Astral Silver").ore.addDisplayListener(new DisplayListenerOreParticles("FantasyOre", 0.6, 0.8, 0.95));
fantasySet.getOreInfo("Carmot").ore.addDisplayListener(new DisplayListenerOreParticles("FantasyOre", 0.8, 0.8, 0.4));
fantasySet.getOreInfo("Mithril").ore.addDisplayListener(new DisplayListenerOreParticles("FantasyOre", 0.6, 0.9, 0.95));
fantasySet.getOreInfo("Orichalcum").ore.addDisplayListener(new DisplayListenerOreParticles("FantasyOre", 0.3, 0.5, 0.15));
fantasySet.getOreInfo("Adamantine").ore.addDisplayListener(new DisplayListenerOreParticles("FantasyOre", 0.5, 0.2, 0.2));
fantasySet.getOreInfo("Atlarus").ore.addDisplayListener(new DisplayListenerOreParticles("FantasyOre", 0.8, 0.8, 0.2));
ParticleRegistry.registerParticle("NetherOre", EntityNetherOreFX.class);
netherSet.getOreInfo("Midasium").ore.addDisplayListener(new DisplayListenerOreParticles("NetherOre", 1.0, 0.8, 0.25));
netherSet.getOreInfo("Vyroxeres").ore.addDisplayListener(new DisplayListenerVyroxeresOreParticles());
netherSet.getOreInfo("Ceruclase").ore.addDisplayListener(new DisplayListenerOreParticles("NetherOre", 0.35, 0.6, 0.9));
netherSet.getOreInfo("Kalendrite").ore.addDisplayListener(new DisplayListenerOreParticles("NetherOre", 0.8, 0.4, 0.8));
netherSet.getOreInfo("Vulcanite").ore.addDisplayListener(new DisplayListenerVulcaniteOreParticles());
netherSet.getOreInfo("Sanguinite").ore.addDisplayListener(new DisplayListenerOreParticles("NetherOre", 0.85, 0.0, 0.0));
netherSet.getOreInfo("Vyroxeres").ore.addCollisionListener(new VyroxeresCollisionListener());
addSwordEffects();
}
@PostInit
public void postInit(FMLPostInitializationEvent event)
{
baseTab.setIconItem(baseSet.getOreInfo("Steel").helmet.itemID);
preciousTab.setIconItem(preciousSet.getOreInfo("Platinum").helmet.itemID);
netherTab.setIconItem(netherSet.getOreInfo("Sanguinite").helmet.itemID);
fantasyTab.setIconItem(fantasySet.getOreInfo("Tartarite").helmet.itemID);
enderTab.setIconItem(enderSet.getOreInfo("Desichalkos").helmet.itemID);
createMidasiumRecipes();
}
public void createUtilityItems()
{
int id = utilityConfig.get("Item IDs", "HE TNT", 920).getInt();
largeTNT = new BlockLargeTNT(id).setUnlocalizedName("M3HETNT").setCreativeTab(utilityTab);
GameRegistry.registerBlock(largeTNT, "M3HETNT");
EntityRegistry.registerModEntity(EntityLargeTNTPrimed.class, "LargeTNTEntity", 113, this, 64, 10, true);
LanguageRegistry.addName(largeTNT, "HE TNT");
id = utilityConfig.get("Item IDs", "LE TNT", 921).getInt();
minersTNT = new BlockMinersTNT(id).setUnlocalizedName("M3LETNT").setCreativeTab(utilityTab);
GameRegistry.registerBlock(minersTNT, "M3LETNT");
EntityRegistry.registerModEntity(EntityMinersTNTPrimed.class, "MinersTNTEntity", 113, this, 64, 10, true);
LanguageRegistry.addName(minersTNT, "LE TNT");
id = utilityConfig.get("Item IDs", "Magnesium Igniter", 29007).getInt();
magnesiumIgniter = new ItemIgniter(id).setUnlocalizedName("Metallurgy:Utility/Igniter").setCreativeTab(utilityTab);
LanguageRegistry.addName(magnesiumIgniter, "Magnesium Igniter");
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(magnesiumIgniter), "X ", " F", 'X', "dustMagnesium", 'F', Item.flintAndSteel));
id = utilityConfig.get("Item IDs", "Match", 29008).getInt();
match = new ItemIgniter(id).setUnlocalizedName("Metallurgy:Utility/Match").setCreativeTab(utilityTab);
LanguageRegistry.addName(match, "Match");
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(match), "X", "|", 'X', "dustPhosphorus", '|', Item.stick));
id = utilityConfig.get("Item IDs", "Fertilizer", 29009).getInt();
fertilizer = new ItemFertilizer(id).setUnlocalizedName("Metallurgy:Utility/Fertilizer").setCreativeTab(utilityTab);
LanguageRegistry.addName(fertilizer, "Fertilizer");
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(fertilizer), "dustPhosphorus", "dustMagnesium", "dustPotash"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(fertilizer), "dustPhosphorus", "dustMagnesium", "dustSaltpeter"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(fertilizer), "dustPhosphorus", "dustSaltpeter", "dustPotash"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(fertilizer), "dustSaltpeter", "dustMagnesium", "dustPotash"));
OreDictionary.registerOre("itemFertilizer", fertilizer);
id = utilityConfig.get("Item IDs", "Tar", 29010).getInt();
tar = new Item(id).setUnlocalizedName("Metallurgy:Utility/Tar").setCreativeTab(utilityTab);
LanguageRegistry.addName(tar, "Tar");
OreDictionary.registerOre("itemTar", tar);
GameRegistry.addRecipe(new ShapelessOreRecipe(Item.gunpowder, "dustSulfur", "dustSaltpeter"));
GameRegistry.addRecipe(new ShapelessOreRecipe(Item.magmaCream, "itemTar", Item.blazePowder));
GameRegistry.addRecipe(new ShapedOreRecipe(Block.pistonStickyBase, "T", "P", 'T', "itemTar", 'P', Block.pistonBase));
GameRegistry.addSmelting(MetalInfoDatabase.getItem("Bitumen").itemID, new ItemStack(tar), 0.1F);
utilityTab.setIconItem(fertilizer.itemID);
}
public Configuration initConfig(String name)
{
File fileDir = new File(MetallurgyCore.proxy.getMinecraftDir() + "/config/Metallurgy3");
fileDir.mkdir();
File cfgFile = new File(MetallurgyCore.proxy.getMinecraftDir() + "/config/Metallurgy3/Metallurgy" + name + ".cfg");
try
{
cfgFile.createNewFile();
} catch (IOException e) {
System.out.println(e);
}
return new Configuration(cfgFile);
}
public void createMidasiumRecipes()
{
String[] ores = OreDictionary.getOreNames();
System.out.println("Searching for dust for midsasium recipes");
int count = 0;
for(String name : ores)
{
if(name.contains("dust"))
{
System.out.println("Adding recipe for " + name + " midasium = gold");
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(dustGold), "dustMidasium", name));
count++;
}
}
}
public void addSwordEffects()
{
ISwordHitListener swordEffects = new NetherSwordHitListener();
MinecraftForge.EVENT_BUS.register(swordEffects); // Registers the on death event needed by Midasium's looting effect
netherSet.getOreInfo("Ignatius").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Ignatius").sword.setSubText("cIgnite I");
netherSet.getOreInfo("Shadow Iron").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Shadow Iron").sword.setSubText("cWeakness I");
netherSet.getOreInfo("Shadow Steel").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Shadow Steel").sword.setSubText("7Weakness II");
// Midsium'ss effect comes from the onDeath event, not the onHit method
netherSet.getOreInfo("Midasium").sword.setSubText("7Looting I");
netherSet.getOreInfo("Vyroxeres").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Vyroxeres").sword.setSubText("cPoison I");
netherSet.getOreInfo("Ceruclase").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Ceruclase").sword.setSubText("cSlowness");
netherSet.getOreInfo("Inolashite").sword.addHitListener(swordEffects);
- netherSet.getOreInfo("Inolashite").sword.setSubText("7Poison, Sloness");
+ netherSet.getOreInfo("Inolashite").sword.setSubText("7Poison, Slowness");
netherSet.getOreInfo("Kalendrite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Kalendrite").sword.setSubText("7Regen");
netherSet.getOreInfo("Amordrine").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Amordrine").sword.setSubText("7Healing");
netherSet.getOreInfo("Vulcanite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Vulcanite").sword.setSubText("cIgnite II");
netherSet.getOreInfo("Sanguinite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Sanguinite").sword.setSubText("cWither I");
swordEffects = new FantasySwordHitListener();
MinecraftForge.EVENT_BUS.register(swordEffects); // Registers the on death event needed by Astral Silver's and Carmot's looting effect
fantasySet.getOreInfo("Deep Iron").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Deep Iron").sword.setSubText("cBlindness I");
fantasySet.getOreInfo("Black Steel").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Black Steel").sword.setSubText("cBlindness II");
fantasySet.getOreInfo("Oureclase").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Oureclase").sword.setSubText("7Resistance I");
//fantasySet.getOreInfo("Astral Silver").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Astral Silver").sword.setSubText("7Looting I");
//fantasySet.getOreInfo("Carmot").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Carmot").sword.setSubText("7Looting II");
fantasySet.getOreInfo("Mithril").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Mithril").sword.setSubText("7Haste I");
fantasySet.getOreInfo("Quicksilver").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Quicksilver").sword.setSubText("7Speed I");
fantasySet.getOreInfo("Haderoth").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Haderoth").sword.setSubText("cHaste I, Ignite II");
fantasySet.getOreInfo("Orichalcum").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Orichalcum").sword.setSubText("cResistance II");
fantasySet.getOreInfo("Celenegil").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Celenegil").sword.setSubText("7Resistance III");
fantasySet.getOreInfo("Adamantine").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Adamantine").sword.setSubText("7Fire Resist I, Ignite II");
fantasySet.getOreInfo("Atlarus").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Atlarus").sword.setSubText("7Strength II");
fantasySet.getOreInfo("Tartarite").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Tartarite").sword.setSubText("cWither, Igntite II");
}
}
| true | true | public void addSwordEffects()
{
ISwordHitListener swordEffects = new NetherSwordHitListener();
MinecraftForge.EVENT_BUS.register(swordEffects); // Registers the on death event needed by Midasium's looting effect
netherSet.getOreInfo("Ignatius").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Ignatius").sword.setSubText("cIgnite I");
netherSet.getOreInfo("Shadow Iron").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Shadow Iron").sword.setSubText("cWeakness I");
netherSet.getOreInfo("Shadow Steel").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Shadow Steel").sword.setSubText("7Weakness II");
// Midsium'ss effect comes from the onDeath event, not the onHit method
netherSet.getOreInfo("Midasium").sword.setSubText("7Looting I");
netherSet.getOreInfo("Vyroxeres").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Vyroxeres").sword.setSubText("cPoison I");
netherSet.getOreInfo("Ceruclase").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Ceruclase").sword.setSubText("cSlowness");
netherSet.getOreInfo("Inolashite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Inolashite").sword.setSubText("7Poison, Sloness");
netherSet.getOreInfo("Kalendrite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Kalendrite").sword.setSubText("7Regen");
netherSet.getOreInfo("Amordrine").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Amordrine").sword.setSubText("7Healing");
netherSet.getOreInfo("Vulcanite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Vulcanite").sword.setSubText("cIgnite II");
netherSet.getOreInfo("Sanguinite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Sanguinite").sword.setSubText("cWither I");
swordEffects = new FantasySwordHitListener();
MinecraftForge.EVENT_BUS.register(swordEffects); // Registers the on death event needed by Astral Silver's and Carmot's looting effect
fantasySet.getOreInfo("Deep Iron").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Deep Iron").sword.setSubText("cBlindness I");
fantasySet.getOreInfo("Black Steel").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Black Steel").sword.setSubText("cBlindness II");
fantasySet.getOreInfo("Oureclase").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Oureclase").sword.setSubText("7Resistance I");
//fantasySet.getOreInfo("Astral Silver").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Astral Silver").sword.setSubText("7Looting I");
//fantasySet.getOreInfo("Carmot").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Carmot").sword.setSubText("7Looting II");
fantasySet.getOreInfo("Mithril").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Mithril").sword.setSubText("7Haste I");
fantasySet.getOreInfo("Quicksilver").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Quicksilver").sword.setSubText("7Speed I");
fantasySet.getOreInfo("Haderoth").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Haderoth").sword.setSubText("cHaste I, Ignite II");
fantasySet.getOreInfo("Orichalcum").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Orichalcum").sword.setSubText("cResistance II");
fantasySet.getOreInfo("Celenegil").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Celenegil").sword.setSubText("7Resistance III");
fantasySet.getOreInfo("Adamantine").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Adamantine").sword.setSubText("7Fire Resist I, Ignite II");
fantasySet.getOreInfo("Atlarus").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Atlarus").sword.setSubText("7Strength II");
fantasySet.getOreInfo("Tartarite").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Tartarite").sword.setSubText("cWither, Igntite II");
}
| public void addSwordEffects()
{
ISwordHitListener swordEffects = new NetherSwordHitListener();
MinecraftForge.EVENT_BUS.register(swordEffects); // Registers the on death event needed by Midasium's looting effect
netherSet.getOreInfo("Ignatius").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Ignatius").sword.setSubText("cIgnite I");
netherSet.getOreInfo("Shadow Iron").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Shadow Iron").sword.setSubText("cWeakness I");
netherSet.getOreInfo("Shadow Steel").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Shadow Steel").sword.setSubText("7Weakness II");
// Midsium'ss effect comes from the onDeath event, not the onHit method
netherSet.getOreInfo("Midasium").sword.setSubText("7Looting I");
netherSet.getOreInfo("Vyroxeres").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Vyroxeres").sword.setSubText("cPoison I");
netherSet.getOreInfo("Ceruclase").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Ceruclase").sword.setSubText("cSlowness");
netherSet.getOreInfo("Inolashite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Inolashite").sword.setSubText("7Poison, Slowness");
netherSet.getOreInfo("Kalendrite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Kalendrite").sword.setSubText("7Regen");
netherSet.getOreInfo("Amordrine").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Amordrine").sword.setSubText("7Healing");
netherSet.getOreInfo("Vulcanite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Vulcanite").sword.setSubText("cIgnite II");
netherSet.getOreInfo("Sanguinite").sword.addHitListener(swordEffects);
netherSet.getOreInfo("Sanguinite").sword.setSubText("cWither I");
swordEffects = new FantasySwordHitListener();
MinecraftForge.EVENT_BUS.register(swordEffects); // Registers the on death event needed by Astral Silver's and Carmot's looting effect
fantasySet.getOreInfo("Deep Iron").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Deep Iron").sword.setSubText("cBlindness I");
fantasySet.getOreInfo("Black Steel").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Black Steel").sword.setSubText("cBlindness II");
fantasySet.getOreInfo("Oureclase").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Oureclase").sword.setSubText("7Resistance I");
//fantasySet.getOreInfo("Astral Silver").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Astral Silver").sword.setSubText("7Looting I");
//fantasySet.getOreInfo("Carmot").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Carmot").sword.setSubText("7Looting II");
fantasySet.getOreInfo("Mithril").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Mithril").sword.setSubText("7Haste I");
fantasySet.getOreInfo("Quicksilver").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Quicksilver").sword.setSubText("7Speed I");
fantasySet.getOreInfo("Haderoth").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Haderoth").sword.setSubText("cHaste I, Ignite II");
fantasySet.getOreInfo("Orichalcum").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Orichalcum").sword.setSubText("cResistance II");
fantasySet.getOreInfo("Celenegil").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Celenegil").sword.setSubText("7Resistance III");
fantasySet.getOreInfo("Adamantine").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Adamantine").sword.setSubText("7Fire Resist I, Ignite II");
fantasySet.getOreInfo("Atlarus").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Atlarus").sword.setSubText("7Strength II");
fantasySet.getOreInfo("Tartarite").sword.addHitListener(swordEffects);
fantasySet.getOreInfo("Tartarite").sword.setSubText("cWither, Igntite II");
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Dialog.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Dialog.java
index f28db6757..3d1891ef7 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Dialog.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Dialog.java
@@ -1,216 +1,216 @@
package com.badlogic.gdx.scenes.scene2d.ui;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener;
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener.FocusEvent;
import com.badlogic.gdx.utils.ObjectMap;
/** Displays a dialog, which is a modal window containing a content table with a button table underneath it. Methods are provided
* to add a label to the content table and buttons to the button table, but any widgets can be added. When a button is clicked,
* {@link #result(Object)} is called and the dialog is removed from the stage.
* @author Nathan Sweet */
public class Dialog extends Window {
/** The time in seconds that dialogs will fade in and out. Set to zero to disable fading. */
static public float fadeDuration = 0.4f;
Table contentTable, buttonTable;
private Skin skin;
ObjectMap<Actor, Object> values = new ObjectMap();
boolean cancelHide;
Actor previousKeyboardFocus, previousScrollFocus;
public Dialog (String title, Skin skin) {
super(title, skin.get(WindowStyle.class));
this.skin = skin;
initialize();
}
public Dialog (String title, Skin skin, String windowStyleName) {
super(title, skin.get(windowStyleName, WindowStyle.class));
this.skin = skin;
initialize();
}
public Dialog (String title, WindowStyle windowStyle) {
super(title, windowStyle);
initialize();
}
private void initialize () {
setModal(true);
defaults().space(6);
add(contentTable = new Table(skin)).expand().fill();
row();
add(buttonTable = new Table(skin));
contentTable.defaults().space(6);
buttonTable.defaults().space(6);
buttonTable.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
while (actor.getParent() != buttonTable)
actor = actor.getParent();
result(values.get(actor));
if (!cancelHide) hide();
cancelHide = false;
}
});
addListener(new FocusListener() {
public void keyboardFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (!focused) focusChanged(event);
}
public void scrollFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (!focused) focusChanged(event);
}
private void focusChanged (FocusEvent event) {
Stage stage = getStage();
- if (isModal && stage.getRoot().getChildren().peek() == Dialog.this) { // This dialog is the top most actor.
+ if (isModal && stage != null && stage.getRoot().getChildren().peek() == Dialog.this) { // Dialog is top most actor.
Actor newFocusedActor = event.getRelatedActor();
if (newFocusedActor == null || !newFocusedActor.isDescendantOf(Dialog.this)) event.cancel();
}
}
});
}
public Table getContentTable () {
return contentTable;
}
public Table getButtonTable () {
return buttonTable;
}
/** Adds a label to the content table. The dialog must have been constructed with a skin to use this method. */
public Dialog text (String text) {
if (skin == null)
throw new IllegalStateException("This method may only be used if the dialog was constructed with a Skin.");
return text(text, skin.get(LabelStyle.class));
}
/** Adds a label to the content table. */
public Dialog text (String text, LabelStyle labelStyle) {
return text(new Label(text, labelStyle));
}
/** Adds the given Label to the content table */
public Dialog text (Label label) {
contentTable.add(label);
return this;
}
/** Adds a text button to the button table. Null will be passed to {@link #result(Object)} if this button is clicked. The dialog
* must have been constructed with a skin to use this method. */
public Dialog button (String text) {
return button(text, null);
}
/** Adds a text button to the button table. The dialog must have been constructed with a skin to use this method.
* @param object The object that will be passed to {@link #result(Object)} if this button is clicked. May be null. */
public Dialog button (String text, Object object) {
if (skin == null)
throw new IllegalStateException("This method may only be used if the dialog was constructed with a Skin.");
return button(text, object, skin.get(TextButtonStyle.class));
}
/** Adds a text button to the button table.
* @param object The object that will be passed to {@link #result(Object)} if this button is clicked. May be null. */
public Dialog button (String text, Object object, TextButtonStyle buttonStyle) {
return button(new TextButton(text, buttonStyle), object);
}
/** Adds the given button to the button table. */
public Dialog button (Button button) {
return button(button, null);
}
/** Adds the given button to the button table.
* @param object The object that will be passed to {@link #result(Object)} if this button is clicked. May be null. */
public Dialog button (Button button, Object object) {
buttonTable.add(button);
setObject(button, object);
return this;
}
/** {@link #pack() Packs} the dialog and adds it to the stage, centered. */
public Dialog show (Stage stage) {
previousKeyboardFocus = stage.getKeyboardFocus();
previousScrollFocus = stage.getScrollFocus();
stage.setKeyboardFocus(this);
stage.setScrollFocus(this);
pack();
setPosition(Math.round((stage.getWidth() - getWidth()) / 2), Math.round((stage.getHeight() - getHeight()) / 2));
stage.addActor(this);
if (fadeDuration > 0) {
getColor().a = 0;
addAction(Actions.fadeIn(fadeDuration, Interpolation.fade));
}
return this;
}
/** Hides the dialog. Called automatically when a button is clicked. The default implementation fades out the dialog over
* {@link #fadeDuration} seconds and then removes it from the stage. */
public void hide () {
addAction(sequence(fadeOut(fadeDuration, Interpolation.fade), Actions.removeActor()));
}
protected void setParent (Group parent) {
super.setParent(parent);
if (parent == null) {
Stage stage = getStage();
if (stage != null) {
Actor actor = stage.getKeyboardFocus();
if (actor == this || actor == null) stage.setKeyboardFocus(previousKeyboardFocus);
actor = stage.getScrollFocus();
if (actor == this || actor == null) stage.setScrollFocus(previousScrollFocus);
}
}
}
public void setObject (Actor actor, Object object) {
values.put(actor, object);
}
/** If this key is pressed, {@link #result(Object)} is called with the specified object.
* @see Keys */
public Dialog key (final int keycode, final Object object) {
addListener(new InputListener() {
public boolean keyDown (InputEvent event, int keycode2) {
if (keycode == keycode2) {
result(object);
if (!cancelHide) hide();
cancelHide = false;
}
return false;
}
});
return this;
}
/** Called when a button is clicked. The dialog will be hidden after this method returns unless {@link #cancel()} is called.
* @param object The object specified when the button was added. */
protected void result (Object object) {
}
public void cancel () {
cancelHide = true;
}
}
| true | true | private void initialize () {
setModal(true);
defaults().space(6);
add(contentTable = new Table(skin)).expand().fill();
row();
add(buttonTable = new Table(skin));
contentTable.defaults().space(6);
buttonTable.defaults().space(6);
buttonTable.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
while (actor.getParent() != buttonTable)
actor = actor.getParent();
result(values.get(actor));
if (!cancelHide) hide();
cancelHide = false;
}
});
addListener(new FocusListener() {
public void keyboardFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (!focused) focusChanged(event);
}
public void scrollFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (!focused) focusChanged(event);
}
private void focusChanged (FocusEvent event) {
Stage stage = getStage();
if (isModal && stage.getRoot().getChildren().peek() == Dialog.this) { // This dialog is the top most actor.
Actor newFocusedActor = event.getRelatedActor();
if (newFocusedActor == null || !newFocusedActor.isDescendantOf(Dialog.this)) event.cancel();
}
}
});
}
| private void initialize () {
setModal(true);
defaults().space(6);
add(contentTable = new Table(skin)).expand().fill();
row();
add(buttonTable = new Table(skin));
contentTable.defaults().space(6);
buttonTable.defaults().space(6);
buttonTable.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
while (actor.getParent() != buttonTable)
actor = actor.getParent();
result(values.get(actor));
if (!cancelHide) hide();
cancelHide = false;
}
});
addListener(new FocusListener() {
public void keyboardFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (!focused) focusChanged(event);
}
public void scrollFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (!focused) focusChanged(event);
}
private void focusChanged (FocusEvent event) {
Stage stage = getStage();
if (isModal && stage != null && stage.getRoot().getChildren().peek() == Dialog.this) { // Dialog is top most actor.
Actor newFocusedActor = event.getRelatedActor();
if (newFocusedActor == null || !newFocusedActor.isDescendantOf(Dialog.this)) event.cancel();
}
}
});
}
|
diff --git a/Java_CCN/test/ccn/data/util/CCNEncodableObjectTest.java b/Java_CCN/test/ccn/data/util/CCNEncodableObjectTest.java
index 99e1b639f..bbc3c6ec7 100644
--- a/Java_CCN/test/ccn/data/util/CCNEncodableObjectTest.java
+++ b/Java_CCN/test/ccn/data/util/CCNEncodableObjectTest.java
@@ -1,244 +1,246 @@
package test.ccn.data.util;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.sql.Timestamp;
import java.util.logging.Level;
import javax.xml.stream.XMLStreamException;
import org.bouncycastle.util.Arrays;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import test.ccn.data.content.CCNEncodableCollectionData;
import com.parc.ccn.Library;
import com.parc.ccn.config.ConfigurationException;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.content.CollectionData;
import com.parc.ccn.data.content.LinkReference;
import com.parc.ccn.data.security.LinkAuthenticator;
import com.parc.ccn.data.security.PublisherID;
import com.parc.ccn.data.security.SignedInfo;
import com.parc.ccn.data.security.PublisherID.PublisherType;
import com.parc.ccn.data.util.NullOutputStream;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.io.CCNVersionedInputStream;
import com.parc.security.crypto.DigestHelper;
/**
* Works. Currently very slow, as it's timing
* out lots of blocks. End of stream markers will help with that, as
* will potentially better binary ccnb decoding.
* @author smetters
*
*/
public class CCNEncodableObjectTest {
static final String baseName = "test";
static final String subName = "smetters";
static final String document1 = "report";
static final String document2 = "key";
static final String document3 = "cv.txt";
static final String prefix = "drawing_";
static ContentName namespace;
static ContentName [] ns = null;
static public byte [] contenthash1 = new byte[32];
static public byte [] contenthash2 = new byte[32];
static public byte [] publisherid1 = new byte[32];
static public byte [] publisherid2 = new byte[32];
static PublisherID pubID1 = null;
static PublisherID pubID2 = null;
static int NUM_LINKS = 100;
static LinkAuthenticator [] las = new LinkAuthenticator[NUM_LINKS];
static LinkReference [] lrs = null;
static CollectionData small1;
static CollectionData small2;
static CollectionData empty;
static CollectionData big;
static CCNLibrary library;
static Level oldLevel;
@AfterClass
public static void tearDownAfterClass() throws Exception {
Library.logger().setLevel(oldLevel);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("Making stuff.");
oldLevel = Library.logger().getLevel();
// Library.logger().setLevel(Level.FINEST);
library = CCNLibrary.open();
namespace = ContentName.fromURI(new String[]{baseName, subName, document1});
ns = new ContentName[NUM_LINKS];
for (int i=0; i < NUM_LINKS; ++i) {
ns[i] = ContentName.fromNative(namespace, prefix+Integer.toString(i));
}
Arrays.fill(publisherid1, (byte)6);
Arrays.fill(publisherid2, (byte)3);
pubID1 = new PublisherID(publisherid1, PublisherType.KEY);
pubID2 = new PublisherID(publisherid2, PublisherType.ISSUER_KEY);
las[0] = new LinkAuthenticator(pubID1);
las[1] = null;
las[2] = new LinkAuthenticator(pubID2, null, null,
SignedInfo.ContentType.DATA, contenthash1);
las[3] = new LinkAuthenticator(pubID1, null, new Timestamp(System.currentTimeMillis()),
null, contenthash1);
for (int j=4; j < NUM_LINKS; ++j) {
las[j] = new LinkAuthenticator(pubID2, null, new Timestamp(System.currentTimeMillis()),null, null);
}
lrs = new LinkReference[NUM_LINKS];
for (int i=0; i < lrs.length; ++i) {
lrs[i] = new LinkReference(ns[i],las[i]);
}
empty = new CollectionData();
small1 = new CollectionData();
small2 = new CollectionData();
for (int i=0; i < 5; ++i) {
small1.add(lrs[i]);
small2.add(lrs[i+5]);
}
big = new CollectionData();
for (int i=0; i < NUM_LINKS; ++i) {
big.add(lrs[i]);
}
}
@Test
public void testSaveUpdate() {
boolean caught = false;
try {
CCNEncodableCollectionData emptycoll = new CCNEncodableCollectionData();
NullOutputStream nos = new NullOutputStream();
emptycoll.save(nos);
} catch (InvalidObjectException iox) {
// this is what we expect to happen
caught = true;
} catch (IOException ie) {
Assert.fail("Unexpected IOException!");
} catch (XMLStreamException e) {
Assert.fail("Unexpected XMLStreamException!");
} catch (ConfigurationException e) {
Assert.fail("Unexpected ConfigurationException!");
}
Assert.assertTrue("Failed to produce expected exception.", caught);
Flosser flosser = null;
boolean done = false;
try {
CCNEncodableCollectionData ecd0 = new CCNEncodableCollectionData(namespace, empty, library);
CCNEncodableCollectionData ecd1 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd2 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd3 = new CCNEncodableCollectionData(namespace, big, library);
CCNEncodableCollectionData ecd4 = new CCNEncodableCollectionData(namespace, empty, library);
flosser = new Flosser(namespace);
flosser.logNamespaces();
+ flosser.handleNamespace(ns[2]);
ecd0.save(ns[2]);
System.out.println("Version for empty collection: " + ecd0.getVersion());
ecd1.save(ns[1]);
ecd2.save(ns[1]);
System.out.println("ecd1 name: " + ecd1.getName());
System.out.println("ecd2 name: " + ecd2.getName());
System.out.println("Versions for matching collection content: " + ecd1.getVersion() + " " + ecd2.getVersion());
Assert.assertFalse(ecd1.equals(ecd2));
Assert.assertTrue(ecd1.contentEquals(ecd2));
CCNVersionedInputStream vis = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buf = new byte[128];
// Will incur a timeout
while (!vis.eof()) {
int read = vis.read(buf);
- baos.write(buf, 0, read);
+ if (read > 0)
+ baos.write(buf, 0, read);
}
System.out.println("Read " + baos.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos.toByteArray()), 16));
CollectionData newData = new CollectionData();
newData.decode(baos.toByteArray());
System.out.println("Decoded collection data: " + newData);
CCNVersionedInputStream vis3 = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
// Will incur a timeout
while (!vis3.eof()) {
int val = vis3.read();
if (val < 0)
break;
baos2.write((byte)val);
}
System.out.println("Read " + baos2.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos2.toByteArray()), 16));
CollectionData newData3 = new CollectionData();
newData3.decode(baos2.toByteArray());
System.out.println("Decoded collection data: " + newData3);
CCNVersionedInputStream vis2 = new CCNVersionedInputStream(ecd1.getName());
CollectionData newData2 = new CollectionData();
newData2.decode(vis2);
System.out.println("Decoded collection data from stream: " + newData);
ecd0.update(ecd1.getName());
Assert.assertEquals(ecd0, ecd1);
System.out.println("Update works!");
// latest version
ecd0.update();
Assert.assertEquals(ecd0, ecd2);
System.out.println("Update really works!");
ecd3.save(ns[2]);
ecd0.update();
ecd4.update(ns[2]);
System.out.println("ns[2]: " + ns[2]);
System.out.println("ecd3 name: " + ecd3.getName());
System.out.println("ecd0 name: " + ecd0.getName());
Assert.assertFalse(ecd0.equals(ecd3));
Assert.assertEquals(ecd3, ecd4);
System.out.println("Update really really works!");
done = true;
} catch (IOException e) {
fail("IOException! " + e.getMessage());
} catch (XMLStreamException e) {
e.printStackTrace();
fail("XMLStreamException! " + e.getMessage());
} catch (ConfigurationException e) {
fail("ConfigurationException! " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
} finally {
try {
if (!done) { // if we have an error, stick around long enough to debug
Thread.sleep(100000);
System.out.println("Done sleeping, finishing.");
}
flosser.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail("Exception " + e.getClass().getName() +": " + e.getMessage());
}
}
}
}
| false | true | public void testSaveUpdate() {
boolean caught = false;
try {
CCNEncodableCollectionData emptycoll = new CCNEncodableCollectionData();
NullOutputStream nos = new NullOutputStream();
emptycoll.save(nos);
} catch (InvalidObjectException iox) {
// this is what we expect to happen
caught = true;
} catch (IOException ie) {
Assert.fail("Unexpected IOException!");
} catch (XMLStreamException e) {
Assert.fail("Unexpected XMLStreamException!");
} catch (ConfigurationException e) {
Assert.fail("Unexpected ConfigurationException!");
}
Assert.assertTrue("Failed to produce expected exception.", caught);
Flosser flosser = null;
boolean done = false;
try {
CCNEncodableCollectionData ecd0 = new CCNEncodableCollectionData(namespace, empty, library);
CCNEncodableCollectionData ecd1 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd2 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd3 = new CCNEncodableCollectionData(namespace, big, library);
CCNEncodableCollectionData ecd4 = new CCNEncodableCollectionData(namespace, empty, library);
flosser = new Flosser(namespace);
flosser.logNamespaces();
ecd0.save(ns[2]);
System.out.println("Version for empty collection: " + ecd0.getVersion());
ecd1.save(ns[1]);
ecd2.save(ns[1]);
System.out.println("ecd1 name: " + ecd1.getName());
System.out.println("ecd2 name: " + ecd2.getName());
System.out.println("Versions for matching collection content: " + ecd1.getVersion() + " " + ecd2.getVersion());
Assert.assertFalse(ecd1.equals(ecd2));
Assert.assertTrue(ecd1.contentEquals(ecd2));
CCNVersionedInputStream vis = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buf = new byte[128];
// Will incur a timeout
while (!vis.eof()) {
int read = vis.read(buf);
baos.write(buf, 0, read);
}
System.out.println("Read " + baos.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos.toByteArray()), 16));
CollectionData newData = new CollectionData();
newData.decode(baos.toByteArray());
System.out.println("Decoded collection data: " + newData);
CCNVersionedInputStream vis3 = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
// Will incur a timeout
while (!vis3.eof()) {
int val = vis3.read();
if (val < 0)
break;
baos2.write((byte)val);
}
System.out.println("Read " + baos2.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos2.toByteArray()), 16));
CollectionData newData3 = new CollectionData();
newData3.decode(baos2.toByteArray());
System.out.println("Decoded collection data: " + newData3);
CCNVersionedInputStream vis2 = new CCNVersionedInputStream(ecd1.getName());
CollectionData newData2 = new CollectionData();
newData2.decode(vis2);
System.out.println("Decoded collection data from stream: " + newData);
ecd0.update(ecd1.getName());
Assert.assertEquals(ecd0, ecd1);
System.out.println("Update works!");
// latest version
ecd0.update();
Assert.assertEquals(ecd0, ecd2);
System.out.println("Update really works!");
ecd3.save(ns[2]);
ecd0.update();
ecd4.update(ns[2]);
System.out.println("ns[2]: " + ns[2]);
System.out.println("ecd3 name: " + ecd3.getName());
System.out.println("ecd0 name: " + ecd0.getName());
Assert.assertFalse(ecd0.equals(ecd3));
Assert.assertEquals(ecd3, ecd4);
System.out.println("Update really really works!");
done = true;
} catch (IOException e) {
fail("IOException! " + e.getMessage());
} catch (XMLStreamException e) {
e.printStackTrace();
fail("XMLStreamException! " + e.getMessage());
} catch (ConfigurationException e) {
fail("ConfigurationException! " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
} finally {
try {
if (!done) { // if we have an error, stick around long enough to debug
Thread.sleep(100000);
System.out.println("Done sleeping, finishing.");
}
flosser.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail("Exception " + e.getClass().getName() +": " + e.getMessage());
}
}
}
| public void testSaveUpdate() {
boolean caught = false;
try {
CCNEncodableCollectionData emptycoll = new CCNEncodableCollectionData();
NullOutputStream nos = new NullOutputStream();
emptycoll.save(nos);
} catch (InvalidObjectException iox) {
// this is what we expect to happen
caught = true;
} catch (IOException ie) {
Assert.fail("Unexpected IOException!");
} catch (XMLStreamException e) {
Assert.fail("Unexpected XMLStreamException!");
} catch (ConfigurationException e) {
Assert.fail("Unexpected ConfigurationException!");
}
Assert.assertTrue("Failed to produce expected exception.", caught);
Flosser flosser = null;
boolean done = false;
try {
CCNEncodableCollectionData ecd0 = new CCNEncodableCollectionData(namespace, empty, library);
CCNEncodableCollectionData ecd1 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd2 = new CCNEncodableCollectionData(namespace, small1);
CCNEncodableCollectionData ecd3 = new CCNEncodableCollectionData(namespace, big, library);
CCNEncodableCollectionData ecd4 = new CCNEncodableCollectionData(namespace, empty, library);
flosser = new Flosser(namespace);
flosser.logNamespaces();
flosser.handleNamespace(ns[2]);
ecd0.save(ns[2]);
System.out.println("Version for empty collection: " + ecd0.getVersion());
ecd1.save(ns[1]);
ecd2.save(ns[1]);
System.out.println("ecd1 name: " + ecd1.getName());
System.out.println("ecd2 name: " + ecd2.getName());
System.out.println("Versions for matching collection content: " + ecd1.getVersion() + " " + ecd2.getVersion());
Assert.assertFalse(ecd1.equals(ecd2));
Assert.assertTrue(ecd1.contentEquals(ecd2));
CCNVersionedInputStream vis = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buf = new byte[128];
// Will incur a timeout
while (!vis.eof()) {
int read = vis.read(buf);
if (read > 0)
baos.write(buf, 0, read);
}
System.out.println("Read " + baos.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos.toByteArray()), 16));
CollectionData newData = new CollectionData();
newData.decode(baos.toByteArray());
System.out.println("Decoded collection data: " + newData);
CCNVersionedInputStream vis3 = new CCNVersionedInputStream(ecd1.getName());
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
// Will incur a timeout
while (!vis3.eof()) {
int val = vis3.read();
if (val < 0)
break;
baos2.write((byte)val);
}
System.out.println("Read " + baos2.toByteArray().length + " bytes, digest: " +
DigestHelper.printBytes(DigestHelper.digest(baos2.toByteArray()), 16));
CollectionData newData3 = new CollectionData();
newData3.decode(baos2.toByteArray());
System.out.println("Decoded collection data: " + newData3);
CCNVersionedInputStream vis2 = new CCNVersionedInputStream(ecd1.getName());
CollectionData newData2 = new CollectionData();
newData2.decode(vis2);
System.out.println("Decoded collection data from stream: " + newData);
ecd0.update(ecd1.getName());
Assert.assertEquals(ecd0, ecd1);
System.out.println("Update works!");
// latest version
ecd0.update();
Assert.assertEquals(ecd0, ecd2);
System.out.println("Update really works!");
ecd3.save(ns[2]);
ecd0.update();
ecd4.update(ns[2]);
System.out.println("ns[2]: " + ns[2]);
System.out.println("ecd3 name: " + ecd3.getName());
System.out.println("ecd0 name: " + ecd0.getName());
Assert.assertFalse(ecd0.equals(ecd3));
Assert.assertEquals(ecd3, ecd4);
System.out.println("Update really really works!");
done = true;
} catch (IOException e) {
fail("IOException! " + e.getMessage());
} catch (XMLStreamException e) {
e.printStackTrace();
fail("XMLStreamException! " + e.getMessage());
} catch (ConfigurationException e) {
fail("ConfigurationException! " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
} finally {
try {
if (!done) { // if we have an error, stick around long enough to debug
Thread.sleep(100000);
System.out.println("Done sleeping, finishing.");
}
flosser.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail("Exception " + e.getClass().getName() +": " + e.getMessage());
}
}
}
|
diff --git a/nuxeo-platform-importer-core/src/main/java/org/nuxeo/ecm/platform/importer/base/GenericThreadedImportTask.java b/nuxeo-platform-importer-core/src/main/java/org/nuxeo/ecm/platform/importer/base/GenericThreadedImportTask.java
index a162b788..67386265 100644
--- a/nuxeo-platform-importer-core/src/main/java/org/nuxeo/ecm/platform/importer/base/GenericThreadedImportTask.java
+++ b/nuxeo-platform-importer-core/src/main/java/org/nuxeo/ecm/platform/importer/base/GenericThreadedImportTask.java
@@ -1,490 +1,496 @@
/*
* (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*/
package org.nuxeo.ecm.platform.importer.base;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.javasimon.SimonManager;
import org.javasimon.Split;
import org.javasimon.Stopwatch;
import org.nuxeo.ecm.core.api.CoreInstance;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.repository.Repository;
import org.nuxeo.ecm.core.api.repository.RepositoryManager;
import org.nuxeo.ecm.platform.importer.factories.ImporterDocumentModelFactory;
import org.nuxeo.ecm.platform.importer.filter.ImportingDocumentFilter;
import org.nuxeo.ecm.platform.importer.listener.ImporterListener;
import org.nuxeo.ecm.platform.importer.log.ImporterLogger;
import org.nuxeo.ecm.platform.importer.source.SourceNode;
import org.nuxeo.ecm.platform.importer.threading.ImporterThreadingPolicy;
import org.nuxeo.runtime.api.Framework;
/**
*
* Generic importer task
*
* @author Thierry Delprat
*
*/
public class GenericThreadedImportTask implements Runnable {
private static final Log log = LogFactory.getLog(GenericThreadedImportTask.class);
protected static int taskCounter = 0;
protected boolean isRunning = false;
protected long uploadedFiles = 0;
protected long uploadedKO;
protected int batchSize;
protected CoreSession session;
protected DocumentModel rootDoc;
protected SourceNode rootSource;
protected Boolean skipContainerCreation = false;
protected Boolean isRootTask = false;
protected String taskId = null;
protected TxHelper txHelper = new TxHelper();
protected static final int TX_TIMEOUT = 600;
protected ImporterThreadingPolicy threadPolicy;
protected ImporterDocumentModelFactory factory;
protected String jobName;
protected List<ImporterListener> listeners = new ArrayList<ImporterListener>();
protected List<ImportingDocumentFilter> importingDocumentFilters = new ArrayList<ImportingDocumentFilter>();
private static synchronized int getNextTaskId() {
taskCounter += 1;
return taskCounter;
}
protected ImporterLogger rsLogger = null;
protected GenericThreadedImportTask(CoreSession session) {
this.session = session;
uploadedFiles = 0;
taskId = "T" + getNextTaskId();
}
public GenericThreadedImportTask(CoreSession session,
SourceNode rootSource, DocumentModel rootDoc,
boolean skipContainerCreation, ImporterLogger rsLogger,
int batchSize, ImporterDocumentModelFactory factory,
ImporterThreadingPolicy threadPolicy) throws Exception {
this.rsLogger = rsLogger;
this.session = session;
this.batchSize = batchSize;
uploadedFiles = 0;
taskId = "T" + getNextTaskId();
this.rootSource = rootSource;
this.rootDoc = rootDoc;
this.skipContainerCreation = skipContainerCreation;
this.factory = factory;
this.threadPolicy = threadPolicy;
// there are documents without path, like versions
if (rootSource == null) {
throw new IllegalArgumentException("source node must be specified");
}
}
public GenericThreadedImportTask(CoreSession session,
SourceNode rootSource, DocumentModel rootDoc,
boolean skipContainerCreation, ImporterLogger rsLogger,
int batchSize, ImporterDocumentModelFactory factory,
ImporterThreadingPolicy threadPolicy, String jobName)
throws Exception {
this(session, rootSource, rootDoc, skipContainerCreation, rsLogger,
batchSize, factory, threadPolicy);
this.jobName = jobName;
}
protected CoreSession getCoreSession() throws Exception {
if (this.session == null) {
RepositoryManager rm = Framework.getService(RepositoryManager.class);
Repository repo = rm.getDefaultRepository();
session = repo.open();
}
return session;
}
protected void commit() throws Exception {
commit(false);
}
protected void commit(boolean force) throws Exception {
uploadedFiles++;
if (uploadedFiles % 10 == 0) {
GenericMultiThreadedImporter.addCreatedDoc(taskId, uploadedFiles);
}
if (uploadedFiles % batchSize == 0 || force) {
Stopwatch stopwatch = SimonManager.getStopwatch("org.nuxeo.ecm.platform.importer.session_save");
Split split = stopwatch.start();
fslog("Comiting Core Session after " + uploadedFiles + " files",
true);
getCoreSession().save();
txHelper.commitOrRollbackTransaction();
txHelper.beginNewTransaction(TX_TIMEOUT);
split.stop();
}
}
protected DocumentModel doCreateFolderishNode(DocumentModel parent,
SourceNode node) throws Exception {
if (!shouldImportDocument(node)) {
return null;
}
Stopwatch stopwatch = SimonManager.getStopwatch("org.nuxeo.ecm.platform.importer.create_folder");
Split split = stopwatch.start();
DocumentModel folder;
try {
folder = getFactory().createFolderishNode(getCoreSession(), parent,
node);
} catch (Exception e) {
String errorMsg = "Unable to create folderish document for "
+ node.getSourcePath() + ":" + e
+ (e.getCause() != null ? e.getCause() : "");
fslog(errorMsg, true);
log.error(errorMsg);
split.stop();
throw new Exception(e);
}
if (folder != null) {
String parentPath = (parent == null) ? "null"
: parent.getPathAsString();
fslog("Created Folder " + folder.getName() + " at " + parentPath,
true);
}
split.stop();
// save session if needed
commit();
return folder;
}
protected DocumentModel doCreateLeafNode(DocumentModel parent,
SourceNode node) throws Exception {
if (!shouldImportDocument(node)) {
return null;
}
Stopwatch stopwatch = SimonManager.getStopwatch("org.nuxeo.ecm.platform.importer.create_leaf");
Split split = stopwatch.start();
DocumentModel leaf;
try {
leaf = getFactory().createLeafNode(getCoreSession(), parent, node);
} catch (Exception e) {
String errMsg = "Unable to create leaf document for "
+ node.getSourcePath() + ":" + e
+ (e.getCause() != null ? e.getCause() : "");
fslog(errMsg, true);
log.error(errMsg);
split.stop();
throw new Exception(e);
}
if (leaf != null && node.getBlobHolder() != null) {
long fileSize = node.getBlobHolder().getBlob().getLength();
String fileName = node.getBlobHolder().getBlob().getFilename();
if (fileSize > 0) {
long kbSize = fileSize / 1024;
String parentPath = (parent == null) ? "null"
: parent.getPathAsString();
fslog("Created doc " + leaf.getName() + " at " + parentPath
+ " with file " + fileName + " of size " + kbSize
+ "KB", true);
}
uploadedKO += fileSize;
}
split.stop();
// save session if needed
commit();
return leaf;
}
protected boolean shouldImportDocument(SourceNode node) {
for (ImportingDocumentFilter importingDocumentFilter : importingDocumentFilters) {
if (!importingDocumentFilter.shouldImportDocument(node)) {
return false;
}
}
return true;
}
protected GenericThreadedImportTask createNewTask(DocumentModel parent,
SourceNode node, ImporterLogger log, Integer batchSize)
throws Exception {
GenericThreadedImportTask newTask = new GenericThreadedImportTask(null,
node, parent, skipContainerCreation, log, batchSize, factory,
threadPolicy);
newTask.addListeners(listeners);
newTask.addImportingDocumentFilters(importingDocumentFilters);
return newTask;
}
protected GenericThreadedImportTask createNewTaskIfNeeded(
DocumentModel parent, SourceNode node) {
if (isRootTask) {
isRootTask = false; // don't fork Root thread on first folder
return null;
}
int scheduledTasks = GenericMultiThreadedImporter.getExecutor().getQueue().size();
boolean createTask = getThreadPolicy().needToCreateThreadAfterNewFolderishNode(
parent, node, uploadedFiles, batchSize, scheduledTasks);
if (createTask) {
GenericThreadedImportTask newTask;
try {
newTask = createNewTask(parent, node, rsLogger, batchSize);
} catch (Exception e) {
log.error("Error while starting new thread", e);
return null;
}
newTask.setBatchSize(getBatchSize());
newTask.setSkipContainerCreation(true);
return newTask;
} else {
return null;
}
}
protected void recursiveCreateDocumentFromNode(DocumentModel parent,
SourceNode node) throws Exception {
if (getFactory().isTargetDocumentModelFolderish(node)) {
DocumentModel folder;
Boolean newThread = false;
if (skipContainerCreation) {
folder = parent;
skipContainerCreation = false;
newThread = true;
} else {
folder = doCreateFolderishNode(parent, node);
if (folder == null) {
return;
}
}
// get a new TaskImporter if available to start
// processing the sub-tree
GenericThreadedImportTask task = null;
if (!newThread) {
task = createNewTaskIfNeeded(folder, node);
}
if (task != null) {
// force comit before starting new thread
commit(true);
GenericMultiThreadedImporter.getExecutor().execute(task);
} else {
Stopwatch stopwatch = SimonManager.getStopwatch("org.nuxeo.ecm.platform.importer.node_get_children");
Split split = stopwatch.start();
List<SourceNode> nodes = node.getChildren();
split.stop();
if (nodes != null) {
for (SourceNode child : nodes) {
recursiveCreateDocumentFromNode(folder, child);
}
}
}
} else {
doCreateLeafNode(parent, node);
}
}
public void setInputSource(SourceNode node) {
this.rootSource = node;
}
public void setTargetFolder(DocumentModel rootDoc) {
this.rootDoc = rootDoc;
}
// TODO isRunning is not yet handled correctly
public boolean isRunning() {
synchronized (this) {
return isRunning;
}
}
public synchronized void run() {
txHelper.beginNewTransaction(TX_TIMEOUT);
synchronized (this) {
if (isRunning) {
throw new IllegalStateException("Task already running");
}
isRunning = true;
// versions have no path, target document can be null
if (rootSource == null) {
isRunning = false;
throw new IllegalArgumentException(
"source node must be specified");
}
}
LoginContext lc = null;
try {
+ log.info("Starting new import task");
lc = Framework.login();
+ if (rootDoc != null) {
+ // reopen the root to be sure the session is valid
+ rootDoc = getCoreSession().getDocument(rootDoc.getRef());
+ }
recursiveCreateDocumentFromNode(rootDoc, rootSource);
getCoreSession().save();
GenericMultiThreadedImporter.addCreatedDoc(taskId, uploadedFiles);
txHelper.commitOrRollbackTransaction();
} catch (Exception e) {
try {
notifyImportError();
} catch (Exception e1) {
log.error("Error during import", e1);
}
log.error("Error during import", e);
} finally {
+ log.info("End of task");
if (session != null) {
CoreInstance.getInstance().close(session);
session = null;
}
if (lc != null) {
try {
lc.logout();
} catch (LoginException e) {
log.error("Error while loging out!", e);
}
}
synchronized (this) {
isRunning = false;
}
}
}
public void dispose() {
try {
if (session != null) {
CoreInstance.getInstance().close(session);
session = null;
}
} catch (Exception e) {
e.printStackTrace();// TODO
}
}
// This should be done with log4j but I did not find a way to configure it
// the way I wanted ...
protected void fslog(String msg, boolean debug) {
if (debug) {
rsLogger.debug(msg);
} else {
rsLogger.info(msg);
}
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
public void setSkipContainerCreation(Boolean skipContainerCreation) {
this.skipContainerCreation = skipContainerCreation;
}
public void setRootTask() {
isRootTask = true;
taskCounter = 0;
taskId = "T0";
}
protected ImporterThreadingPolicy getThreadPolicy() {
return threadPolicy;
}
protected ImporterDocumentModelFactory getFactory() {
return factory;
}
public void addImportingDocumentFilters(
ImportingDocumentFilter... importingDocumentFilters) {
addImportingDocumentFilters(Arrays.asList(importingDocumentFilters));
}
public void addImportingDocumentFilters(
Collection<ImportingDocumentFilter> importingDocumentFilters) {
this.importingDocumentFilters.addAll(importingDocumentFilters);
}
public void addListeners(ImporterListener... listeners) {
addListeners(Arrays.asList(listeners));
}
public void addListeners(Collection<ImporterListener> listeners) {
this.listeners.addAll(listeners);
}
protected void notifyImportError() throws Exception {
for (ImporterListener listener : listeners) {
listener.importError();
}
}
protected void setRootDoc(DocumentModel rootDoc) {
this.rootDoc = rootDoc;
}
protected void setRootSource(SourceNode rootSource) {
this.rootSource = rootSource;
}
protected void setFactory(ImporterDocumentModelFactory factory) {
this.factory = factory;
}
protected void setRsLogger(ImporterLogger rsLogger) {
this.rsLogger = rsLogger;
}
protected void setThreadPolicy(ImporterThreadingPolicy threadPolicy) {
this.threadPolicy = threadPolicy;
}
protected void setJobName(String jobName) {
this.jobName = jobName;
}
}
| false | true | public synchronized void run() {
txHelper.beginNewTransaction(TX_TIMEOUT);
synchronized (this) {
if (isRunning) {
throw new IllegalStateException("Task already running");
}
isRunning = true;
// versions have no path, target document can be null
if (rootSource == null) {
isRunning = false;
throw new IllegalArgumentException(
"source node must be specified");
}
}
LoginContext lc = null;
try {
lc = Framework.login();
recursiveCreateDocumentFromNode(rootDoc, rootSource);
getCoreSession().save();
GenericMultiThreadedImporter.addCreatedDoc(taskId, uploadedFiles);
txHelper.commitOrRollbackTransaction();
} catch (Exception e) {
try {
notifyImportError();
} catch (Exception e1) {
log.error("Error during import", e1);
}
log.error("Error during import", e);
} finally {
if (session != null) {
CoreInstance.getInstance().close(session);
session = null;
}
if (lc != null) {
try {
lc.logout();
} catch (LoginException e) {
log.error("Error while loging out!", e);
}
}
synchronized (this) {
isRunning = false;
}
}
}
| public synchronized void run() {
txHelper.beginNewTransaction(TX_TIMEOUT);
synchronized (this) {
if (isRunning) {
throw new IllegalStateException("Task already running");
}
isRunning = true;
// versions have no path, target document can be null
if (rootSource == null) {
isRunning = false;
throw new IllegalArgumentException(
"source node must be specified");
}
}
LoginContext lc = null;
try {
log.info("Starting new import task");
lc = Framework.login();
if (rootDoc != null) {
// reopen the root to be sure the session is valid
rootDoc = getCoreSession().getDocument(rootDoc.getRef());
}
recursiveCreateDocumentFromNode(rootDoc, rootSource);
getCoreSession().save();
GenericMultiThreadedImporter.addCreatedDoc(taskId, uploadedFiles);
txHelper.commitOrRollbackTransaction();
} catch (Exception e) {
try {
notifyImportError();
} catch (Exception e1) {
log.error("Error during import", e1);
}
log.error("Error during import", e);
} finally {
log.info("End of task");
if (session != null) {
CoreInstance.getInstance().close(session);
session = null;
}
if (lc != null) {
try {
lc.logout();
} catch (LoginException e) {
log.error("Error while loging out!", e);
}
}
synchronized (this) {
isRunning = false;
}
}
}
|
diff --git a/src/org/eclipse/jface/dialogs/DialogMessageArea.java b/src/org/eclipse/jface/dialogs/DialogMessageArea.java
index c3e52f53..b4be7051 100644
--- a/src/org/eclipse/jface/dialogs/DialogMessageArea.java
+++ b/src/org/eclipse/jface/dialogs/DialogMessageArea.java
@@ -1,190 +1,196 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.dialogs;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* The DialogMessageArea is a resusable component for adding an accessible
* message area to a dialog.
*
* When the message is normal a CLabel is used but an errors replaces the
* message area with a non editable text that can take focus for use by screen
* readers.
*
* @since 3.0
*/
public class DialogMessageArea extends Object {
private Text messageText;
private Label messageImageLabel;
private Composite messageComposite;
private String lastMessageText;
private int lastMessageType;
private CLabel titleLabel;
/**
* Create a new instance of the receiver.
*/
public DialogMessageArea() {
//No initial behaviour
}
/**
* Create the contents for the receiver.
*
* @param parent
* the Composite that the children will be created in
*/
public void createContents(Composite parent) {
// Message label
titleLabel = new CLabel(parent, SWT.NONE);
titleLabel.setFont(JFaceResources.getBannerFont());
messageComposite = new Composite(parent, SWT.NONE);
GridLayout messageLayout = new GridLayout();
messageLayout.numColumns = 2;
messageLayout.marginWidth = 0;
messageLayout.marginHeight = 0;
messageLayout.makeColumnsEqualWidth = false;
messageComposite.setLayout(messageLayout);
messageImageLabel = new Label(messageComposite, SWT.NONE);
messageImageLabel.setImage(JFaceResources
.getImage(Dialog.DLG_IMG_MESSAGE_INFO));
messageImageLabel.setLayoutData(new GridData(
GridData.VERTICAL_ALIGN_CENTER));
messageText = new Text(messageComposite, SWT.NONE);
messageText.setEditable(false);
GridData textData = new GridData(GridData.GRAB_HORIZONTAL
| GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER);
messageText.setLayoutData(textData);
}
/**
* Set the layoutData for the title area. In most cases this will be a copy
* of the layoutData used in setMessageLayoutData.
*
* @param layoutData
* the layoutData for the title
* @see #setMessageLayoutData(Object)
*/
public void setTitleLayoutData(Object layoutData) {
titleLabel.setLayoutData(layoutData);
}
/**
* Set the layoutData for the messageArea. In most cases this will be a copy
* of the layoutData used in setTitleLayoutData.
*
* @param layoutData
* the layoutData for the message area composite.
* @see #setTitleLayoutData(Object)
*/
public void setMessageLayoutData(Object layoutData) {
messageComposite.setLayoutData(layoutData);
}
/**
* Show the title.
*
* @param titleMessage
* String for the titke
* @param titleImage
* Image or <code>null</code>
*/
public void showTitle(String titleMessage, Image titleImage) {
titleLabel.setImage(titleImage);
titleLabel.setText(titleMessage);
restoreTitle();
return;
}
/**
* Enable the title and disable the message text and image.
*/
public void restoreTitle() {
titleLabel.setVisible(true);
messageComposite.setVisible(false);
lastMessageText = null;
lastMessageType = IMessageProvider.NONE;
}
/**
* Show the new message in the message text and update the image. Base the
* background color on whether or not there are errors.
*
* @param newMessage
* The new value for the message
* @param newType
* One of the IMessageProvider constants. If newType is
* IMessageProvider.NONE show the title.
* @see IMessageProvider
*/
public void updateText(String newMessage, int newType) {
Image newImage = null;
switch (newType) {
case IMessageProvider.NONE:
if (newMessage == null)
restoreTitle();
else
showTitle(newMessage, null);
return;
case IMessageProvider.INFORMATION:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_INFO);
break;
case IMessageProvider.WARNING:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_WARNING);
break;
case IMessageProvider.ERROR:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_ERROR);
break;
}
messageComposite.setVisible(true);
titleLabel.setVisible(false);
- // Any more updates required
- if (newMessage.equals(messageText.getText())
- && newImage == messageImageLabel.getImage())
+ // Any more updates required?
+ // If the message text equals the tooltip (i.e. non-shortened text is the same)
+ // and shortened text is the same (i.e. not a resize)
+ // and the image is the same then nothing to do
+ String shortText = Dialog.shortenText(newMessage,messageText);
+ if (newMessage.equals(messageText.getToolTipText())
+ && newImage == messageImageLabel.getImage()
+ && shortText.equals(messageText.getText()))
return;
messageImageLabel.setImage(newImage);
messageText.setText(Dialog.shortenText(newMessage,messageText));
+ messageText.setToolTipText(newMessage);
lastMessageText = newMessage;
}
/**
* Clear the error message. Restore the previously displayed message if
* there is one, if not restore the title label.
*
*/
public void clearErrorMessage() {
if (lastMessageText == null)
restoreTitle();
else
updateText(lastMessageText, lastMessageType);
}
}
| false | true | public void updateText(String newMessage, int newType) {
Image newImage = null;
switch (newType) {
case IMessageProvider.NONE:
if (newMessage == null)
restoreTitle();
else
showTitle(newMessage, null);
return;
case IMessageProvider.INFORMATION:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_INFO);
break;
case IMessageProvider.WARNING:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_WARNING);
break;
case IMessageProvider.ERROR:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_ERROR);
break;
}
messageComposite.setVisible(true);
titleLabel.setVisible(false);
// Any more updates required
if (newMessage.equals(messageText.getText())
&& newImage == messageImageLabel.getImage())
return;
messageImageLabel.setImage(newImage);
messageText.setText(Dialog.shortenText(newMessage,messageText));
lastMessageText = newMessage;
}
| public void updateText(String newMessage, int newType) {
Image newImage = null;
switch (newType) {
case IMessageProvider.NONE:
if (newMessage == null)
restoreTitle();
else
showTitle(newMessage, null);
return;
case IMessageProvider.INFORMATION:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_INFO);
break;
case IMessageProvider.WARNING:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_WARNING);
break;
case IMessageProvider.ERROR:
newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_ERROR);
break;
}
messageComposite.setVisible(true);
titleLabel.setVisible(false);
// Any more updates required?
// If the message text equals the tooltip (i.e. non-shortened text is the same)
// and shortened text is the same (i.e. not a resize)
// and the image is the same then nothing to do
String shortText = Dialog.shortenText(newMessage,messageText);
if (newMessage.equals(messageText.getToolTipText())
&& newImage == messageImageLabel.getImage()
&& shortText.equals(messageText.getText()))
return;
messageImageLabel.setImage(newImage);
messageText.setText(Dialog.shortenText(newMessage,messageText));
messageText.setToolTipText(newMessage);
lastMessageText = newMessage;
}
|
diff --git a/src/org/pentaho/pms/example/AdvancedSQLGenerator.java b/src/org/pentaho/pms/example/AdvancedSQLGenerator.java
index bd023274..044996a8 100644
--- a/src/org/pentaho/pms/example/AdvancedSQLGenerator.java
+++ b/src/org/pentaho/pms/example/AdvancedSQLGenerator.java
@@ -1,615 +1,617 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2009 Pentaho Corporation. All rights reserved.
*/
package org.pentaho.pms.example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.pms.core.exception.PentahoMetadataException;
import org.pentaho.pms.example.AdvancedMQLQuery.AliasedSelection;
import org.pentaho.pms.messages.Messages;
import org.pentaho.pms.mql.MappedQuery;
import org.pentaho.pms.mql.OrderBy;
import org.pentaho.pms.mql.Path;
import org.pentaho.pms.mql.SQLAndTables;
import org.pentaho.pms.mql.SQLGenerator;
import org.pentaho.pms.mql.Selection;
import org.pentaho.pms.mql.WhereCondition;
import org.pentaho.pms.mql.dialect.JoinType;
import org.pentaho.pms.mql.dialect.SQLDialectFactory;
import org.pentaho.pms.mql.dialect.SQLDialectInterface;
import org.pentaho.pms.mql.dialect.SQLQueryModel;
import org.pentaho.pms.mql.dialect.SQLQueryModel.OrderType;
import org.pentaho.pms.schema.BusinessModel;
import org.pentaho.pms.schema.BusinessTable;
import org.pentaho.pms.schema.RelationshipMeta;
/**
* This class demonstrates extending SQLGenerator. The example here
* is an alias algorithm, allowing multiple aliased join paths.
*
* @author Will Gorman ([email protected])
*
*/
@SuppressWarnings("deprecation")
public class AdvancedSQLGenerator extends SQLGenerator {
public static final String DEFAULT_ALIAS = "__DEFAULT__"; //$NON-NLS-1$
static class AliasedPathBusinessTable {
private String alias;
private BusinessTable table;
AliasedPathBusinessTable(String alias, BusinessTable table) {
this.alias = alias;
this.table = table;
}
public boolean equals(Object obj) {
AliasedPathBusinessTable apbt = (AliasedPathBusinessTable)obj;
return apbt.alias.equals(alias) && apbt.table.equals(table);
}
public String getAlias() {
return alias;
}
public BusinessTable getBusinessTable() {
return table;
}
}
public MappedQuery getQuery(
BusinessModel model,
List<Selection> selections,
List<WhereCondition> constraints,
List<OrderBy> orderbys,
DatabaseMeta databaseMeta,
boolean disableDistinct,
String locale) throws PentahoMetadataException
{
Map<String,String> columnsMap = new HashMap<String,String>();
if (model == null || selections.size() == 0) {
return null;
}
// implement SQL generation here
List<Selection> defaultList = null;
List<List<Selection>> lists = new ArrayList<List<Selection>>();
List<String> aliasNames = new ArrayList<String>();
Map<String, List<Selection>> listlookup = new HashMap<String, List<Selection>>();
List<Selection> selectionsAndOrderBys = new ArrayList<Selection>();
selectionsAndOrderBys.addAll(selections);
for (OrderBy orderBy : orderbys) {
selectionsAndOrderBys.add(orderBy.getSelection());
}
// default + alias lists
for (Selection selection : selectionsAndOrderBys) {
AliasedSelection sel = (AliasedSelection)selection;
if (sel.hasFormula()) {
sel.initPMSFormula(model, databaseMeta, selections);
}
if (sel.alias == null) {
sel.alias = DEFAULT_ALIAS;
}
List<Selection> list = listlookup.get(sel.alias);
if (list == null) {
list = new ArrayList<Selection>();
if (sel.alias.equals(DEFAULT_ALIAS)) {
defaultList = list;
lists.add(0, list);
aliasNames.add(0, DEFAULT_ALIAS);
} else {
lists.add(list);
aliasNames.add(sel.alias);
}
listlookup.put(sel.alias, list);
}
if (!list.contains(sel)) {
list.add(sel);
}
}
if (!listlookup.containsKey(DEFAULT_ALIAS)) {
throw new PentahoMetadataException("No non-aliased columns selected"); //$NON-NLS-1$
}
// generate paths for all the lists
List<AliasedRelationshipMeta> allRelationships = new ArrayList<AliasedRelationshipMeta>();
List<BusinessTable> defaultTables = getTablesInvolved(model, defaultList, constraints, orderbys, databaseMeta, locale);
Path defaultPath = getShortestPathBetween(model, defaultTables);
List<BusinessTable> tbls = defaultPath.getUsedTables();
List<AliasedPathBusinessTable> allTables = new ArrayList<AliasedPathBusinessTable>();
for (BusinessTable tbl : tbls) {
allTables.add(new AliasedPathBusinessTable(DEFAULT_ALIAS, tbl));
}
if (tbls.size() == 0) {
allTables.add(new AliasedPathBusinessTable(DEFAULT_ALIAS, defaultTables.get(0)));
}
if (defaultPath == null) {
throw new PentahoMetadataException(Messages.getErrorString("BusinessModel.ERROR_0001_FAILED_TO_FIND_PATH")); //$NON-NLS-1$
}
for (int i = 0; i < defaultPath.size(); i++) {
allRelationships.add(new AliasedRelationshipMeta(DEFAULT_ALIAS, DEFAULT_ALIAS, defaultPath.getRelationship(i)));
}
for (int i = 1; i < lists.size(); i++) {
List<Selection> aliasedColumns = lists.get(i);
List<Selection> aliasedAndDefaultColumns = new ArrayList<Selection>();
aliasedAndDefaultColumns.addAll(aliasedColumns);
aliasedAndDefaultColumns.addAll(defaultList);
List<BusinessTable> aliasedTables = getTablesInvolved(model, aliasedColumns, null, null, databaseMeta, locale);
List<BusinessTable> aliasedAndDefaultTables = getTablesInvolved(model, aliasedAndDefaultColumns, null, null, databaseMeta, locale);
Path aliasedAndDefaultPath = getShortestPathBetween(model, aliasedAndDefaultTables);
// Prune and connect aliased path with default path
for (BusinessTable aliasedTable : aliasedTables) {
// follow the path, move relationships into allRelationships and allTables
traversePath((String)aliasNames.get(i), aliasedTable, aliasedAndDefaultPath, aliasedTables, defaultTables, allTables, allRelationships);
}
}
SQLQueryModel sqlquery = new SQLQueryModel();
boolean group = hasFactsInIt(selections, constraints);
// SELECT
sqlquery.setDistinct(!disableDistinct && !group);
for (int i = 0; i < selections.size(); i++) {
AliasedSelection selection = (AliasedSelection)selections.get(i);
String formula;
if (selection.hasFormula()) {
try {
formula = selection.getPMSFormula().generateSQL(locale);
} catch (PentahoMetadataException e) {
throw new RuntimeException(e);
}
} else {
SQLAndTables sqlAndTables = getSelectionSQL(model, selection, databaseMeta, locale);
formula = sqlAndTables.getSql();
// formula = getFunctionTableAndColumnForSQL(model, selection, databaseMeta, locale);
}
// in some database implementations, the "as" name has a finite length;
// for instance, oracle cannot handle a name longer than 30 characters.
// So, we map a short name here to the longer id, and replace the id
// later in the resultset metadata.
String alias = null;
if(columnsMap != null){
- alias = databaseMeta.generateColumnAlias(i, selection.getBusinessColumn().getId());
+ String suggestedName;
if (selection.getBusinessColumn() != null && selection.getAlias().equals(DEFAULT_ALIAS)) {
// BIG TODO: map bizcol correctly
- columnsMap.put(alias, selection.getBusinessColumn().getId());
- } else {
- columnsMap.put(alias, "CUSTOM_" + i);
- }
+ suggestedName = selection.getBusinessColumn().getId();
+ } else {
+ suggestedName = "CUSTOM_" + i;
+ }
+ alias = databaseMeta.generateColumnAlias(i, suggestedName);
+ columnsMap.put(alias, suggestedName);
alias = databaseMeta.quoteField(alias); //$NON-NLS-1$
}else{
alias = databaseMeta.quoteField(selection.getBusinessColumn().getId());
}
sqlquery.addSelection(formula, alias);
}
// FROM
for (int i = 0; i < allTables.size(); i++) {
AliasedPathBusinessTable tbl = (AliasedPathBusinessTable)allTables.get(i);
// if __DEFAULT__, no alias
// otherwise TABLE_ALIAS
String alias = tbl.getBusinessTable().getId();
if (!tbl.getAlias().equals(DEFAULT_ALIAS)) {
alias = alias + "_" + tbl.getAlias(); //$NON-NLS-1$
}
String schemaName = null;
if (tbl.getBusinessTable().getTargetSchema() != null) {
schemaName = databaseMeta.quoteField(tbl.getBusinessTable().getTargetSchema());
}
String tableName = databaseMeta.quoteField(tbl.getBusinessTable().getTargetTable());
sqlquery.addTable(databaseMeta.getSchemaTableCombination(schemaName, tableName), databaseMeta.quoteField(alias));
}
// JOINS
// for (int i = 0; i < allRelationships.size(); i++) {
// AliasedRelationshipMeta relation = allRelationships.get(i);
// String join = getJoin(relation, databaseMeta, locale);
// sqlquery.addWhereFormula(join, "AND");
// }
for (int i = 0; i < allRelationships.size(); i++) {
AliasedRelationshipMeta aliasedRelation = allRelationships.get(i);
String joinFormula = getJoin(model, aliasedRelation, databaseMeta, locale, selections);
String joinOrderKey = aliasedRelation.relation.getJoinOrderKey();
JoinType joinType;
switch(aliasedRelation.relation.getJoinType()) {
case RelationshipMeta.TYPE_JOIN_LEFT_OUTER : joinType = JoinType.LEFT_OUTER_JOIN; break;
case RelationshipMeta.TYPE_JOIN_RIGHT_OUTER : joinType = JoinType.RIGHT_OUTER_JOIN; break;
case RelationshipMeta.TYPE_JOIN_FULL_OUTER : joinType = JoinType.FULL_OUTER_JOIN; break;
default: joinType = JoinType.INNER_JOIN; break;
}
String leftTableName = databaseMeta.getQuotedSchemaTableCombination(aliasedRelation.relation.getTableFrom().getTargetSchema(), aliasedRelation.relation.getTableFrom().getTargetTable());
String rightTableName = databaseMeta.getQuotedSchemaTableCombination(aliasedRelation.relation.getTableTo().getTargetSchema(), aliasedRelation.relation.getTableTo().getTargetTable());
String leftTableAlias = aliasedRelation.relation.getTableFrom().getId();
if (!aliasedRelation.leftAlias.equals(DEFAULT_ALIAS)) {
leftTableAlias = leftTableAlias + "_" + aliasedRelation.leftAlias; //$NON-NLS-1$
}
String rightTableAlias = aliasedRelation.relation.getTableTo().getId();
if (!aliasedRelation.rightAlias.equals(DEFAULT_ALIAS)) {
rightTableAlias = rightTableAlias + "_" + aliasedRelation.rightAlias; //$NON-NLS-1$
}
sqlquery.addJoin(leftTableName, leftTableAlias, rightTableName, rightTableAlias, joinType, joinFormula, joinOrderKey);
}
// WHERE CONDITIONS
if (constraints != null) {
boolean first = true;
for (WhereCondition constraint : constraints) {
// The ones with aggregates in it are for the HAVING clause
if (!constraint.hasAggregate() && !constraint.getPMSFormula().hasAggregateFunction()) {
String sql = constraint.getPMSFormula().generateSQL(locale);
// usedTables should be getBusinessAliases()
String[] usedTables = ((AliasAwarePMSFormula)constraint.getPMSFormula()).getTableAliasNames();
sqlquery.addWhereFormula(sql, first ? "AND" : constraint.getOperator(), usedTables); //$NON-NLS-1$
first = false;
} else {
sqlquery.addHavingFormula(constraint.getPMSFormula().generateSQL(locale), constraint.getOperator());
}
}
}
// GROUP BY
if (group) {
// can be moved to selection loop
for (Selection selection : selections) {
// BusinessColumn businessColumn = selection.getBusinessColumn();
AliasedSelection aliasedSelection = (AliasedSelection)selection;
if (!aliasedSelection.hasAggregate()) {
SQLAndTables sqlAndTables = getSelectionSQL(model, aliasedSelection, databaseMeta, locale);
sqlquery.addGroupBy(sqlAndTables.getSql(), null);
}
}
}
// ORDER BY
if (orderbys != null) {
for (OrderBy orderItem : orderbys) {
AliasedSelection selection = (AliasedSelection)orderItem.getSelection();
String sqlSelection = null;
if (!selection.hasFormula()) {
SQLAndTables sqlAndTables = getSelectionSQL(model, selection, databaseMeta, locale);
sqlSelection = sqlAndTables.getSql();
} else {
sqlSelection = selection.getPMSFormula().generateSQL(locale);
}
sqlquery.addOrderBy(sqlSelection, null, !orderItem.isAscending() ? OrderType.DESCENDING : null); //$NON-NLS-1$
}
}
SQLDialectInterface dialect = SQLDialectFactory.getSQLDialect(databaseMeta);
String sql = dialect.generateSelectStatement(sqlquery);
MappedQuery query = new MappedQuery(sql, columnsMap, selections);
// defaultPath.getUsedTables();
// selections, constraints, order, disableDistinct, locale, etc
// first, generate join paths
// second generate select statement
return query;
}
public boolean hasFactsInIt(List<Selection> selections, List<WhereCondition> conditions) {
for (Selection selection : selections) {
AliasedSelection aliasedSelection = (AliasedSelection)selection;
if (aliasedSelection.hasAggregate()) {
return true;
}
}
if (conditions != null) {
for (WhereCondition condition : conditions) {
if (condition.hasAggregate())
return true;
}
}
return false;
}
protected List<BusinessTable> getTablesInvolved(BusinessModel model, List<Selection> selections, List<WhereCondition> conditions, List<OrderBy> orderBys, DatabaseMeta databaseMeta, String locale) {
Set<BusinessTable> treeSet = new TreeSet<BusinessTable>();
for (Selection selection : selections) {
AliasedSelection aliasedSelection = (AliasedSelection)selection;
if (aliasedSelection.hasFormula()) {
List<Selection> cols = aliasedSelection.getPMSFormula().getBusinessColumns();
for(Selection sel : cols) {
BusinessTable businessTable = sel.getBusinessColumn().getBusinessTable();
treeSet.add(businessTable); //$NON-NLS-1$
}
} else {
// BusinessTable businessTable = selection.getBusinessColumn().getBusinessTable();
// treeSet.add(businessTable); //$NON-NLS-1$
SQLAndAliasedTables sqlAndTables = getSelectionSQL(model, aliasedSelection, databaseMeta, locale);
// Add the involved tables to the list...
//
for (AliasedPathBusinessTable businessTable : sqlAndTables.getAliasedBusinessTables()) {
treeSet.add(businessTable.getBusinessTable());
}
}
}
if (conditions != null) {
for(WhereCondition condition : conditions) {
List<Selection> cols = condition.getBusinessColumns();
for (Selection sel : cols) {
BusinessTable businessTable = sel.getBusinessColumn().getBusinessTable();
treeSet.add(businessTable); //$NON-NLS-1$
}
}
}
// Figure out which tables are involved in the ORDER BY
//
if (orderBys != null) {
for(OrderBy order : orderBys) {
AliasedSelection aliasedSelection = (AliasedSelection)order.getSelection();
if (aliasedSelection.hasFormula()) {
List<Selection> cols = aliasedSelection.getPMSFormula().getBusinessColumns();
for (Selection sel : cols) {
BusinessTable businessTable = sel.getBusinessColumn().getBusinessTable();
treeSet.add(businessTable); //$NON-NLS-1$
}
} else {
SQLAndAliasedTables sqlAndTables = getSelectionSQL(model, (AliasedSelection)order.getSelection(), databaseMeta, locale);
// Add the involved tables to the list...
//
for (AliasedPathBusinessTable businessTable : sqlAndTables.getAliasedBusinessTables()) {
treeSet.add(businessTable.getBusinessTable());
}
}
}
}
return new ArrayList<BusinessTable>(treeSet);
}
public static class SQLAndAliasedTables extends SQLAndTables {
final List<AliasedPathBusinessTable> aliasedTables;
public SQLAndAliasedTables(String sql, AliasedPathBusinessTable aliasedTable) {
super(sql, (BusinessTable)null, (Selection)null);
aliasedTables = new ArrayList<AliasedPathBusinessTable>();
aliasedTables.add(aliasedTable);
}
public SQLAndAliasedTables(String sql, List<AliasedPathBusinessTable> aliasedTables) {
super(sql, (BusinessTable)null, (Selection)null);
this.aliasedTables = aliasedTables;
}
public List<AliasedPathBusinessTable> getAliasedBusinessTables() {
return aliasedTables;
}
public List<BusinessTable> getUsedTables() {
throw new UnsupportedOperationException();
}
public void setUsedTables(List<BusinessTable> tables) {
throw new UnsupportedOperationException();
}
}
// we should do something with this other than a static method that is alias aware.
// The folks that call this should be alias aware or not, and call a different method possibly?
// this is primarily due to the context that would need to get passed into PMSFormula
// we don't want the pentaho MQL solution to ever come across aliases, etc.
public static SQLAndAliasedTables getSelectionSQL(BusinessModel businessModel, AliasedSelection selection, DatabaseMeta databaseMeta, String locale) {
if (selection.getBusinessColumn().isExact()) {
// convert to sql using libformula subsystem
try {
// we'll need to pass in some context to PMSFormula so it can resolve aliases if necessary
AliasAwarePMSFormula formula = new AliasAwarePMSFormula(businessModel, selection.getBusinessColumn().getBusinessTable(), databaseMeta, selection.getBusinessColumn().getFormula(), selection.getAlias());
formula.parseAndValidate();
// return formula.generateSQL(locale);
return new SQLAndAliasedTables(formula.generateSQL(locale), formula.getUsedAliasedTables());
} catch (PentahoMetadataException e) {
// this is for backwards compatibility.
// eventually throw any errors
throw new RuntimeException(Messages.getErrorString("BusinessColumn.ERROR_0001_FAILED_TO_PARSE_FORMULA", selection.getBusinessColumn().getFormula())); //$NON-NLS-1$
}
} else {
String tableColumn = ""; //$NON-NLS-1$
String tblName = selection.getBusinessColumn().getBusinessTable().getId();
if (!selection.getAlias().equals(DEFAULT_ALIAS)) {
tblName += "_" + selection.getAlias(); //$NON-NLS-1$
}
tableColumn += databaseMeta.quoteField( tblName );
tableColumn += "."; //$NON-NLS-1$
// TODO: WPG: instead of using formula, shouldn't we use the physical column's name?
tableColumn += databaseMeta.quoteField( selection.getBusinessColumn().getFormula() );
if (selection.hasAggregate()) // For the having clause, for example: HAVING sum(turnover) > 100
{
// return getFunctionExpression(selection.getBusinessColumn(), tableColumn, databaseMeta);
return new SQLAndAliasedTables(
getFunctionExpression(selection, tableColumn, databaseMeta),
new AliasedPathBusinessTable(tblName, selection.getBusinessColumn().getBusinessTable())
);
}
else
{
return new SQLAndAliasedTables(tableColumn, new AliasedPathBusinessTable(tblName, selection.getBusinessColumn().getBusinessTable()));
}
}
}
public String getJoin(BusinessModel businessModel, AliasedRelationshipMeta relation, DatabaseMeta databaseMeta, String locale, List<Selection> selections) throws PentahoMetadataException
{
String join=""; //$NON-NLS-1$
if (relation.relation.isComplex()) {
// parse join as MQL
String formulaString = relation.relation.getComplexJoin();
AliasAwarePMSFormula formula = new AliasAwarePMSFormula(businessModel, databaseMeta, formulaString, selections, DEFAULT_ALIAS);
// if we're dealing with an aliased join, inform the formula
if (!relation.rightAlias.equals(DEFAULT_ALIAS) || !relation.leftAlias.equals(DEFAULT_ALIAS)) {
Map<String, String> businessTableToAliasMap = new HashMap<String, String>();
if (!relation.rightAlias.equals(DEFAULT_ALIAS)) {
businessTableToAliasMap.put(relation.relation.getTableTo().getId(), relation.rightAlias);
}
if (!relation.leftAlias.equals(DEFAULT_ALIAS)) {
businessTableToAliasMap.put(relation.relation.getTableFrom().getId(), relation.leftAlias);
}
formula.setBusinessTableToAliasMap(businessTableToAliasMap);
}
formula.parseAndValidate();
join = formula.generateSQL(locale);
} else if (relation.relation.getTableFrom() != null && relation.relation.getTableTo() != null && relation.relation.getFieldFrom() !=null && relation.relation.getFieldTo() != null) {
String rightAlias = relation.relation.getTableTo().getId();
if (!relation.rightAlias.equals(DEFAULT_ALIAS)) {
rightAlias = rightAlias + "_" + relation.rightAlias; //$NON-NLS-1$
}
String leftAlias = relation.relation.getTableFrom().getId();
if (!relation.leftAlias.equals(DEFAULT_ALIAS)) {
leftAlias = leftAlias + "_" + relation.leftAlias; //$NON-NLS-1$
}
// Left side
join = databaseMeta.quoteField(leftAlias );
join += "."; //$NON-NLS-1$
join += databaseMeta.quoteField( relation.relation.getFieldFrom().getFormula() );
// Equals
join += " = "; //$NON-NLS-1$
// Right side
join += databaseMeta.quoteField(rightAlias );
join += "."; //$NON-NLS-1$
join += databaseMeta.quoteField( relation.relation.getFieldTo().getFormula() );
}
return join;
}
class AliasedRelationshipMeta {
String leftAlias;
String rightAlias;
RelationshipMeta relation;
AliasedRelationshipMeta(String left, String right, RelationshipMeta rel) {
this.leftAlias = left;
this.rightAlias = right;
this.relation = rel;
}
}
protected void traversePath(String alias, BusinessTable aliasedTable, Path aliasedPath, List<BusinessTable> aliasedTables, List<BusinessTable> defaultTables, List<AliasedPathBusinessTable> allTables, List<AliasedRelationshipMeta> allRelationships) {
AliasedPathBusinessTable aliasedPathTable = new AliasedPathBusinessTable(alias, aliasedTable);
if (allTables.contains(aliasedPathTable)) {
allTables.add(aliasedPathTable);
}
allTables.add(aliasedPathTable);
List<RelationshipMeta> cachedAliasedPath = new ArrayList<RelationshipMeta>();
for (int i = 0; i < aliasedPath.size(); i++) {
cachedAliasedPath.add(aliasedPath.getRelationship(i));
}
for (int i = 0; i < cachedAliasedPath.size(); i++) {
RelationshipMeta rel = cachedAliasedPath.get(i);
int index = -1;
for (int j = 0; j < aliasedPath.size(); j++) {
if (aliasedPath.getRelationship(j) == rel) {
index = j;
break;
}
}
if (index == -1) {
continue;
}
if (rel.isUsingTable(aliasedTable)) {
// this needs to either be an aliased relation or a alias to default relation
boolean joinsToADefaultTable = false;
for (BusinessTable defaultTable : defaultTables) {
if (rel.isUsingTable(defaultTable)) {
boolean inAliasedTables = false;
for (BusinessTable aliased : aliasedTables) {
if (defaultTable.equals(aliased)) {
inAliasedTables = true;
}
}
if (!inAliasedTables) {
joinsToADefaultTable = true;
// this relation will join to the default path
aliasedPath.removeRelationship(index);
String leftAlias = null;
String rightAlias = null;
if (aliasedTable.equals(rel.getTableFrom())) {
leftAlias = alias;
rightAlias = DEFAULT_ALIAS;
} else {
leftAlias = DEFAULT_ALIAS;
rightAlias = alias;
}
allRelationships.add(new AliasedRelationshipMeta(leftAlias,rightAlias,rel));
}
}
}
if (!joinsToADefaultTable) {
// this relation is joined to either an aliased or a soon to be aliased table
aliasedPath.removeRelationship(index);
// we need to add this to the aliased path list, along with the table we're joining to
// check for uniqueness?
allRelationships.add(new AliasedRelationshipMeta(alias,alias,rel));
BusinessTable tbl = rel.getTableFrom() == aliasedTable ? rel.getTableTo() : rel.getTableFrom();
traversePath(alias, tbl, aliasedPath, aliasedTables, defaultTables, allTables, allRelationships);
}
}
}
}
}
| false | true | public MappedQuery getQuery(
BusinessModel model,
List<Selection> selections,
List<WhereCondition> constraints,
List<OrderBy> orderbys,
DatabaseMeta databaseMeta,
boolean disableDistinct,
String locale) throws PentahoMetadataException
{
Map<String,String> columnsMap = new HashMap<String,String>();
if (model == null || selections.size() == 0) {
return null;
}
// implement SQL generation here
List<Selection> defaultList = null;
List<List<Selection>> lists = new ArrayList<List<Selection>>();
List<String> aliasNames = new ArrayList<String>();
Map<String, List<Selection>> listlookup = new HashMap<String, List<Selection>>();
List<Selection> selectionsAndOrderBys = new ArrayList<Selection>();
selectionsAndOrderBys.addAll(selections);
for (OrderBy orderBy : orderbys) {
selectionsAndOrderBys.add(orderBy.getSelection());
}
// default + alias lists
for (Selection selection : selectionsAndOrderBys) {
AliasedSelection sel = (AliasedSelection)selection;
if (sel.hasFormula()) {
sel.initPMSFormula(model, databaseMeta, selections);
}
if (sel.alias == null) {
sel.alias = DEFAULT_ALIAS;
}
List<Selection> list = listlookup.get(sel.alias);
if (list == null) {
list = new ArrayList<Selection>();
if (sel.alias.equals(DEFAULT_ALIAS)) {
defaultList = list;
lists.add(0, list);
aliasNames.add(0, DEFAULT_ALIAS);
} else {
lists.add(list);
aliasNames.add(sel.alias);
}
listlookup.put(sel.alias, list);
}
if (!list.contains(sel)) {
list.add(sel);
}
}
if (!listlookup.containsKey(DEFAULT_ALIAS)) {
throw new PentahoMetadataException("No non-aliased columns selected"); //$NON-NLS-1$
}
// generate paths for all the lists
List<AliasedRelationshipMeta> allRelationships = new ArrayList<AliasedRelationshipMeta>();
List<BusinessTable> defaultTables = getTablesInvolved(model, defaultList, constraints, orderbys, databaseMeta, locale);
Path defaultPath = getShortestPathBetween(model, defaultTables);
List<BusinessTable> tbls = defaultPath.getUsedTables();
List<AliasedPathBusinessTable> allTables = new ArrayList<AliasedPathBusinessTable>();
for (BusinessTable tbl : tbls) {
allTables.add(new AliasedPathBusinessTable(DEFAULT_ALIAS, tbl));
}
if (tbls.size() == 0) {
allTables.add(new AliasedPathBusinessTable(DEFAULT_ALIAS, defaultTables.get(0)));
}
if (defaultPath == null) {
throw new PentahoMetadataException(Messages.getErrorString("BusinessModel.ERROR_0001_FAILED_TO_FIND_PATH")); //$NON-NLS-1$
}
for (int i = 0; i < defaultPath.size(); i++) {
allRelationships.add(new AliasedRelationshipMeta(DEFAULT_ALIAS, DEFAULT_ALIAS, defaultPath.getRelationship(i)));
}
for (int i = 1; i < lists.size(); i++) {
List<Selection> aliasedColumns = lists.get(i);
List<Selection> aliasedAndDefaultColumns = new ArrayList<Selection>();
aliasedAndDefaultColumns.addAll(aliasedColumns);
aliasedAndDefaultColumns.addAll(defaultList);
List<BusinessTable> aliasedTables = getTablesInvolved(model, aliasedColumns, null, null, databaseMeta, locale);
List<BusinessTable> aliasedAndDefaultTables = getTablesInvolved(model, aliasedAndDefaultColumns, null, null, databaseMeta, locale);
Path aliasedAndDefaultPath = getShortestPathBetween(model, aliasedAndDefaultTables);
// Prune and connect aliased path with default path
for (BusinessTable aliasedTable : aliasedTables) {
// follow the path, move relationships into allRelationships and allTables
traversePath((String)aliasNames.get(i), aliasedTable, aliasedAndDefaultPath, aliasedTables, defaultTables, allTables, allRelationships);
}
}
SQLQueryModel sqlquery = new SQLQueryModel();
boolean group = hasFactsInIt(selections, constraints);
// SELECT
sqlquery.setDistinct(!disableDistinct && !group);
for (int i = 0; i < selections.size(); i++) {
AliasedSelection selection = (AliasedSelection)selections.get(i);
String formula;
if (selection.hasFormula()) {
try {
formula = selection.getPMSFormula().generateSQL(locale);
} catch (PentahoMetadataException e) {
throw new RuntimeException(e);
}
} else {
SQLAndTables sqlAndTables = getSelectionSQL(model, selection, databaseMeta, locale);
formula = sqlAndTables.getSql();
// formula = getFunctionTableAndColumnForSQL(model, selection, databaseMeta, locale);
}
// in some database implementations, the "as" name has a finite length;
// for instance, oracle cannot handle a name longer than 30 characters.
// So, we map a short name here to the longer id, and replace the id
// later in the resultset metadata.
String alias = null;
if(columnsMap != null){
alias = databaseMeta.generateColumnAlias(i, selection.getBusinessColumn().getId());
if (selection.getBusinessColumn() != null && selection.getAlias().equals(DEFAULT_ALIAS)) {
// BIG TODO: map bizcol correctly
columnsMap.put(alias, selection.getBusinessColumn().getId());
} else {
columnsMap.put(alias, "CUSTOM_" + i);
}
alias = databaseMeta.quoteField(alias); //$NON-NLS-1$
}else{
alias = databaseMeta.quoteField(selection.getBusinessColumn().getId());
}
sqlquery.addSelection(formula, alias);
}
// FROM
for (int i = 0; i < allTables.size(); i++) {
AliasedPathBusinessTable tbl = (AliasedPathBusinessTable)allTables.get(i);
// if __DEFAULT__, no alias
// otherwise TABLE_ALIAS
String alias = tbl.getBusinessTable().getId();
if (!tbl.getAlias().equals(DEFAULT_ALIAS)) {
alias = alias + "_" + tbl.getAlias(); //$NON-NLS-1$
}
String schemaName = null;
if (tbl.getBusinessTable().getTargetSchema() != null) {
schemaName = databaseMeta.quoteField(tbl.getBusinessTable().getTargetSchema());
}
String tableName = databaseMeta.quoteField(tbl.getBusinessTable().getTargetTable());
sqlquery.addTable(databaseMeta.getSchemaTableCombination(schemaName, tableName), databaseMeta.quoteField(alias));
}
// JOINS
// for (int i = 0; i < allRelationships.size(); i++) {
// AliasedRelationshipMeta relation = allRelationships.get(i);
// String join = getJoin(relation, databaseMeta, locale);
// sqlquery.addWhereFormula(join, "AND");
// }
for (int i = 0; i < allRelationships.size(); i++) {
AliasedRelationshipMeta aliasedRelation = allRelationships.get(i);
String joinFormula = getJoin(model, aliasedRelation, databaseMeta, locale, selections);
String joinOrderKey = aliasedRelation.relation.getJoinOrderKey();
JoinType joinType;
switch(aliasedRelation.relation.getJoinType()) {
case RelationshipMeta.TYPE_JOIN_LEFT_OUTER : joinType = JoinType.LEFT_OUTER_JOIN; break;
case RelationshipMeta.TYPE_JOIN_RIGHT_OUTER : joinType = JoinType.RIGHT_OUTER_JOIN; break;
case RelationshipMeta.TYPE_JOIN_FULL_OUTER : joinType = JoinType.FULL_OUTER_JOIN; break;
default: joinType = JoinType.INNER_JOIN; break;
}
String leftTableName = databaseMeta.getQuotedSchemaTableCombination(aliasedRelation.relation.getTableFrom().getTargetSchema(), aliasedRelation.relation.getTableFrom().getTargetTable());
String rightTableName = databaseMeta.getQuotedSchemaTableCombination(aliasedRelation.relation.getTableTo().getTargetSchema(), aliasedRelation.relation.getTableTo().getTargetTable());
String leftTableAlias = aliasedRelation.relation.getTableFrom().getId();
if (!aliasedRelation.leftAlias.equals(DEFAULT_ALIAS)) {
leftTableAlias = leftTableAlias + "_" + aliasedRelation.leftAlias; //$NON-NLS-1$
}
String rightTableAlias = aliasedRelation.relation.getTableTo().getId();
if (!aliasedRelation.rightAlias.equals(DEFAULT_ALIAS)) {
rightTableAlias = rightTableAlias + "_" + aliasedRelation.rightAlias; //$NON-NLS-1$
}
sqlquery.addJoin(leftTableName, leftTableAlias, rightTableName, rightTableAlias, joinType, joinFormula, joinOrderKey);
}
// WHERE CONDITIONS
if (constraints != null) {
boolean first = true;
for (WhereCondition constraint : constraints) {
// The ones with aggregates in it are for the HAVING clause
if (!constraint.hasAggregate() && !constraint.getPMSFormula().hasAggregateFunction()) {
String sql = constraint.getPMSFormula().generateSQL(locale);
// usedTables should be getBusinessAliases()
String[] usedTables = ((AliasAwarePMSFormula)constraint.getPMSFormula()).getTableAliasNames();
sqlquery.addWhereFormula(sql, first ? "AND" : constraint.getOperator(), usedTables); //$NON-NLS-1$
first = false;
} else {
sqlquery.addHavingFormula(constraint.getPMSFormula().generateSQL(locale), constraint.getOperator());
}
}
}
// GROUP BY
if (group) {
// can be moved to selection loop
for (Selection selection : selections) {
// BusinessColumn businessColumn = selection.getBusinessColumn();
AliasedSelection aliasedSelection = (AliasedSelection)selection;
if (!aliasedSelection.hasAggregate()) {
SQLAndTables sqlAndTables = getSelectionSQL(model, aliasedSelection, databaseMeta, locale);
sqlquery.addGroupBy(sqlAndTables.getSql(), null);
}
}
}
// ORDER BY
if (orderbys != null) {
for (OrderBy orderItem : orderbys) {
AliasedSelection selection = (AliasedSelection)orderItem.getSelection();
String sqlSelection = null;
if (!selection.hasFormula()) {
SQLAndTables sqlAndTables = getSelectionSQL(model, selection, databaseMeta, locale);
sqlSelection = sqlAndTables.getSql();
} else {
sqlSelection = selection.getPMSFormula().generateSQL(locale);
}
sqlquery.addOrderBy(sqlSelection, null, !orderItem.isAscending() ? OrderType.DESCENDING : null); //$NON-NLS-1$
}
}
SQLDialectInterface dialect = SQLDialectFactory.getSQLDialect(databaseMeta);
String sql = dialect.generateSelectStatement(sqlquery);
MappedQuery query = new MappedQuery(sql, columnsMap, selections);
// defaultPath.getUsedTables();
// selections, constraints, order, disableDistinct, locale, etc
// first, generate join paths
// second generate select statement
return query;
}
| public MappedQuery getQuery(
BusinessModel model,
List<Selection> selections,
List<WhereCondition> constraints,
List<OrderBy> orderbys,
DatabaseMeta databaseMeta,
boolean disableDistinct,
String locale) throws PentahoMetadataException
{
Map<String,String> columnsMap = new HashMap<String,String>();
if (model == null || selections.size() == 0) {
return null;
}
// implement SQL generation here
List<Selection> defaultList = null;
List<List<Selection>> lists = new ArrayList<List<Selection>>();
List<String> aliasNames = new ArrayList<String>();
Map<String, List<Selection>> listlookup = new HashMap<String, List<Selection>>();
List<Selection> selectionsAndOrderBys = new ArrayList<Selection>();
selectionsAndOrderBys.addAll(selections);
for (OrderBy orderBy : orderbys) {
selectionsAndOrderBys.add(orderBy.getSelection());
}
// default + alias lists
for (Selection selection : selectionsAndOrderBys) {
AliasedSelection sel = (AliasedSelection)selection;
if (sel.hasFormula()) {
sel.initPMSFormula(model, databaseMeta, selections);
}
if (sel.alias == null) {
sel.alias = DEFAULT_ALIAS;
}
List<Selection> list = listlookup.get(sel.alias);
if (list == null) {
list = new ArrayList<Selection>();
if (sel.alias.equals(DEFAULT_ALIAS)) {
defaultList = list;
lists.add(0, list);
aliasNames.add(0, DEFAULT_ALIAS);
} else {
lists.add(list);
aliasNames.add(sel.alias);
}
listlookup.put(sel.alias, list);
}
if (!list.contains(sel)) {
list.add(sel);
}
}
if (!listlookup.containsKey(DEFAULT_ALIAS)) {
throw new PentahoMetadataException("No non-aliased columns selected"); //$NON-NLS-1$
}
// generate paths for all the lists
List<AliasedRelationshipMeta> allRelationships = new ArrayList<AliasedRelationshipMeta>();
List<BusinessTable> defaultTables = getTablesInvolved(model, defaultList, constraints, orderbys, databaseMeta, locale);
Path defaultPath = getShortestPathBetween(model, defaultTables);
List<BusinessTable> tbls = defaultPath.getUsedTables();
List<AliasedPathBusinessTable> allTables = new ArrayList<AliasedPathBusinessTable>();
for (BusinessTable tbl : tbls) {
allTables.add(new AliasedPathBusinessTable(DEFAULT_ALIAS, tbl));
}
if (tbls.size() == 0) {
allTables.add(new AliasedPathBusinessTable(DEFAULT_ALIAS, defaultTables.get(0)));
}
if (defaultPath == null) {
throw new PentahoMetadataException(Messages.getErrorString("BusinessModel.ERROR_0001_FAILED_TO_FIND_PATH")); //$NON-NLS-1$
}
for (int i = 0; i < defaultPath.size(); i++) {
allRelationships.add(new AliasedRelationshipMeta(DEFAULT_ALIAS, DEFAULT_ALIAS, defaultPath.getRelationship(i)));
}
for (int i = 1; i < lists.size(); i++) {
List<Selection> aliasedColumns = lists.get(i);
List<Selection> aliasedAndDefaultColumns = new ArrayList<Selection>();
aliasedAndDefaultColumns.addAll(aliasedColumns);
aliasedAndDefaultColumns.addAll(defaultList);
List<BusinessTable> aliasedTables = getTablesInvolved(model, aliasedColumns, null, null, databaseMeta, locale);
List<BusinessTable> aliasedAndDefaultTables = getTablesInvolved(model, aliasedAndDefaultColumns, null, null, databaseMeta, locale);
Path aliasedAndDefaultPath = getShortestPathBetween(model, aliasedAndDefaultTables);
// Prune and connect aliased path with default path
for (BusinessTable aliasedTable : aliasedTables) {
// follow the path, move relationships into allRelationships and allTables
traversePath((String)aliasNames.get(i), aliasedTable, aliasedAndDefaultPath, aliasedTables, defaultTables, allTables, allRelationships);
}
}
SQLQueryModel sqlquery = new SQLQueryModel();
boolean group = hasFactsInIt(selections, constraints);
// SELECT
sqlquery.setDistinct(!disableDistinct && !group);
for (int i = 0; i < selections.size(); i++) {
AliasedSelection selection = (AliasedSelection)selections.get(i);
String formula;
if (selection.hasFormula()) {
try {
formula = selection.getPMSFormula().generateSQL(locale);
} catch (PentahoMetadataException e) {
throw new RuntimeException(e);
}
} else {
SQLAndTables sqlAndTables = getSelectionSQL(model, selection, databaseMeta, locale);
formula = sqlAndTables.getSql();
// formula = getFunctionTableAndColumnForSQL(model, selection, databaseMeta, locale);
}
// in some database implementations, the "as" name has a finite length;
// for instance, oracle cannot handle a name longer than 30 characters.
// So, we map a short name here to the longer id, and replace the id
// later in the resultset metadata.
String alias = null;
if(columnsMap != null){
String suggestedName;
if (selection.getBusinessColumn() != null && selection.getAlias().equals(DEFAULT_ALIAS)) {
// BIG TODO: map bizcol correctly
suggestedName = selection.getBusinessColumn().getId();
} else {
suggestedName = "CUSTOM_" + i;
}
alias = databaseMeta.generateColumnAlias(i, suggestedName);
columnsMap.put(alias, suggestedName);
alias = databaseMeta.quoteField(alias); //$NON-NLS-1$
}else{
alias = databaseMeta.quoteField(selection.getBusinessColumn().getId());
}
sqlquery.addSelection(formula, alias);
}
// FROM
for (int i = 0; i < allTables.size(); i++) {
AliasedPathBusinessTable tbl = (AliasedPathBusinessTable)allTables.get(i);
// if __DEFAULT__, no alias
// otherwise TABLE_ALIAS
String alias = tbl.getBusinessTable().getId();
if (!tbl.getAlias().equals(DEFAULT_ALIAS)) {
alias = alias + "_" + tbl.getAlias(); //$NON-NLS-1$
}
String schemaName = null;
if (tbl.getBusinessTable().getTargetSchema() != null) {
schemaName = databaseMeta.quoteField(tbl.getBusinessTable().getTargetSchema());
}
String tableName = databaseMeta.quoteField(tbl.getBusinessTable().getTargetTable());
sqlquery.addTable(databaseMeta.getSchemaTableCombination(schemaName, tableName), databaseMeta.quoteField(alias));
}
// JOINS
// for (int i = 0; i < allRelationships.size(); i++) {
// AliasedRelationshipMeta relation = allRelationships.get(i);
// String join = getJoin(relation, databaseMeta, locale);
// sqlquery.addWhereFormula(join, "AND");
// }
for (int i = 0; i < allRelationships.size(); i++) {
AliasedRelationshipMeta aliasedRelation = allRelationships.get(i);
String joinFormula = getJoin(model, aliasedRelation, databaseMeta, locale, selections);
String joinOrderKey = aliasedRelation.relation.getJoinOrderKey();
JoinType joinType;
switch(aliasedRelation.relation.getJoinType()) {
case RelationshipMeta.TYPE_JOIN_LEFT_OUTER : joinType = JoinType.LEFT_OUTER_JOIN; break;
case RelationshipMeta.TYPE_JOIN_RIGHT_OUTER : joinType = JoinType.RIGHT_OUTER_JOIN; break;
case RelationshipMeta.TYPE_JOIN_FULL_OUTER : joinType = JoinType.FULL_OUTER_JOIN; break;
default: joinType = JoinType.INNER_JOIN; break;
}
String leftTableName = databaseMeta.getQuotedSchemaTableCombination(aliasedRelation.relation.getTableFrom().getTargetSchema(), aliasedRelation.relation.getTableFrom().getTargetTable());
String rightTableName = databaseMeta.getQuotedSchemaTableCombination(aliasedRelation.relation.getTableTo().getTargetSchema(), aliasedRelation.relation.getTableTo().getTargetTable());
String leftTableAlias = aliasedRelation.relation.getTableFrom().getId();
if (!aliasedRelation.leftAlias.equals(DEFAULT_ALIAS)) {
leftTableAlias = leftTableAlias + "_" + aliasedRelation.leftAlias; //$NON-NLS-1$
}
String rightTableAlias = aliasedRelation.relation.getTableTo().getId();
if (!aliasedRelation.rightAlias.equals(DEFAULT_ALIAS)) {
rightTableAlias = rightTableAlias + "_" + aliasedRelation.rightAlias; //$NON-NLS-1$
}
sqlquery.addJoin(leftTableName, leftTableAlias, rightTableName, rightTableAlias, joinType, joinFormula, joinOrderKey);
}
// WHERE CONDITIONS
if (constraints != null) {
boolean first = true;
for (WhereCondition constraint : constraints) {
// The ones with aggregates in it are for the HAVING clause
if (!constraint.hasAggregate() && !constraint.getPMSFormula().hasAggregateFunction()) {
String sql = constraint.getPMSFormula().generateSQL(locale);
// usedTables should be getBusinessAliases()
String[] usedTables = ((AliasAwarePMSFormula)constraint.getPMSFormula()).getTableAliasNames();
sqlquery.addWhereFormula(sql, first ? "AND" : constraint.getOperator(), usedTables); //$NON-NLS-1$
first = false;
} else {
sqlquery.addHavingFormula(constraint.getPMSFormula().generateSQL(locale), constraint.getOperator());
}
}
}
// GROUP BY
if (group) {
// can be moved to selection loop
for (Selection selection : selections) {
// BusinessColumn businessColumn = selection.getBusinessColumn();
AliasedSelection aliasedSelection = (AliasedSelection)selection;
if (!aliasedSelection.hasAggregate()) {
SQLAndTables sqlAndTables = getSelectionSQL(model, aliasedSelection, databaseMeta, locale);
sqlquery.addGroupBy(sqlAndTables.getSql(), null);
}
}
}
// ORDER BY
if (orderbys != null) {
for (OrderBy orderItem : orderbys) {
AliasedSelection selection = (AliasedSelection)orderItem.getSelection();
String sqlSelection = null;
if (!selection.hasFormula()) {
SQLAndTables sqlAndTables = getSelectionSQL(model, selection, databaseMeta, locale);
sqlSelection = sqlAndTables.getSql();
} else {
sqlSelection = selection.getPMSFormula().generateSQL(locale);
}
sqlquery.addOrderBy(sqlSelection, null, !orderItem.isAscending() ? OrderType.DESCENDING : null); //$NON-NLS-1$
}
}
SQLDialectInterface dialect = SQLDialectFactory.getSQLDialect(databaseMeta);
String sql = dialect.generateSelectStatement(sqlquery);
MappedQuery query = new MappedQuery(sql, columnsMap, selections);
// defaultPath.getUsedTables();
// selections, constraints, order, disableDistinct, locale, etc
// first, generate join paths
// second generate select statement
return query;
}
|
diff --git a/SpagoBIWhatIfEngine/src/it/eng/spagobi/engines/whatif/WhatIfEngineInstance.java b/SpagoBIWhatIfEngine/src/it/eng/spagobi/engines/whatif/WhatIfEngineInstance.java
index c430ef49e..8712ff1c1 100644
--- a/SpagoBIWhatIfEngine/src/it/eng/spagobi/engines/whatif/WhatIfEngineInstance.java
+++ b/SpagoBIWhatIfEngine/src/it/eng/spagobi/engines/whatif/WhatIfEngineInstance.java
@@ -1,290 +1,298 @@
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package it.eng.spagobi.engines.whatif;
import it.eng.spago.security.IEngUserProfile;
import it.eng.spagobi.commons.constants.SpagoBIConstants;
import it.eng.spagobi.commons.utilities.StringUtilities;
import it.eng.spagobi.engines.whatif.model.ModelConfig;
import it.eng.spagobi.engines.whatif.model.SpagoBIPivotModel;
import it.eng.spagobi.engines.whatif.parameters.MDXParametersUtilities;
import it.eng.spagobi.engines.whatif.schema.MondrianSchemaManager;
import it.eng.spagobi.engines.whatif.template.WhatIfTemplate;
import it.eng.spagobi.engines.whatif.template.WhatIfTemplateParser;
import it.eng.spagobi.services.proxy.ArtifactServiceProxy;
import it.eng.spagobi.services.proxy.EventServiceProxy;
import it.eng.spagobi.tools.dataset.bo.IDataSet;
import it.eng.spagobi.tools.datasource.bo.IDataSource;
import it.eng.spagobi.utilities.engines.AbstractEngineInstance;
import it.eng.spagobi.utilities.engines.AuditServiceProxy;
import it.eng.spagobi.utilities.engines.EngineConstants;
import it.eng.spagobi.utilities.engines.IEngineAnalysisState;
import it.eng.spagobi.utilities.engines.SpagoBIEngineException;
import it.eng.spagobi.utilities.engines.SpagoBIEngineRuntimeException;
import it.eng.spagobi.utilities.exceptions.SpagoBIEngineRestServiceRuntimeException;
import it.eng.spagobi.writeback4j.WriteBackEditConfig;
import it.eng.spagobi.writeback4j.WriteBackManager;
import it.eng.spagobi.writeback4j.mondrian.MondrianDriver;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.log4j.Logger;
import org.olap4j.OlapConnection;
import org.olap4j.OlapDataSource;
import com.eyeq.pivot4j.PivotModel;
/**
* @author ...
*/
public class WhatIfEngineInstance extends AbstractEngineInstance implements Serializable {
private static final long serialVersionUID = 1329486982941461093L;
public static transient Logger logger = Logger.getLogger(WhatIfEngineInstance.class);
//private JSONObject guiSettings;
private List<String> includes;
private OlapDataSource olapDataSource;
private PivotModel pivotModel;
private ModelConfig modelConfig;
private WriteBackManager writeBackManager;
private String mondrianSchemaFilePath;
protected WhatIfEngineInstance(Object template, Map env) {
this( WhatIfTemplateParser.getInstance() != null ? WhatIfTemplateParser.getInstance().parse(template) : null, env );
}
public WhatIfEngineInstance(WhatIfTemplate template, Map env) {
super( env );
includes = WhatIfEngine.getConfig().getIncludes();
try {
Class.forName("mondrian.olap4j.MondrianOlap4jDriver");
Class.forName("org.olap4j.OlapWrapper");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot load Mondrian Olap4j Driver", e);
}
String reference = initMondrianSchema(env);
this.setMondrianSchemaFilePath(reference);
IDataSource ds = (IDataSource) env.get(EngineConstants.ENV_DATASOURCE);
olapDataSource = WhatIfEngineConfig.getInstance().getOlapDataSource( ds, reference );
//pivotModel = new PivotModelImpl(olapDataSource);
pivotModel = new SpagoBIPivotModel(olapDataSource);
pivotModel.setLocale( this.getLocale() );
String initialMDX = this.getInitialMDX( template, env );
logger.debug("Initial MDX is [" + initialMDX + "]");
pivotModel.setMdx( initialMDX );
pivotModel.initialize();
// execute the MDX now
- pivotModel.getCellSet();
+ try {
+ pivotModel.getCellSet();
+ } catch (Throwable t) {
+ Throwable rootException = t;
+ while (rootException.getCause() != null) {
+ rootException = rootException.getCause();
+ }
+ throw new SpagoBIEngineRuntimeException("Error while executing MDX statement: " + rootException.getMessage(), t);
+ }
//init configs
modelConfig = new ModelConfig();
modelConfig.setWriteBackConf(template.getWritebackEditConfig());
WriteBackEditConfig writeBackConfig = getModelConfig().getWriteBackConf();
if(writeBackConfig!= null ){
try {
writeBackManager = new WriteBackManager(getEditCubeName(), new MondrianDriver(getMondrianSchemaFilePath()));
} catch (SpagoBIEngineException e) {
logger.debug("Exception creating the whatif component", e);
throw new SpagoBIEngineRestServiceRuntimeException("whatif.engine.instance.writeback.exception", getLocale(), "Exception creating the whatif component", e);
}
}
}
private String getInitialMDX(WhatIfTemplate template, Map env) {
String query = null;
logger.debug("IN");
query = template.getMdxQuery();
logger.debug("MDX query found in template is [" + query + "]");
// substitute query parameters
query = MDXParametersUtilities.substituteParametersInMDXQuery(query, template.getParameters(), env);
logger.debug("MDX query after parameters substitution is [" + query + "]");
// substitute user profile attributes
IEngUserProfile profile = (IEngUserProfile) env.get(EngineConstants.ENV_USER_PROFILE);
try {
query = StringUtilities.substituteProfileAttributesInString(query, profile);
} catch (Exception e) {
throw new SpagoBIEngineRuntimeException("Error while substituting user profile attributes in MDX query", e);
}
logger.debug("MDX query after user profile attributes substitution is [" + query + "]");
logger.debug("OUT");
return query;
}
public WhatIfEngineInstance(Map env) {
super( env );
includes = WhatIfEngine.getConfig().getIncludes();
try {
Class.forName("mondrian.olap4j.MondrianOlap4jDriver");
Class.forName("org.olap4j.OlapWrapper");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot load Mondrian Olap4j Driver", e);
}
String reference = (String) env.get(EngineConstants.ENV_OLAP_SCHEMA);
this.setMondrianSchemaFilePath(reference);
IDataSource ds = (IDataSource) env.get(EngineConstants.ENV_DATASOURCE);
olapDataSource = WhatIfEngineConfig.getInstance().getOlapDataSource( ds, reference );
//pivotModel = new PivotModelImpl(olapDataSource);
pivotModel = new SpagoBIPivotModel(olapDataSource);
pivotModel.setLocale( this.getLocale() );
pivotModel.setMdx( (String) env.get("ENV_INITIAL_MDX_QUERY") );
pivotModel.initialize();
//init configs
modelConfig = new ModelConfig();
modelConfig.setWriteBackConf(WhatIfEngineConfig.getInstance().getWritebackEditConfig());
WriteBackEditConfig writeBackConfig = getModelConfig().getWriteBackConf();
if(writeBackConfig!= null ){
try {
writeBackManager = new WriteBackManager(getEditCubeName(), new MondrianDriver(getMondrianSchemaFilePath()));
} catch (SpagoBIEngineException e) {
logger.debug("Exception creating the whatif component", e);
throw new SpagoBIEngineRestServiceRuntimeException("whatif.engine.instance.writeback.exception", getLocale(), "Exception creating the whatif component", e);
}
}
}
private String initMondrianSchema(Map env) {
ArtifactServiceProxy artifactProxy = (ArtifactServiceProxy) env.get( EngineConstants.ENV_ARTIFACT_PROXY );
MondrianSchemaManager schemaManager = new MondrianSchemaManager(artifactProxy);
Integer artifactVersionId = getArtifactVersionId( env );
logger.debug("Artifact version id :" + artifactVersionId);
String reference = schemaManager.getMondrianSchemaURI(artifactVersionId);
logger.debug("Reference :" + reference);
return reference;
}
private Integer getArtifactVersionId(Map env) {
try {
if (!env.containsKey( SpagoBIConstants.SBI_ARTIFACT_VERSION_ID )) {
logger.error("Missing artifact version id");
throw new SpagoBIEngineRuntimeException("Missing artifact version id");
}
String str = (String) env.get( SpagoBIConstants.SBI_ARTIFACT_VERSION_ID );
Integer id = new Integer(str);
return id;
} catch (Exception e) {
logger.error("Error while getting artifact version id", e);
throw new SpagoBIEngineRuntimeException("Error while getting artifact version id", e);
}
}
public OlapConnection getOlapConnection () {
OlapConnection connection;
try {
connection = getOlapDataSource().getConnection();
} catch (SQLException e) {
logger.error("Error getting the connection", e);
throw new SpagoBIEngineRuntimeException("Error getting the connection", e);
}
return connection;
}
public ModelConfig getModelConfig() {
return modelConfig;
}
public OlapDataSource getOlapDataSource () {
return olapDataSource;
}
// public JSONObject getGuiSettings() {
// return guiSettings;
// }
public List getIncludes() {
return includes;
}
public PivotModel getPivotModel() {
return pivotModel;
}
public IDataSource getDataSource() {
return (IDataSource)this.getEnv().get(EngineConstants.ENV_DATASOURCE);
}
public String getEditCubeName() {
return getModelConfig().getWriteBackConf().getEditCubeName();
}
public IDataSet getDataSet() {
return (IDataSet)this.getEnv().get(EngineConstants.ENV_DATASET);
}
public Locale getLocale() {
return (Locale)this.getEnv().get(EngineConstants.ENV_LOCALE);
}
public AuditServiceProxy getAuditServiceProxy() {
return (AuditServiceProxy)this.getEnv().get(EngineConstants.ENV_AUDIT_SERVICE_PROXY);
}
public EventServiceProxy getEventServiceProxy() {
return (EventServiceProxy)this.getEnv().get(EngineConstants.ENV_EVENT_SERVICE_PROXY);
}
// -- unimplemented methods ------------------------------------------------------------
public IEngineAnalysisState getAnalysisState() {
throw new WhatIfEngineRuntimeException("Unsupported method [getAnalysisState]");
}
public void setAnalysisState(IEngineAnalysisState analysisState) {
throw new WhatIfEngineRuntimeException("Unsupported method [setAnalysisState]");
}
public void validate() throws SpagoBIEngineException {
throw new WhatIfEngineRuntimeException("Unsupported method [validate]");
}
public WriteBackManager getWriteBackManager() {
return writeBackManager;
}
public String getMondrianSchemaFilePath() {
return mondrianSchemaFilePath;
}
private void setMondrianSchemaFilePath(String mondrianSchemaFilePath) {
this.mondrianSchemaFilePath = mondrianSchemaFilePath;
}
}
| true | true | public WhatIfEngineInstance(WhatIfTemplate template, Map env) {
super( env );
includes = WhatIfEngine.getConfig().getIncludes();
try {
Class.forName("mondrian.olap4j.MondrianOlap4jDriver");
Class.forName("org.olap4j.OlapWrapper");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot load Mondrian Olap4j Driver", e);
}
String reference = initMondrianSchema(env);
this.setMondrianSchemaFilePath(reference);
IDataSource ds = (IDataSource) env.get(EngineConstants.ENV_DATASOURCE);
olapDataSource = WhatIfEngineConfig.getInstance().getOlapDataSource( ds, reference );
//pivotModel = new PivotModelImpl(olapDataSource);
pivotModel = new SpagoBIPivotModel(olapDataSource);
pivotModel.setLocale( this.getLocale() );
String initialMDX = this.getInitialMDX( template, env );
logger.debug("Initial MDX is [" + initialMDX + "]");
pivotModel.setMdx( initialMDX );
pivotModel.initialize();
// execute the MDX now
pivotModel.getCellSet();
//init configs
modelConfig = new ModelConfig();
modelConfig.setWriteBackConf(template.getWritebackEditConfig());
WriteBackEditConfig writeBackConfig = getModelConfig().getWriteBackConf();
if(writeBackConfig!= null ){
try {
writeBackManager = new WriteBackManager(getEditCubeName(), new MondrianDriver(getMondrianSchemaFilePath()));
} catch (SpagoBIEngineException e) {
logger.debug("Exception creating the whatif component", e);
throw new SpagoBIEngineRestServiceRuntimeException("whatif.engine.instance.writeback.exception", getLocale(), "Exception creating the whatif component", e);
}
}
}
| public WhatIfEngineInstance(WhatIfTemplate template, Map env) {
super( env );
includes = WhatIfEngine.getConfig().getIncludes();
try {
Class.forName("mondrian.olap4j.MondrianOlap4jDriver");
Class.forName("org.olap4j.OlapWrapper");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot load Mondrian Olap4j Driver", e);
}
String reference = initMondrianSchema(env);
this.setMondrianSchemaFilePath(reference);
IDataSource ds = (IDataSource) env.get(EngineConstants.ENV_DATASOURCE);
olapDataSource = WhatIfEngineConfig.getInstance().getOlapDataSource( ds, reference );
//pivotModel = new PivotModelImpl(olapDataSource);
pivotModel = new SpagoBIPivotModel(olapDataSource);
pivotModel.setLocale( this.getLocale() );
String initialMDX = this.getInitialMDX( template, env );
logger.debug("Initial MDX is [" + initialMDX + "]");
pivotModel.setMdx( initialMDX );
pivotModel.initialize();
// execute the MDX now
try {
pivotModel.getCellSet();
} catch (Throwable t) {
Throwable rootException = t;
while (rootException.getCause() != null) {
rootException = rootException.getCause();
}
throw new SpagoBIEngineRuntimeException("Error while executing MDX statement: " + rootException.getMessage(), t);
}
//init configs
modelConfig = new ModelConfig();
modelConfig.setWriteBackConf(template.getWritebackEditConfig());
WriteBackEditConfig writeBackConfig = getModelConfig().getWriteBackConf();
if(writeBackConfig!= null ){
try {
writeBackManager = new WriteBackManager(getEditCubeName(), new MondrianDriver(getMondrianSchemaFilePath()));
} catch (SpagoBIEngineException e) {
logger.debug("Exception creating the whatif component", e);
throw new SpagoBIEngineRestServiceRuntimeException("whatif.engine.instance.writeback.exception", getLocale(), "Exception creating the whatif component", e);
}
}
}
|
diff --git a/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java b/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java
index b224eeb1..fd826bdf 100644
--- a/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java
+++ b/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java
@@ -1,666 +1,666 @@
/*
* Copyright (C) 2007 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* Author: Steve Ratcliffe
* Create date: Feb 17, 2008
*/
package uk.me.parabola.mkgmap.osmstyle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import uk.me.parabola.imgfmt.app.Area;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.imgfmt.app.CoordNode;
import uk.me.parabola.log.Logger;
import uk.me.parabola.mkgmap.general.AreaClipper;
import uk.me.parabola.mkgmap.general.Clipper;
import uk.me.parabola.mkgmap.general.LineAdder;
import uk.me.parabola.mkgmap.general.LineClipper;
import uk.me.parabola.mkgmap.general.MapCollector;
import uk.me.parabola.mkgmap.general.MapElement;
import uk.me.parabola.mkgmap.general.MapLine;
import uk.me.parabola.mkgmap.general.MapPoint;
import uk.me.parabola.mkgmap.general.MapRoad;
import uk.me.parabola.mkgmap.general.MapShape;
import uk.me.parabola.mkgmap.general.RoadNetwork;
import uk.me.parabola.mkgmap.reader.osm.Element;
import uk.me.parabola.mkgmap.reader.osm.GType;
import uk.me.parabola.mkgmap.reader.osm.Node;
import uk.me.parabola.mkgmap.reader.osm.OsmConverter;
import uk.me.parabola.mkgmap.reader.osm.Relation;
import uk.me.parabola.mkgmap.reader.osm.Rule;
import uk.me.parabola.mkgmap.reader.osm.Style;
import uk.me.parabola.mkgmap.reader.osm.Way;
/**
* Convert from OSM to the mkgmap intermediate format using a style.
* A style is a collection of files that describe the mappings to be used
* when converting.
*
* @author Steve Ratcliffe
*/
public class StyledConverter implements OsmConverter {
private static final Logger log = Logger.getLogger(StyledConverter.class);
private final String[] nameTagList;
private final MapCollector collector;
private Clipper clipper = Clipper.NULL_CLIPPER;
private Area bbox = null;
private Set<Coord> boundaryCoords = new HashSet<Coord>();
private int roadId;
private final int MAX_NODES_IN_WAY = 16;
private final double MIN_DISTANCE_BETWEEN_NODES = 5.5;
// nodeIdMap maps a Coord into a nodeId
private final Map<Coord, Integer> nodeIdMap = new HashMap<Coord, Integer>();
private int nextNodeId;
private final Rule wayRules;
private final Rule nodeRules;
private final Rule relationRules;
private LineAdder lineAdder = new LineAdder() {
public void add(MapLine element) {
if (element instanceof MapRoad)
collector.addRoad((MapRoad) element);
else
collector.addLine(element);
}
};
public StyledConverter(Style style, MapCollector collector) {
this.collector = collector;
nameTagList = style.getNameTagList();
wayRules = style.getWayRules();
nodeRules = style.getNodeRules();
relationRules = style.getRelationRules();
LineAdder overlayAdder = style.getOverlays(lineAdder);
if (overlayAdder != null)
lineAdder = overlayAdder;
}
/**
* This takes the way and works out what kind of map feature it is and makes
* the relevant call to the mapper callback.
* <p>
* As a few examples we might want to check for the 'highway' tag, work out
* if it is an area of a park etc.
*
* @param way The OSM way.
*/
public void convertWay(Way way) {
if (way.getPoints().size() < 2)
return;
preConvertRules(way);
GType foundType = wayRules.resolveType(way);
if (foundType == null)
return;
postConvertRules(way, foundType);
if (foundType.getFeatureKind() == GType.POLYLINE) {
if(foundType.isRoad())
addRoad(way, foundType);
else
addLine(way, foundType);
}
else
addShape(way, foundType);
}
/**
* Takes a node (that has its own identity) and converts it from the OSM
* type to the Garmin map type.
*
* @param node The node to convert.
*/
public void convertNode(Node node) {
preConvertRules(node);
GType foundType = nodeRules.resolveType(node);
if (foundType == null)
return;
// If the node does not have a name, then set the name from this
// type rule.
log.debug("node name", node.getName());
if (node.getName() == null) {
node.setName(foundType.getDefaultName());
log.debug("after set", node.getName());
}
postConvertRules(node, foundType);
addPoint(node, foundType);
}
/**
* Rules to run before converting the element.
*/
private void preConvertRules(Element el) {
if (nameTagList == null)
return;
for (String t : nameTagList) {
String val = el.getTag(t);
if (val != null) {
el.addTag("name", val);
break;
}
}
}
/**
* Built in rules to run after converting the element.
*/
private void postConvertRules(Element el, GType type) {
// Set the name from the 'name' tag or failing that from
// the default_name.
el.setName(el.getTag("name"));
if (el.getName() == null)
el.setName(type.getDefaultName());
}
/**
* Set the bounding box for this map. This should be set before any other
* elements are converted if you want to use it. All elements that are added
* are clipped to this box, new points are added as needed at the boundry.
*
* If a node or a way falls completely outside the boundry then it would be
* ommited. This would not normally happen in the way this option is typically
* used however.
*
* @param bbox The bounding area.
*/
public void setBoundingBox(Area bbox) {
this.clipper = new AreaClipper(bbox);
this.bbox = bbox;
}
/**
* Run the rules for this relation. As this is not an end object, then
* the only useful rules are action rules that set tags on the contained
* ways or nodes. Every rule should probably start with 'type=".."'.
*
* @param relation The relation to convert.
*/
public void convertRelation(Relation relation) {
// Relations never resolve to a GType and so we ignore the return
// value.
relationRules.resolveType(relation);
}
private void addLine(Way way, GType gt) {
MapLine line = new MapLine();
elementSetup(line, gt, way);
line.setPoints(way.getPoints());
if (way.isBoolTag("oneway"))
line.setDirection(true);
clipper.clipLine(line, lineAdder);
}
private void addShape(Way way, GType gt) {
MapShape shape = new MapShape();
elementSetup(shape, gt, way);
shape.setPoints(way.getPoints());
clipper.clipShape(shape, collector);
}
private void addPoint(Node node, GType gt) {
if (!clipper.contains(node.getLocation()))
return;
MapPoint mp = new MapPoint();
elementSetup(mp, gt, node);
mp.setLocation(node.getLocation());
collector.addPoint(mp);
}
private void elementSetup(MapElement ms, GType gt, Element element) {
ms.setName(element.getName());
ms.setType(gt.getType());
ms.setMinResolution(gt.getMinResolution());
ms.setMaxResolution(gt.getMaxResolution());
}
void addRoad(Way way, GType gt) {
if("roundabout".equals(way.getTag("junction"))) {
String frigFactorTag = way.getTag("mkgmap:frig_roundabout");
if(frigFactorTag != null) {
// do special roundabout frigging to make gps
// routing prompt use the correct exit number
double frigFactor = 0.25; // default
try {
frigFactor = Double.parseDouble(frigFactorTag);
}
catch (NumberFormatException nfe) {
// relax, tag was probably not a number anyway
}
frigRoundabout(way, frigFactor);
}
}
// if there is a bounding box, clip the way with it
List<Way> clippedWays = null;
if(bbox != null) {
List<List<Coord>> lineSegs = LineClipper.clip(bbox, way.getPoints());
boundaryCoords = new HashSet<Coord>();
if (lineSegs != null) {
clippedWays = new ArrayList<Way>();
for (List<Coord> lco : lineSegs) {
Way nWay = new Way();
nWay.setName(way.getName());
nWay.copyTags(way);
for(Coord co : lco) {
nWay.addPoint(co);
if(co.getHighwayCount() == 0) {
boundaryCoords.add(co);
co.incHighwayCount();
}
}
clippedWays.add(nWay);
}
}
}
if(clippedWays != null) {
for(Way cw : clippedWays) {
addRoadAfterSplittingLoops(cw, gt);
}
}
else {
// no bounding box or way was not clipped
addRoadAfterSplittingLoops(way, gt);
}
}
void addRoadAfterSplittingLoops(Way way, GType gt) {
// check if the way is a loop or intersects with itself
boolean wayWasSplit = true; // aka rescan required
while(wayWasSplit) {
List<Coord> wayPoints = way.getPoints();
int numPointsInWay = wayPoints.size();
wayWasSplit = false; // assume way won't be split
// check each point in the way to see if it is
// the same point as a following point in the way
for(int p1I = 0; !wayWasSplit && p1I < (numPointsInWay - 1); p1I++) {
Coord p1 = wayPoints.get(p1I);
for(int p2I = p1I + 1; !wayWasSplit && p2I < numPointsInWay; p2I++) {
if(p1 == wayPoints.get(p2I)) {
// way is a loop or intersects itself
int splitI = p2I - 1; // split before second point
if(splitI == p1I) {
log.info("Way has zero length segment - " + wayPoints.get(splitI).toOSMURL());
wayPoints.remove(p2I);
// next point to inspect has same index
--p2I;
// but number of points has reduced
--numPointsInWay;
}
else {
// split the way before the second point
log.info("Split way at " + wayPoints.get(splitI).toDegreeString() + " - it has " + (numPointsInWay - splitI - 1 ) + " following segments.");
Way loopTail = splitWayAt(way, splitI);
// way before split has now been verified
addRoadWithoutLoops(way, gt);
// now repeat for the tail of the way
way = loopTail;
wayWasSplit = true;
}
}
}
}
if(!wayWasSplit) {
// no split required so make road from way
addRoadWithoutLoops(way, gt);
}
}
}
void addRoadWithoutLoops(Way way, GType gt) {
List<Integer> nodeIndices = new ArrayList<Integer>();
List<Coord> points = way.getPoints();
Way trailingWay = null;
// make sure the way has nodes at each end
points.get(0).incHighwayCount();
points.get(points.size() - 1).incHighwayCount();
// collect the Way's nodes
for(int i = 0; i < points.size(); ++i) {
Coord p = points.get(i);
int highwayCount = p.getHighwayCount();
if(highwayCount > 1) {
// this point is a node connecting highways
Integer nodeId = nodeIdMap.get(p);
if(nodeId == null) {
// assign a node id
nodeId = nextNodeId++;
nodeIdMap.put(p, nodeId);
}
nodeIndices.add(i);
if((i + 1) < points.size() &&
nodeIndices.size() == MAX_NODES_IN_WAY) {
// this isn't the last point in the way
// so split it here to avoid exceeding
// the max nodes in way limit
trailingWay = splitWayAt(way, i);
// this will have truncated
// the current Way's points so
// the loop will now terminate
log.info("Splitting way " + way.getName() + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes");
}
}
}
MapLine line = new MapLine();
elementSetup(line, gt, way);
line.setPoints(points);
MapRoad road = new MapRoad(roadId++, line);
// set road parameters.
road.setRoadClass(gt.getRoadClass());
if (way.isBoolTag("oneway")) {
road.setDirection(true);
road.setOneway();
}
// maxspeed attribute overrides default for road type
String maxSpeed = way.getTag("maxspeed");
int speedIdx = -1;
if(maxSpeed != null)
speedIdx = getSpeedIdx(maxSpeed);
road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed());
boolean[] noAccess = new boolean[RoadNetwork.NO_MAX];
String highwayType = way.getTag("highway");
if(highwayType == null) {
// it's a routable way but not a highway (e.g. a ferry)
// use the value of the route tag as the highwayType
// for the purpose of testing for access restrictions
highwayType = way.getTag("route");
}
String[] vehicleClass = { "access",
"bicycle",
"foot",
"hgv",
"motorcar",
"motorcycle",
"psv",
};
int[] accessSelector = { RoadNetwork.NO_MAX,
RoadNetwork.NO_BIKE,
RoadNetwork.NO_FOOT,
RoadNetwork.NO_TRUCK,
RoadNetwork.NO_CAR,
RoadNetwork.NO_CAR, // motorcycle
RoadNetwork.NO_BUS };
for(int i = 0; i < vehicleClass.length; ++i) {
String access = way.getTag(vehicleClass[i]);
if(access != null)
access = access.toUpperCase();
if(access != null &&
(access.equals("PRIVATE") ||
access.equals("DESTINATION") || // FIXME - too strict
access.equals("UNKNOWN") ||
access.equals("NO"))) {
if(accessSelector[i] == RoadNetwork.NO_MAX) {
// everything is denied access
for(int j = 0; j < noAccess.length; ++j)
noAccess[j] = true;
}
else {
// just the specific vehicle
// class is denied access
noAccess[accessSelector[i]] = true;
}
log.info("No " + vehicleClass[i] + " allowed in " + highwayType + " " + way.getName());
}
}
if("footway".equals(highwayType)) {
noAccess[RoadNetwork.EMERGENCY] = true;
noAccess[RoadNetwork.DELIVERY] = true;
noAccess[RoadNetwork.NO_CAR] = true;
noAccess[RoadNetwork.NO_BUS] = true;
noAccess[RoadNetwork.NO_TAXI] = true;
if(!way.accessExplicitlyAllowed("bicycle"))
noAccess[RoadNetwork.NO_BIKE] = true;
noAccess[RoadNetwork.NO_TRUCK] = true;
}
else if("cycleway".equals(highwayType) ||
"bridleway".equals(highwayType)) {
noAccess[RoadNetwork.EMERGENCY] = true;
noAccess[RoadNetwork.DELIVERY] = true;
noAccess[RoadNetwork.NO_CAR] = true;
noAccess[RoadNetwork.NO_BUS] = true;
noAccess[RoadNetwork.NO_TAXI] = true;
noAccess[RoadNetwork.NO_TRUCK] = true;
}
road.setAccess(noAccess);
if(way.isBoolTag("toll"))
road.setToll();
int numNodes = nodeIndices.size();
road.setNumNodes(numNodes);
if(numNodes > 0) {
// replace Coords that are nodes with CoordNodes
boolean hasInternalNodes = false;
for(int i = 0; i < numNodes; ++i) {
int n = nodeIndices.get(i);
if(n > 0 && n < points.size() - 1)
hasInternalNodes = true;
Coord coord = points.get(n);
Integer nodeId = nodeIdMap.get(coord);
boolean boundary = boundaryCoords.contains(coord);
if(boundary) {
log.info("Way " + way.getName() + "'s point #" + n + " at " + points.get(0).toDegreeString() + " is a boundary node");
}
points.set(n, new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary));
}
road.setStartsWithNode(nodeIndices.get(0) == 0);
road.setInternalNodes(hasInternalNodes);
}
- clipper.clipLine(road, lineAdder);
+ lineAdder.add(road);
if(trailingWay != null)
addRoadWithoutLoops(trailingWay, gt);
}
// split a Way at the specified point and return the new Way
// (the original Way is truncated)
Way splitWayAt(Way way, int index) {
Way trailingWay = new Way();
List<Coord> wayPoints = way.getPoints();
int numPointsInWay = wayPoints.size();
for(int i = index; i < numPointsInWay; ++i)
trailingWay.addPoint(wayPoints.get(i));
// ensure split point becomes a node
wayPoints.get(index).incHighwayCount();
// copy the way's name and tags to the new way
trailingWay.setName(way.getName());
trailingWay.copyTags(way);
// remove the points after the split from the original way
// it's probably more efficient to remove from the end first
for(int i = numPointsInWay - 1; i > index; --i)
wayPoints.remove(i);
return trailingWay;
}
// function to add points between adjacent nodes in a roundabout
// to make gps use correct exit number in routing instructions
void frigRoundabout(Way way, double frigFactor) {
List<Coord> wayPoints = way.getPoints();
int origNumPoints = wayPoints.size();
if(origNumPoints < 3) {
// forget it!
return;
}
int[] highWayCounts = new int[origNumPoints];
int middleLat = 0;
int middleLon = 0;
highWayCounts[0] = wayPoints.get(0).getHighwayCount();
for(int i = 1; i < origNumPoints; ++i) {
Coord p = wayPoints.get(i);
middleLat += p.getLatitude();
middleLon += p.getLongitude();
highWayCounts[i] = p.getHighwayCount();
}
middleLat /= origNumPoints - 1;
middleLon /= origNumPoints - 1;
Coord middleCoord = new Coord(middleLat, middleLon);
// account for fact that roundabout joins itself
--highWayCounts[0];
--highWayCounts[origNumPoints - 1];
for(int i = origNumPoints - 2; i >= 0; --i) {
Coord p1 = wayPoints.get(i);
Coord p2 = wayPoints.get(i + 1);
if(highWayCounts[i] > 1 && highWayCounts[i + 1] > 1) {
// both points will be nodes so insert
// a new point between them that
// (approximately) falls on the
// roundabout's perimeter
int newLat = (p1.getLatitude() + p2.getLatitude()) / 2;
int newLon = (p1.getLongitude() + p2.getLongitude()) / 2;
// new point has to be "outside" of
// existing line joining p1 and p2 -
// how far outside is determined by
// the ratio of the distance between
// p1 and p2 compared to the distance
// of p1 from the "middle" of the
// roundabout (aka, the approx radius
// of the roundabout) - the higher the
// value of frigFactor, the further out
// the point will be
double scale = 1 + frigFactor * p1.distance(p2) / p1.distance(middleCoord);
newLat = (int)((newLat - middleLat) * scale) + middleLat;
newLon = (int)((newLon - middleLon) * scale) + middleLon;
Coord newPoint = new Coord(newLat, newLon);
double d1 = p1.distance(newPoint);
double d2 = p2.distance(newPoint);
double maxDistance = 100;
if(d1 >= MIN_DISTANCE_BETWEEN_NODES && d1 <= maxDistance &&
d2 >= MIN_DISTANCE_BETWEEN_NODES && d2 <= maxDistance) {
newPoint.incHighwayCount();
wayPoints.add(i + 1, newPoint);
}
else if(false) {
System.err.println("Not inserting point in roundabout after node " +
i + " " +
way.getName() +
" @ " +
middleCoord.toDegreeString() +
" (d1 = " +
p1.distance(newPoint) +
" d2 = " +
p2.distance(newPoint) +
")");
}
}
}
}
int getSpeedIdx(String tag)
{
double kmh = 0.0;
double factor = 1.0;
String speedTag = tag.toLowerCase().trim();
if(speedTag.matches(".*mph")) // Check if it is a limit in mph
{
speedTag = speedTag.replaceFirst("mph", "");
factor = 1.61;
}
else
speedTag = speedTag.replaceFirst("kmh", ""); // get rid of kmh just in case
try {
kmh = Integer.parseInt(speedTag) * factor;
}
catch (Exception e)
{
return -1;
}
if(kmh > 110)
return 7;
if(kmh > 90)
return 6;
if(kmh > 80)
return 5;
if(kmh > 60)
return 4;
if(kmh > 40)
return 3;
if(kmh > 20)
return 2;
if(kmh > 10)
return 1;
else
return 0;
}
}
| true | true | void addRoadWithoutLoops(Way way, GType gt) {
List<Integer> nodeIndices = new ArrayList<Integer>();
List<Coord> points = way.getPoints();
Way trailingWay = null;
// make sure the way has nodes at each end
points.get(0).incHighwayCount();
points.get(points.size() - 1).incHighwayCount();
// collect the Way's nodes
for(int i = 0; i < points.size(); ++i) {
Coord p = points.get(i);
int highwayCount = p.getHighwayCount();
if(highwayCount > 1) {
// this point is a node connecting highways
Integer nodeId = nodeIdMap.get(p);
if(nodeId == null) {
// assign a node id
nodeId = nextNodeId++;
nodeIdMap.put(p, nodeId);
}
nodeIndices.add(i);
if((i + 1) < points.size() &&
nodeIndices.size() == MAX_NODES_IN_WAY) {
// this isn't the last point in the way
// so split it here to avoid exceeding
// the max nodes in way limit
trailingWay = splitWayAt(way, i);
// this will have truncated
// the current Way's points so
// the loop will now terminate
log.info("Splitting way " + way.getName() + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes");
}
}
}
MapLine line = new MapLine();
elementSetup(line, gt, way);
line.setPoints(points);
MapRoad road = new MapRoad(roadId++, line);
// set road parameters.
road.setRoadClass(gt.getRoadClass());
if (way.isBoolTag("oneway")) {
road.setDirection(true);
road.setOneway();
}
// maxspeed attribute overrides default for road type
String maxSpeed = way.getTag("maxspeed");
int speedIdx = -1;
if(maxSpeed != null)
speedIdx = getSpeedIdx(maxSpeed);
road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed());
boolean[] noAccess = new boolean[RoadNetwork.NO_MAX];
String highwayType = way.getTag("highway");
if(highwayType == null) {
// it's a routable way but not a highway (e.g. a ferry)
// use the value of the route tag as the highwayType
// for the purpose of testing for access restrictions
highwayType = way.getTag("route");
}
String[] vehicleClass = { "access",
"bicycle",
"foot",
"hgv",
"motorcar",
"motorcycle",
"psv",
};
int[] accessSelector = { RoadNetwork.NO_MAX,
RoadNetwork.NO_BIKE,
RoadNetwork.NO_FOOT,
RoadNetwork.NO_TRUCK,
RoadNetwork.NO_CAR,
RoadNetwork.NO_CAR, // motorcycle
RoadNetwork.NO_BUS };
for(int i = 0; i < vehicleClass.length; ++i) {
String access = way.getTag(vehicleClass[i]);
if(access != null)
access = access.toUpperCase();
if(access != null &&
(access.equals("PRIVATE") ||
access.equals("DESTINATION") || // FIXME - too strict
access.equals("UNKNOWN") ||
access.equals("NO"))) {
if(accessSelector[i] == RoadNetwork.NO_MAX) {
// everything is denied access
for(int j = 0; j < noAccess.length; ++j)
noAccess[j] = true;
}
else {
// just the specific vehicle
// class is denied access
noAccess[accessSelector[i]] = true;
}
log.info("No " + vehicleClass[i] + " allowed in " + highwayType + " " + way.getName());
}
}
if("footway".equals(highwayType)) {
noAccess[RoadNetwork.EMERGENCY] = true;
noAccess[RoadNetwork.DELIVERY] = true;
noAccess[RoadNetwork.NO_CAR] = true;
noAccess[RoadNetwork.NO_BUS] = true;
noAccess[RoadNetwork.NO_TAXI] = true;
if(!way.accessExplicitlyAllowed("bicycle"))
noAccess[RoadNetwork.NO_BIKE] = true;
noAccess[RoadNetwork.NO_TRUCK] = true;
}
else if("cycleway".equals(highwayType) ||
"bridleway".equals(highwayType)) {
noAccess[RoadNetwork.EMERGENCY] = true;
noAccess[RoadNetwork.DELIVERY] = true;
noAccess[RoadNetwork.NO_CAR] = true;
noAccess[RoadNetwork.NO_BUS] = true;
noAccess[RoadNetwork.NO_TAXI] = true;
noAccess[RoadNetwork.NO_TRUCK] = true;
}
road.setAccess(noAccess);
if(way.isBoolTag("toll"))
road.setToll();
int numNodes = nodeIndices.size();
road.setNumNodes(numNodes);
if(numNodes > 0) {
// replace Coords that are nodes with CoordNodes
boolean hasInternalNodes = false;
for(int i = 0; i < numNodes; ++i) {
int n = nodeIndices.get(i);
if(n > 0 && n < points.size() - 1)
hasInternalNodes = true;
Coord coord = points.get(n);
Integer nodeId = nodeIdMap.get(coord);
boolean boundary = boundaryCoords.contains(coord);
if(boundary) {
log.info("Way " + way.getName() + "'s point #" + n + " at " + points.get(0).toDegreeString() + " is a boundary node");
}
points.set(n, new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary));
}
road.setStartsWithNode(nodeIndices.get(0) == 0);
road.setInternalNodes(hasInternalNodes);
}
clipper.clipLine(road, lineAdder);
if(trailingWay != null)
addRoadWithoutLoops(trailingWay, gt);
}
| void addRoadWithoutLoops(Way way, GType gt) {
List<Integer> nodeIndices = new ArrayList<Integer>();
List<Coord> points = way.getPoints();
Way trailingWay = null;
// make sure the way has nodes at each end
points.get(0).incHighwayCount();
points.get(points.size() - 1).incHighwayCount();
// collect the Way's nodes
for(int i = 0; i < points.size(); ++i) {
Coord p = points.get(i);
int highwayCount = p.getHighwayCount();
if(highwayCount > 1) {
// this point is a node connecting highways
Integer nodeId = nodeIdMap.get(p);
if(nodeId == null) {
// assign a node id
nodeId = nextNodeId++;
nodeIdMap.put(p, nodeId);
}
nodeIndices.add(i);
if((i + 1) < points.size() &&
nodeIndices.size() == MAX_NODES_IN_WAY) {
// this isn't the last point in the way
// so split it here to avoid exceeding
// the max nodes in way limit
trailingWay = splitWayAt(way, i);
// this will have truncated
// the current Way's points so
// the loop will now terminate
log.info("Splitting way " + way.getName() + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes");
}
}
}
MapLine line = new MapLine();
elementSetup(line, gt, way);
line.setPoints(points);
MapRoad road = new MapRoad(roadId++, line);
// set road parameters.
road.setRoadClass(gt.getRoadClass());
if (way.isBoolTag("oneway")) {
road.setDirection(true);
road.setOneway();
}
// maxspeed attribute overrides default for road type
String maxSpeed = way.getTag("maxspeed");
int speedIdx = -1;
if(maxSpeed != null)
speedIdx = getSpeedIdx(maxSpeed);
road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed());
boolean[] noAccess = new boolean[RoadNetwork.NO_MAX];
String highwayType = way.getTag("highway");
if(highwayType == null) {
// it's a routable way but not a highway (e.g. a ferry)
// use the value of the route tag as the highwayType
// for the purpose of testing for access restrictions
highwayType = way.getTag("route");
}
String[] vehicleClass = { "access",
"bicycle",
"foot",
"hgv",
"motorcar",
"motorcycle",
"psv",
};
int[] accessSelector = { RoadNetwork.NO_MAX,
RoadNetwork.NO_BIKE,
RoadNetwork.NO_FOOT,
RoadNetwork.NO_TRUCK,
RoadNetwork.NO_CAR,
RoadNetwork.NO_CAR, // motorcycle
RoadNetwork.NO_BUS };
for(int i = 0; i < vehicleClass.length; ++i) {
String access = way.getTag(vehicleClass[i]);
if(access != null)
access = access.toUpperCase();
if(access != null &&
(access.equals("PRIVATE") ||
access.equals("DESTINATION") || // FIXME - too strict
access.equals("UNKNOWN") ||
access.equals("NO"))) {
if(accessSelector[i] == RoadNetwork.NO_MAX) {
// everything is denied access
for(int j = 0; j < noAccess.length; ++j)
noAccess[j] = true;
}
else {
// just the specific vehicle
// class is denied access
noAccess[accessSelector[i]] = true;
}
log.info("No " + vehicleClass[i] + " allowed in " + highwayType + " " + way.getName());
}
}
if("footway".equals(highwayType)) {
noAccess[RoadNetwork.EMERGENCY] = true;
noAccess[RoadNetwork.DELIVERY] = true;
noAccess[RoadNetwork.NO_CAR] = true;
noAccess[RoadNetwork.NO_BUS] = true;
noAccess[RoadNetwork.NO_TAXI] = true;
if(!way.accessExplicitlyAllowed("bicycle"))
noAccess[RoadNetwork.NO_BIKE] = true;
noAccess[RoadNetwork.NO_TRUCK] = true;
}
else if("cycleway".equals(highwayType) ||
"bridleway".equals(highwayType)) {
noAccess[RoadNetwork.EMERGENCY] = true;
noAccess[RoadNetwork.DELIVERY] = true;
noAccess[RoadNetwork.NO_CAR] = true;
noAccess[RoadNetwork.NO_BUS] = true;
noAccess[RoadNetwork.NO_TAXI] = true;
noAccess[RoadNetwork.NO_TRUCK] = true;
}
road.setAccess(noAccess);
if(way.isBoolTag("toll"))
road.setToll();
int numNodes = nodeIndices.size();
road.setNumNodes(numNodes);
if(numNodes > 0) {
// replace Coords that are nodes with CoordNodes
boolean hasInternalNodes = false;
for(int i = 0; i < numNodes; ++i) {
int n = nodeIndices.get(i);
if(n > 0 && n < points.size() - 1)
hasInternalNodes = true;
Coord coord = points.get(n);
Integer nodeId = nodeIdMap.get(coord);
boolean boundary = boundaryCoords.contains(coord);
if(boundary) {
log.info("Way " + way.getName() + "'s point #" + n + " at " + points.get(0).toDegreeString() + " is a boundary node");
}
points.set(n, new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary));
}
road.setStartsWithNode(nodeIndices.get(0) == 0);
road.setInternalNodes(hasInternalNodes);
}
lineAdder.add(road);
if(trailingWay != null)
addRoadWithoutLoops(trailingWay, gt);
}
|
diff --git a/libcore/luni/src/test/java/tests/api/java/util/CurrencyTest.java b/libcore/luni/src/test/java/tests/api/java/util/CurrencyTest.java
index b7a5648d7..14068a3e2 100644
--- a/libcore/luni/src/test/java/tests/api/java/util/CurrencyTest.java
+++ b/libcore/luni/src/test/java/tests/api/java/util/CurrencyTest.java
@@ -1,469 +1,469 @@
/*
* 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 tests.api.java.util;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.AndroidOnly;
import java.util.Arrays;
import java.util.Collection;
import java.util.Currency;
import java.util.Iterator;
import java.util.Locale;
@TestTargetClass(Currency.class)
public class CurrencyTest extends junit.framework.TestCase {
private static Locale defaultLocale = Locale.getDefault();
/**
* @tests java.util.Currency#getInstance(java.lang.String)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "getInstance(String) method is tested in test_getInstanceLjava_util_Locale() test.",
method = "getInstance",
args = {java.lang.String.class}
)
public void test_getInstanceLjava_lang_String() {
// see test_getInstanceLjava_util_Locale() tests
}
/**
* @tests java.util.Currency#getInstance(java.util.Locale)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getInstance",
args = {java.util.Locale.class}
)
public void test_getInstanceLjava_util_Locale() {
/*
* the behaviour in all these three cases should be the same since this
* method ignores language and variant component of the locale.
*/
Currency c0 = Currency.getInstance("CAD");
Currency c1 = Currency.getInstance(new Locale("en", "CA"));
assertTrue(
"Currency.getInstance(new Locale(\"en\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
c1 == c0);
Currency c2 = Currency.getInstance(new Locale("fr", "CA"));
assertTrue(
"Currency.getInstance(new Locale(\"fr\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
c2 == c0);
Currency c3 = Currency.getInstance(new Locale("", "CA"));
assertTrue(
"Currency.getInstance(new Locale(\"\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
c3 == c0);
c0 = Currency.getInstance("JPY");
c1 = Currency.getInstance(new Locale("ja", "JP"));
assertTrue(
"Currency.getInstance(new Locale(\"ja\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
c1 == c0);
c2 = Currency.getInstance(new Locale("", "JP"));
assertTrue(
"Currency.getInstance(new Locale(\"\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
c2 == c0);
c3 = Currency.getInstance(new Locale("bogus", "JP"));
assertTrue(
"Currency.getInstance(new Locale(\"bogus\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
c3 == c0);
Locale localeGu = new Locale("gu", "IN");
Currency cGu = Currency.getInstance(localeGu);
Locale localeKn = new Locale("kn", "IN");
Currency cKn = Currency.getInstance(localeKn);
assertTrue("Currency.getInstance(Locale_" + localeGu.toString() + "))"
+ "isn't equal to " + "Currency.getInstance(Locale_"
+ localeKn.toString() + "))", cGu == cKn);
// some teritories do not have currencies, like Antarctica
Locale loc = new Locale("", "AQ");
try {
Currency curr = Currency.getInstance(loc);
assertNull(
"Currency.getInstance(new Locale(\"\", \"AQ\")) did not return null",
curr);
} catch (IllegalArgumentException e) {
fail("Unexpected IllegalArgumentException " + e);
}
// unsupported/legacy iso3 countries
loc = new Locale("", "ZR");
try {
Currency curr = Currency.getInstance(loc);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
loc = new Locale("", "ZAR");
try {
Currency curr = Currency.getInstance(loc);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
loc = new Locale("", "FX");
try {
Currency curr = Currency.getInstance(loc);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
loc = new Locale("", "FXX");
try {
Currency curr = Currency.getInstance(loc);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
}
/**
* @tests java.util.Currency#getSymbol()
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getSymbol",
args = {}
)
@AndroidOnly("icu and the RI have different data. Because Android"
+ "only defines a few locales as a must have, it was not possible"
+ "to find a set of combinations where no differences between"
+ "the RI and Android exist.")
public void test_getSymbol() {
Currency currK = Currency.getInstance("KRW");
Currency currI = Currency.getInstance("IEP");
Currency currUS = Currency.getInstance("USD");
Locale.setDefault(Locale.US);
// BEGIN android-changed
// KRW currency symbol is \u20a9 since CLDR1.7 release.
assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
// END android-changed
assertEquals("currI.getSymbol()", "IR\u00a3", currI.getSymbol());
assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
Locale.setDefault(new Locale("en", "IE"));
// BEGIN android-changed
assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
// END android-changed
assertEquals("currI.getSymbol()", "IR\u00a3", currI.getSymbol());
// BEGIN android-changed
assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
// END android-changed
// test what happens if this is an invalid locale,
// one with Korean country but an India language
Locale.setDefault(new Locale("kr", "KR"));
// BEGIN android-changed
assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
// END android-changed
assertEquals("currI.getSymbol()", "IR\u00a3", currI.getSymbol());
assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
}
/**
* @tests java.util.Currency#getSymbol(java.util.Locale)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getSymbol",
args = {java.util.Locale.class}
)
@AndroidOnly("specification doesn't include strong requirements for returnig symbol. On android platform used wrong character for yen sign: \u00a5 instead of \uffe5. Both of them give correct image though")
public void test_getSymbolLjava_util_Locale() {
//Tests was simplified because java specification not
// includes strong requirements for returnig symbol.
// on android platform used wrong character for yen
// sign: \u00a5 instead of \uffe5
Locale[] loc1 = new Locale[]{
Locale.JAPAN, Locale.JAPANESE,
Locale.FRANCE, Locale.FRENCH,
Locale.US, Locale.UK,
Locale.CANADA, Locale.CANADA_FRENCH,
Locale.ENGLISH,
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("fr", "FR"), new Locale("", "FR"),
new Locale("en", "US"), new Locale("", "US"),
new Locale("es", "US"), new Locale("ar", "US"),
new Locale("ja", "US"),
new Locale("en", "CA"), new Locale("fr", "CA"),
new Locale("", "CA"), new Locale("ar", "CA"),
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("ar", "JP"),
new Locale("ja", "AE"), new Locale("en", "AE"),
new Locale("ar", "AE"),
new Locale("da", "DK"), new Locale("", "DK"),
new Locale("da", ""), new Locale("ja", ""),
new Locale("en", "")};
String[] euro = new String[] {"EUR", "\u20ac"};
// \u00a5 and \uffe5 are actually the same symbol, just different code points.
// But the RI returns the \uffe5 and Android returns those with \u00a5
String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"};
String[] dollar = new String[] {"USD", "$", "US$", "$US"};
// BEGIN android-changed
// Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja.
- String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$Ca"};
+ String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$CA"};
// END android-changed
Currency currE = Currency.getInstance("EUR");
Currency currJ = Currency.getInstance("JPY");
Currency currUS = Currency.getInstance("USD");
Currency currCA = Currency.getInstance("CAD");
int i, j, k;
boolean flag;
for(k = 0; k < loc1.length; k++) {
Locale.setDefault(loc1[k]);
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < euro.length; j++) {
if (currE.getSymbol(loc1[i]).equals(euro[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Euro currency returned "
+ currE.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(euro), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < yen.length; j++) {
byte[] b1 = null;
byte[] b2 = null;
if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Yen currency returned "
+ currJ.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(yen), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < dollar.length; j++) {
if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Dollar currency returned "
+ currUS.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(dollar), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < cDollar.length; j++) {
if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Canadian Dollar currency returned "
+ currCA.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(cDollar), flag);
}
}
}
/**
* @tests java.util.Currency#getDefaultFractionDigits()
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getDefaultFractionDigits",
args = {}
)
public void test_getDefaultFractionDigits() {
Currency c1 = Currency.getInstance("TND");
c1.getDefaultFractionDigits();
assertEquals(" Currency.getInstance(\"" + c1
+ "\") returned incorrect number of digits. ", 3, c1
.getDefaultFractionDigits());
Currency c2 = Currency.getInstance("EUR");
c2.getDefaultFractionDigits();
assertEquals(" Currency.getInstance(\"" + c2
+ "\") returned incorrect number of digits. ", 2, c2
.getDefaultFractionDigits());
Currency c3 = Currency.getInstance("JPY");
c3.getDefaultFractionDigits();
assertEquals(" Currency.getInstance(\"" + c3
+ "\") returned incorrect number of digits. ", 0, c3
.getDefaultFractionDigits());
Currency c4 = Currency.getInstance("XXX");
c4.getDefaultFractionDigits();
assertEquals(" Currency.getInstance(\"" + c4
+ "\") returned incorrect number of digits. ", -1, c4
.getDefaultFractionDigits());
}
/**
* @tests java.util.Currency#getCurrencyCode() Note: lines under remarks
* (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
* Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
* on SUN VM
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getCurrencyCode",
args = {}
)
public void test_getCurrencyCode() {
final Collection<Locale> locVal = Arrays.asList(
Locale.CANADA,
Locale.CANADA_FRENCH,
Locale.CHINA,
// Locale.CHINESE,
// Locale.ENGLISH,
Locale.FRANCE,
// Locale.FRENCH,
// Locale.GERMAN,
Locale.GERMANY,
// Locale.ITALIAN,
Locale.ITALY, Locale.JAPAN,
// Locale.JAPANESE,
Locale.KOREA,
// Locale.KOREAN,
Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
Locale.UK, Locale.US);
final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
"JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
Iterator<String> dat = locDat.iterator();
for (Locale l : locVal) {
String d = dat.next().trim();
assertEquals("For locale " + l + " currency code wrong", Currency.getInstance(l)
.getCurrencyCode(), d);
}
}
/**
* @tests java.util.Currency#toString() Note: lines under remarks
* (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
* Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
* on SUN VM
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "toString",
args = {}
)
public void test_toString() {
final Collection<Locale> locVal = Arrays.asList(
Locale.CANADA,
Locale.CANADA_FRENCH,
Locale.CHINA,
// Locale.CHINESE,
// Locale.ENGLISH,
Locale.FRANCE,
// Locale.FRENCH,
// Locale.GERMAN,
Locale.GERMANY,
// Locale.ITALIAN,
Locale.ITALY, Locale.JAPAN,
// Locale.JAPANESE,
Locale.KOREA,
// Locale.KOREAN,
Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
Locale.UK, Locale.US);
final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
"JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
Iterator<String> dat = locDat.iterator();
for (Locale l : locVal) {
String d = dat.next().trim();
assertEquals("For locale " + l + " Currency.toString method returns wrong value",
Currency.getInstance(l).toString(), d);
}
}
protected void setUp() {
Locale.setDefault(defaultLocale);
}
protected void tearDown() {
}
/**
* Helper method to display Currency info
*
* @param c
*/
private void printCurrency(Currency c) {
System.out.println();
System.out.println(c.getCurrencyCode());
System.out.println(c.getSymbol());
System.out.println(c.getDefaultFractionDigits());
}
/**
* helper method to display Locale info
*/
private static void printLocale(Locale loc) {
System.out.println();
System.out.println(loc.getDisplayName());
System.out.println(loc.getCountry());
System.out.println(loc.getLanguage());
System.out.println(loc.getDisplayCountry());
System.out.println(loc.getDisplayLanguage());
System.out.println(loc.getDisplayName());
System.out.println(loc.getISO3Country());
System.out.println(loc.getISO3Language());
}
}
| true | true | public void test_getSymbolLjava_util_Locale() {
//Tests was simplified because java specification not
// includes strong requirements for returnig symbol.
// on android platform used wrong character for yen
// sign: \u00a5 instead of \uffe5
Locale[] loc1 = new Locale[]{
Locale.JAPAN, Locale.JAPANESE,
Locale.FRANCE, Locale.FRENCH,
Locale.US, Locale.UK,
Locale.CANADA, Locale.CANADA_FRENCH,
Locale.ENGLISH,
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("fr", "FR"), new Locale("", "FR"),
new Locale("en", "US"), new Locale("", "US"),
new Locale("es", "US"), new Locale("ar", "US"),
new Locale("ja", "US"),
new Locale("en", "CA"), new Locale("fr", "CA"),
new Locale("", "CA"), new Locale("ar", "CA"),
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("ar", "JP"),
new Locale("ja", "AE"), new Locale("en", "AE"),
new Locale("ar", "AE"),
new Locale("da", "DK"), new Locale("", "DK"),
new Locale("da", ""), new Locale("ja", ""),
new Locale("en", "")};
String[] euro = new String[] {"EUR", "\u20ac"};
// \u00a5 and \uffe5 are actually the same symbol, just different code points.
// But the RI returns the \uffe5 and Android returns those with \u00a5
String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"};
String[] dollar = new String[] {"USD", "$", "US$", "$US"};
// BEGIN android-changed
// Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja.
String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$Ca"};
// END android-changed
Currency currE = Currency.getInstance("EUR");
Currency currJ = Currency.getInstance("JPY");
Currency currUS = Currency.getInstance("USD");
Currency currCA = Currency.getInstance("CAD");
int i, j, k;
boolean flag;
for(k = 0; k < loc1.length; k++) {
Locale.setDefault(loc1[k]);
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < euro.length; j++) {
if (currE.getSymbol(loc1[i]).equals(euro[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Euro currency returned "
+ currE.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(euro), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < yen.length; j++) {
byte[] b1 = null;
byte[] b2 = null;
if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Yen currency returned "
+ currJ.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(yen), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < dollar.length; j++) {
if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Dollar currency returned "
+ currUS.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(dollar), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < cDollar.length; j++) {
if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Canadian Dollar currency returned "
+ currCA.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(cDollar), flag);
}
}
}
| public void test_getSymbolLjava_util_Locale() {
//Tests was simplified because java specification not
// includes strong requirements for returnig symbol.
// on android platform used wrong character for yen
// sign: \u00a5 instead of \uffe5
Locale[] loc1 = new Locale[]{
Locale.JAPAN, Locale.JAPANESE,
Locale.FRANCE, Locale.FRENCH,
Locale.US, Locale.UK,
Locale.CANADA, Locale.CANADA_FRENCH,
Locale.ENGLISH,
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("fr", "FR"), new Locale("", "FR"),
new Locale("en", "US"), new Locale("", "US"),
new Locale("es", "US"), new Locale("ar", "US"),
new Locale("ja", "US"),
new Locale("en", "CA"), new Locale("fr", "CA"),
new Locale("", "CA"), new Locale("ar", "CA"),
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("ar", "JP"),
new Locale("ja", "AE"), new Locale("en", "AE"),
new Locale("ar", "AE"),
new Locale("da", "DK"), new Locale("", "DK"),
new Locale("da", ""), new Locale("ja", ""),
new Locale("en", "")};
String[] euro = new String[] {"EUR", "\u20ac"};
// \u00a5 and \uffe5 are actually the same symbol, just different code points.
// But the RI returns the \uffe5 and Android returns those with \u00a5
String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"};
String[] dollar = new String[] {"USD", "$", "US$", "$US"};
// BEGIN android-changed
// Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja.
String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$CA"};
// END android-changed
Currency currE = Currency.getInstance("EUR");
Currency currJ = Currency.getInstance("JPY");
Currency currUS = Currency.getInstance("USD");
Currency currCA = Currency.getInstance("CAD");
int i, j, k;
boolean flag;
for(k = 0; k < loc1.length; k++) {
Locale.setDefault(loc1[k]);
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < euro.length; j++) {
if (currE.getSymbol(loc1[i]).equals(euro[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Euro currency returned "
+ currE.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(euro), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < yen.length; j++) {
byte[] b1 = null;
byte[] b2 = null;
if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Yen currency returned "
+ currJ.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(yen), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < dollar.length; j++) {
if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Dollar currency returned "
+ currUS.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(dollar), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < cDollar.length; j++) {
if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Canadian Dollar currency returned "
+ currCA.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(cDollar), flag);
}
}
}
|
diff --git a/android/InCarDisplay/src/com/totoro/incardisplay/Login.java b/android/InCarDisplay/src/com/totoro/incardisplay/Login.java
index 21f034a..f9f0e8c 100644
--- a/android/InCarDisplay/src/com/totoro/incardisplay/Login.java
+++ b/android/InCarDisplay/src/com/totoro/incardisplay/Login.java
@@ -1,256 +1,256 @@
package com.totoro.incardisplay;
import com.facebook.*;
import com.facebook.model.*;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.totoro.incardisplay.util.SystemUiHider;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class Login extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {@link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {@link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
private Activity loginActivity;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginActivity = this;
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(
mDelayHideTouchListener);
// Dummy button goes to car profile page
final Button dummy_button = (Button) findViewById(R.id.dummy_button);
dummy_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
ProfileCarDB db = new ProfileCarDB(v.getContext());
db.deleteProfile();
db.close();
} catch (Exception e) {
}
}
});
// facebook login button!!!!
final Button login_button = (Button) findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// start Facebook Login
Session.openActiveSession(loginActivity, true, new Session.StatusCallback() {
// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("Hello " + user.getName() + "!");
}
}
});
}
}
});
- Intent k = new Intent(Login.this, CarProfileForm.class);
- startActivity(k);
+ //Intent k = new Intent(Login.this, CarProfileForm.class);
+ //startActivity(k);
} catch (Exception e) {
}
}
});
final Button logout_button = (Button) findViewById(R.id.login_with_email);
logout_button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
if (Session.getActiveSession() != null) {
Session.getActiveSession().closeAndClearTokenInformation();
Session.getActiveSession().close();
Session.setActiveSession(null);
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("Goodbye");
} else {
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("You weren't logged in to start with");
}
} catch (Exception e) {
}
}
});
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginActivity = this;
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(
mDelayHideTouchListener);
// Dummy button goes to car profile page
final Button dummy_button = (Button) findViewById(R.id.dummy_button);
dummy_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
ProfileCarDB db = new ProfileCarDB(v.getContext());
db.deleteProfile();
db.close();
} catch (Exception e) {
}
}
});
// facebook login button!!!!
final Button login_button = (Button) findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// start Facebook Login
Session.openActiveSession(loginActivity, true, new Session.StatusCallback() {
// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("Hello " + user.getName() + "!");
}
}
});
}
}
});
Intent k = new Intent(Login.this, CarProfileForm.class);
startActivity(k);
} catch (Exception e) {
}
}
});
final Button logout_button = (Button) findViewById(R.id.login_with_email);
logout_button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
if (Session.getActiveSession() != null) {
Session.getActiveSession().closeAndClearTokenInformation();
Session.getActiveSession().close();
Session.setActiveSession(null);
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("Goodbye");
} else {
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("You weren't logged in to start with");
}
} catch (Exception e) {
}
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginActivity = this;
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(
mDelayHideTouchListener);
// Dummy button goes to car profile page
final Button dummy_button = (Button) findViewById(R.id.dummy_button);
dummy_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
ProfileCarDB db = new ProfileCarDB(v.getContext());
db.deleteProfile();
db.close();
} catch (Exception e) {
}
}
});
// facebook login button!!!!
final Button login_button = (Button) findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// start Facebook Login
Session.openActiveSession(loginActivity, true, new Session.StatusCallback() {
// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("Hello " + user.getName() + "!");
}
}
});
}
}
});
//Intent k = new Intent(Login.this, CarProfileForm.class);
//startActivity(k);
} catch (Exception e) {
}
}
});
final Button logout_button = (Button) findViewById(R.id.login_with_email);
logout_button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
if (Session.getActiveSession() != null) {
Session.getActiveSession().closeAndClearTokenInformation();
Session.getActiveSession().close();
Session.setActiveSession(null);
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("Goodbye");
} else {
TextView welcome = (TextView) findViewById(R.id.logo);
welcome.setText("You weren't logged in to start with");
}
} catch (Exception e) {
}
}
});
}
|
diff --git a/src/main/java/org/neo4j/server/extensions/ServerExtension.java b/src/main/java/org/neo4j/server/extensions/ServerExtension.java
index f9bcd732..2f336f46 100644
--- a/src/main/java/org/neo4j/server/extensions/ServerExtension.java
+++ b/src/main/java/org/neo4j/server/extensions/ServerExtension.java
@@ -1,185 +1,185 @@
/**
* Copyright (c) 2002-2010 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.extensions;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.configuration.Configuration;
import org.neo4j.helpers.Service;
/**
* API for creating extensions for the Neo4j server.
*
* Extensions are created by creating a subclass of this class. The subclass
* should have a public no-argument constructor. Then place this class in a
* jar-file that contains a file called
* <code>META-INF/services/org.neo4j.server.extensions.ServerExtension</code>.
* This file should contain the fully qualified name of the class that extends
* {@link ServerExtension}, e.g. <code>com.example.MyNeo4jServerExtension</code>
* on a single line. If the jar contains multiple extensions to the Neo4j
* server, this file should contain the fully qualified class names of all
* extension classes, each class name on its own line in the file. When the jar
* file is placed on the class path of the server, it will be loaded
* automatically when the server starts.
*
* The easiest way to implement Neo4j server extensions is by defining public
* methods on the extension class annotated with
* <code>@{@link ExtensionTarget}</code>. The parameter for the
* {@link ExtensionTarget} annotation should be the class representing the
* entity that the method extends. The entities that can be extended are
* currently:
* <ul>
* <li>{@link org.neo4j.graphdb.GraphDatabaseService} - a general extension
* method to the server</li>
* <li>{@link org.neo4j.graphdb.Node} - an extension method for a node</li>
* <li>{@link org.neo4j.graphdb.Relationship} - an extension method for a
* relationship</li>
* </ul>
* You can then use the <code>@{@link Source}</code> annotation on one parameter of the method to get
* the instance that was extended. Additional parameters needs to be of a
* supported type, and annotated with the <code>@{@link Parameter}</code> annotation specifying the name by which the
* parameter is passed from the client. The supported parameter types are:
* <ul>
* <li>{@link org.neo4j.graphdb.Node}</li>
* <li>{@link org.neo4j.graphdb.Relationship}</li>
* <li>{@link java.net.URI} or {@link java.net.URL}</li>
* <li>{@link Integer}</li>
* <li>{@link Long}</li>
* <li>{@link Short}</li>
* <li>{@link Byte}</li>
* <li>{@link Character}</li>
* <li>{@link Boolean}</li>
* <li>{@link Double}</li>
* <li>{@link Float}</li>
* <li>{@link java.util.List lists}, {@link java.util.Set sets} or arrays of any
* of the above types.</li>
* </ul>
*
* All exceptions thrown by an {@link ExtensionTarget} method are treated as
* server errors, unless the method has declared the ability to throw such an
* exception, in that case the exception is treated as a bad request and
* propagated to the invoking client.
*
* @see java.util.ServiceLoader
*
* @author Tobias Ivarsson <[email protected]>
*/
public abstract class ServerExtension
{
final String name;
/**
* Create a server extension with the specified name.
*
* @param name the name of this extension.
*/
public ServerExtension( String name )
{
this.name = verifyName( name );
}
/**
* Create a server extension using the simple name of the concrete class
* that extends {@link ServerExtension} as the name for the extension.
*/
public ServerExtension()
{
this.name = verifyName( getClass().getSimpleName() );
}
static String verifyName( String name )
{
if ( name == null )
{
throw new IllegalArgumentException( "Name may not be null" );
}
try
{
if ( !URLEncoder.encode( name, "UTF-8" ).equals( name ) )
{
- throw new IllegalArgumentException( "Name contained illegal characters" );
+ throw new IllegalArgumentException( "Name contains illegal characters" );
}
}
catch ( UnsupportedEncodingException e )
{
throw new Error( "UTF-8 should be supported", e );
}
return name;
}
@Override
public String toString()
{
return "ServerExtension[" + name + "]";
}
static Iterable<ServerExtension> load()
{
return Service.load( ServerExtension.class );
}
/**
* Loads the extension points of this server extension. Override this method
* to provide your own, custom way of loading extension points. The default
* implementation loads {@link ExtensionPoint} based on methods with the
* {@link ExtensionTarget} annotation.
*
* @param extender the collection of {@link ExtensionPoint}s for this
* {@link ServerExtension}.
* @param serverConfig the configuration parameters for the server.
*/
protected void loadServerExtender( ServerExtender extender, Configuration serverConfig )
{
for ( ExtensionPoint extension : getDefaultExtensionPoints( serverConfig ) )
{
extender.addExtension( extension.forType(), extension );
}
}
/**
* Loads the extension points of this server extension. Override this method
* to provide your own, custom way of loading extension points. The default
* implementation loads {@link ExtensionPoint} based on methods with the
* {@link ExtensionTarget} annotation.
*
* @param serverConfig the configuration parameters for the server.
* @return the collection of {@link ExtensionPoint}s for this
* {@link ServerExtension}.
*/
protected Collection<ExtensionPoint> getDefaultExtensionPoints( Configuration serverConfig )
{
List<ExtensionPoint> result = new ArrayList<ExtensionPoint>();
for ( Method method : getClass().getMethods() )
{
ExtensionTarget target = method.getAnnotation( ExtensionTarget.class );
if ( target != null )
{
result.add( ServerExtensionMethod.createFrom( this, method, target.value() ) );
}
}
return result;
}
}
| true | true | static String verifyName( String name )
{
if ( name == null )
{
throw new IllegalArgumentException( "Name may not be null" );
}
try
{
if ( !URLEncoder.encode( name, "UTF-8" ).equals( name ) )
{
throw new IllegalArgumentException( "Name contained illegal characters" );
}
}
catch ( UnsupportedEncodingException e )
{
throw new Error( "UTF-8 should be supported", e );
}
return name;
}
| static String verifyName( String name )
{
if ( name == null )
{
throw new IllegalArgumentException( "Name may not be null" );
}
try
{
if ( !URLEncoder.encode( name, "UTF-8" ).equals( name ) )
{
throw new IllegalArgumentException( "Name contains illegal characters" );
}
}
catch ( UnsupportedEncodingException e )
{
throw new Error( "UTF-8 should be supported", e );
}
return name;
}
|
diff --git a/src/main/java/com/laytonsmith/core/functions/Persistance.java b/src/main/java/com/laytonsmith/core/functions/Persistance.java
index 11521b46..a26e9103 100644
--- a/src/main/java/com/laytonsmith/core/functions/Persistance.java
+++ b/src/main/java/com/laytonsmith/core/functions/Persistance.java
@@ -1,384 +1,384 @@
package com.laytonsmith.core.functions;
import com.laytonsmith.PureUtilities.StringUtils;
import com.laytonsmith.annotations.api;
import com.laytonsmith.annotations.noboilerplate;
import com.laytonsmith.core.*;
import com.laytonsmith.core.constructs.*;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.exceptions.MarshalException;
import com.laytonsmith.core.functions.Exceptions.ExceptionType;
import com.laytonsmith.persistance.DataSourceException;
import com.laytonsmith.persistance.PersistanceNetwork;
import com.laytonsmith.persistance.ReadOnlyException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Layton
*/
public class Persistance {
public static String docs() {
return "Allows scripts to store data from execution to execution. See the guide on [[CommandHelper/Persistance|persistance]] for more information."
+ " In all the functions, you may send multiple arguments for the key, which will automatically"
+ " be concatenated with a period (the namespace separator). No magic happens here, you can"
+ " put periods yourself, or combine manually namespaced values or automatically namespaced values"
+ " with no side effects.";
}
@api(environments={GlobalEnv.class})
@noboilerplate
public static class store_value extends AbstractFunction {
public String getName() {
return "store_value";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public String docs() {
return "void {[namespace, ...,] key, value} Allows you to store a value, which can then be retrieved later. key must be a string containing"
+ " only letters, numbers, underscores. Periods may also be used, but they form a namespace, and have special meaning."
+ " (See get_values())";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException, ExceptionType.IOException, ExceptionType.FormatException};
}
public boolean isRestricted() {
return true;
}
public CHVersion since() {
return CHVersion.V3_0_2;
}
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
String key = GetNamespace(args, args.length - 1, getName(), t);
String value = null;
try {
value = Construct.json_encode(args[args.length - 1], t);
} catch (MarshalException e) {
- throw ConfigRuntimeException.CreateUncatchableException(e.getMessage(), t);
+ throw new Exceptions.FormatException(e.getMessage(), t);
}
char pc = '.';
for (int i = 0; i < key.length(); i++) {
Character c = key.charAt(i);
if (i != 0) {
pc = key.charAt(i - 1);
}
if ((i == 0 || i == key.length() - 1 || pc == '.') && c == '.') {
throw new ConfigRuntimeException("Periods may only be used as seperators between namespaces.", ExceptionType.FormatException, t);
}
if (c != '_' && c != '.' && !Character.isLetterOrDigit(c)) {
throw new ConfigRuntimeException("Param 1 in store_value must only contain letters, digits, underscores, or dots, (which denote namespaces).",
ExceptionType.FormatException, t);
}
}
CHLog.GetLogger().Log(CHLog.Tags.PERSISTANCE, LogLevel.DEBUG, "Storing: " + key + " -> " + value, t);
try {
env.getEnv(GlobalEnv.class).GetPersistanceNetwork().set(env.getEnv(GlobalEnv.class).GetDaemonManager(), ("storage." + key).split("\\."), value);
} catch(IllegalArgumentException e){
throw new ConfigRuntimeException(e.getMessage(), ExceptionType.FormatException, t);
} catch (Exception ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
}
return new CVoid(t);
}
public Boolean runAsync() {
//Because we do IO
return true;
}
@Override
public LogLevel profileAt() {
return LogLevel.DEBUG;
}
}
@api(environments={GlobalEnv.class})
@noboilerplate
public static class get_value extends AbstractFunction {
public String getName() {
return "get_value";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public String docs() {
return "Mixed {[namespace, ...,] key} Returns a stored value stored with store_value. If the key doesn't exist in storage, null"
+ " is returned. On a more detailed note: If the value stored in the persistance database is not actually a construct,"
+ " then null is also returned.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.IOException, ExceptionType.FormatException};
}
public boolean isRestricted() {
return true;
}
public CHVersion since() {
return CHVersion.V3_0_2;
}
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
Object o;
String namespace = GetNamespace(args, null, getName(), t);
CHLog.GetLogger().Log(CHLog.Tags.PERSISTANCE, LogLevel.DEBUG, "Getting value: " + namespace, t);
try {
Object obj;
try {
obj = env.getEnv(GlobalEnv.class).GetPersistanceNetwork().get(("storage." + namespace).split("\\."));
} catch (DataSourceException ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
} catch(IllegalArgumentException e){
throw new ConfigRuntimeException(e.getMessage(), ExceptionType.FormatException, t, e);
}
if (obj == null) {
return new CNull(t);
}
o = Construct.json_decode(obj.toString(), t);
} catch (MarshalException ex) {
throw ConfigRuntimeException.CreateUncatchableException(ex.getMessage(), t);
}
try {
return (Construct) o;
} catch (ClassCastException e) {
return new CNull(t);
}
}
public Boolean runAsync() {
//Because we do IO
return true;
}
@Override
public LogLevel profileAt() {
return LogLevel.DEBUG;
}
}
@api(environments={GlobalEnv.class})
@noboilerplate
public static class get_values extends AbstractFunction {
public String getName() {
return "get_values";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public String docs() {
return "array {name[, space, ...]} Returns all the values in a particular namespace"
+ " as an associative"
+ " array(key: value, key: value). Only full namespace matches are considered,"
+ " so if the key 'users.data.username.hi' existed in the database, and you tried"
+ " get_values('users.data.user'), nothing would be returned. The last segment in"
+ " a key is also considered a namespace, so 'users.data.username.hi' would return"
+ " a single value (in this case).";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.IOException, ExceptionType.FormatException};
}
public boolean isRestricted() {
return true;
}
public Boolean runAsync() {
return true;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
PersistanceNetwork p = environment.getEnv(GlobalEnv.class).GetPersistanceNetwork();
List<String> keyChain = new ArrayList<String>();
keyChain.add("storage");
String namespace = GetNamespace(args, null, getName(), t);
CHLog.GetLogger().Log(CHLog.Tags.PERSISTANCE, LogLevel.DEBUG, "Getting all values from " + namespace, t);
keyChain.addAll(Arrays.asList(namespace.split("\\.")));
Map<String[], String> list;
try {
list = p.getNamespace(keyChain.toArray(new String[keyChain.size()]));
} catch (DataSourceException ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
} catch(IllegalArgumentException e){
throw new ConfigRuntimeException(e.getMessage(), ExceptionType.FormatException, t, e);
}
CArray ca = new CArray(t);
CHLog.GetLogger().Log(CHLog.Tags.PERSISTANCE, LogLevel.DEBUG, list.size() + " value(s) are being returned", t);
for (String[] e : list.keySet()) {
try {
String key = StringUtils.Join(e, ".").replaceFirst("storage\\.", ""); //Get that junk out of here
ca.set(new CString(key, t),
Construct.json_decode(list.get(e), t), t);
} catch (MarshalException ex) {
Logger.getLogger(Persistance.class.getName()).log(Level.SEVERE, null, ex);
}
}
return ca;
}
public CHVersion since() {
return CHVersion.V3_3_0;
}
@Override
public LogLevel profileAt() {
return LogLevel.DEBUG;
}
}
@api(environments={GlobalEnv.class})
@noboilerplate
public static class has_value extends AbstractFunction {
public String getName() {
return "has_value";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public String docs() {
return "boolean {[namespace, ...,] key} Returns whether or not there is data stored at the specified key in the Persistance database.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.IOException, ExceptionType.FormatException};
}
public boolean isRestricted() {
return true;
}
public CHVersion since() {
return CHVersion.V3_1_2;
}
public Boolean runAsync() {
return true;
}
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException {
try {
return new CBoolean(env.getEnv(GlobalEnv.class).GetPersistanceNetwork().hasKey(("storage." + GetNamespace(args, null, getName(), t)).split("\\.")), t);
} catch (DataSourceException ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
} catch(IllegalArgumentException e){
throw new ConfigRuntimeException(e.getMessage(), ExceptionType.FormatException, t, e);
}
}
@Override
public LogLevel profileAt() {
return LogLevel.DEBUG;
}
}
@api(environments={GlobalEnv.class})
@noboilerplate
public static class clear_value extends AbstractFunction {
public String getName() {
return "clear_value";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public String docs() {
return "void {[namespace, ...,] key} Completely removes a value from storage. Calling has_value(key) after this call will return false.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.IOException, ExceptionType.FormatException};
}
public boolean isRestricted() {
return true;
}
public CHVersion since() {
return CHVersion.V3_3_0;
}
public Boolean runAsync() {
return null;
}
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
String namespace = GetNamespace(args, null, getName(), t);
CHLog.GetLogger().Log(CHLog.Tags.PERSISTANCE, LogLevel.DEBUG, "Clearing value: " + namespace, t);
try {
environment.getEnv(GlobalEnv.class).GetPersistanceNetwork().clearKey(environment.getEnv(GlobalEnv.class).GetDaemonManager(), ("storage." + namespace).split("\\."));
} catch (DataSourceException ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
} catch (ReadOnlyException ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
} catch (IOException ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
} catch(IllegalArgumentException e){
throw new ConfigRuntimeException(e.getMessage(), ExceptionType.FormatException, t, e);
}
return new CVoid(t);
}
@Override
public LogLevel profileAt() {
return LogLevel.DEBUG;
}
}
/**
* Generates the namespace for this value, given an array of constructs. If
* the entire list of arguments isn't supposed to be part of the namespace,
* the value to be excluded may be specified.
*
* @param args
* @param exclude
* @return
*/
private static String GetNamespace(Construct[] args, Integer exclude, String name, Target t) {
if (exclude != null && args.length < 2 || exclude == null && args.length < 1) {
throw new ConfigRuntimeException(name + " was not provided with enough arguments. Check the documentation, and try again.", ExceptionType.InsufficientArgumentsException, t);
}
boolean first = true;
StringBuilder b = new StringBuilder();
for (int i = 0; i < args.length; i++) {
if (exclude != null && exclude == i) {
continue;
}
if (!first) {
b.append(".");
}
first = false;
b.append(args[i].val());
}
return b.toString();
}
}
| true | true | public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
String key = GetNamespace(args, args.length - 1, getName(), t);
String value = null;
try {
value = Construct.json_encode(args[args.length - 1], t);
} catch (MarshalException e) {
throw ConfigRuntimeException.CreateUncatchableException(e.getMessage(), t);
}
char pc = '.';
for (int i = 0; i < key.length(); i++) {
Character c = key.charAt(i);
if (i != 0) {
pc = key.charAt(i - 1);
}
if ((i == 0 || i == key.length() - 1 || pc == '.') && c == '.') {
throw new ConfigRuntimeException("Periods may only be used as seperators between namespaces.", ExceptionType.FormatException, t);
}
if (c != '_' && c != '.' && !Character.isLetterOrDigit(c)) {
throw new ConfigRuntimeException("Param 1 in store_value must only contain letters, digits, underscores, or dots, (which denote namespaces).",
ExceptionType.FormatException, t);
}
}
CHLog.GetLogger().Log(CHLog.Tags.PERSISTANCE, LogLevel.DEBUG, "Storing: " + key + " -> " + value, t);
try {
env.getEnv(GlobalEnv.class).GetPersistanceNetwork().set(env.getEnv(GlobalEnv.class).GetDaemonManager(), ("storage." + key).split("\\."), value);
} catch(IllegalArgumentException e){
throw new ConfigRuntimeException(e.getMessage(), ExceptionType.FormatException, t);
} catch (Exception ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
}
return new CVoid(t);
}
| public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
String key = GetNamespace(args, args.length - 1, getName(), t);
String value = null;
try {
value = Construct.json_encode(args[args.length - 1], t);
} catch (MarshalException e) {
throw new Exceptions.FormatException(e.getMessage(), t);
}
char pc = '.';
for (int i = 0; i < key.length(); i++) {
Character c = key.charAt(i);
if (i != 0) {
pc = key.charAt(i - 1);
}
if ((i == 0 || i == key.length() - 1 || pc == '.') && c == '.') {
throw new ConfigRuntimeException("Periods may only be used as seperators between namespaces.", ExceptionType.FormatException, t);
}
if (c != '_' && c != '.' && !Character.isLetterOrDigit(c)) {
throw new ConfigRuntimeException("Param 1 in store_value must only contain letters, digits, underscores, or dots, (which denote namespaces).",
ExceptionType.FormatException, t);
}
}
CHLog.GetLogger().Log(CHLog.Tags.PERSISTANCE, LogLevel.DEBUG, "Storing: " + key + " -> " + value, t);
try {
env.getEnv(GlobalEnv.class).GetPersistanceNetwork().set(env.getEnv(GlobalEnv.class).GetDaemonManager(), ("storage." + key).split("\\."), value);
} catch(IllegalArgumentException e){
throw new ConfigRuntimeException(e.getMessage(), ExceptionType.FormatException, t);
} catch (Exception ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.IOException, t, ex);
}
return new CVoid(t);
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/EmptyStatementCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/EmptyStatementCheck.java
index ffb0448a..240b828b 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/EmptyStatementCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/EmptyStatementCheck.java
@@ -1,52 +1,52 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
/**
* <p>
* Check that finds empty statements.
* </p>
* <p>
* An example of how to configure the check is:
* </p>
* <pre>
* <module name="EmptyStatement"/>
* </pre>
* @author Rick Giles
* @version 1.0
*/
public class EmptyStatementCheck extends Check
{
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getDefaultTokens()
{
- return new int[] { TokenTypes.EMPTY_STAT };
+ return new int[] {TokenTypes.EMPTY_STAT};
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public void visitToken(DetailAST aAST)
{
log(aAST.getLineNo(), aAST.getColumnNo(), "empty.statement");
}
}
| true | true | public int[] getDefaultTokens()
{
return new int[] { TokenTypes.EMPTY_STAT };
}
| public int[] getDefaultTokens()
{
return new int[] {TokenTypes.EMPTY_STAT};
}
|
diff --git a/src/MaxSubarray.java b/src/MaxSubarray.java
index 50df91e..0f39514 100644
--- a/src/MaxSubarray.java
+++ b/src/MaxSubarray.java
@@ -1,30 +1,30 @@
/**
* http://leetcode.com/onlinejudge#question_53
*
*
*/
public class MaxSubarray {
public int maxSubArray(int[] A) {
int maxSofar = 0;
int maxEndingHere = 0;
boolean allNegative = true;
- int max = 0;
+ int max = Integer.MIN_VALUE;
for (int element : A) {
if (element > max) {
max = element;
}
if (element >= 0) {
allNegative = false;
break;
}
}
if (allNegative) {
return max;
}
for (int element : A) {
maxEndingHere = Math.max(0, maxEndingHere + element);
maxSofar = Math.max(maxEndingHere, maxSofar);
}
return maxSofar;
}
}
| true | true | public int maxSubArray(int[] A) {
int maxSofar = 0;
int maxEndingHere = 0;
boolean allNegative = true;
int max = 0;
for (int element : A) {
if (element > max) {
max = element;
}
if (element >= 0) {
allNegative = false;
break;
}
}
if (allNegative) {
return max;
}
for (int element : A) {
maxEndingHere = Math.max(0, maxEndingHere + element);
maxSofar = Math.max(maxEndingHere, maxSofar);
}
return maxSofar;
}
| public int maxSubArray(int[] A) {
int maxSofar = 0;
int maxEndingHere = 0;
boolean allNegative = true;
int max = Integer.MIN_VALUE;
for (int element : A) {
if (element > max) {
max = element;
}
if (element >= 0) {
allNegative = false;
break;
}
}
if (allNegative) {
return max;
}
for (int element : A) {
maxEndingHere = Math.max(0, maxEndingHere + element);
maxSofar = Math.max(maxEndingHere, maxSofar);
}
return maxSofar;
}
|
diff --git a/app/src/main/java/com/github/mobile/core/issue/IssueUtils.java b/app/src/main/java/com/github/mobile/core/issue/IssueUtils.java
index 736e5c43..acb64363 100644
--- a/app/src/main/java/com/github/mobile/core/issue/IssueUtils.java
+++ b/app/src/main/java/com/github/mobile/core/issue/IssueUtils.java
@@ -1,67 +1,69 @@
/*
* Copyright 2012 GitHub Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.mobile.core.issue;
import android.text.TextUtils;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.PullRequest;
/**
* Utilities for working with {@link Issue} models
*/
public class IssueUtils {
/**
* Is the given issue a pull request?
*
* @param issue
* @return true if pull request, false otherwise
*/
public static boolean isPullRequest(Issue issue) {
return issue != null && issue.getPullRequest() != null
&& !TextUtils.isEmpty(issue.getPullRequest().getHtmlUrl());
}
/**
* Convert {@link PullRequest} model {@link Issue} model
*
* @param pullRequest
* @return issue
*/
public static Issue toIssue(final PullRequest pullRequest) {
if (pullRequest == null)
return null;
Issue issue = new Issue();
+ issue.setAssignee(pullRequest.getAssignee());
issue.setBody(pullRequest.getBody());
issue.setBodyHtml(pullRequest.getBodyHtml());
issue.setBodyText(pullRequest.getBodyText());
issue.setClosedAt(pullRequest.getClosedAt());
issue.setComments(pullRequest.getComments());
issue.setCreatedAt(pullRequest.getCreatedAt());
issue.setHtmlUrl(pullRequest.getHtmlUrl());
issue.setId(pullRequest.getId());
+ issue.setMilestone(pullRequest.getMilestone());
issue.setNumber(pullRequest.getNumber());
issue.setPullRequest(pullRequest);
issue.setState(pullRequest.getState());
issue.setTitle(pullRequest.getTitle());
issue.setUpdatedAt(pullRequest.getUpdatedAt());
issue.setUrl(pullRequest.getUrl());
issue.setUser(pullRequest.getUser());
return issue;
}
}
| false | true | public static Issue toIssue(final PullRequest pullRequest) {
if (pullRequest == null)
return null;
Issue issue = new Issue();
issue.setBody(pullRequest.getBody());
issue.setBodyHtml(pullRequest.getBodyHtml());
issue.setBodyText(pullRequest.getBodyText());
issue.setClosedAt(pullRequest.getClosedAt());
issue.setComments(pullRequest.getComments());
issue.setCreatedAt(pullRequest.getCreatedAt());
issue.setHtmlUrl(pullRequest.getHtmlUrl());
issue.setId(pullRequest.getId());
issue.setNumber(pullRequest.getNumber());
issue.setPullRequest(pullRequest);
issue.setState(pullRequest.getState());
issue.setTitle(pullRequest.getTitle());
issue.setUpdatedAt(pullRequest.getUpdatedAt());
issue.setUrl(pullRequest.getUrl());
issue.setUser(pullRequest.getUser());
return issue;
}
| public static Issue toIssue(final PullRequest pullRequest) {
if (pullRequest == null)
return null;
Issue issue = new Issue();
issue.setAssignee(pullRequest.getAssignee());
issue.setBody(pullRequest.getBody());
issue.setBodyHtml(pullRequest.getBodyHtml());
issue.setBodyText(pullRequest.getBodyText());
issue.setClosedAt(pullRequest.getClosedAt());
issue.setComments(pullRequest.getComments());
issue.setCreatedAt(pullRequest.getCreatedAt());
issue.setHtmlUrl(pullRequest.getHtmlUrl());
issue.setId(pullRequest.getId());
issue.setMilestone(pullRequest.getMilestone());
issue.setNumber(pullRequest.getNumber());
issue.setPullRequest(pullRequest);
issue.setState(pullRequest.getState());
issue.setTitle(pullRequest.getTitle());
issue.setUpdatedAt(pullRequest.getUpdatedAt());
issue.setUrl(pullRequest.getUrl());
issue.setUser(pullRequest.getUser());
return issue;
}
|
diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglNet.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglNet.java
index a2d48aa05..c8302a2a4 100755
--- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglNet.java
+++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglNet.java
@@ -1,221 +1,222 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.backends.lwjgl;
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Net.HttpMethods;
import com.badlogic.gdx.Net.HttpResponse;
import com.badlogic.gdx.net.ServerSocket;
import com.badlogic.gdx.net.ServerSocketHints;
import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.net.SocketHints;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.JsonWriter;
public class LwjglNet implements Net {
private final class HttpClientResponse implements HttpResponse {
private HttpURLConnection connection;
private HttpStatus status;
private InputStream inputStream;
public HttpClientResponse(HttpURLConnection connection) throws IOException {
this.connection = connection;
this.inputStream = connection.getInputStream();
try {
this.status = new HttpStatus(connection.getResponseCode());
} catch (IOException e) {
this.status = new HttpStatus(-1);
}
}
@Override
public byte[] getResult () {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
try {
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
} catch (IOException e) {
return new byte[0];
}
return buffer.toByteArray();
}
@Override
public String getResultAsString () {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String tmp, line = "";
try {
while((tmp=reader.readLine()) != null)
line += tmp;
reader.close();
return line;
} catch (IOException e) {
return "";
}
}
@Override
public InputStream getResultAsStream () {
return inputStream;
}
@Override
public HttpStatus getStatus () {
return status;
}
}
// IMPORTANT: The Gdx.net classes are a currently duplicated for LWJGL + Android!
// If you make changes here, make changes in the other backend as well.
private final ExecutorService executorService;
public LwjglNet() {
executorService = Executors.newCachedThreadPool();
}
@Override
public void sendHttpRequest (HttpRequest httpRequest, final HttpResponseListener httpResultListener) {
if (httpRequest.getUrl() == null) {
httpResultListener.failed(new GdxRuntimeException("can't process a HTTP request without URL set"));
return;
}
try {
- String value = httpRequest.convertHttpRequest();
+// String value = httpRequest.convertHttpRequest();
+ String value = httpRequest.getContent();
String method = httpRequest.getMethod();
URL url;
if(method.equalsIgnoreCase(HttpMethods.GET))
url = new URL(httpRequest.getUrl()+"?"+value);
else
url = new URL(httpRequest.getUrl());
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
- connection.setRequestMethod((method.equalsIgnoreCase(HttpMethods.JSON))? HttpMethods.POST : method);
+ connection.setRequestMethod(method);
// Headers get set regardless of the method
Map<String,String> content = httpRequest.getHeaders();
Set<String> keySet = content.keySet();
for (String name : keySet) {
connection.addRequestProperty(name, content.get(name));
}
// Set Timeouts
- connection.setConnectTimeout(httpRequest.getTimeout());
- connection.setReadTimeout(httpRequest.getTimeout());
+ connection.setConnectTimeout(httpRequest.getTimeOut());
+ connection.setReadTimeout(httpRequest.getTimeOut());
// Set the content for JSON or POST (GET has the information embedded in the URL)
if(!method.equalsIgnoreCase(HttpMethods.GET)) {
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream ());
wr.write(value);
wr.flush();
wr.close();
}
executorService.submit(new Runnable() {
@Override
public void run () {
try {
connection.connect();
// post a runnable to sync the handler with the main thread
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
try {
httpResultListener.handleHttpResponse(new HttpClientResponse(connection));
} catch (IOException e) {
httpResultListener.failed(e);
connection.disconnect();
}
}
});
} catch (final Exception e) {
// post a runnable to sync the handler with the main thread
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
httpResultListener.failed(e);
connection.disconnect();
}
});
}
}
});
} catch (Exception e) {
httpResultListener.failed(e);
return;
}
}
@Override
public ServerSocket newServerSocket (Protocol protocol, int port, ServerSocketHints hints) {
return new LwjglServerSocket(protocol, port, hints);
}
@Override
public Socket newClientSocket (Protocol protocol, String host, int port, SocketHints hints) {
return new LwjglSocket(protocol, host, port, hints);
}
@Override
public void openURI (String URI) {
if (!Desktop.isDesktopSupported()) return;
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.BROWSE)) return;
try {
desktop.browse(new java.net.URI(URI));
} catch (Exception e) {
throw new GdxRuntimeException(e);
}
}
}
| false | true | public void sendHttpRequest (HttpRequest httpRequest, final HttpResponseListener httpResultListener) {
if (httpRequest.getUrl() == null) {
httpResultListener.failed(new GdxRuntimeException("can't process a HTTP request without URL set"));
return;
}
try {
String value = httpRequest.convertHttpRequest();
String method = httpRequest.getMethod();
URL url;
if(method.equalsIgnoreCase(HttpMethods.GET))
url = new URL(httpRequest.getUrl()+"?"+value);
else
url = new URL(httpRequest.getUrl());
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod((method.equalsIgnoreCase(HttpMethods.JSON))? HttpMethods.POST : method);
// Headers get set regardless of the method
Map<String,String> content = httpRequest.getHeaders();
Set<String> keySet = content.keySet();
for (String name : keySet) {
connection.addRequestProperty(name, content.get(name));
}
// Set Timeouts
connection.setConnectTimeout(httpRequest.getTimeout());
connection.setReadTimeout(httpRequest.getTimeout());
// Set the content for JSON or POST (GET has the information embedded in the URL)
if(!method.equalsIgnoreCase(HttpMethods.GET)) {
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream ());
wr.write(value);
wr.flush();
wr.close();
}
executorService.submit(new Runnable() {
@Override
public void run () {
try {
connection.connect();
// post a runnable to sync the handler with the main thread
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
try {
httpResultListener.handleHttpResponse(new HttpClientResponse(connection));
} catch (IOException e) {
httpResultListener.failed(e);
connection.disconnect();
}
}
});
} catch (final Exception e) {
// post a runnable to sync the handler with the main thread
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
httpResultListener.failed(e);
connection.disconnect();
}
});
}
}
});
} catch (Exception e) {
httpResultListener.failed(e);
return;
}
}
| public void sendHttpRequest (HttpRequest httpRequest, final HttpResponseListener httpResultListener) {
if (httpRequest.getUrl() == null) {
httpResultListener.failed(new GdxRuntimeException("can't process a HTTP request without URL set"));
return;
}
try {
// String value = httpRequest.convertHttpRequest();
String value = httpRequest.getContent();
String method = httpRequest.getMethod();
URL url;
if(method.equalsIgnoreCase(HttpMethods.GET))
url = new URL(httpRequest.getUrl()+"?"+value);
else
url = new URL(httpRequest.getUrl());
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(method);
// Headers get set regardless of the method
Map<String,String> content = httpRequest.getHeaders();
Set<String> keySet = content.keySet();
for (String name : keySet) {
connection.addRequestProperty(name, content.get(name));
}
// Set Timeouts
connection.setConnectTimeout(httpRequest.getTimeOut());
connection.setReadTimeout(httpRequest.getTimeOut());
// Set the content for JSON or POST (GET has the information embedded in the URL)
if(!method.equalsIgnoreCase(HttpMethods.GET)) {
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream ());
wr.write(value);
wr.flush();
wr.close();
}
executorService.submit(new Runnable() {
@Override
public void run () {
try {
connection.connect();
// post a runnable to sync the handler with the main thread
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
try {
httpResultListener.handleHttpResponse(new HttpClientResponse(connection));
} catch (IOException e) {
httpResultListener.failed(e);
connection.disconnect();
}
}
});
} catch (final Exception e) {
// post a runnable to sync the handler with the main thread
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
httpResultListener.failed(e);
connection.disconnect();
}
});
}
}
});
} catch (Exception e) {
httpResultListener.failed(e);
return;
}
}
|
diff --git a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/rest/RESTfulTestBase.java b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/rest/RESTfulTestBase.java
index fc9e9465..fb87a5e9 100644
--- a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/rest/RESTfulTestBase.java
+++ b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/rest/RESTfulTestBase.java
@@ -1,83 +1,84 @@
/*******************************************************************************
* Copyright (c) 2010-2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ws.ui.bot.test.rest;
import org.jboss.tools.ui.bot.ext.Timing;
import org.jboss.tools.ui.bot.ext.config.Annotations.Require;
import org.jboss.tools.ui.bot.ext.config.Annotations.Server;
import org.jboss.tools.ui.bot.ext.config.Annotations.ServerState;
import org.jboss.tools.ws.ui.bot.test.WSTestBase;
/**
* Test base for bot tests using RESTFul support
*
* @author jjankovi
*
*/
@Require(server = @Server(state=ServerState.NotRunning), perspective = "Java EE")
public class RESTfulTestBase extends WSTestBase {
protected final RESTfulHelper restfulHelper = new RESTfulHelper();
protected final String CONFIGURE_MENU_LABEL = "Configure";
protected final String REST_SUPPORT_MENU_LABEL_ADD = "Add JAX-RS 1.1 support...";
protected final String REST_SUPPORT_MENU_LABEL_REMOVE = "Remove JAX-RS 1.1 support...";
protected final String REST_EXPLORER_LABEL = "JAX-RS REST Web Services";
protected final String REST_EXPLORER_LABEL_BUILD = "Building RESTful Web Services...";
protected final String BASIC_WS_RESOURCE = "/resources/restful/BasicRestfulWS.java.ws";
protected final String ADVANCED_WS_RESOURCE = "/resources/restful/AdvancedRestfulWS.java.ws";
protected final String EMPTY_WS_RESOURCE = "/resources/restful/EmptyRestfulWS.java.ws";
protected final String SIMPLE_REST_WS_RESOURCE = "/resources/restful/SimpleRestWS.java.ws";
protected String getWsPackage() {
return "org.rest.test";
}
protected String getWsName() {
return "RestService";
}
@Override
public void setup() {
prepareRestProject();
}
protected void prepareRestProject() {
if (!projectExists(getWsProjectName())) {
//importing project without targeted runtime set
importWSTestProject("resources/projects/" +
getWsProjectName(), getWsProjectName());
//set target runtime - TO DO
- projectHelper.addDefaultRuntimeIntoProject(getWsProjectName());
+ projectHelper.addConfiguredRuntimeIntoProject(
+ getWsProjectName(), configuredState.getServer().name);
projectExplorer.selectProject(getWsProjectName());
eclipse.cleanAllProjects();
bot.sleep(Timing.time3S());
if (!restfulHelper.isRestSupportEnabled(getWsProjectName())) {
// workaround for EAP 5.1
if (configuredState.getServer().type.equals("EAP") &&
configuredState.getServer().version.equals("5.1")) {
restfulHelper.addRestEasyLibs(getWsProjectName());
}
restfulHelper.addRestSupport(getWsProjectName());
}
}
}
}
| true | true | protected void prepareRestProject() {
if (!projectExists(getWsProjectName())) {
//importing project without targeted runtime set
importWSTestProject("resources/projects/" +
getWsProjectName(), getWsProjectName());
//set target runtime - TO DO
projectHelper.addDefaultRuntimeIntoProject(getWsProjectName());
projectExplorer.selectProject(getWsProjectName());
eclipse.cleanAllProjects();
bot.sleep(Timing.time3S());
if (!restfulHelper.isRestSupportEnabled(getWsProjectName())) {
// workaround for EAP 5.1
if (configuredState.getServer().type.equals("EAP") &&
configuredState.getServer().version.equals("5.1")) {
restfulHelper.addRestEasyLibs(getWsProjectName());
}
restfulHelper.addRestSupport(getWsProjectName());
}
}
}
| protected void prepareRestProject() {
if (!projectExists(getWsProjectName())) {
//importing project without targeted runtime set
importWSTestProject("resources/projects/" +
getWsProjectName(), getWsProjectName());
//set target runtime - TO DO
projectHelper.addConfiguredRuntimeIntoProject(
getWsProjectName(), configuredState.getServer().name);
projectExplorer.selectProject(getWsProjectName());
eclipse.cleanAllProjects();
bot.sleep(Timing.time3S());
if (!restfulHelper.isRestSupportEnabled(getWsProjectName())) {
// workaround for EAP 5.1
if (configuredState.getServer().type.equals("EAP") &&
configuredState.getServer().version.equals("5.1")) {
restfulHelper.addRestEasyLibs(getWsProjectName());
}
restfulHelper.addRestSupport(getWsProjectName());
}
}
}
|
diff --git a/CodenameG/src/edu/chl/codenameg/model/Vector2D.java b/CodenameG/src/edu/chl/codenameg/model/Vector2D.java
index aaacc24..1115c4a 100644
--- a/CodenameG/src/edu/chl/codenameg/model/Vector2D.java
+++ b/CodenameG/src/edu/chl/codenameg/model/Vector2D.java
@@ -1,80 +1,80 @@
package edu.chl.codenameg.model;
/**
* This represents a two dimensional vector
* @author ???
*
*/
public class Vector2D {
private float x;
private float y;
public Vector2D(float x,float y){
this.setX(x);
this.setY(y);
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
/**
* Add a vector this vector
* @param a Vector2D
*/
public void add(Vector2D v2d){
this.setX(this.getX()+v2d.getX());
this.setY(this.getY()+v2d.getY());
}
/**
* Subtract a vector from this vector
* @param a Vector2D
*/
public void subtract(Vector2D v2d){
this.x=this.getX()-v2d.getX();
this.y=this.getY()-v2d.getY();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector2D other = (Vector2D) obj;
- if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x))
+ if (Float.floatToIntBits(x) != Float.floatToIntBits(other.getX()))
return false;
- if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y))
+ if (Float.floatToIntBits(y) != Float.floatToIntBits(other.getY()))
return false;
return true;
}
public Vector2D(Vector2D v2d){
this(v2d.getX(),v2d.getY());
}
}
| false | true | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector2D other = (Vector2D) obj;
if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x))
return false;
if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y))
return false;
return true;
}
| public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector2D other = (Vector2D) obj;
if (Float.floatToIntBits(x) != Float.floatToIntBits(other.getX()))
return false;
if (Float.floatToIntBits(y) != Float.floatToIntBits(other.getY()))
return false;
return true;
}
|
diff --git a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/operation/DartModelOperation.java b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/operation/DartModelOperation.java
index 10893a000..2c3f1d52b 100644
--- a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/operation/DartModelOperation.java
+++ b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/operation/DartModelOperation.java
@@ -1,1027 +1,1026 @@
/*
* Copyright (c) 2011, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html
*
* 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.dart.tools.core.internal.operation;
import com.google.dart.tools.core.DartCore;
import com.google.dart.tools.core.buffer.Buffer;
import com.google.dart.tools.core.internal.buffer.DocumentAdapter;
import com.google.dart.tools.core.internal.model.DartElementImpl;
import com.google.dart.tools.core.internal.model.DartModelManager;
import com.google.dart.tools.core.internal.model.DartModelStatusImpl;
import com.google.dart.tools.core.internal.model.delta.DartElementDeltaImpl;
import com.google.dart.tools.core.internal.model.delta.DeltaProcessor;
import com.google.dart.tools.core.internal.util.Messages;
import com.google.dart.tools.core.model.CompilationUnit;
import com.google.dart.tools.core.model.DartElement;
import com.google.dart.tools.core.model.DartElementDelta;
import com.google.dart.tools.core.model.DartModel;
import com.google.dart.tools.core.model.DartModelException;
import com.google.dart.tools.core.model.DartModelStatus;
import com.google.dart.tools.core.model.DartModelStatusConstants;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.TextEdit;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
/**
* The class <code>DartModelOperation</code> defines the behavior common to all Dart Model
* operations
*/
public abstract class DartModelOperation implements IWorkspaceRunnable, IProgressMonitor {
protected interface IPostAction {
/*
* Returns the id of this action.
*
* @see DartModelOperation#postAction
*/
String getID();
/*
* Run this action.
*/
void run() throws DartModelException;
}
/*
* Constants controlling the insertion mode of an action.
*
* @see DartModelOperation#postAction
*/
// insert at the end
protected static final int APPEND = 1;
// remove all existing ones with same ID, and add new one at the end
protected static final int REMOVEALL_APPEND = 2;
// do not insert if already existing with same ID
protected static final int KEEP_EXISTING = 3;
/*
* Whether tracing post actions is enabled.
*/
protected static boolean POST_ACTION_VERBOSE;
/**
* Return the attribute registered at the given key with the top level operation. Returns
* <code>null</code> if no such attribute is found.
*
* @return the attribute registered at the given key with the top level operation
*/
protected static Object getAttribute(Object key) {
ArrayList<DartModelOperation> stack = getCurrentOperationStack();
if (stack.size() == 0) {
return null;
}
DartModelOperation topLevelOp = stack.get(0);
if (topLevelOp.attributes == null) {
return null;
} else {
return topLevelOp.attributes.get(key);
}
}
/**
* Return the stack of operations running in the current thread. Returns an empty stack if no
* operations are currently running in this thread.
*
* @return the stack of operations running in the current thread
*/
protected static ArrayList<DartModelOperation> getCurrentOperationStack() {
ArrayList<DartModelOperation> stack = OPERATION_STACKS.get();
if (stack == null) {
stack = new ArrayList<DartModelOperation>();
OPERATION_STACKS.set(stack);
}
return stack;
}
/**
* Register the given attribute at the given key with the top level operation.
*
* @param key the key with which the attribute is to be registered
* @param attribute the attribute to be registered
*/
protected static void setAttribute(String key, String attribute) {
ArrayList<DartModelOperation> operationStack = getCurrentOperationStack();
if (operationStack.size() == 0) {
return;
}
DartModelOperation topLevelOp = operationStack.get(0);
if (topLevelOp.attributes == null) {
topLevelOp.attributes = new HashMap<String, String>();
}
topLevelOp.attributes.put(key, attribute);
}
/*
* A list of IPostActions.
*/
protected IPostAction[] actions;
protected int actionsStart = 0;
protected int actionsEnd = -1;
/*
* A HashMap of attributes that can be used by operations.
*/
// This used to be <Object, Object>
protected HashMap<String, String> attributes;
public static final String HAS_MODIFIED_RESOURCE_ATTR = "hasModifiedResource"; //$NON-NLS-1$
public static final String TRUE = "true"; // DartModelManager.TRUE;
// public static final String FALSE = "false";
/**
* The elements this operation operates on, or <code>null</code> if this operation does not
* operate on specific elements.
*/
protected DartElement[] elementsToProcess;
/**
* The parent elements this operation operates with or <code>null</code> if this operation does
* not operate with specific parent elements.
*/
protected DartElement[] parentElements;
/**
* An empty collection of <code>DartElement</code>s - the common empty result if no elements are
* created, or if this operation is not actually executed.
*/
protected static final DartElement[] NO_ELEMENTS = new DartElement[] {};
/**
* The elements created by this operation - empty until the operation actually creates elements.
*/
protected DartElement[] resultElements = NO_ELEMENTS;
/**
* The progress monitor passed into this operation
*/
public IProgressMonitor progressMonitor = null;
/**
* A flag indicating whether this operation is nested.
*/
protected boolean isNested = false;
/**
* Conflict resolution policy - by default do not force (fail on a conflict).
*/
protected boolean force = false;
/*
* A per thread stack of Dart model operations.
*/
protected static final ThreadLocal<ArrayList<DartModelOperation>> OPERATION_STACKS = new ThreadLocal<ArrayList<DartModelOperation>>();
protected DartModelOperation() {
// default constructor used in subclasses
}
/**
* Common constructor for all Dart Model operations.
*/
protected DartModelOperation(DartElement element) {
this.elementsToProcess = new DartElement[] {element};
}
/**
* A common constructor for all Dart Model operations.
*/
protected DartModelOperation(DartElement[] elements) {
this.elementsToProcess = elements;
}
/**
* A common constructor for all Dart Model operations.
*/
protected DartModelOperation(DartElement[] elements, boolean force) {
this.elementsToProcess = elements;
this.force = force;
}
/**
* Common constructor for all Dart Model operations.
*/
protected DartModelOperation(DartElement[] elementsToProcess, DartElement[] parentElements) {
this.elementsToProcess = elementsToProcess;
this.parentElements = parentElements;
}
/**
* A common constructor for all Dart Model operations.
*/
protected DartModelOperation(DartElement[] elementsToProcess, DartElement[] parentElements,
boolean force) {
this.elementsToProcess = elementsToProcess;
this.parentElements = parentElements;
this.force = force;
}
@Override
public void beginTask(String name, int totalWork) {
if (progressMonitor != null) {
progressMonitor.beginTask(name, totalWork);
}
}
@Override
public void done() {
if (progressMonitor != null) {
progressMonitor.done();
}
}
/**
* Convenience method to run an operation within this operation.
*/
public void executeNestedOperation(DartModelOperation operation, int subWorkAmount)
throws DartModelException {
DartModelStatus status = operation.verify();
if (!status.isOK()) {
throw new DartModelException(status);
}
IProgressMonitor subProgressMonitor = getSubProgressMonitor(subWorkAmount);
// fix for 1FW7IKC, part (1)
try {
operation.setNested(true);
operation.run(subProgressMonitor);
} catch (CoreException ce) {
if (ce instanceof DartModelException) {
throw (DartModelException) ce;
} else {
// translate the core exception to a Dart model exception
if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
Throwable e = ce.getStatus().getException();
if (e instanceof DartModelException) {
throw (DartModelException) e;
}
}
throw new DartModelException(ce);
}
}
}
/**
* Return the Dart Model this operation is operating in.
*
* @return the Dart Model this operation is operating in
*/
public DartModel getDartModel() {
return DartModelManager.getInstance().getDartModel();
}
/**
* Return the elements created by this operation.
*
* @return the elements created by this operation
*/
public DartElement[] getResultElements() {
return resultElements;
}
/**
* Return <code>true</code> if this operation has performed any resource modifications. Return
* <code>false</code> if this operation has not been executed yet.
*/
public boolean hasModifiedResource() {
return !isReadOnly() && getAttribute(HAS_MODIFIED_RESOURCE_ATTR) == TRUE;
}
@Override
public void internalWorked(double work) {
if (progressMonitor != null) {
progressMonitor.internalWorked(work);
}
}
@Override
public boolean isCanceled() {
if (progressMonitor != null) {
return progressMonitor.isCanceled();
}
return false;
}
/**
* Return <code>true</code> if this operation performs no resource modifications, otherwise
* <code>false</code>. Subclasses must override.
*/
public boolean isReadOnly() {
return false;
}
/**
* Create and return a new delta on the Dart Model.
*
* @return the delta that was created
*/
public DartElementDeltaImpl newDartElementDelta() {
return new DartElementDeltaImpl(getDartModel());
}
/**
* Run this operation and register any deltas created.
*
* @throws CoreException if the operation fails
*/
@Override
public void run(IProgressMonitor monitor) throws CoreException {
DartCore.notYetImplemented();
DartModelManager manager = DartModelManager.getInstance();
DeltaProcessor deltaProcessor = manager.getDeltaProcessor();
int previousDeltaCount = deltaProcessor.dartModelDeltas.size();
try {
progressMonitor = monitor;
pushOperation(this);
try {
if (canModifyRoots()) {
// // computes the root infos before executing the operation
// // noop if already initialized
// DartModelManager.getInstance().getDeltaState().initializeRoots(false);
}
executeOperation();
} finally {
if (isTopLevelOperation()) {
runPostActions();
}
}
} finally {
try {
// re-acquire delta processor as it can have been reset during
// executeOperation()
deltaProcessor = manager.getDeltaProcessor();
// update DartModel using deltas that were recorded during this
// operation
for (int i = previousDeltaCount, size = deltaProcessor.dartModelDeltas.size(); i < size; i++) {
deltaProcessor.updateDartModel(deltaProcessor.dartModelDeltas.get(i));
}
// // close the parents of the created elements and reset their
// // project's cache (in case we are in an IWorkspaceRunnable and the
// // clients wants to use the created element's parent)
// // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646
// for (int i = 0, length = resultElements.length; i < length; i++)
// {
// DartElement element = resultElements[i];
// Openable openable = (Openable) element.getOpenable();
// if (!(openable instanceof CompilationUnit) || !((CompilationUnit)
// openable).isWorkingCopy()) { // a working copy must remain a child of
// its parent even after a move
// ((DartElementImpl) openable.getParent()).close();
// }
// switch (element.getElementType()) {
// case DartElement.PACKAGE_FRAGMENT_ROOT:
// case DartElement.PACKAGE_FRAGMENT:
// deltaProcessor.projectCachesToReset.add(element.getDartProject());
// break;
// }
// }
deltaProcessor.resetProjectCaches();
// fire only iff:
// - the operation is a top level operation
// - the operation did produce some delta(s)
// - but the operation has not modified any resource
if (isTopLevelOperation()) {
- // if ((deltaProcessor.dartModelDeltas.size() > previousDeltaCount ||
- // !deltaProcessor.reconcileDeltas.isEmpty())
- // && !hasModifiedResource()) {
- // deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT);
- // } // else deltas are fired while processing the resource delta
+ if ((deltaProcessor.dartModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty())
+ && !hasModifiedResource()) {
+ deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT);
+ } // else deltas are fired while processing the resource delta
}
} finally {
popOperation();
}
}
}
/**
* Main entry point for Dart Model operations. Runs a Dart Model Operation as an
* IWorkspaceRunnable if not read-only.
*/
public void runOperation(IProgressMonitor monitor) throws DartModelException {
DartModelStatus status = verify();
if (!status.isOK()) {
throw new DartModelException(status);
}
try {
if (isReadOnly()) {
run(monitor);
} else {
// Use IWorkspace.run(...) to ensure that resource changes are batched
// Note that if the tree is locked, this will throw a CoreException, but
// this is ok as this operation is modifying the tree (not read-only)
// and a CoreException will be thrown anyway.
ResourcesPlugin.getWorkspace().run(this, getSchedulingRule(), IWorkspace.AVOID_UPDATE,
monitor);
}
} catch (CoreException ce) {
if (ce instanceof DartModelException) {
throw (DartModelException) ce;
} else {
if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
Throwable e = ce.getStatus().getException();
if (e instanceof DartModelException) {
throw (DartModelException) e;
}
}
throw new DartModelException(ce);
}
}
}
@Override
public void setCanceled(boolean b) {
if (progressMonitor != null) {
progressMonitor.setCanceled(b);
}
}
@Override
public void setTaskName(String name) {
if (progressMonitor != null) {
progressMonitor.setTaskName(name);
}
}
@Override
public void subTask(String name) {
if (progressMonitor != null) {
progressMonitor.subTask(name);
}
}
@Override
public void worked(int work) {
if (progressMonitor != null) {
progressMonitor.worked(work);
checkCanceled();
}
}
/**
* Register the given action at the end of the list of actions to run.
*/
protected void addAction(IPostAction action) {
int length = actions.length;
if (length == ++actionsEnd) {
System.arraycopy(actions, 0, actions = new IPostAction[length * 2], 0, length);
}
actions[actionsEnd] = action;
}
/**
* Register the given delta with the Dart Model Manager.
*/
protected void addDelta(DartElementDelta delta) {
DartModelManager.getInstance().getDeltaProcessor().registerDartModelDelta(delta);
}
/**
* Register the given reconcile delta with the Dart Model Manager.
*
* @param workingCopy the working copy with which the delta is to be associated
* @param delta the delta to be added
*/
protected void addReconcileDelta(CompilationUnit workingCopy, DartElementDeltaImpl delta) {
HashMap<CompilationUnit, DartElementDelta> reconcileDeltas = DartModelManager.getInstance().getDeltaProcessor().reconcileDeltas;
DartElementDeltaImpl previousDelta = (DartElementDeltaImpl) reconcileDeltas.get(workingCopy);
if (previousDelta != null) {
DartElementDelta[] children = delta.getAffectedChildren();
for (int i = 0, length = children.length; i < length; i++) {
DartElementDeltaImpl child = (DartElementDeltaImpl) children[i];
previousDelta.insertDeltaTree(child.getElement(), child);
}
// note that the last delta's AST always takes precedence over the
// existing delta's AST since it is the result of the last reconcile
// operation
if ((delta.getFlags() & DartElementDelta.F_AST_AFFECTED) != 0) {
previousDelta.changedAST(delta.getCompilationUnitAST());
}
} else {
reconcileDeltas.put(workingCopy, delta);
}
}
protected void applyTextEdit(CompilationUnit cu, TextEdit edits) throws DartModelException {
try {
edits.apply(getDocument(cu));
} catch (BadLocationException e) {
// content changed under us
throw new DartModelException(e, DartModelStatusConstants.INVALID_CONTENTS);
}
}
/**
* Return <code>true</code> if this operation can modify the package fragment roots.
*
* @return <code>true</code> if this operation can modify the package fragment roots
*/
protected boolean canModifyRoots() {
return false;
}
/**
* Checks with the progress monitor to see whether this operation should be canceled. An operation
* should regularly call this method during its operation so that the user can cancel it.
*
* @throws OperationCanceledException if cancelling the operation has been requested
*/
protected void checkCanceled() {
if (isCanceled()) {
throw new OperationCanceledException(Messages.operation_cancelled);
}
}
/**
* Common code used to verify the elements this operation is processing.
*/
protected DartModelStatus commonVerify() {
if (elementsToProcess == null || elementsToProcess.length == 0) {
return new DartModelStatusImpl(DartModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
}
for (int i = 0; i < elementsToProcess.length; i++) {
if (elementsToProcess[i] == null) {
return new DartModelStatusImpl(DartModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
}
}
return DartModelStatusImpl.VERIFIED_OK;
}
/**
* Convenience method to copy resources.
*/
protected void copyResources(IResource[] resources, IPath container) throws DartModelException {
IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
try {
for (int i = 0, length = resources.length; i < length; i++) {
IResource resource = resources[i];
IPath destination = container.append(resource.getName());
if (root.findMember(destination) == null) {
resource.copy(destination, false, subProgressMonitor);
}
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new DartModelException(e);
}
}
/**
* Convenience method to create a file.
*/
protected void createFile(IContainer folder, String name, InputStream contents, boolean forceFlag)
throws DartModelException {
IFile file = folder.getFile(new Path(name));
try {
file.create(contents, forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY
: IResource.KEEP_HISTORY, getSubProgressMonitor(1));
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new DartModelException(e);
}
}
/**
* Convenience method to create a folder.
*/
protected void createFolder(IContainer parentFolder, String name, boolean forceFlag)
throws DartModelException {
IFolder folder = parentFolder.getFolder(new Path(name));
try {
// we should use true to create the file locally. Only VCM should use
// true/false
folder.create(forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
true, // local
getSubProgressMonitor(1));
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new DartModelException(e);
}
}
/**
* Convenience method to delete an empty package fragment.
*/
// protected void deleteEmptyPackageFragment(
// IPackageFragment fragment,
// boolean forceFlag,
// IResource rootResource)
// throws DartModelException {
// IContainer resource = (IContainer) ((DartElementImpl)fragment).resource();
// try {
// resource.delete(
// forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY :
// IResource.KEEP_HISTORY,
// getSubProgressMonitor(1));
// setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
// while (resource instanceof IFolder) {
// // deleting a package: delete the parent if it is empty (e.g. deleting x.y
// where folder x doesn't have resources but y)
// // without deleting the package fragment root
// resource = resource.getParent();
// if (!resource.equals(rootResource) && resource.members().length == 0) {
// resource.delete(
// forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY :
// IResource.KEEP_HISTORY,
// getSubProgressMonitor(1));
// setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
// }
// }
// } catch (CoreException e) {
// throw new DartModelException(e);
// }
// }
/**
* Convenience method to delete a single resource.
*/
protected void deleteResource(IResource resource, int flags) throws DartModelException {
try {
resource.delete(flags, getSubProgressMonitor(1));
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new DartModelException(e);
}
}
/**
* Convenience method to delete resources.
*/
protected void deleteResources(IResource[] resources, boolean forceFlag)
throws DartModelException {
if (resources == null || resources.length == 0) {
return;
}
IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
IWorkspace workspace = resources[0].getWorkspace();
try {
workspace.delete(resources, forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY
: IResource.KEEP_HISTORY, subProgressMonitor);
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new DartModelException(e);
}
}
/**
* Return <code>true</code> if the given path is equals to one of the given other paths.
*/
protected boolean equalsOneOf(IPath path, IPath[] otherPaths) {
for (int i = 0, length = otherPaths.length; i < length; i++) {
if (path.equals(otherPaths[i])) {
return true;
}
}
return false;
}
/**
* Perform the operation specific behavior. Subclasses must override.
*/
protected abstract void executeOperation() throws DartModelException;
/**
* Return the index of the first registered action with the given id, starting from a given
* position, or -1 if not found.
*
* @return the index of the first registered action with the given id
*/
protected int firstActionWithID(String id, int start) {
for (int i = start; i <= actionsEnd; i++) {
if (actions[i].getID().equals(id)) {
return i;
}
}
return -1;
}
/**
* Return the compilation unit the given element is contained in, or the element itself (if it is
* a compilation unit), otherwise <code>null</code>.
*
* @return the compilation unit the given element is contained in
*/
protected CompilationUnit getCompilationUnitFor(DartElement element) {
return ((DartElementImpl) element).getCompilationUnit();
}
/**
* Return the existing document for the given compilation unit, or a DocumentAdapter if none.
*
* @return the existing document for the given compilation unit
*/
protected IDocument getDocument(CompilationUnit cu) throws DartModelException {
Buffer buffer = cu.getBuffer();
if (buffer instanceof IDocument) {
return (IDocument) buffer;
}
return new DocumentAdapter(buffer);
}
/**
* Return the element to which this operation applies, or <code>null</code> if not applicable.
*
* @return the element to which this operation applies
*/
protected DartElement getElementToProcess() {
if (elementsToProcess == null || elementsToProcess.length == 0) {
return null;
}
return elementsToProcess[0];
}
// protected IPath[] getNestedFolders(IPackageFragmentRoot root) throws
// DartModelException {
// IPath rootPath = root.getPath();
// IClasspathEntry[] classpath = root.getDartProject().getRawClasspath();
// int length = classpath.length;
// IPath[] result = new IPath[length];
// int index = 0;
// for (int i = 0; i < length; i++) {
// IPath path = classpath[i].getPath();
// if (rootPath.isPrefixOf(path) && !rootPath.equals(path)) {
// result[index++] = path;
// }
// }
// if (index < length) {
// System.arraycopy(result, 0, result = new IPath[index], 0, index);
// }
// return result;
// }
/**
* Return the parent element to which this operation applies, or <code>null</code> if not
* applicable.
*
* @return the parent element to which this operation applies
*/
protected DartElement getParentElement() {
if (parentElements == null || parentElements.length == 0) {
return null;
}
return parentElements[0];
}
/**
* Return the parent elements to which this operation applies, or <code>null</code> if not
* applicable.
*
* @return the parent elements to which this operation applies
*/
protected DartElement[] getParentElements() {
return parentElements;
}
/**
* Return the scheduling rule for this operation (i.e. the resource that needs to be locked while
* this operation is running). Subclasses can override.
*
* @return the scheduling rule for this operation
*/
protected ISchedulingRule getSchedulingRule() {
return ResourcesPlugin.getWorkspace().getRoot();
}
/**
* Create and return a sub-progress monitor if appropriate.
*
* @return the sub-progress monitor that was created
*/
protected IProgressMonitor getSubProgressMonitor(int workAmount) {
IProgressMonitor sub = null;
if (progressMonitor != null) {
sub = new SubProgressMonitor(progressMonitor, workAmount,
SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
}
return sub;
}
/**
* Return <code>true</code> if this operation is the first operation to run in the current thread.
*
* @return <code>true</code> if this operation is the first operation to run in the current thread
*/
protected boolean isTopLevelOperation() {
ArrayList<DartModelOperation> stack = getCurrentOperationStack();
return stack.size() > 0 && stack.get(0) == this;
}
/**
* Convenience method to move resources.
*/
protected void moveResources(IResource[] resources, IPath container) throws DartModelException {
IProgressMonitor subProgressMonitor = null;
if (progressMonitor != null) {
subProgressMonitor = new SubProgressMonitor(progressMonitor, resources.length,
SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
}
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
try {
for (int i = 0, length = resources.length; i < length; i++) {
IResource resource = resources[i];
IPath destination = container.append(resource.getName());
if (root.findMember(destination) == null) {
resource.move(destination, false, subProgressMonitor);
}
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException exception) {
throw new DartModelException(exception);
}
}
/**
* Remove the last pushed operation from the stack of running operations. Return the popped
* operation, or <code>null<code> if the stack was empty.
*
* @return the popped operation
*/
protected DartModelOperation popOperation() {
ArrayList<DartModelOperation> stack = getCurrentOperationStack();
int size = stack.size();
if (size > 0) {
if (size == 1) { // top level operation
// release reference (see
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=33927)
OPERATION_STACKS.set(null);
}
return stack.remove(size - 1);
} else {
return null;
}
}
/**
* Register the given action to be run when the outer most Dart model operation has finished. The
* insertion mode controls whether: - the action should discard all existing actions with the same
* id, and be queued at the end (REMOVEALL_APPEND), - the action should be ignored if there is
* already an action with the same id (KEEP_EXISTING), - the action should be queued at the end
* without looking at existing actions (APPEND)
*/
protected void postAction(IPostAction action, int insertionMode) {
if (POST_ACTION_VERBOSE) {
System.out.print("(" + Thread.currentThread() + ") [DartModelOperation.postAction(IPostAction, int)] Posting action " + action.getID()); //$NON-NLS-1$ //$NON-NLS-2$
switch (insertionMode) {
case REMOVEALL_APPEND:
System.out.println(" (REMOVEALL_APPEND)"); //$NON-NLS-1$
break;
case KEEP_EXISTING:
System.out.println(" (KEEP_EXISTING)"); //$NON-NLS-1$
break;
case APPEND:
System.out.println(" (APPEND)"); //$NON-NLS-1$
break;
}
}
DartModelOperation topLevelOp = getCurrentOperationStack().get(0);
IPostAction[] postActions = topLevelOp.actions;
if (postActions == null) {
topLevelOp.actions = postActions = new IPostAction[1];
postActions[0] = action;
topLevelOp.actionsEnd = 0;
} else {
String id = action.getID();
switch (insertionMode) {
case REMOVEALL_APPEND:
int index = actionsStart - 1;
while ((index = topLevelOp.firstActionWithID(id, index + 1)) >= 0) {
// remove action[index]
System.arraycopy(postActions, index + 1, postActions, index, topLevelOp.actionsEnd
- index);
postActions[topLevelOp.actionsEnd--] = null;
}
topLevelOp.addAction(action);
break;
case KEEP_EXISTING:
if (topLevelOp.firstActionWithID(id, 0) < 0) {
topLevelOp.addAction(action);
}
break;
case APPEND:
topLevelOp.addAction(action);
break;
}
}
}
/**
* Return <code>true</code> if the given path is the prefix of one of the given other paths.
*
* @return <code>true</code> if the given path is the prefix of one of the given other paths
*/
protected boolean prefixesOneOf(IPath path, IPath[] otherPaths) {
for (int i = 0, length = otherPaths.length; i < length; i++) {
if (path.isPrefixOf(otherPaths[i])) {
return true;
}
}
return false;
}
/**
* Push the given operation on the stack of operations currently running in this thread.
*
* @param operation the operation to be pushed
*/
protected void pushOperation(DartModelOperation operation) {
getCurrentOperationStack().add(operation);
}
/**
* Remove all actions with the given id from the queue of post actions. Does nothing if no such
* action is in the queue.
*
* @param actionID the id of the actions to be removed
*/
protected void removeAllPostAction(String actionID) {
if (POST_ACTION_VERBOSE) {
System.out.println("(" + Thread.currentThread() + ") [DartModelOperation.removeAllPostAction(String)] Removing actions " + actionID); //$NON-NLS-1$ //$NON-NLS-2$
}
DartModelOperation topLevelOp = getCurrentOperationStack().get(0);
IPostAction[] postActions = topLevelOp.actions;
if (postActions == null) {
return;
}
int index = actionsStart - 1;
while ((index = topLevelOp.firstActionWithID(actionID, index + 1)) >= 0) {
// remove action[index]
System.arraycopy(postActions, index + 1, postActions, index, topLevelOp.actionsEnd - index);
postActions[topLevelOp.actionsEnd--] = null;
}
}
/**
* Unregister the reconcile delta for the given working copy.
*
* @param workingCopy the working copy whose delta is to be removed
*/
protected void removeReconcileDelta(CompilationUnit workingCopy) {
DartCore.notYetImplemented();
// DartModelManager.getInstance().getDeltaProcessor().reconcileDeltas.remove(workingCopy);
}
protected void runPostActions() throws DartModelException {
while (actionsStart <= actionsEnd) {
IPostAction postAction = actions[actionsStart++];
if (POST_ACTION_VERBOSE) {
System.out.println("(" + Thread.currentThread() + ") [DartModelOperation.runPostActions()] Running action " + postAction.getID()); //$NON-NLS-1$ //$NON-NLS-2$
}
postAction.run();
}
}
/**
* Set whether this operation is nested or not.
*
* @see CreateElementInCUOperation#checkCanceled
*/
protected void setNested(boolean nested) {
isNested = nested;
}
/**
* Return a status indicating whether there is any known reason this operation will fail.
* Operations are verified before they are run.
* <p>
* Subclasses must override if they have any conditions to verify before this operation executes.
*/
protected DartModelStatus verify() {
return commonVerify();
}
}
| true | true | public void run(IProgressMonitor monitor) throws CoreException {
DartCore.notYetImplemented();
DartModelManager manager = DartModelManager.getInstance();
DeltaProcessor deltaProcessor = manager.getDeltaProcessor();
int previousDeltaCount = deltaProcessor.dartModelDeltas.size();
try {
progressMonitor = monitor;
pushOperation(this);
try {
if (canModifyRoots()) {
// // computes the root infos before executing the operation
// // noop if already initialized
// DartModelManager.getInstance().getDeltaState().initializeRoots(false);
}
executeOperation();
} finally {
if (isTopLevelOperation()) {
runPostActions();
}
}
} finally {
try {
// re-acquire delta processor as it can have been reset during
// executeOperation()
deltaProcessor = manager.getDeltaProcessor();
// update DartModel using deltas that were recorded during this
// operation
for (int i = previousDeltaCount, size = deltaProcessor.dartModelDeltas.size(); i < size; i++) {
deltaProcessor.updateDartModel(deltaProcessor.dartModelDeltas.get(i));
}
// // close the parents of the created elements and reset their
// // project's cache (in case we are in an IWorkspaceRunnable and the
// // clients wants to use the created element's parent)
// // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646
// for (int i = 0, length = resultElements.length; i < length; i++)
// {
// DartElement element = resultElements[i];
// Openable openable = (Openable) element.getOpenable();
// if (!(openable instanceof CompilationUnit) || !((CompilationUnit)
// openable).isWorkingCopy()) { // a working copy must remain a child of
// its parent even after a move
// ((DartElementImpl) openable.getParent()).close();
// }
// switch (element.getElementType()) {
// case DartElement.PACKAGE_FRAGMENT_ROOT:
// case DartElement.PACKAGE_FRAGMENT:
// deltaProcessor.projectCachesToReset.add(element.getDartProject());
// break;
// }
// }
deltaProcessor.resetProjectCaches();
// fire only iff:
// - the operation is a top level operation
// - the operation did produce some delta(s)
// - but the operation has not modified any resource
if (isTopLevelOperation()) {
// if ((deltaProcessor.dartModelDeltas.size() > previousDeltaCount ||
// !deltaProcessor.reconcileDeltas.isEmpty())
// && !hasModifiedResource()) {
// deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT);
// } // else deltas are fired while processing the resource delta
}
} finally {
popOperation();
}
}
}
| public void run(IProgressMonitor monitor) throws CoreException {
DartCore.notYetImplemented();
DartModelManager manager = DartModelManager.getInstance();
DeltaProcessor deltaProcessor = manager.getDeltaProcessor();
int previousDeltaCount = deltaProcessor.dartModelDeltas.size();
try {
progressMonitor = monitor;
pushOperation(this);
try {
if (canModifyRoots()) {
// // computes the root infos before executing the operation
// // noop if already initialized
// DartModelManager.getInstance().getDeltaState().initializeRoots(false);
}
executeOperation();
} finally {
if (isTopLevelOperation()) {
runPostActions();
}
}
} finally {
try {
// re-acquire delta processor as it can have been reset during
// executeOperation()
deltaProcessor = manager.getDeltaProcessor();
// update DartModel using deltas that were recorded during this
// operation
for (int i = previousDeltaCount, size = deltaProcessor.dartModelDeltas.size(); i < size; i++) {
deltaProcessor.updateDartModel(deltaProcessor.dartModelDeltas.get(i));
}
// // close the parents of the created elements and reset their
// // project's cache (in case we are in an IWorkspaceRunnable and the
// // clients wants to use the created element's parent)
// // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646
// for (int i = 0, length = resultElements.length; i < length; i++)
// {
// DartElement element = resultElements[i];
// Openable openable = (Openable) element.getOpenable();
// if (!(openable instanceof CompilationUnit) || !((CompilationUnit)
// openable).isWorkingCopy()) { // a working copy must remain a child of
// its parent even after a move
// ((DartElementImpl) openable.getParent()).close();
// }
// switch (element.getElementType()) {
// case DartElement.PACKAGE_FRAGMENT_ROOT:
// case DartElement.PACKAGE_FRAGMENT:
// deltaProcessor.projectCachesToReset.add(element.getDartProject());
// break;
// }
// }
deltaProcessor.resetProjectCaches();
// fire only iff:
// - the operation is a top level operation
// - the operation did produce some delta(s)
// - but the operation has not modified any resource
if (isTopLevelOperation()) {
if ((deltaProcessor.dartModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty())
&& !hasModifiedResource()) {
deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT);
} // else deltas are fired while processing the resource delta
}
} finally {
popOperation();
}
}
}
|
diff --git a/pmd/src/main/java/net/sourceforge/pmd/lang/java/rule/javabeans/BeanMembersShouldSerializeRule.java b/pmd/src/main/java/net/sourceforge/pmd/lang/java/rule/javabeans/BeanMembersShouldSerializeRule.java
index 286e09118..52b96866a 100644
--- a/pmd/src/main/java/net/sourceforge/pmd/lang/java/rule/javabeans/BeanMembersShouldSerializeRule.java
+++ b/pmd/src/main/java/net/sourceforge/pmd/lang/java/rule/javabeans/BeanMembersShouldSerializeRule.java
@@ -1,113 +1,114 @@
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.javabeans;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator;
import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType;
import net.sourceforge.pmd.lang.java.ast.ASTResultType;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
import net.sourceforge.pmd.lang.java.symboltable.MethodNameDeclaration;
import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;
import net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration;
import net.sourceforge.pmd.lang.rule.properties.StringProperty;
public class BeanMembersShouldSerializeRule extends AbstractJavaRule {
private String prefixProperty;
private static final StringProperty PREFIX_DESCRIPTOR = new StringProperty("prefix", "A variable prefix to skip, i.e., m_",
"", 1.0f);
public BeanMembersShouldSerializeRule() {
definePropertyDescriptor(PREFIX_DESCRIPTOR);
}
@Override
public Object visit(ASTCompilationUnit node, Object data) {
prefixProperty = getProperty(PREFIX_DESCRIPTOR);
super.visit(node, data);
return data;
}
private static String[] imagesOf(List<? extends Node> nodes) {
String[] imageArray = new String[nodes.size()];
for (int i = 0; i < nodes.size(); i++) {
imageArray[i] = nodes.get(i).getImage();
}
return imageArray;
}
@Override
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if (node.isInterface()) {
return data;
}
Map<MethodNameDeclaration, List<NameOccurrence>> methods = node.getScope().getEnclosingClassScope()
.getMethodDeclarations();
List<ASTMethodDeclarator> getSetMethList = new ArrayList<ASTMethodDeclarator>(methods.size());
for (MethodNameDeclaration d : methods.keySet()) {
ASTMethodDeclarator mnd = d.getMethodNameDeclaratorNode();
if (isBeanAccessor(mnd)) {
getSetMethList.add(mnd);
}
}
String[] methNameArray = imagesOf(getSetMethList);
Arrays.sort(methNameArray);
Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope().getVariableDeclarations();
for (VariableNameDeclaration decl : vars.keySet()) {
if (vars.get(decl).isEmpty() || decl.getAccessNodeParent().isTransient()
|| decl.getAccessNodeParent().isStatic()) {
continue;
}
String varName = trimIfPrefix(decl.getImage());
varName = varName.substring(0, 1).toUpperCase() + varName.substring(1, varName.length());
boolean hasGetMethod = Arrays.binarySearch(methNameArray, "get" + varName) >= 0
|| Arrays.binarySearch(methNameArray, "is" + varName) >= 0;
boolean hasSetMethod = Arrays.binarySearch(methNameArray, "set" + varName) >= 0;
- if (!hasGetMethod || !hasSetMethod) {
+ // Note that a Setter method is not applicable to a final variable...
+ if (!hasGetMethod || (!decl.getAccessNodeParent().isFinal() && !hasSetMethod)) {
addViolation(data, decl.getNode(), decl.getImage());
}
}
return super.visit(node, data);
}
private String trimIfPrefix(String img) {
if (prefixProperty != null && img.startsWith(prefixProperty)) {
return img.substring(prefixProperty.length());
}
return img;
}
private boolean isBeanAccessor(ASTMethodDeclarator meth) {
String methodName = meth.getImage();
if (methodName.startsWith("get") || methodName.startsWith("set")) {
return true;
}
if (methodName.startsWith("is")) {
ASTResultType ret = ((ASTMethodDeclaration) meth.jjtGetParent()).getResultType();
List<ASTPrimitiveType> primitives = ret.findDescendantsOfType(ASTPrimitiveType.class);
if (!primitives.isEmpty() && primitives.get(0).isBoolean()) {
return true;
}
}
return false;
}
}
| true | true | public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if (node.isInterface()) {
return data;
}
Map<MethodNameDeclaration, List<NameOccurrence>> methods = node.getScope().getEnclosingClassScope()
.getMethodDeclarations();
List<ASTMethodDeclarator> getSetMethList = new ArrayList<ASTMethodDeclarator>(methods.size());
for (MethodNameDeclaration d : methods.keySet()) {
ASTMethodDeclarator mnd = d.getMethodNameDeclaratorNode();
if (isBeanAccessor(mnd)) {
getSetMethList.add(mnd);
}
}
String[] methNameArray = imagesOf(getSetMethList);
Arrays.sort(methNameArray);
Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope().getVariableDeclarations();
for (VariableNameDeclaration decl : vars.keySet()) {
if (vars.get(decl).isEmpty() || decl.getAccessNodeParent().isTransient()
|| decl.getAccessNodeParent().isStatic()) {
continue;
}
String varName = trimIfPrefix(decl.getImage());
varName = varName.substring(0, 1).toUpperCase() + varName.substring(1, varName.length());
boolean hasGetMethod = Arrays.binarySearch(methNameArray, "get" + varName) >= 0
|| Arrays.binarySearch(methNameArray, "is" + varName) >= 0;
boolean hasSetMethod = Arrays.binarySearch(methNameArray, "set" + varName) >= 0;
if (!hasGetMethod || !hasSetMethod) {
addViolation(data, decl.getNode(), decl.getImage());
}
}
return super.visit(node, data);
}
| public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if (node.isInterface()) {
return data;
}
Map<MethodNameDeclaration, List<NameOccurrence>> methods = node.getScope().getEnclosingClassScope()
.getMethodDeclarations();
List<ASTMethodDeclarator> getSetMethList = new ArrayList<ASTMethodDeclarator>(methods.size());
for (MethodNameDeclaration d : methods.keySet()) {
ASTMethodDeclarator mnd = d.getMethodNameDeclaratorNode();
if (isBeanAccessor(mnd)) {
getSetMethList.add(mnd);
}
}
String[] methNameArray = imagesOf(getSetMethList);
Arrays.sort(methNameArray);
Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope().getVariableDeclarations();
for (VariableNameDeclaration decl : vars.keySet()) {
if (vars.get(decl).isEmpty() || decl.getAccessNodeParent().isTransient()
|| decl.getAccessNodeParent().isStatic()) {
continue;
}
String varName = trimIfPrefix(decl.getImage());
varName = varName.substring(0, 1).toUpperCase() + varName.substring(1, varName.length());
boolean hasGetMethod = Arrays.binarySearch(methNameArray, "get" + varName) >= 0
|| Arrays.binarySearch(methNameArray, "is" + varName) >= 0;
boolean hasSetMethod = Arrays.binarySearch(methNameArray, "set" + varName) >= 0;
// Note that a Setter method is not applicable to a final variable...
if (!hasGetMethod || (!decl.getAccessNodeParent().isFinal() && !hasSetMethod)) {
addViolation(data, decl.getNode(), decl.getImage());
}
}
return super.visit(node, data);
}
|
diff --git a/src/net/idlesoft/android/apps/github/ui/fragments/EventsFragment.java b/src/net/idlesoft/android/apps/github/ui/fragments/EventsFragment.java
index ffbe9e4..e6b5f05 100644
--- a/src/net/idlesoft/android/apps/github/ui/fragments/EventsFragment.java
+++ b/src/net/idlesoft/android/apps/github/ui/fragments/EventsFragment.java
@@ -1,452 +1,452 @@
/*
* Copyright (c) 2012 Eddie Ringle
* 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 net.idlesoft.android.apps.github.ui.fragments;
import android.accounts.AccountsException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.viewpagerindicator.TitlePageIndicator;
import net.idlesoft.android.apps.github.R;
import net.idlesoft.android.apps.github.ui.adapters.EventListAdapter;
import net.idlesoft.android.apps.github.ui.widgets.IdleList;
import net.idlesoft.android.apps.github.ui.widgets.ListViewPager;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GsonUtils;
import org.eclipse.egit.github.core.client.PageIterator;
import org.eclipse.egit.github.core.event.Event;
import org.eclipse.egit.github.core.service.EventService;
import java.io.IOException;
import java.util.ArrayList;
import static net.idlesoft.android.apps.github.HubroidConstants.ARG_TARGET_USER;
public
class EventsFragment extends UIFragment<EventsFragment.EventsDataFragment>
{
public static final int LIST_RECEIVED = 1;
public static final int LIST_PUBLIC = 2;
public static final int LIST_TIMELINE = 4;
protected
class ListHolder
{
ArrayList<Event> events;
CharSequence title;
ArrayList<Bitmap> gravatars;
int type;
PageIterator<Event> request;
}
public static
class EventsDataFragment extends DataFragment
{
ArrayList<ListHolder> eventLists;
User targetUser;
int currentItem;
int currentItemScroll;
public
int findListIndexByType(int listType)
{
if (eventLists == null) return -1;
for (ListHolder holder : eventLists) {
if (holder.type == listType)
return eventLists.indexOf(holder);
}
return -1;
}
}
ListViewPager mViewPager;
TitlePageIndicator mTitlePageIndicator;
int mCurrentPage;
public
EventsFragment()
{
super(EventsDataFragment.class);
}
@Override
public
View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (container == null)
getBaseActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
View v = inflater.inflate(R.layout.viewpager_fragment, container, false);
if (v != null) {
mViewPager = (ListViewPager) v.findViewById(R.id.vp_pages);
mTitlePageIndicator = (TitlePageIndicator) v.findViewById(R.id.tpi_header);
}
return v;
}
@Override
public
void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
final Bundle args = getArguments();
final String userJson;
if (args != null) {
userJson = args.getString(ARG_TARGET_USER, null);
if (userJson != null) {
mDataFragment.targetUser = GsonUtils.fromJson(userJson, User.class);
}
}
if (mDataFragment.targetUser == null) {
mDataFragment.targetUser = new User();
mDataFragment.targetUser.setLogin(getBaseActivity().getCurrentUserLogin());
}
if (mDataFragment.eventLists == null)
mDataFragment.eventLists = new ArrayList<ListHolder>();
ListViewPager.MultiListPagerAdapter adapter =
new ListViewPager.MultiListPagerAdapter(getContext());
if (mDataFragment.targetUser.getLogin().equals(getBaseActivity().getCurrentUserLogin())
&& !mDataFragment.targetUser.getLogin().equals("")) {
/* Display received events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_RECEIVED);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_RECEIVED;
holder.title = getString(R.string.events_received);
list.setTitle(holder.title);
holder.gravatars = new ArrayList<Bitmap>();
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable receivedRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
try {
Log.d("hubroid", "RECEIVED TASK");
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pageUserReceivedEvents(mDataFragment.targetUser.getLogin());
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.getProgressBar().setVisibility(View.GONE);
list.setListShown(true);
}
};
mDataFragment.executeNewTask(receivedRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
if (!mDataFragment.targetUser.getLogin().equals("")) {
/* Display a user's public events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_PUBLIC);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_PUBLIC;
holder.title = getString(R.string.events_public);
list.setTitle(holder.title);
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable publicRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
Log.d("hubroid", "PUBLIC TASKS");
try {
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pageUserEvents(mDataFragment.targetUser.getLogin());
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getProgressBar().setVisibility(View.GONE);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.setListShown(true);
}
};
mDataFragment.executeNewTask(publicRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
- { /* This bit causes some weird issue with egit-github at the moment, disabling */
+ {
/* Display timeline events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_TIMELINE);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_TIMELINE;
holder.title = getString(R.string.events_timeline);
list.setTitle(holder.title);
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable publicRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
try {
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pagePublicEvents(30);
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getProgressBar().setVisibility(View.GONE);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.setListShown(true);
}
};
mDataFragment.executeNewTask(publicRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
mViewPager.setAdapter(adapter);
mTitlePageIndicator.setViewPager(mViewPager);
mViewPager.setCurrentItem(mDataFragment.currentItem);
}
@Override
public
void onDestroy()
{
super.onDestroy();
mDataFragment.currentItem = mViewPager.getCurrentItem();
}
}
| true | true | void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
final Bundle args = getArguments();
final String userJson;
if (args != null) {
userJson = args.getString(ARG_TARGET_USER, null);
if (userJson != null) {
mDataFragment.targetUser = GsonUtils.fromJson(userJson, User.class);
}
}
if (mDataFragment.targetUser == null) {
mDataFragment.targetUser = new User();
mDataFragment.targetUser.setLogin(getBaseActivity().getCurrentUserLogin());
}
if (mDataFragment.eventLists == null)
mDataFragment.eventLists = new ArrayList<ListHolder>();
ListViewPager.MultiListPagerAdapter adapter =
new ListViewPager.MultiListPagerAdapter(getContext());
if (mDataFragment.targetUser.getLogin().equals(getBaseActivity().getCurrentUserLogin())
&& !mDataFragment.targetUser.getLogin().equals("")) {
/* Display received events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_RECEIVED);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_RECEIVED;
holder.title = getString(R.string.events_received);
list.setTitle(holder.title);
holder.gravatars = new ArrayList<Bitmap>();
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable receivedRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
try {
Log.d("hubroid", "RECEIVED TASK");
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pageUserReceivedEvents(mDataFragment.targetUser.getLogin());
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.getProgressBar().setVisibility(View.GONE);
list.setListShown(true);
}
};
mDataFragment.executeNewTask(receivedRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
if (!mDataFragment.targetUser.getLogin().equals("")) {
/* Display a user's public events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_PUBLIC);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_PUBLIC;
holder.title = getString(R.string.events_public);
list.setTitle(holder.title);
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable publicRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
Log.d("hubroid", "PUBLIC TASKS");
try {
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pageUserEvents(mDataFragment.targetUser.getLogin());
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getProgressBar().setVisibility(View.GONE);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.setListShown(true);
}
};
mDataFragment.executeNewTask(publicRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
{ /* This bit causes some weird issue with egit-github at the moment, disabling */
/* Display timeline events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_TIMELINE);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_TIMELINE;
holder.title = getString(R.string.events_timeline);
list.setTitle(holder.title);
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable publicRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
try {
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pagePublicEvents(30);
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getProgressBar().setVisibility(View.GONE);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.setListShown(true);
}
};
mDataFragment.executeNewTask(publicRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
mViewPager.setAdapter(adapter);
mTitlePageIndicator.setViewPager(mViewPager);
mViewPager.setCurrentItem(mDataFragment.currentItem);
}
| void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
final Bundle args = getArguments();
final String userJson;
if (args != null) {
userJson = args.getString(ARG_TARGET_USER, null);
if (userJson != null) {
mDataFragment.targetUser = GsonUtils.fromJson(userJson, User.class);
}
}
if (mDataFragment.targetUser == null) {
mDataFragment.targetUser = new User();
mDataFragment.targetUser.setLogin(getBaseActivity().getCurrentUserLogin());
}
if (mDataFragment.eventLists == null)
mDataFragment.eventLists = new ArrayList<ListHolder>();
ListViewPager.MultiListPagerAdapter adapter =
new ListViewPager.MultiListPagerAdapter(getContext());
if (mDataFragment.targetUser.getLogin().equals(getBaseActivity().getCurrentUserLogin())
&& !mDataFragment.targetUser.getLogin().equals("")) {
/* Display received events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_RECEIVED);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_RECEIVED;
holder.title = getString(R.string.events_received);
list.setTitle(holder.title);
holder.gravatars = new ArrayList<Bitmap>();
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable receivedRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
try {
Log.d("hubroid", "RECEIVED TASK");
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pageUserReceivedEvents(mDataFragment.targetUser.getLogin());
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.getProgressBar().setVisibility(View.GONE);
list.setListShown(true);
}
};
mDataFragment.executeNewTask(receivedRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
if (!mDataFragment.targetUser.getLogin().equals("")) {
/* Display a user's public events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_PUBLIC);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_PUBLIC;
holder.title = getString(R.string.events_public);
list.setTitle(holder.title);
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable publicRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
Log.d("hubroid", "PUBLIC TASKS");
try {
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pageUserEvents(mDataFragment.targetUser.getLogin());
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getProgressBar().setVisibility(View.GONE);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.setListShown(true);
}
};
mDataFragment.executeNewTask(publicRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
{
/* Display timeline events */
final IdleList<Event> list = new IdleList<Event>(getContext());
final ListHolder holder;
list.setAdapter(new EventListAdapter(getBaseActivity()));
final int index = mDataFragment.findListIndexByType(LIST_TIMELINE);
if (index >= 0) {
holder = mDataFragment.eventLists.get(index);
list.setTitle(holder.title);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
} else {
holder = new ListHolder();
holder.type = LIST_TIMELINE;
holder.title = getString(R.string.events_timeline);
list.setTitle(holder.title);
holder.events = new ArrayList<Event>();
mDataFragment.eventLists.add(holder);
final DataFragment.DataTask.DataTaskRunnable publicRunnable =
new DataFragment.DataTask.DataTaskRunnable()
{
@Override
public
void runTask() throws InterruptedException
{
try {
final EventService es =
new EventService(getBaseActivity().getGHClient());
PageIterator<Event> itr =
es.pagePublicEvents(30);
holder.events.addAll(itr.next());
} catch (IOException e) {
e.printStackTrace();
} catch (AccountsException e) {
e.printStackTrace();
}
}
};
final DataFragment.DataTask.DataTaskCallbacks receivedCallbacks =
new DataFragment.DataTask.DataTaskCallbacks()
{
@Override
public
void onTaskStart()
{
list.getProgressBar().setVisibility(View.VISIBLE);
list.setFooterShown(true);
list.setListShown(true);
}
@Override
public
void onTaskCancelled()
{
}
@Override
public
void onTaskComplete()
{
list.setListShown(false);
list.getProgressBar().setVisibility(View.GONE);
list.getListAdapter().fillWithItems(holder.events);
list.getListAdapter().notifyDataSetChanged();
list.setListShown(true);
}
};
mDataFragment.executeNewTask(publicRunnable, receivedCallbacks);
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public
void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final Event e = holder.events.get(position);
final Bundle args = new Bundle();
args.putString(ARG_TARGET_USER, GsonUtils.toJson(e.getActor()));
getBaseActivity().startFragmentTransaction();
getBaseActivity().addFragmentToTransaction(ProfileFragment.class,
R.id.fragment_container_more,
args);
getBaseActivity().finishFragmentTransaction();
}
});
adapter.addList(list);
}
mViewPager.setAdapter(adapter);
mTitlePageIndicator.setViewPager(mViewPager);
mViewPager.setCurrentItem(mDataFragment.currentItem);
}
|
diff --git a/sources/Watcher/src/kesako/watcher/runnable/SourceWatcher.java b/sources/Watcher/src/kesako/watcher/runnable/SourceWatcher.java
index 2563adb..0244135 100755
--- a/sources/Watcher/src/kesako/watcher/runnable/SourceWatcher.java
+++ b/sources/Watcher/src/kesako/watcher/runnable/SourceWatcher.java
@@ -1,259 +1,259 @@
/*
* Copyright 2012 Frederic SACHOT
*
* 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 kesako.watcher.runnable;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import kesako.utilities.Constant;
import kesako.utilities.DBUtilities;
import kesako.utilities.FileUtilities;
import org.apache.log4j.Logger;
/**
* Check the content of a source and update the index<br>
* The class implements the Log4J logging system.
* @author Frederic SACHOT
*/
public class SourceWatcher extends IntervalDBWork{
/**
* Log4J logger of the class
*/
private static final Logger logger = Logger.getLogger(SourceWatcher.class);
/**
* id of the source
*/
private int idSource;
/**
* Directory of the source.
*/
private File directory;
/**
* Constructor of the watcher. The name of the watcher is: Th_SW< idSource >
* @param idSource id of the source
* @param path path of the source
* @param intervalSeconds number of seconds between to check of the directory.
*/
public SourceWatcher(int idSource, String path,int intervalSeconds) {
super(intervalSeconds,"Th_SW"+Integer.toString(idSource));
logger.debug("SourceWatcher");
this.idSource=idSource;
this.directory=new File(path);
if(!this.directory.exists()){
logger.fatal("The directory "+path+" doesn't exist");
}
}
/**
* Constructor of the watcher
* @param rs resultset with all data of the source: id, path
* @param intervalSeconds number of seconds between to check of the directory.
* @throws SQLException
*/
public SourceWatcher(ResultSet rs,int intervalSeconds) throws SQLException{
this(rs.getInt("id_source"),rs.getString("chemin"),intervalSeconds);
}
/**
* Return the id of the source
*/
public int getIdSource() {
return this.idSource;
}
/**
* Return the directory of the file
*/
public File getDirectory(){
return this.directory;
}
public String toString(){
return this.idSource+ " : "+this.getThredName()+" : "+this.directory.getAbsolutePath();
}
/**
* Check the content of the directory and add all indexable file to the data-base.
* If the file fileName.xxx has a meta-file fileName.meta, meta-data is added in the data-base. <br>
* To check subdirectories, the function is a recursive function, and call itself on all subdirectories
* @param dir directory to check file.
* @throws SQLException
*/
private void checkDirectory(Connection cn,File dir) throws SQLException{
File file;
String query;
ResultSet rs;
logger.debug("add Directory");
query="select flag from t_sources where id_source="+idSource;
rs=DBUtilities.executeQuery(cn,query);
if(rs.next() && rs.getInt("flag")==Constant.TO_INDEX){
if(dir.isDirectory()){
File[] children = dir.listFiles();
for (int i = 0; i < children.length; i++) {
file = children[i];
if(file.isFile() && FileUtilities.isValidExtansion(file)){
fileProcessing(cn,file);
}else{
if(file.isDirectory()){
checkDirectory(cn,file);
}
}
}
}else{
if(dir.isFile()&& FileUtilities.isValidExtansion(dir)){
fileProcessing(cn,dir);
}
}
}
}
/**
* If a new file is discovered, the file is added to the data-base.
* If the file or the meta-file, has been modified, the data-base is updated to allow its reindexing.
* @param file file to add to the data-base.
* @throws SQLException
*/
private void fileProcessing(Connection cn,File file){
/*
* nouveau 0
* meta 1
* modifié 2
* error 3
*/
Date dM;
File fileMeta;
String query="";
ResultSet rs;
int fileId;
Calendar c=Calendar.getInstance();
logger.debug("******************************************************************");
logger.debug("File Processing "+file.getAbsolutePath());
logger.debug("******************************************************************");
try {
query="start transaction";
DBUtilities.executeQuery(cn,query);
fileId=DBUtilities.getFileId(cn,file.getAbsolutePath());
dM=new Date(file.lastModified());
c.setTime(dM);
if(fileId<0){ //it's a new file to add
logger.debug("putFile : "+file.getAbsolutePath());
query="insert into t_fichiers (ID_SOURCE,NOM,TITRE_F,TITRE_Doc,DATEMODIFIED,DATEEXTRACTED," +
"CHEMIN,FLAG,flag_meta,date_meta_modified,author_f,priority) values ("+
this.idSource+",'"+
DBUtilities.getStringSQL(file.getName())+"','"+
DBUtilities.getStringSQL(file.getName())+"','',"+
file.lastModified()+",'"+
- c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH)+"','"+
+ c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH)+"','"+
DBUtilities.getStringSQL(file.getAbsolutePath())+"',"+
Constant.TO_INDEX+","+
Constant.TO_EXTRACT_META+",0,'',"+Constant.PRIORITY_NEW_FILE+")";
DBUtilities.executeQuery(cn,query);
}else{//the file is already added
query="select flag,DATEMODIFIED,date_meta_modified from t_fichiers where id_fichier="+fileId;
rs=DBUtilities.executeQuery(cn,query);
fileMeta=new File(FileUtilities.getFileMetaName(file.getAbsolutePath()));
if(rs.next()){
if(rs.getLong("DATEMODIFIED")!=file.lastModified()){//the file has been modified
query="update t_fichiers set "+
"ID_SOURCE="+ this.idSource+","+
"TITRE_F='" + DBUtilities.getStringSQL(file.getName())+"',"+
"TITRE_Doc='',"+
"author_f='',"+
"DATEMODIFIED="+file.lastModified()+","+
- "DATEEXTRACTED='"+c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH)+"',"+
+ "DATEEXTRACTED='"+c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH)+"',"+
"FLAG="+Constant.TO_INDEX+","+
"flag_meta="+Constant.TO_EXTRACT_META+","+
"priority="+Constant.PRIORITY_MODIFIED_FILE+
" where id_fichier="+fileId;
DBUtilities.executeQuery(cn,query);
}else{
if(rs.getInt("flag")==Constant.INDEXED && fileMeta.exists()&&fileMeta.isFile()&&rs.getLong("DATE_META_MODIFIED")!=fileMeta.lastModified()){
//the meta-file has been modified
query="update t_fichiers set "+
"ID_SOURCE="+ this.idSource+","+
"flag_meta="+Constant.TO_EXTRACT_META+","+
"priority="+Constant.PRIORITY_MODIFIED_FILE+
" where id_fichier="+fileId;
DBUtilities.executeQuery(cn,query);
}
}
}else{
logger.fatal("No file was found : " + query);
}
}
cn.commit();
} catch (SQLException e) {
logger.fatal("ERROR : "+query,e);
try {
cn.rollback();
} catch (SQLException e1) {
logger.fatal("ERROR Rollback : "+query,e1);
}
}
logger.debug("******************************************************************");
logger.debug("END FILE PROCESSING");
logger.debug("******************************************************************");
}
/**
* Check the directory for any changes.
*/
protected void doWork() {
File f;
String query="";
ResultSet rs;
logger.debug("SourceWatcher dowork");
Connection cn=getConnection();
if(this.directory.exists()){
try {
query="select flag from t_sources where id_source="+idSource;
rs=DBUtilities.executeQuery(cn,query);
if(rs.next()){
if(rs.getInt("flag")==Constant.TO_INDEX){
checkDirectory(cn,this.directory);
//Now we need to iterate through the list of files and see if any that existed before don't exist anymore
query="select id_fichier,chemin from t_fichiers where id_source="+this.idSource;
rs=DBUtilities.executeQuery(cn,query);
while(rs.next()){
f=new File(rs.getString("chemin"));
if(!f.exists()){
query="update t_fichiers set flag="+Constant.TO_SUPPRESSED+" where id_fichier="+rs.getInt("id_fichier");
DBUtilities.executeQuery(cn,query);
}
}
}else{
stopWorking();
}
}else{
stopWorking();
}
} catch (SQLException e) {
logger.error(query,e);
}
}else{
stopWorking();
}
try {
cn.close();
} catch (SQLException e) {
logger.fatal("ERROR closing connection",e);
}
}
}
| false | true | private void fileProcessing(Connection cn,File file){
/*
* nouveau 0
* meta 1
* modifié 2
* error 3
*/
Date dM;
File fileMeta;
String query="";
ResultSet rs;
int fileId;
Calendar c=Calendar.getInstance();
logger.debug("******************************************************************");
logger.debug("File Processing "+file.getAbsolutePath());
logger.debug("******************************************************************");
try {
query="start transaction";
DBUtilities.executeQuery(cn,query);
fileId=DBUtilities.getFileId(cn,file.getAbsolutePath());
dM=new Date(file.lastModified());
c.setTime(dM);
if(fileId<0){ //it's a new file to add
logger.debug("putFile : "+file.getAbsolutePath());
query="insert into t_fichiers (ID_SOURCE,NOM,TITRE_F,TITRE_Doc,DATEMODIFIED,DATEEXTRACTED," +
"CHEMIN,FLAG,flag_meta,date_meta_modified,author_f,priority) values ("+
this.idSource+",'"+
DBUtilities.getStringSQL(file.getName())+"','"+
DBUtilities.getStringSQL(file.getName())+"','',"+
file.lastModified()+",'"+
c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH)+"','"+
DBUtilities.getStringSQL(file.getAbsolutePath())+"',"+
Constant.TO_INDEX+","+
Constant.TO_EXTRACT_META+",0,'',"+Constant.PRIORITY_NEW_FILE+")";
DBUtilities.executeQuery(cn,query);
}else{//the file is already added
query="select flag,DATEMODIFIED,date_meta_modified from t_fichiers where id_fichier="+fileId;
rs=DBUtilities.executeQuery(cn,query);
fileMeta=new File(FileUtilities.getFileMetaName(file.getAbsolutePath()));
if(rs.next()){
if(rs.getLong("DATEMODIFIED")!=file.lastModified()){//the file has been modified
query="update t_fichiers set "+
"ID_SOURCE="+ this.idSource+","+
"TITRE_F='" + DBUtilities.getStringSQL(file.getName())+"',"+
"TITRE_Doc='',"+
"author_f='',"+
"DATEMODIFIED="+file.lastModified()+","+
"DATEEXTRACTED='"+c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH)+"',"+
"FLAG="+Constant.TO_INDEX+","+
"flag_meta="+Constant.TO_EXTRACT_META+","+
"priority="+Constant.PRIORITY_MODIFIED_FILE+
" where id_fichier="+fileId;
DBUtilities.executeQuery(cn,query);
}else{
if(rs.getInt("flag")==Constant.INDEXED && fileMeta.exists()&&fileMeta.isFile()&&rs.getLong("DATE_META_MODIFIED")!=fileMeta.lastModified()){
//the meta-file has been modified
query="update t_fichiers set "+
"ID_SOURCE="+ this.idSource+","+
"flag_meta="+Constant.TO_EXTRACT_META+","+
"priority="+Constant.PRIORITY_MODIFIED_FILE+
" where id_fichier="+fileId;
DBUtilities.executeQuery(cn,query);
}
}
}else{
logger.fatal("No file was found : " + query);
}
}
cn.commit();
} catch (SQLException e) {
logger.fatal("ERROR : "+query,e);
try {
cn.rollback();
} catch (SQLException e1) {
logger.fatal("ERROR Rollback : "+query,e1);
}
}
logger.debug("******************************************************************");
logger.debug("END FILE PROCESSING");
logger.debug("******************************************************************");
}
| private void fileProcessing(Connection cn,File file){
/*
* nouveau 0
* meta 1
* modifié 2
* error 3
*/
Date dM;
File fileMeta;
String query="";
ResultSet rs;
int fileId;
Calendar c=Calendar.getInstance();
logger.debug("******************************************************************");
logger.debug("File Processing "+file.getAbsolutePath());
logger.debug("******************************************************************");
try {
query="start transaction";
DBUtilities.executeQuery(cn,query);
fileId=DBUtilities.getFileId(cn,file.getAbsolutePath());
dM=new Date(file.lastModified());
c.setTime(dM);
if(fileId<0){ //it's a new file to add
logger.debug("putFile : "+file.getAbsolutePath());
query="insert into t_fichiers (ID_SOURCE,NOM,TITRE_F,TITRE_Doc,DATEMODIFIED,DATEEXTRACTED," +
"CHEMIN,FLAG,flag_meta,date_meta_modified,author_f,priority) values ("+
this.idSource+",'"+
DBUtilities.getStringSQL(file.getName())+"','"+
DBUtilities.getStringSQL(file.getName())+"','',"+
file.lastModified()+",'"+
c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH)+"','"+
DBUtilities.getStringSQL(file.getAbsolutePath())+"',"+
Constant.TO_INDEX+","+
Constant.TO_EXTRACT_META+",0,'',"+Constant.PRIORITY_NEW_FILE+")";
DBUtilities.executeQuery(cn,query);
}else{//the file is already added
query="select flag,DATEMODIFIED,date_meta_modified from t_fichiers where id_fichier="+fileId;
rs=DBUtilities.executeQuery(cn,query);
fileMeta=new File(FileUtilities.getFileMetaName(file.getAbsolutePath()));
if(rs.next()){
if(rs.getLong("DATEMODIFIED")!=file.lastModified()){//the file has been modified
query="update t_fichiers set "+
"ID_SOURCE="+ this.idSource+","+
"TITRE_F='" + DBUtilities.getStringSQL(file.getName())+"',"+
"TITRE_Doc='',"+
"author_f='',"+
"DATEMODIFIED="+file.lastModified()+","+
"DATEEXTRACTED='"+c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH)+"',"+
"FLAG="+Constant.TO_INDEX+","+
"flag_meta="+Constant.TO_EXTRACT_META+","+
"priority="+Constant.PRIORITY_MODIFIED_FILE+
" where id_fichier="+fileId;
DBUtilities.executeQuery(cn,query);
}else{
if(rs.getInt("flag")==Constant.INDEXED && fileMeta.exists()&&fileMeta.isFile()&&rs.getLong("DATE_META_MODIFIED")!=fileMeta.lastModified()){
//the meta-file has been modified
query="update t_fichiers set "+
"ID_SOURCE="+ this.idSource+","+
"flag_meta="+Constant.TO_EXTRACT_META+","+
"priority="+Constant.PRIORITY_MODIFIED_FILE+
" where id_fichier="+fileId;
DBUtilities.executeQuery(cn,query);
}
}
}else{
logger.fatal("No file was found : " + query);
}
}
cn.commit();
} catch (SQLException e) {
logger.fatal("ERROR : "+query,e);
try {
cn.rollback();
} catch (SQLException e1) {
logger.fatal("ERROR Rollback : "+query,e1);
}
}
logger.debug("******************************************************************");
logger.debug("END FILE PROCESSING");
logger.debug("******************************************************************");
}
|
diff --git a/components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java b/components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java
index 7b658272..68be05bd 100644
--- a/components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java
+++ b/components/dotnet-dao-project/src/main/java/npanday/dao/impl/ProjectDaoImpl.java
@@ -1,1262 +1,1265 @@
/*
* 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 npanday.dao.impl;
import npanday.ArtifactType;
import npanday.ArtifactTypeHelper;
import npanday.dao.ProjectDao;
import npanday.dao.ProjectUri;
import npanday.dao.ProjectFactory;
import npanday.dao.Project;
import npanday.dao.ProjectDependency;
import npanday.dao.Requirement;
import npanday.registry.RepositoryRegistry;
import npanday.PathUtil;
import org.apache.maven.project.MavenProject;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.DefaultArtifactRepository;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.Model;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.Repository;
import org.openrdf.OpenRDFException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.BindingSet;
import org.openrdf.query.Binding;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.DefaultConsumer;
import org.codehaus.plexus.util.cli.StreamConsumer;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.codehaus.plexus.util.FileUtils;
import java.util.logging.Logger;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.EOFException;
import java.lang.ExceptionInInitializerError;
import java.net.URISyntaxException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public final class ProjectDaoImpl
implements ProjectDao
{
private String className;
private String id;
private static Logger logger = Logger.getAnonymousLogger();
private org.openrdf.repository.Repository rdfRepository;
/**
* The artifact factory component, which is used for creating artifacts.
*/
private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;
private int getProjectForCounter = 0;
private int storeCounter = 0;
private RepositoryConnection repositoryConnection;
private String dependencyQuery;
private String projectQuery;
private ArtifactResolver artifactResolver;
public void init( ArtifactFactory artifactFactory, ArtifactResolver artifactResolver )
{
this.artifactFactory = artifactFactory;
this.artifactResolver = artifactResolver;
List<ProjectUri> projectUris = new ArrayList<ProjectUri>();
projectUris.add( ProjectUri.GROUP_ID );
projectUris.add( ProjectUri.ARTIFACT_ID );
projectUris.add( ProjectUri.VERSION );
projectUris.add( ProjectUri.ARTIFACT_TYPE );
projectUris.add( ProjectUri.IS_RESOLVED );
projectUris.add( ProjectUri.DEPENDENCY );
projectUris.add( ProjectUri.CLASSIFIER );
dependencyQuery = "SELECT * FROM " + this.constructQueryFragmentFor( "{x}", projectUris );
projectUris = new ArrayList<ProjectUri>();
projectUris.add( ProjectUri.GROUP_ID );
projectUris.add( ProjectUri.ARTIFACT_ID );
projectUris.add( ProjectUri.VERSION );
projectUris.add( ProjectUri.ARTIFACT_TYPE );
projectUris.add( ProjectUri.IS_RESOLVED );
projectUris.add( ProjectUri.DEPENDENCY );
projectUris.add( ProjectUri.CLASSIFIER );
projectUris.add( ProjectUri.PARENT );
projectQuery = "SELECT * FROM " + this.constructQueryFragmentFor( "{x}", projectUris );
}
public Set<Project> getAllProjects()
throws IOException
{
Set<Project> projects = new HashSet<Project>();
TupleQueryResult result = null;
try
{
TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, projectQuery );
result = tupleQuery.evaluate();
while ( result.hasNext() )
{
BindingSet set = result.next();
String groupId = set.getBinding( ProjectUri.GROUP_ID.getObjectBinding() ).getValue().toString();
String version = set.getBinding( ProjectUri.VERSION.getObjectBinding() ).getValue().toString();
String artifactId = set.getBinding( ProjectUri.ARTIFACT_ID.getObjectBinding() ).getValue().toString();
String artifactType =
set.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString();
String classifier = null;
if ( set.hasBinding( ProjectUri.CLASSIFIER.getObjectBinding() ) )
{
classifier = set.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() ).getValue().toString();
}
// Project project = getProjectFor( groupId, artifactId, version, artifactType, null );
/*
* for ( Iterator<Binding> i = set.iterator(); i.hasNext(); ) { Binding b = i.next();
* System.out.println( b.getName() + ":" + b.getValue() ); }
*/
projects.add( getProjectFor( groupId, artifactId, version, artifactType, classifier ) );
}
}
catch ( RepositoryException e )
{
throw new IOException( "NPANDAY-180-000: Message = " + e.getMessage() );
}
catch ( MalformedQueryException e )
{
throw new IOException( "NPANDAY-180-001: Message = " + e.getMessage() );
}
catch ( QueryEvaluationException e )
{
throw new IOException( "NPANDAY-180-002: Message = " + e.getMessage() );
}
finally
{
if ( result != null )
{
try
{
result.close();
}
catch ( QueryEvaluationException e )
{
}
}
}
return projects;
}
public void setRdfRepository( Repository repository )
{
this.rdfRepository = repository;
}
public boolean openConnection()
{
try
{
repositoryConnection = rdfRepository.getConnection();
repositoryConnection.setAutoCommit( false );
}
catch ( RepositoryException e )
{
return false;
}
return true;
}
public boolean closeConnection()
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.commit();
repositoryConnection.close();
}
catch ( RepositoryException e )
{
return false;
}
}
return true;
}
public void removeProjectFor( String groupId, String artifactId, String version, String artifactType )
throws IOException
{
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id = valueFactory.createURI( groupId + ":" + artifactId + ":" + version + ":" + artifactType );
try
{
repositoryConnection.remove( repositoryConnection.getStatements( id, null, null, true ) );
}
catch ( RepositoryException e )
{
throw new IOException( e.getMessage() );
}
}
public Project getProjectFor( String groupId, String artifactId, String version, String artifactType,
String publicKeyTokenId )
throws IOException
{
long startTime = System.currentTimeMillis();
ValueFactory valueFactory = rdfRepository.getValueFactory();
Project project = new ProjectDependency();
project.setArtifactId( artifactId );
project.setGroupId( groupId );
project.setVersion( version );
project.setArtifactType( artifactType );
project.setPublicKeyTokenId( publicKeyTokenId );
TupleQueryResult result = null;
try
{
TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, projectQuery );
tupleQuery.setBinding( ProjectUri.GROUP_ID.getObjectBinding(), valueFactory.createLiteral( groupId ) );
tupleQuery.setBinding( ProjectUri.ARTIFACT_ID.getObjectBinding(), valueFactory.createLiteral( artifactId ) );
tupleQuery.setBinding( ProjectUri.VERSION.getObjectBinding(), valueFactory.createLiteral( version ) );
tupleQuery.setBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding(),
valueFactory.createLiteral( artifactType ) );
if ( publicKeyTokenId != null )
{
tupleQuery.setBinding( ProjectUri.CLASSIFIER.getObjectBinding(),
valueFactory.createLiteral( publicKeyTokenId ) );
project.setPublicKeyTokenId( publicKeyTokenId.replace( ":", "" ) );
}
result = tupleQuery.evaluate();
if ( !result.hasNext() )
{
if ( artifactType != null && ArtifactTypeHelper.isDotnetAnyGac( artifactType ) )
{
Artifact artifact =
ProjectFactory.createArtifactFrom( (ProjectDependency) project, artifactFactory );
if ( !artifact.getFile().exists() )
{
throw new IOException( "NPANDAY-180-003: Could not find GAC assembly: Group ID = " + groupId
+ ", Artifact ID = " + artifactId + ", Version = " + version + ", Artifact Type = "
+ artifactType + ", File Path = " + artifact.getFile().getAbsolutePath() );
}
project.setResolved( true );
return project;
}
throw new IOException( "NPANDAY-180-004: Could not find the project: Group ID = " + groupId
+ ", Artifact ID = " + artifactId + ", Version = " + version + ", Artifact Type = " + artifactType );
}
while ( result.hasNext() )
{
BindingSet set = result.next();
/*
* for ( Iterator<Binding> i = set.iterator(); i.hasNext(); ) { Binding b = i.next();
* System.out.println( b.getName() + ":" + b.getValue() ); }
*/
if ( set.hasBinding( ProjectUri.IS_RESOLVED.getObjectBinding() )
&& set.getBinding( ProjectUri.IS_RESOLVED.getObjectBinding() ).getValue().toString().equalsIgnoreCase(
"true" ) )
{
project.setResolved( true );
}
project.setArtifactType( set.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString() );
/*
* if ( set.hasBinding( ProjectUri.PARENT.getObjectBinding() ) ) { String pid = set.getBinding(
* ProjectUri.PARENT.getObjectBinding() ).getValue().toString(); String[] tokens = pid.split( "[:]" );
* Project parentProject = getProjectFor( tokens[0], tokens[1], tokens[2], null, null );
* project.setParentProject( parentProject ); }
*/
if ( set.hasBinding( ProjectUri.DEPENDENCY.getObjectBinding() ) )
{
Binding binding = set.getBinding( ProjectUri.DEPENDENCY.getObjectBinding() );
addDependenciesToProject( project, repositoryConnection, binding.getValue() );
}
if ( set.hasBinding( ProjectUri.CLASSIFIER.getObjectBinding() ) )
{
Binding binding = set.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() );
addClassifiersToProject( project, repositoryConnection, binding.getValue() );
}
}
}
catch ( QueryEvaluationException e )
{
throw new IOException( "NPANDAY-180-005: Message = " + e.getMessage() );
}
catch ( RepositoryException e )
{
throw new IOException( "NPANDAY-180-006: Message = " + e.getMessage() );
}
catch ( MalformedQueryException e )
{
throw new IOException( "NPANDAY-180-007: Message = " + e.getMessage() );
}
finally
{
if ( result != null )
{
try
{
result.close();
}
catch ( QueryEvaluationException e )
{
}
}
}
// TODO: If has parent, then need to modify dependencies, etc of returned project
logger.finest( "NPANDAY-180-008: ProjectDao.GetProjectFor - Artifact Id = " + project.getArtifactId()
+ ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = " + getProjectForCounter++ );
return project;
}
public Project getProjectFor( MavenProject mavenProject )
throws IOException
{
return getProjectFor( mavenProject.getGroupId(), mavenProject.getArtifactId(), mavenProject.getVersion(),
mavenProject.getArtifact().getType(), mavenProject.getArtifact().getClassifier() );
}
public void storeProject( Project project, File localRepository, List<ArtifactRepository> artifactRepositories )
throws IOException
{
}
/**
* Generates the system path for gac dependencies.
*/
private String generateDependencySystemPath( ProjectDependency projectDependency )
{
return new File( System.getenv( "SystemRoot" ), "/assembly/"
+ projectDependency.getArtifactType().toUpperCase() + "/" + projectDependency.getArtifactId() + "/"
+ projectDependency.getVersion() + "__" + projectDependency.getPublicKeyTokenId() + "/"
+ projectDependency.getArtifactId() + ".dll" ).getAbsolutePath();
}
public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException, IllegalArgumentException
{
long startTime = System.currentTimeMillis();
String snapshotVersion = null;
if ( project == null )
{
throw new IllegalArgumentException( "NPANDAY-180-009: Project is null" );
}
if ( project.getGroupId() == null || project.getArtifactId() == null || project.getVersion() == null )
{
throw new IllegalArgumentException( "NPANDAY-180-010: Project value is null: Group Id ="
+ project.getGroupId() + ", Artifact Id = " + project.getArtifactId() + ", Version = "
+ project.getVersion() );
}
Set<Artifact> artifactDependencies = new HashSet<Artifact>();
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id =
valueFactory.createURI( project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
+ ":" + project.getArtifactType() );
URI groupId = valueFactory.createURI( ProjectUri.GROUP_ID.getPredicate() );
URI artifactId = valueFactory.createURI( ProjectUri.ARTIFACT_ID.getPredicate() );
URI version = valueFactory.createURI( ProjectUri.VERSION.getPredicate() );
URI artifactType = valueFactory.createURI( ProjectUri.ARTIFACT_TYPE.getPredicate() );
URI classifier = valueFactory.createURI( ProjectUri.CLASSIFIER.getPredicate() );
URI isResolved = valueFactory.createURI( ProjectUri.IS_RESOLVED.getPredicate() );
URI artifact = valueFactory.createURI( ProjectUri.ARTIFACT.getPredicate() );
URI dependency = valueFactory.createURI( ProjectUri.DEPENDENCY.getPredicate() );
URI parent = valueFactory.createURI( ProjectUri.PARENT.getPredicate() );
Set<Model> modelDependencies = new HashSet<Model>();
try
{
repositoryConnection.add( id, RDF.TYPE, artifact );
repositoryConnection.add( id, groupId, valueFactory.createLiteral( project.getGroupId() ) );
repositoryConnection.add( id, artifactId, valueFactory.createLiteral( project.getArtifactId() ) );
repositoryConnection.add( id, version, valueFactory.createLiteral( project.getVersion() ) );
repositoryConnection.add( id, artifactType, valueFactory.createLiteral( project.getArtifactType() ) );
if ( project.getPublicKeyTokenId() != null )
{
URI classifierNode = valueFactory.createURI( project.getPublicKeyTokenId() + ":" );
for ( Requirement requirement : project.getRequirements() )
{
URI uri = valueFactory.createURI( requirement.getUri().toString() );
repositoryConnection.add( classifierNode, uri, valueFactory.createLiteral( requirement.getValue() ) );
}
repositoryConnection.add( id, classifier, classifierNode );
}
if ( project.getParentProject() != null )
{
Project parentProject = project.getParentProject();
URI pid =
valueFactory.createURI( parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":"
+ parentProject.getVersion() + ":" + project.getArtifactType() );
repositoryConnection.add( id, parent, pid );
artifactDependencies.addAll( storeProjectAndResolveDependencies( parentProject, null,
artifactRepositories ) );
}
for ( ProjectDependency projectDependency : project.getProjectDependencies() )
{
snapshotVersion = null;
logger.finest( "NPANDAY-180-011: Project Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Artifact Type = "
+ projectDependency.getArtifactType() );
// If artifact has been deleted, then re-resolve
if ( projectDependency.isResolved() && !ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
File dependencyFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if ( !dependencyFile.exists() )
{
projectDependency.setResolved( false );
}
}
// resolve system scope dependencies
if ( projectDependency.getScope() != null && projectDependency.getScope().equals( "system" ) )
{
if ( projectDependency.getSystemPath() == null )
{
throw new IOException( "systemPath required for System Scoped dependencies " + "in Group ID = "
+ projectDependency.getGroupId() + ", Artiract ID = " + projectDependency.getArtifactId() );
}
File f = new File( projectDependency.getSystemPath() );
if ( !f.exists() )
{
throw new IOException( "Dependency systemPath File not found:"
+ projectDependency.getSystemPath() + "in Group ID = " + projectDependency.getGroupId()
+ ", Artiract ID = " + projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve com reference
// flow:
// 1. generate the interop dll in temp folder and resolve to that path during dependency resolution
// 2. cut and paste the dll to buildDirectory and update the paths once we grab the reference of
// MavenProject (CompilerContext.java)
if ( projectDependency.getArtifactType().equals( "com_reference" ) )
{
String tokenId = projectDependency.getPublicKeyTokenId();
String interopPath = generateInteropDll( projectDependency.getArtifactId(), tokenId );
File f = new File( interopPath );
if ( !f.exists() )
{
throw new IOException( "Dependency com_reference File not found:" + interopPath
+ "in Group ID = " + projectDependency.getGroupId() + ", Artiract ID = "
+ projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve gac references
// note: the old behavior of gac references, used to have system path properties in the pom of the
// project
// now we need to generate the system path of the gac references so we can use
// System.getenv("SystemRoot")
if ( !projectDependency.isResolved() )
{
if ( ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
try
{
projectDependency.setResolved( true );
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
File f = new File( projectDependency.getSystemPath() );
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
}
catch ( ExceptionInInitializerError e )
{
logger.warning( "NPANDAY-180-516.82: Project Failed to Resolve Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = "
+ projectDependency.getScope() + "SystemPath = " + projectDependency.getSystemPath() );
}
}
else
{
try
{
Project dep =
this.getProjectFor( projectDependency.getGroupId(), projectDependency.getArtifactId(),
projectDependency.getVersion(),
projectDependency.getArtifactType(),
projectDependency.getPublicKeyTokenId() );
if ( dep.isResolved() )
{
projectDependency = (ProjectDependency) dep;
Artifact assembly =
ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
artifactDependencies.add( assembly );
artifactDependencies.addAll( this.storeProjectAndResolveDependencies(
projectDependency,
localRepository,
artifactRepositories ) );
}
}
catch ( IOException e )
{
// safe to ignore: dependency not found
}
}
}
if ( !projectDependency.isResolved() )
{
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
if ( assembly.getType().equals( "jar" ) )
{
logger.info( "Detected jar dependency - skipping: Artifact Dependency ID = "
+ assembly.getArtifactId() );
continue;
}
ArtifactType type = ArtifactType.getArtifactTypeForPackagingName( assembly.getType() );
logger.info( "NPANDAY-180-012: Resolving artifact for unresolved dependency: "
+ assembly.getId());
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ))// TODO: Generalize to any attached artifact
{
Artifact pomArtifact =
artifactFactory.createProjectArtifact( projectDependency.getGroupId(),
projectDependency.getArtifactId(),
projectDependency.getVersion() );
try
{
artifactResolver.resolve( pomArtifact, artifactRepositories,
localArtifactRepository );
logger.info( "NPANDAY-180-024: resolving pom artifact: " + pomArtifact.toString() );
snapshotVersion = pomArtifact.getVersion();
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-180-025: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-180-026: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
if ( pomArtifact.getFile() != null && pomArtifact.getFile().exists() )
{
FileReader fileReader = new FileReader( pomArtifact.getFile() );
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
try
{
model = reader.read( fileReader ); // TODO: interpolate values
}
catch ( XmlPullParserException e )
{
throw new IOException( "NPANDAY-180-015: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
catch ( EOFException e )
{
throw new IOException( "NPANDAY-180-016: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
// small hack for not doing inheritence
String g = model.getGroupId();
if ( g == null )
{
g = model.getParent().getGroupId();
}
String v = model.getVersion();
if ( v == null )
{
v = model.getParent().getVersion();
}
if ( !( g.equals( projectDependency.getGroupId() )
&& model.getArtifactId().equals( projectDependency.getArtifactId() ) && v.equals( projectDependency.getVersion() ) ) )
{
throw new IOException(
"NPANDAY-180-017: Model parameters do not match project dependencies parameters: Model: "
+ g + ":" + model.getArtifactId() + ":" + v + ", Project: "
+ projectDependency.getGroupId() + ":"
+ projectDependency.getArtifactId() + ":"
+ projectDependency.getVersion() );
}
modelDependencies.add( model );
}
}
if ( snapshotVersion != null )
{
assembly.setVersion( snapshotVersion );
}
File uacFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if (uacFile.exists())
{
assembly.setFile( uacFile );
}
else
{
logger.info( "NPANDAY-180-018: Not found in UAC, now retrieving artifact from wagon:"
+ assembly.getId()
+ ", Failed UAC Path Check = " + uacFile.getAbsolutePath());
try
{
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
- uacFile.getParentFile().mkdirs();
- FileUtils.copyFile( assembly.getFile(), uacFile );
+ if ( assembly != null && assembly.getFile().exists() )
+ {
+ uacFile.getParentFile().mkdirs();
+ FileUtils.copyFile( assembly.getFile(), uacFile );
+ }
}
catch ( ArtifactNotFoundException e )
{
throw new IOException(
"NPANDAY-180-020: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
throw new IOException(
"NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
}
artifactDependencies.add( assembly );
}// end if dependency not resolved
URI did =
valueFactory.createURI( projectDependency.getGroupId() + ":" + projectDependency.getArtifactId()
+ ":" + projectDependency.getVersion() + ":" + projectDependency.getArtifactType() );
repositoryConnection.add( did, RDF.TYPE, artifact );
repositoryConnection.add( did, groupId, valueFactory.createLiteral( projectDependency.getGroupId() ) );
repositoryConnection.add( did, artifactId,
valueFactory.createLiteral( projectDependency.getArtifactId() ) );
repositoryConnection.add( did, version, valueFactory.createLiteral( projectDependency.getVersion() ) );
repositoryConnection.add( did, artifactType,
valueFactory.createLiteral( projectDependency.getArtifactType() ) );
if ( projectDependency.getPublicKeyTokenId() != null )
{
repositoryConnection.add(
did,
classifier,
valueFactory.createLiteral( projectDependency.getPublicKeyTokenId() + ":" ) );
}
repositoryConnection.add( id, dependency, did );
}// end for
repositoryConnection.add( id, isResolved, valueFactory.createLiteral( true ) );
repositoryConnection.commit();
}
catch ( OpenRDFException e )
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.rollback();
}
catch ( RepositoryException e1 )
{
}
}
throw new IOException( "NPANDAY-180-021: Could not open RDF Repository: Message =" + e.getMessage() );
}
for ( Model model : modelDependencies )
{
// System.out.println( "Storing dependency: Artifact Id = " + model.getArtifactId() );
artifactDependencies.addAll( storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model,
null ),
localRepository, artifactRepositories ) );
}
logger.finest( "NPANDAY-180-022: ProjectDao.storeProjectAndResolveDependencies - Artifact Id = "
+ project.getArtifactId() + ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = "
+ storeCounter++ );
return artifactDependencies;
}
public Set<Artifact> storeModelAndResolveDependencies( Model model, File pomFileDirectory,
File localArtifactRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException
{
return storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model, pomFileDirectory ),
localArtifactRepository, artifactRepositories );
}
public String getClassName()
{
return className;
}
public String getID()
{
return id;
}
public void init( Object dataStoreObject, String id, String className )
throws IllegalArgumentException
{
if ( dataStoreObject == null || !( dataStoreObject instanceof org.openrdf.repository.Repository ) )
{
throw new IllegalArgumentException(
"NPANDAY-180-023: Must initialize with an instance of org.openrdf.repository.Repository" );
}
this.id = id;
this.className = className;
this.rdfRepository = (org.openrdf.repository.Repository) dataStoreObject;
}
public void setRepositoryRegistry( RepositoryRegistry repositoryRegistry )
{
}
protected void initForUnitTest( Object dataStoreObject, String id, String className,
ArtifactResolver artifactResolver, ArtifactFactory artifactFactory )
{
this.init( dataStoreObject, id, className );
init( artifactFactory, artifactResolver );
}
private void addClassifiersToProject( Project project, RepositoryConnection repositoryConnection,
Value classifierUri )
throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
String query = "SELECT * FROM {x} p {y}";
TupleQuery tq = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, query );
tq.setBinding( "x", classifierUri );
TupleQueryResult result = tq.evaluate();
while ( result.hasNext() )
{
BindingSet set = result.next();
for ( Iterator<Binding> i = set.iterator(); i.hasNext(); )
{
Binding binding = i.next();
if ( binding.getValue().toString().startsWith( "http://maven.apache.org/artifact/requirement" ) )
{
try
{
project.addRequirement( Requirement.Factory.createDefaultRequirement(
new java.net.URI(
binding.getValue().toString() ),
set.getValue( "y" ).toString() ) );
}
catch ( URISyntaxException e )
{
e.printStackTrace();
}
}
}
}
}
private void addDependenciesToProject( Project project, RepositoryConnection repositoryConnection,
Value dependencyUri )
throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
TupleQuery tq = repositoryConnection.prepareTupleQuery( QueryLanguage.SERQL, dependencyQuery );
tq.setBinding( "x", dependencyUri );
TupleQueryResult dependencyResult = tq.evaluate();
try
{
while ( dependencyResult.hasNext() )
{
ProjectDependency projectDependency = new ProjectDependency();
BindingSet bs = dependencyResult.next();
projectDependency.setGroupId( bs.getBinding( ProjectUri.GROUP_ID.getObjectBinding() ).getValue().toString() );
projectDependency.setArtifactId( bs.getBinding( ProjectUri.ARTIFACT_ID.getObjectBinding() ).getValue().toString() );
projectDependency.setVersion( bs.getBinding( ProjectUri.VERSION.getObjectBinding() ).getValue().toString() );
projectDependency.setArtifactType( bs.getBinding( ProjectUri.ARTIFACT_TYPE.getObjectBinding() ).getValue().toString() );
Binding classifierBinding = bs.getBinding( ProjectUri.CLASSIFIER.getObjectBinding() );
if ( classifierBinding != null )
{
projectDependency.setPublicKeyTokenId( classifierBinding.getValue().toString().replace( ":", "" ) );
}
project.addProjectDependency( projectDependency );
if ( bs.hasBinding( ProjectUri.DEPENDENCY.getObjectBinding() ) )
{
addDependenciesToProject( projectDependency, repositoryConnection,
bs.getValue( ProjectUri.DEPENDENCY.getObjectBinding() ) );
}
}
}
finally
{
dependencyResult.close();
}
}
private String constructQueryFragmentFor( String subject, List<ProjectUri> projectUris )
{
// ProjectUri nonOptionalUri = this.getNonOptionalUriFrom( projectUris );
// projectUris.remove( nonOptionalUri );
StringBuffer buffer = new StringBuffer();
buffer.append( subject );
for ( Iterator<ProjectUri> i = projectUris.iterator(); i.hasNext(); )
{
ProjectUri projectUri = i.next();
buffer.append( " " );
if ( projectUri.isOptional() )
{
buffer.append( "[" );
}
buffer.append( "<" ).append( projectUri.getPredicate() ).append( "> {" ).append(
projectUri.getObjectBinding() ).append(
"}" );
if ( projectUri.isOptional() )
{
buffer.append( "]" );
}
if ( i.hasNext() )
{
buffer.append( ";" );
}
}
return buffer.toString();
}
private ProjectUri getNonOptionalUriFrom( List<ProjectUri> projectUris )
{
for ( ProjectUri projectUri : projectUris )
{
if ( !projectUri.isOptional() )
{
return projectUri;
}
}
return null;
}
// TODO: move generateInteropDll, getInteropParameters, getTempDirectory, and execute methods to another class
private String generateInteropDll( String name, String classifier )
throws IOException
{
File tmpDir;
String comReferenceAbsolutePath = "";
try
{
tmpDir = getTempDirectory();
}
catch ( IOException e )
{
throw new IOException( "Unable to create temporary directory" );
}
try
{
comReferenceAbsolutePath = resolveComReferencePath( name, classifier );
}
catch ( Exception e )
{
throw new IOException( e.getMessage() );
}
String interopAbsolutePath = tmpDir.getAbsolutePath() + File.separator + "Interop." + name + ".dll";
List<String> params = getInteropParameters( interopAbsolutePath, comReferenceAbsolutePath, name );
try
{
execute( "tlbimp", params );
}
catch ( Exception e )
{
throw new IOException( e.getMessage() );
}
return interopAbsolutePath;
}
private String resolveComReferencePath( String name, String classifier )
throws Exception
{
String[] classTokens = classifier.split( "}" );
classTokens[1] = classTokens[1].replace( "-", "\\" );
String newClassifier = classTokens[0] + "}" + classTokens[1];
String registryPath = "HKEY_CLASSES_ROOT\\TypeLib\\" + newClassifier + "\\win32\\";
int lineNoOfPath = 1;
List<String> parameters = new ArrayList<String>();
parameters.add( "query" );
parameters.add( registryPath );
parameters.add( "/ve" );
StreamConsumer outConsumer = new StreamConsumerImpl();
StreamConsumer errorConsumer = new StreamConsumerImpl();
try
{
// TODO: investigate why outConsumer ignores newline
execute( "reg", parameters, outConsumer, errorConsumer );
}
catch ( Exception e )
{
throw new Exception( "Cannot find information of [" + name
+ "] ActiveX component in your system, you need to install this component first to continue." );
}
// parse outConsumer
String out = outConsumer.toString();
String tokens[] = out.split( "\n" );
String lineResult = "";
String[] result;
if ( tokens.length >= lineNoOfPath - 1 )
{
lineResult = tokens[lineNoOfPath - 1];
}
result = lineResult.split( "REG_SZ" );
if ( result.length > 1 )
{
return result[1].trim();
}
return null;
}
private List<String> readPomAttribute( String pomFileLoc, String tag )
{
List<String> attributes = new ArrayList<String>();
try
{
File file = new File( pomFileLoc );
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( file );
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName( tag );
for ( int s = 0; s < nodeLst.getLength(); s++ )
{
Node currentNode = nodeLst.item( s );
NodeList childrenList = currentNode.getChildNodes();
for ( int i = 0; i < childrenList.getLength(); i++ )
{
Node child = childrenList.item( i );
attributes.add( child.getNodeValue() );
}
}
}
catch ( Exception e )
{
}
return attributes;
}
private List<String> getInteropParameters( String interopAbsolutePath, String comRerefenceAbsolutePath,
String namespace )
{
List<String> parameters = new ArrayList<String>();
parameters.add( comRerefenceAbsolutePath );
parameters.add( "/out:" + interopAbsolutePath );
parameters.add( "/namespace:" + namespace );
try
{
// beginning code for checking of strong name key or signing of projects
String key = "";
String keyfile = "";
String currentWorkingDir = System.getProperty( "user.dir" );
// Check if Parent pom
List<String> modules = readPomAttribute( currentWorkingDir + File.separator + "pom.xml", "module" );
if ( !modules.isEmpty() )
{
// check if there is a matching dependency with the namespace
for ( String child : modules )
{
// check each module pom file if there is existing keyfile
String tempDir = currentWorkingDir + File.separator + child;
try
{
List<String> keyfiles = readPomAttribute( tempDir + "\\pom.xml", "keyfile" );
if ( keyfiles.get( 0 ) != null )
{
// PROBLEM WITH MULTIMODULES
boolean hasComRef = false;
List<String> dependencies = readPomAttribute( tempDir + "\\pom.xml", "groupId" );
for ( String item : dependencies )
{
if ( item.equals( namespace ) )
{
hasComRef = true;
break;
}
}
if ( hasComRef )
{
key = keyfiles.get( 0 );
currentWorkingDir = tempDir;
}
}
}
catch ( Exception e )
{
}
}
}
else
{
// not a parent pom, so read project pom file for keyfile value
List<String> keyfiles = readPomAttribute( currentWorkingDir + File.separator + "pom.xml", "keyfile" );
key = keyfiles.get( 0 );
}
if ( key != "" )
{
keyfile = currentWorkingDir + File.separator + key;
parameters.add( "/keyfile:" + keyfile );
}
// end code for checking of strong name key or signing of projects
}
catch ( Exception ex )
{
}
return parameters;
}
private File getTempDirectory()
throws IOException
{
File tempFile = File.createTempFile( "interop-dll-", "" );
File tmpDir = new File( tempFile.getParentFile(), tempFile.getName() );
tempFile.delete();
tmpDir.mkdir();
return tmpDir;
}
// can't use dotnet-executable due to cyclic dependency.
private void execute( String executable, List<String> commands )
throws Exception
{
execute( executable, commands, null, null );
}
private void execute( String executable, List<String> commands, StreamConsumer systemOut, StreamConsumer systemError )
throws Exception
{
int result = 0;
Commandline commandline = new Commandline();
commandline.setExecutable( executable );
commandline.addArguments( commands.toArray( new String[commands.size()] ) );
try
{
result = CommandLineUtils.executeCommandLine( commandline, systemOut, systemError );
System.out.println( "NPANDAY-040-000: Executed command: Commandline = " + commandline + ", Result = "
+ result );
if ( result != 0 )
{
throw new Exception( "NPANDAY-040-001: Could not execute: Command = " + commandline.toString()
+ ", Result = " + result );
}
}
catch ( CommandLineException e )
{
throw new Exception( "NPANDAY-040-002: Could not execute: Command = " + commandline.toString() );
}
}
/**
* TODO: refactor this to another class and all methods concerning com_reference StreamConsumer instance that
* buffers the entire output
*/
class StreamConsumerImpl
implements StreamConsumer
{
private DefaultConsumer consumer;
private StringBuffer sb = new StringBuffer();
public StreamConsumerImpl()
{
consumer = new DefaultConsumer();
}
public void consumeLine( String line )
{
sb.append( line );
if ( logger != null )
{
consumer.consumeLine( line );
}
}
/**
* Returns the stream
*
* @return the stream
*/
public String toString()
{
return sb.toString();
}
}
}
| true | true | public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException, IllegalArgumentException
{
long startTime = System.currentTimeMillis();
String snapshotVersion = null;
if ( project == null )
{
throw new IllegalArgumentException( "NPANDAY-180-009: Project is null" );
}
if ( project.getGroupId() == null || project.getArtifactId() == null || project.getVersion() == null )
{
throw new IllegalArgumentException( "NPANDAY-180-010: Project value is null: Group Id ="
+ project.getGroupId() + ", Artifact Id = " + project.getArtifactId() + ", Version = "
+ project.getVersion() );
}
Set<Artifact> artifactDependencies = new HashSet<Artifact>();
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id =
valueFactory.createURI( project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
+ ":" + project.getArtifactType() );
URI groupId = valueFactory.createURI( ProjectUri.GROUP_ID.getPredicate() );
URI artifactId = valueFactory.createURI( ProjectUri.ARTIFACT_ID.getPredicate() );
URI version = valueFactory.createURI( ProjectUri.VERSION.getPredicate() );
URI artifactType = valueFactory.createURI( ProjectUri.ARTIFACT_TYPE.getPredicate() );
URI classifier = valueFactory.createURI( ProjectUri.CLASSIFIER.getPredicate() );
URI isResolved = valueFactory.createURI( ProjectUri.IS_RESOLVED.getPredicate() );
URI artifact = valueFactory.createURI( ProjectUri.ARTIFACT.getPredicate() );
URI dependency = valueFactory.createURI( ProjectUri.DEPENDENCY.getPredicate() );
URI parent = valueFactory.createURI( ProjectUri.PARENT.getPredicate() );
Set<Model> modelDependencies = new HashSet<Model>();
try
{
repositoryConnection.add( id, RDF.TYPE, artifact );
repositoryConnection.add( id, groupId, valueFactory.createLiteral( project.getGroupId() ) );
repositoryConnection.add( id, artifactId, valueFactory.createLiteral( project.getArtifactId() ) );
repositoryConnection.add( id, version, valueFactory.createLiteral( project.getVersion() ) );
repositoryConnection.add( id, artifactType, valueFactory.createLiteral( project.getArtifactType() ) );
if ( project.getPublicKeyTokenId() != null )
{
URI classifierNode = valueFactory.createURI( project.getPublicKeyTokenId() + ":" );
for ( Requirement requirement : project.getRequirements() )
{
URI uri = valueFactory.createURI( requirement.getUri().toString() );
repositoryConnection.add( classifierNode, uri, valueFactory.createLiteral( requirement.getValue() ) );
}
repositoryConnection.add( id, classifier, classifierNode );
}
if ( project.getParentProject() != null )
{
Project parentProject = project.getParentProject();
URI pid =
valueFactory.createURI( parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":"
+ parentProject.getVersion() + ":" + project.getArtifactType() );
repositoryConnection.add( id, parent, pid );
artifactDependencies.addAll( storeProjectAndResolveDependencies( parentProject, null,
artifactRepositories ) );
}
for ( ProjectDependency projectDependency : project.getProjectDependencies() )
{
snapshotVersion = null;
logger.finest( "NPANDAY-180-011: Project Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Artifact Type = "
+ projectDependency.getArtifactType() );
// If artifact has been deleted, then re-resolve
if ( projectDependency.isResolved() && !ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
File dependencyFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if ( !dependencyFile.exists() )
{
projectDependency.setResolved( false );
}
}
// resolve system scope dependencies
if ( projectDependency.getScope() != null && projectDependency.getScope().equals( "system" ) )
{
if ( projectDependency.getSystemPath() == null )
{
throw new IOException( "systemPath required for System Scoped dependencies " + "in Group ID = "
+ projectDependency.getGroupId() + ", Artiract ID = " + projectDependency.getArtifactId() );
}
File f = new File( projectDependency.getSystemPath() );
if ( !f.exists() )
{
throw new IOException( "Dependency systemPath File not found:"
+ projectDependency.getSystemPath() + "in Group ID = " + projectDependency.getGroupId()
+ ", Artiract ID = " + projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve com reference
// flow:
// 1. generate the interop dll in temp folder and resolve to that path during dependency resolution
// 2. cut and paste the dll to buildDirectory and update the paths once we grab the reference of
// MavenProject (CompilerContext.java)
if ( projectDependency.getArtifactType().equals( "com_reference" ) )
{
String tokenId = projectDependency.getPublicKeyTokenId();
String interopPath = generateInteropDll( projectDependency.getArtifactId(), tokenId );
File f = new File( interopPath );
if ( !f.exists() )
{
throw new IOException( "Dependency com_reference File not found:" + interopPath
+ "in Group ID = " + projectDependency.getGroupId() + ", Artiract ID = "
+ projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve gac references
// note: the old behavior of gac references, used to have system path properties in the pom of the
// project
// now we need to generate the system path of the gac references so we can use
// System.getenv("SystemRoot")
if ( !projectDependency.isResolved() )
{
if ( ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
try
{
projectDependency.setResolved( true );
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
File f = new File( projectDependency.getSystemPath() );
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
}
catch ( ExceptionInInitializerError e )
{
logger.warning( "NPANDAY-180-516.82: Project Failed to Resolve Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = "
+ projectDependency.getScope() + "SystemPath = " + projectDependency.getSystemPath() );
}
}
else
{
try
{
Project dep =
this.getProjectFor( projectDependency.getGroupId(), projectDependency.getArtifactId(),
projectDependency.getVersion(),
projectDependency.getArtifactType(),
projectDependency.getPublicKeyTokenId() );
if ( dep.isResolved() )
{
projectDependency = (ProjectDependency) dep;
Artifact assembly =
ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
artifactDependencies.add( assembly );
artifactDependencies.addAll( this.storeProjectAndResolveDependencies(
projectDependency,
localRepository,
artifactRepositories ) );
}
}
catch ( IOException e )
{
// safe to ignore: dependency not found
}
}
}
if ( !projectDependency.isResolved() )
{
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
if ( assembly.getType().equals( "jar" ) )
{
logger.info( "Detected jar dependency - skipping: Artifact Dependency ID = "
+ assembly.getArtifactId() );
continue;
}
ArtifactType type = ArtifactType.getArtifactTypeForPackagingName( assembly.getType() );
logger.info( "NPANDAY-180-012: Resolving artifact for unresolved dependency: "
+ assembly.getId());
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ))// TODO: Generalize to any attached artifact
{
Artifact pomArtifact =
artifactFactory.createProjectArtifact( projectDependency.getGroupId(),
projectDependency.getArtifactId(),
projectDependency.getVersion() );
try
{
artifactResolver.resolve( pomArtifact, artifactRepositories,
localArtifactRepository );
logger.info( "NPANDAY-180-024: resolving pom artifact: " + pomArtifact.toString() );
snapshotVersion = pomArtifact.getVersion();
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-180-025: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-180-026: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
if ( pomArtifact.getFile() != null && pomArtifact.getFile().exists() )
{
FileReader fileReader = new FileReader( pomArtifact.getFile() );
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
try
{
model = reader.read( fileReader ); // TODO: interpolate values
}
catch ( XmlPullParserException e )
{
throw new IOException( "NPANDAY-180-015: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
catch ( EOFException e )
{
throw new IOException( "NPANDAY-180-016: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
// small hack for not doing inheritence
String g = model.getGroupId();
if ( g == null )
{
g = model.getParent().getGroupId();
}
String v = model.getVersion();
if ( v == null )
{
v = model.getParent().getVersion();
}
if ( !( g.equals( projectDependency.getGroupId() )
&& model.getArtifactId().equals( projectDependency.getArtifactId() ) && v.equals( projectDependency.getVersion() ) ) )
{
throw new IOException(
"NPANDAY-180-017: Model parameters do not match project dependencies parameters: Model: "
+ g + ":" + model.getArtifactId() + ":" + v + ", Project: "
+ projectDependency.getGroupId() + ":"
+ projectDependency.getArtifactId() + ":"
+ projectDependency.getVersion() );
}
modelDependencies.add( model );
}
}
if ( snapshotVersion != null )
{
assembly.setVersion( snapshotVersion );
}
File uacFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if (uacFile.exists())
{
assembly.setFile( uacFile );
}
else
{
logger.info( "NPANDAY-180-018: Not found in UAC, now retrieving artifact from wagon:"
+ assembly.getId()
+ ", Failed UAC Path Check = " + uacFile.getAbsolutePath());
try
{
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
uacFile.getParentFile().mkdirs();
FileUtils.copyFile( assembly.getFile(), uacFile );
}
catch ( ArtifactNotFoundException e )
{
throw new IOException(
"NPANDAY-180-020: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
throw new IOException(
"NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
}
artifactDependencies.add( assembly );
}// end if dependency not resolved
URI did =
valueFactory.createURI( projectDependency.getGroupId() + ":" + projectDependency.getArtifactId()
+ ":" + projectDependency.getVersion() + ":" + projectDependency.getArtifactType() );
repositoryConnection.add( did, RDF.TYPE, artifact );
repositoryConnection.add( did, groupId, valueFactory.createLiteral( projectDependency.getGroupId() ) );
repositoryConnection.add( did, artifactId,
valueFactory.createLiteral( projectDependency.getArtifactId() ) );
repositoryConnection.add( did, version, valueFactory.createLiteral( projectDependency.getVersion() ) );
repositoryConnection.add( did, artifactType,
valueFactory.createLiteral( projectDependency.getArtifactType() ) );
if ( projectDependency.getPublicKeyTokenId() != null )
{
repositoryConnection.add(
did,
classifier,
valueFactory.createLiteral( projectDependency.getPublicKeyTokenId() + ":" ) );
}
repositoryConnection.add( id, dependency, did );
}// end for
repositoryConnection.add( id, isResolved, valueFactory.createLiteral( true ) );
repositoryConnection.commit();
}
catch ( OpenRDFException e )
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.rollback();
}
catch ( RepositoryException e1 )
{
}
}
throw new IOException( "NPANDAY-180-021: Could not open RDF Repository: Message =" + e.getMessage() );
}
for ( Model model : modelDependencies )
{
// System.out.println( "Storing dependency: Artifact Id = " + model.getArtifactId() );
artifactDependencies.addAll( storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model,
null ),
localRepository, artifactRepositories ) );
}
logger.finest( "NPANDAY-180-022: ProjectDao.storeProjectAndResolveDependencies - Artifact Id = "
+ project.getArtifactId() + ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = "
+ storeCounter++ );
return artifactDependencies;
}
| public Set<Artifact> storeProjectAndResolveDependencies( Project project, File localRepository,
List<ArtifactRepository> artifactRepositories )
throws IOException, IllegalArgumentException
{
long startTime = System.currentTimeMillis();
String snapshotVersion = null;
if ( project == null )
{
throw new IllegalArgumentException( "NPANDAY-180-009: Project is null" );
}
if ( project.getGroupId() == null || project.getArtifactId() == null || project.getVersion() == null )
{
throw new IllegalArgumentException( "NPANDAY-180-010: Project value is null: Group Id ="
+ project.getGroupId() + ", Artifact Id = " + project.getArtifactId() + ", Version = "
+ project.getVersion() );
}
Set<Artifact> artifactDependencies = new HashSet<Artifact>();
ValueFactory valueFactory = rdfRepository.getValueFactory();
URI id =
valueFactory.createURI( project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
+ ":" + project.getArtifactType() );
URI groupId = valueFactory.createURI( ProjectUri.GROUP_ID.getPredicate() );
URI artifactId = valueFactory.createURI( ProjectUri.ARTIFACT_ID.getPredicate() );
URI version = valueFactory.createURI( ProjectUri.VERSION.getPredicate() );
URI artifactType = valueFactory.createURI( ProjectUri.ARTIFACT_TYPE.getPredicate() );
URI classifier = valueFactory.createURI( ProjectUri.CLASSIFIER.getPredicate() );
URI isResolved = valueFactory.createURI( ProjectUri.IS_RESOLVED.getPredicate() );
URI artifact = valueFactory.createURI( ProjectUri.ARTIFACT.getPredicate() );
URI dependency = valueFactory.createURI( ProjectUri.DEPENDENCY.getPredicate() );
URI parent = valueFactory.createURI( ProjectUri.PARENT.getPredicate() );
Set<Model> modelDependencies = new HashSet<Model>();
try
{
repositoryConnection.add( id, RDF.TYPE, artifact );
repositoryConnection.add( id, groupId, valueFactory.createLiteral( project.getGroupId() ) );
repositoryConnection.add( id, artifactId, valueFactory.createLiteral( project.getArtifactId() ) );
repositoryConnection.add( id, version, valueFactory.createLiteral( project.getVersion() ) );
repositoryConnection.add( id, artifactType, valueFactory.createLiteral( project.getArtifactType() ) );
if ( project.getPublicKeyTokenId() != null )
{
URI classifierNode = valueFactory.createURI( project.getPublicKeyTokenId() + ":" );
for ( Requirement requirement : project.getRequirements() )
{
URI uri = valueFactory.createURI( requirement.getUri().toString() );
repositoryConnection.add( classifierNode, uri, valueFactory.createLiteral( requirement.getValue() ) );
}
repositoryConnection.add( id, classifier, classifierNode );
}
if ( project.getParentProject() != null )
{
Project parentProject = project.getParentProject();
URI pid =
valueFactory.createURI( parentProject.getGroupId() + ":" + parentProject.getArtifactId() + ":"
+ parentProject.getVersion() + ":" + project.getArtifactType() );
repositoryConnection.add( id, parent, pid );
artifactDependencies.addAll( storeProjectAndResolveDependencies( parentProject, null,
artifactRepositories ) );
}
for ( ProjectDependency projectDependency : project.getProjectDependencies() )
{
snapshotVersion = null;
logger.finest( "NPANDAY-180-011: Project Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Artifact Type = "
+ projectDependency.getArtifactType() );
// If artifact has been deleted, then re-resolve
if ( projectDependency.isResolved() && !ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
File dependencyFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if ( !dependencyFile.exists() )
{
projectDependency.setResolved( false );
}
}
// resolve system scope dependencies
if ( projectDependency.getScope() != null && projectDependency.getScope().equals( "system" ) )
{
if ( projectDependency.getSystemPath() == null )
{
throw new IOException( "systemPath required for System Scoped dependencies " + "in Group ID = "
+ projectDependency.getGroupId() + ", Artiract ID = " + projectDependency.getArtifactId() );
}
File f = new File( projectDependency.getSystemPath() );
if ( !f.exists() )
{
throw new IOException( "Dependency systemPath File not found:"
+ projectDependency.getSystemPath() + "in Group ID = " + projectDependency.getGroupId()
+ ", Artiract ID = " + projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve com reference
// flow:
// 1. generate the interop dll in temp folder and resolve to that path during dependency resolution
// 2. cut and paste the dll to buildDirectory and update the paths once we grab the reference of
// MavenProject (CompilerContext.java)
if ( projectDependency.getArtifactType().equals( "com_reference" ) )
{
String tokenId = projectDependency.getPublicKeyTokenId();
String interopPath = generateInteropDll( projectDependency.getArtifactId(), tokenId );
File f = new File( interopPath );
if ( !f.exists() )
{
throw new IOException( "Dependency com_reference File not found:" + interopPath
+ "in Group ID = " + projectDependency.getGroupId() + ", Artiract ID = "
+ projectDependency.getArtifactId() );
}
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
projectDependency.setResolved( true );
logger.info( "NPANDAY-180-011.1: Project Dependency Resolved: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = " + projectDependency.getScope()
+ "SystemPath = " + projectDependency.getSystemPath()
);
continue;
}
// resolve gac references
// note: the old behavior of gac references, used to have system path properties in the pom of the
// project
// now we need to generate the system path of the gac references so we can use
// System.getenv("SystemRoot")
if ( !projectDependency.isResolved() )
{
if ( ArtifactTypeHelper.isDotnetAnyGac( projectDependency.getArtifactType() ) )
{
try
{
projectDependency.setResolved( true );
if ( projectDependency.getSystemPath() == null )
{
projectDependency.setSystemPath( generateDependencySystemPath( projectDependency ) );
}
File f = new File( projectDependency.getSystemPath() );
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
assembly.setFile( f );
assembly.setResolved( true );
artifactDependencies.add( assembly );
}
catch ( ExceptionInInitializerError e )
{
logger.warning( "NPANDAY-180-516.82: Project Failed to Resolve Dependency: Artifact ID = "
+ projectDependency.getArtifactId() + ", Group ID = " + projectDependency.getGroupId()
+ ", Version = " + projectDependency.getVersion() + ", Scope = "
+ projectDependency.getScope() + "SystemPath = " + projectDependency.getSystemPath() );
}
}
else
{
try
{
Project dep =
this.getProjectFor( projectDependency.getGroupId(), projectDependency.getArtifactId(),
projectDependency.getVersion(),
projectDependency.getArtifactType(),
projectDependency.getPublicKeyTokenId() );
if ( dep.isResolved() )
{
projectDependency = (ProjectDependency) dep;
Artifact assembly =
ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
artifactDependencies.add( assembly );
artifactDependencies.addAll( this.storeProjectAndResolveDependencies(
projectDependency,
localRepository,
artifactRepositories ) );
}
}
catch ( IOException e )
{
// safe to ignore: dependency not found
}
}
}
if ( !projectDependency.isResolved() )
{
Artifact assembly = ProjectFactory.createArtifactFrom( projectDependency, artifactFactory );
if ( assembly.getType().equals( "jar" ) )
{
logger.info( "Detected jar dependency - skipping: Artifact Dependency ID = "
+ assembly.getArtifactId() );
continue;
}
ArtifactType type = ArtifactType.getArtifactTypeForPackagingName( assembly.getType() );
logger.info( "NPANDAY-180-012: Resolving artifact for unresolved dependency: "
+ assembly.getId());
ArtifactRepository localArtifactRepository =
new DefaultArtifactRepository( "local", "file://" + localRepository,
new DefaultRepositoryLayout() );
if ( !ArtifactTypeHelper.isDotnetExecutableConfig( type ))// TODO: Generalize to any attached artifact
{
Artifact pomArtifact =
artifactFactory.createProjectArtifact( projectDependency.getGroupId(),
projectDependency.getArtifactId(),
projectDependency.getVersion() );
try
{
artifactResolver.resolve( pomArtifact, artifactRepositories,
localArtifactRepository );
logger.info( "NPANDAY-180-024: resolving pom artifact: " + pomArtifact.toString() );
snapshotVersion = pomArtifact.getVersion();
}
catch ( ArtifactNotFoundException e )
{
logger.info( "NPANDAY-180-025: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
logger.info( "NPANDAY-180-026: Problem in resolving pom artifact: " + pomArtifact.toString()
+ ", Message = " + e.getMessage() );
}
if ( pomArtifact.getFile() != null && pomArtifact.getFile().exists() )
{
FileReader fileReader = new FileReader( pomArtifact.getFile() );
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model;
try
{
model = reader.read( fileReader ); // TODO: interpolate values
}
catch ( XmlPullParserException e )
{
throw new IOException( "NPANDAY-180-015: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
catch ( EOFException e )
{
throw new IOException( "NPANDAY-180-016: Unable to read model: Message = "
+ e.getMessage() + ", Path = " + pomArtifact.getFile().getAbsolutePath() );
}
// small hack for not doing inheritence
String g = model.getGroupId();
if ( g == null )
{
g = model.getParent().getGroupId();
}
String v = model.getVersion();
if ( v == null )
{
v = model.getParent().getVersion();
}
if ( !( g.equals( projectDependency.getGroupId() )
&& model.getArtifactId().equals( projectDependency.getArtifactId() ) && v.equals( projectDependency.getVersion() ) ) )
{
throw new IOException(
"NPANDAY-180-017: Model parameters do not match project dependencies parameters: Model: "
+ g + ":" + model.getArtifactId() + ":" + v + ", Project: "
+ projectDependency.getGroupId() + ":"
+ projectDependency.getArtifactId() + ":"
+ projectDependency.getVersion() );
}
modelDependencies.add( model );
}
}
if ( snapshotVersion != null )
{
assembly.setVersion( snapshotVersion );
}
File uacFile = PathUtil.getUserAssemblyCacheFileFor( assembly, localRepository );
if (uacFile.exists())
{
assembly.setFile( uacFile );
}
else
{
logger.info( "NPANDAY-180-018: Not found in UAC, now retrieving artifact from wagon:"
+ assembly.getId()
+ ", Failed UAC Path Check = " + uacFile.getAbsolutePath());
try
{
artifactResolver.resolve( assembly, artifactRepositories,
localArtifactRepository );
if ( assembly != null && assembly.getFile().exists() )
{
uacFile.getParentFile().mkdirs();
FileUtils.copyFile( assembly.getFile(), uacFile );
}
}
catch ( ArtifactNotFoundException e )
{
throw new IOException(
"NPANDAY-180-020: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
catch ( ArtifactResolutionException e )
{
throw new IOException(
"NPANDAY-180-019: Problem in resolving artifact: Artifact = "
+ assembly.getId()
+ ", Message = " + e.getMessage() );
}
}
artifactDependencies.add( assembly );
}// end if dependency not resolved
URI did =
valueFactory.createURI( projectDependency.getGroupId() + ":" + projectDependency.getArtifactId()
+ ":" + projectDependency.getVersion() + ":" + projectDependency.getArtifactType() );
repositoryConnection.add( did, RDF.TYPE, artifact );
repositoryConnection.add( did, groupId, valueFactory.createLiteral( projectDependency.getGroupId() ) );
repositoryConnection.add( did, artifactId,
valueFactory.createLiteral( projectDependency.getArtifactId() ) );
repositoryConnection.add( did, version, valueFactory.createLiteral( projectDependency.getVersion() ) );
repositoryConnection.add( did, artifactType,
valueFactory.createLiteral( projectDependency.getArtifactType() ) );
if ( projectDependency.getPublicKeyTokenId() != null )
{
repositoryConnection.add(
did,
classifier,
valueFactory.createLiteral( projectDependency.getPublicKeyTokenId() + ":" ) );
}
repositoryConnection.add( id, dependency, did );
}// end for
repositoryConnection.add( id, isResolved, valueFactory.createLiteral( true ) );
repositoryConnection.commit();
}
catch ( OpenRDFException e )
{
if ( repositoryConnection != null )
{
try
{
repositoryConnection.rollback();
}
catch ( RepositoryException e1 )
{
}
}
throw new IOException( "NPANDAY-180-021: Could not open RDF Repository: Message =" + e.getMessage() );
}
for ( Model model : modelDependencies )
{
// System.out.println( "Storing dependency: Artifact Id = " + model.getArtifactId() );
artifactDependencies.addAll( storeProjectAndResolveDependencies( ProjectFactory.createProjectFrom( model,
null ),
localRepository, artifactRepositories ) );
}
logger.finest( "NPANDAY-180-022: ProjectDao.storeProjectAndResolveDependencies - Artifact Id = "
+ project.getArtifactId() + ", Time = " + ( System.currentTimeMillis() - startTime ) + ", Count = "
+ storeCounter++ );
return artifactDependencies;
}
|
diff --git a/pac4j-http/src/main/java/org/pac4j/http/client/FormClient.java b/pac4j-http/src/main/java/org/pac4j/http/client/FormClient.java
index f906cebc..0e42b777 100644
--- a/pac4j-http/src/main/java/org/pac4j/http/client/FormClient.java
+++ b/pac4j-http/src/main/java/org/pac4j/http/client/FormClient.java
@@ -1,175 +1,175 @@
/*
Copyright 2012 - 2014 Jerome Leleu
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.pac4j.http.client;
import org.pac4j.core.client.BaseClient;
import org.pac4j.core.client.Mechanism;
import org.pac4j.core.client.RedirectAction;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.exception.RequiresHttpAction;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.http.credentials.UsernamePasswordAuthenticator;
import org.pac4j.http.credentials.UsernamePasswordCredentials;
import org.pac4j.http.profile.HttpProfile;
import org.pac4j.http.profile.ProfileCreator;
/**
* This class is the client to authenticate users through HTTP form.
* <p />
* The login url of the form must be defined through the {@link #setLoginUrl(String)} method. For authentication, the user is redirected to
* this login form. The username and password inputs must be posted on the callback url. Their names can be defined by using the
* {@link #setUsernameParameter(String)} and {@link #setPasswordParameter(String)} methods.
* <p />
* It returns a {@link org.pac4j.http.profile.HttpProfile}.
*
* @see org.pac4j.http.profile.HttpProfile
* @author Jerome Leleu
* @since 1.4.0
*/
public class FormClient extends BaseHttpClient {
private String loginUrl;
public final static String ERROR_PARAMETER = "error";
public final static String MISSING_FIELD_ERROR = "missing_field";
public final static String DEFAULT_USERNAME_PARAMETER = "username";
private String usernameParameter = DEFAULT_USERNAME_PARAMETER;
public final static String DEFAULT_PASSWORD_PARAMETER = "password";
private String passwordParameter = DEFAULT_PASSWORD_PARAMETER;
public FormClient() {
}
public FormClient(final String loginUrl, final UsernamePasswordAuthenticator usernamePasswordAuthenticator) {
setLoginUrl(loginUrl);
setUsernamePasswordAuthenticator(usernamePasswordAuthenticator);
}
public FormClient(final String loginUrl, final UsernamePasswordAuthenticator usernamePasswordAuthenticator,
final ProfileCreator profileCreator) {
this(loginUrl, usernamePasswordAuthenticator);
setProfileCreator(profileCreator);
}
@Override
protected BaseClient<UsernamePasswordCredentials, HttpProfile> newClient() {
final FormClient newClient = new FormClient();
newClient.setLoginUrl(this.loginUrl);
newClient.setUsernameParameter(this.usernameParameter);
newClient.setPasswordParameter(this.passwordParameter);
return newClient;
}
@Override
protected void internalInit() {
super.internalInit();
CommonHelper.assertNotBlank("loginUrl", this.loginUrl);
}
@Override
protected RedirectAction retrieveRedirectAction(final WebContext context) {
return RedirectAction.redirect(this.loginUrl);
}
@Override
protected UsernamePasswordCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction {
final String username = context.getRequestParameter(this.usernameParameter);
final String password = context.getRequestParameter(this.passwordParameter);
if (CommonHelper.isNotBlank(username) && CommonHelper.isNotBlank(password)) {
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password,
getName());
logger.debug("usernamePasswordCredentials : {}", credentials);
try {
// validate credentials
this.usernamePasswordAuthenticator.validate(credentials);
} catch (final TechnicalException e) {
String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username);
String errorMessage = computeErrorMessage(e);
redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, errorMessage);
logger.debug("redirectionUrl : {}", redirectionUrl);
final String message = "Credentials validation fails -> return to the form with error";
- logger.error(message);
+ logger.debug(message);
throw RequiresHttpAction.redirect(message, context, redirectionUrl);
}
return credentials;
}
String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username);
redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, MISSING_FIELD_ERROR);
logger.debug("redirectionUrl : {}", redirectionUrl);
final String message = "Username and password cannot be blank -> return to the form with error";
- logger.error(message);
+ logger.debug(message);
throw RequiresHttpAction.redirect(message, context, redirectionUrl);
}
/**
* Return the error message depending on the thrown exception. Can be overriden for other message computation.
*
* @param e
* @return the error message
*/
protected String computeErrorMessage(final TechnicalException e) {
return e.getClass().getSimpleName();
}
public String getLoginUrl() {
return this.loginUrl;
}
public void setLoginUrl(final String loginUrl) {
this.loginUrl = loginUrl;
}
public String getUsernameParameter() {
return this.usernameParameter;
}
public void setUsernameParameter(final String usernameParameter) {
this.usernameParameter = usernameParameter;
}
public String getPasswordParameter() {
return this.passwordParameter;
}
public void setPasswordParameter(final String passwordParameter) {
this.passwordParameter = passwordParameter;
}
@Override
public String toString() {
return CommonHelper.toString(this.getClass(), "callbackUrl", this.callbackUrl, "name", getName(), "loginUrl",
this.loginUrl, "usernameParameter", this.usernameParameter, "passwordParameter",
this.passwordParameter, "usernamePasswordAuthenticator",
getUsernamePasswordAuthenticator(), "profileCreator", getProfileCreator());
}
@Override
protected boolean isDirectRedirection() {
return true;
}
@Override
public Mechanism getMechanism() {
return Mechanism.FORM_MECHANISM;
}
}
| false | true | protected UsernamePasswordCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction {
final String username = context.getRequestParameter(this.usernameParameter);
final String password = context.getRequestParameter(this.passwordParameter);
if (CommonHelper.isNotBlank(username) && CommonHelper.isNotBlank(password)) {
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password,
getName());
logger.debug("usernamePasswordCredentials : {}", credentials);
try {
// validate credentials
this.usernamePasswordAuthenticator.validate(credentials);
} catch (final TechnicalException e) {
String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username);
String errorMessage = computeErrorMessage(e);
redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, errorMessage);
logger.debug("redirectionUrl : {}", redirectionUrl);
final String message = "Credentials validation fails -> return to the form with error";
logger.error(message);
throw RequiresHttpAction.redirect(message, context, redirectionUrl);
}
return credentials;
}
String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username);
redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, MISSING_FIELD_ERROR);
logger.debug("redirectionUrl : {}", redirectionUrl);
final String message = "Username and password cannot be blank -> return to the form with error";
logger.error(message);
throw RequiresHttpAction.redirect(message, context, redirectionUrl);
}
| protected UsernamePasswordCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction {
final String username = context.getRequestParameter(this.usernameParameter);
final String password = context.getRequestParameter(this.passwordParameter);
if (CommonHelper.isNotBlank(username) && CommonHelper.isNotBlank(password)) {
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password,
getName());
logger.debug("usernamePasswordCredentials : {}", credentials);
try {
// validate credentials
this.usernamePasswordAuthenticator.validate(credentials);
} catch (final TechnicalException e) {
String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username);
String errorMessage = computeErrorMessage(e);
redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, errorMessage);
logger.debug("redirectionUrl : {}", redirectionUrl);
final String message = "Credentials validation fails -> return to the form with error";
logger.debug(message);
throw RequiresHttpAction.redirect(message, context, redirectionUrl);
}
return credentials;
}
String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username);
redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, MISSING_FIELD_ERROR);
logger.debug("redirectionUrl : {}", redirectionUrl);
final String message = "Username and password cannot be blank -> return to the form with error";
logger.debug(message);
throw RequiresHttpAction.redirect(message, context, redirectionUrl);
}
|
diff --git a/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java b/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java
index 21cda73d..289bbd37 100644
--- a/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java
+++ b/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java
@@ -1,9547 +1,9551 @@
/* @(#)BasicJideTabbedPaneUI.java
*
* Copyright 2002 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.plaf.basic;
import com.jidesoft.plaf.JideTabbedPaneUI;
import com.jidesoft.plaf.UIDefaultsLookup;
import com.jidesoft.popup.JidePopup;
import com.jidesoft.swing.JideSwingUtilities;
import com.jidesoft.swing.JideTabbedPane;
import com.jidesoft.swing.PartialLineBorder;
import com.jidesoft.swing.Sticky;
import com.jidesoft.utils.PortingUtils;
import com.jidesoft.utils.SecurityUtils;
import com.jidesoft.utils.SystemInfo;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;
import java.awt.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Vector;
/**
* A basic L&f implementation of JideTabbedPaneUI
*/
public class BasicJideTabbedPaneUI extends JideTabbedPaneUI implements SwingConstants, DocumentListener {
// pixels
protected int _tabRectPadding;// distance from tab rect to icon/text
protected int _closeButtonMarginHorizon; // when tab is on top or bottom, and each tab has close button, the gap around the close button
protected int _closeButtonMarginVertical;// when tab is on left or right, and each tab has close button, the gap around the close button
protected int _textMarginVertical;// tab area and text area gap
protected int _noIconMargin;// gap around text area when there is no icon
protected int _iconMargin;// distance from icon to tab rect start x
protected int _textPadding;// distance from text to tab rect start
protected int _buttonSize;// scroll button size
protected int _buttonMargin;// scroll button margin
protected int _fitStyleBoundSize;// margin for the whole tab area
protected int _fitStyleFirstTabMargin;// the first tab position
protected int _fitStyleIconMinWidth;// minimum width to display icon
protected int _fitStyleTextMinWidth;// minimum width to display text
protected int _compressedStyleNoIconRectSize;// tab size when there is no icon and tab not selected
protected int _compressedStyleIconMargin;// margin around icon
protected int _compressedStyleCloseButtonMarginHorizon;// the close button margin on the left or right when the tab is on the top or bottom
protected int _compressedStyleCloseButtonMarginVertical;// the close button margin on the top or bottom when the tab is on the left or right
protected int _fixedStyleRectSize;// tab rect size
protected int _closeButtonMargin;// margin around close button
protected int _gripLeftMargin;// left margin
protected int _closeButtonMarginSize;// margin around the close button
protected int _closeButtonLeftMargin;// the close button gap when the tab is on the left
protected int _closeButtonRightMargin;// the close button gap when the tab is on the right
protected Component _tabLeadingComponent = null;
protected Component _tabTrailingComponent = null;
protected JideTabbedPane _tabPane;
protected Color _tabBackground;
protected Color _background;
protected Color _highlight;
protected Color _lightHighlight;
protected Color _shadow;
protected Color _darkShadow;
protected Color _focus;
protected Color _inactiveTabForeground;
protected Color _activeTabForeground;
protected Color _tabListBackground;
protected Color _selectedColor;
protected int _textIconGap;
protected int _tabRunOverlay;
protected boolean _showIconOnTab;
protected boolean _showCloseButtonOnTab;
protected int _closeButtonAlignment = SwingConstants.TRAILING;
protected Insets _tabInsets;
protected Insets _selectedTabPadInsets;
protected Insets _tabAreaInsets;
protected boolean _ignoreContentBorderInsetsIfNoTabs;
// Transient variables (recalculated each time TabbedPane is laid out)
protected int _tabRuns[] = new int[10];
protected int _runCount = 0;
protected int _selectedRun = -1;
protected Rectangle _rects[] = new Rectangle[0];
protected int _maxTabHeight;
protected int _maxTabWidth;
protected int _gripperWidth = 6;
protected int _gripperHeight = 6;
// Listeners
protected ChangeListener _tabChangeListener;
protected FocusListener _tabFocusListener;
protected PropertyChangeListener _propertyChangeListener;
protected MouseListener _mouseListener;
protected MouseMotionListener _mousemotionListener;
protected MouseWheelListener _mouseWheelListener;
// PENDING(api): See comment for ContainerHandler
private ContainerListener _containerListener;
private ComponentListener _componentListener;
// Private instance data
private Insets _currentTabInsets = new Insets(0, 0, 0, 0);
private Insets _currentPadInsets = new Insets(0, 0, 0, 0);
private Insets _currentTabAreaInsets = new Insets(2, 4, 0, 4);
private Insets _currentContentBorderInsets = new Insets(3, 0, 0, 0);
private Component visibleComponent;
// PENDING(api): See comment for ContainerHandler
private Vector htmlViews;
private Hashtable _mnemonicToIndexMap;
/**
* InputMap used for mnemonics. Only non-null if the JTabbedPane has mnemonics associated with it. Lazily created in
* initMnemonics.
*/
private InputMap _mnemonicInputMap;
// For use when tabLayoutPolicy = SCROLL_TAB_LAYOUT
public ScrollableTabSupport _tabScroller;
/**
* A rectangle used for general layout calculations in order to avoid constructing many new Rectangles on the fly.
*/
protected transient Rectangle _calcRect = new Rectangle(0, 0, 0, 0);
/**
* Number of tabs. When the count differs, the mnemonics are updated.
*/
// PENDING: This wouldn't be necessary if JTabbedPane had a better
// way of notifying listeners when the count changed.
protected int _tabCount;
protected TabCloseButton[] _closeButtons;
// UI creation
private ThemePainter _painter;
private Painter _gripperPainter;
private DropTargetListener _dropListener;
public DropTarget _dt;
// the left margin of the first tab according to the style
public static final int DEFAULT_LEFT_MARGIN = 0;
public static final int OFFICE2003_LEFT_MARGIN = 18;
public static final int EXCEL_LEFT_MARGIN = 6;
protected int _rectSizeExtend = 0;//when the style is eclipse,
//we should extend the size of the rects for hold the title
protected Polygon tabRegion = null;
protected Color _selectColor1 = null;
protected Color _selectColor2 = null;
protected Color _selectColor3 = null;
protected Color _unselectColor1 = null;
protected Color _unselectColor2 = null;
protected Color _unselectColor3 = null;
protected Color _officeTabBorderColor;
protected Color _defaultTabBorderShadowColor;
protected boolean _mouseEnter = false;
protected int _indexMouseOver = -1;
protected boolean _alwaysShowLineBorder = false;
protected boolean _showFocusIndicator = false;
public static final String BUTTON_NAME_CLOSE = "JideTabbedPane.close";
public static final String BUTTON_NAME_TAB_LIST = "JideTabbedPane.showList";
public static final String BUTTON_NAME_SCROLL_BACKWARD = "JideTabbedPane.scrollBackward";
public static final String BUTTON_NAME_SCROLL_FORWARD = "JideTabbedPane.scrollForward";
@SuppressWarnings({"UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new BasicJideTabbedPaneUI();
}
// UI Installation/De-installation
@Override
public void installUI(JComponent c) {
if (c == null) {
return;
}
_tabPane = (JideTabbedPane) c;
if (_tabPane.isTabShown() && _tabPane.getTabLeadingComponent() != null) {
_tabLeadingComponent = _tabPane.getTabLeadingComponent();
}
if (_tabPane.isTabShown() && _tabPane.getTabTrailingComponent() != null) {
_tabTrailingComponent = _tabPane.getTabTrailingComponent();
}
c.setLayout(createLayoutManager());
installComponents();
installDefaults();
installColorTheme();
installListeners();
installKeyboardActions();
}
public void installColorTheme() {
switch (getTabShape()) {
case JideTabbedPane.SHAPE_EXCEL:
_selectColor1 = _darkShadow;
_selectColor2 = _lightHighlight;
_selectColor3 = _shadow;
_unselectColor1 = _darkShadow;
_unselectColor2 = _lightHighlight;
_unselectColor3 = _shadow;
break;
case JideTabbedPane.SHAPE_WINDOWS:
case JideTabbedPane.SHAPE_WINDOWS_SELECTED:
_selectColor1 = _lightHighlight;
_selectColor2 = _shadow;
_selectColor3 = _defaultTabBorderShadowColor;
_unselectColor1 = _selectColor1;
_unselectColor2 = _selectColor2;
_unselectColor3 = _selectColor3;
break;
case JideTabbedPane.SHAPE_VSNET:
_selectColor1 = _shadow;
_selectColor2 = _shadow;
_unselectColor1 = _selectColor1;
break;
case JideTabbedPane.SHAPE_ROUNDED_VSNET:
_selectColor1 = _shadow;
_selectColor2 = _selectColor1;
_unselectColor1 = _selectColor1;
break;
case JideTabbedPane.SHAPE_FLAT:
_selectColor1 = _shadow;
_unselectColor1 = _selectColor1;
break;
case JideTabbedPane.SHAPE_ROUNDED_FLAT:
_selectColor1 = _shadow;
_selectColor2 = _shadow;
_unselectColor1 = _selectColor1;
_unselectColor2 = _selectColor2;
break;
case JideTabbedPane.SHAPE_BOX:
_selectColor1 = _shadow;
_selectColor2 = _lightHighlight;
_unselectColor1 = getPainter().getControlShadow();
_unselectColor2 = _lightHighlight;
break;
case JideTabbedPane.SHAPE_OFFICE2003:
default:
_selectColor1 = _shadow;
_selectColor2 = _lightHighlight;
_unselectColor1 = _shadow;
_unselectColor2 = null;
_unselectColor3 = null;
}
}
@Override
public void uninstallUI(JComponent c) {
uninstallKeyboardActions();
uninstallListeners();
uninstallColorTheme();
uninstallDefaults();
uninstallComponents();
c.setLayout(null);
_tabTrailingComponent = null;
_tabLeadingComponent = null;
_tabPane = null;
}
public void uninstallColorTheme() {
_selectColor1 = null;
_selectColor2 = null;
_selectColor3 = null;
_unselectColor1 = null;
_unselectColor2 = null;
_unselectColor3 = null;
}
/**
* Invoked by <code>installUI</code> to create a layout manager object to manage the <code>JTabbedPane</code>.
*
* @return a layout manager object
*
* @see TabbedPaneLayout
* @see JTabbedPane#getTabLayoutPolicy
*/
protected LayoutManager createLayoutManager() {
if (_tabPane.getTabLayoutPolicy() == JideTabbedPane.SCROLL_TAB_LAYOUT) {
return new TabbedPaneScrollLayout();
}
else { /* WRAP_TAB_LAYOUT */
return new TabbedPaneLayout();
}
}
/* In an attempt to preserve backward compatibility for programs
* which have extended VsnetJideTabbedPaneUI to do their own layout, the
* UI uses the installed layoutManager (and not tabLayoutPolicy) to
* determine if scrollTabLayout is enabled.
*/
protected boolean scrollableTabLayoutEnabled() {
return (_tabPane.getLayout() instanceof TabbedPaneScrollLayout);
}
/**
* Creates and installs any required subcomponents for the JTabbedPane. Invoked by installUI.
*/
protected void installComponents() {
if (scrollableTabLayoutEnabled()) {
if (_tabScroller == null) {
_tabScroller = new ScrollableTabSupport(_tabPane.getTabPlacement());
_tabPane.add(_tabScroller.viewport);
_tabPane.add(_tabScroller.scrollForwardButton);
_tabPane.add(_tabScroller.scrollBackwardButton);
_tabPane.add(_tabScroller.listButton);
_tabPane.add(_tabScroller.closeButton);
if (_tabLeadingComponent != null) {
_tabPane.add(_tabLeadingComponent);
}
if (_tabTrailingComponent != null) {
_tabPane.add(_tabTrailingComponent);
}
}
}
}
/**
* Removes any installed subcomponents from the JTabbedPane. Invoked by uninstallUI.
*/
protected void uninstallComponents() {
if (scrollableTabLayoutEnabled()) {
_tabPane.remove(_tabScroller.viewport);
_tabPane.remove(_tabScroller.scrollForwardButton);
_tabPane.remove(_tabScroller.scrollBackwardButton);
_tabPane.remove(_tabScroller.listButton);
_tabPane.remove(_tabScroller.closeButton);
if (_tabLeadingComponent != null) {
_tabPane.remove(_tabLeadingComponent);
}
if (_tabTrailingComponent != null) {
_tabPane.remove(_tabTrailingComponent);
}
_tabScroller = null;
}
}
protected void installDefaults() {
_painter = (ThemePainter) UIDefaultsLookup.get("Theme.painter");
_gripperPainter = (Painter) UIDefaultsLookup.get("JideTabbedPane.gripperPainter");
LookAndFeel.installColorsAndFont(_tabPane, "JideTabbedPane.background",
"JideTabbedPane.foreground", "JideTabbedPane.font");
LookAndFeel.installBorder(_tabPane, "JideTabbedPane.border");
Font f = _tabPane.getSelectedTabFont();
if (f == null || f instanceof UIResource) {
_tabPane.setSelectedTabFont(UIDefaultsLookup.getFont("JideTabbedPane.selectedTabFont"));
}
_highlight = UIDefaultsLookup.getColor("JideTabbedPane.light");
_lightHighlight = UIDefaultsLookup.getColor("JideTabbedPane.highlight");
_shadow = UIDefaultsLookup.getColor("JideTabbedPane.shadow");
_darkShadow = UIDefaultsLookup.getColor("JideTabbedPane.darkShadow");
_focus = UIDefaultsLookup.getColor("TabbedPane.focus");
if (getTabShape() == JideTabbedPane.SHAPE_BOX) {
_background = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground");
_tabBackground = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground");
_inactiveTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.foreground"); // text is black
_activeTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.foreground"); // text is black
_selectedColor = _lightHighlight;
}
else {
_background = UIDefaultsLookup.getColor("JideTabbedPane.background");
_tabBackground = UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground");
_inactiveTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.unselectedTabTextForeground");
_activeTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabTextForeground");
_selectedColor = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground");
}
_tabListBackground = UIDefaultsLookup.getColor("JideTabbedPane.tabListBackground");
_textIconGap = UIDefaultsLookup.getInt("JideTabbedPane.textIconGap");
_tabInsets = UIDefaultsLookup.getInsets("JideTabbedPane.tabInsets");
_selectedTabPadInsets = UIDefaultsLookup.getInsets("TabbedPane.selectedTabPadInsets");
if (_selectedTabPadInsets == null) _selectedTabPadInsets = new InsetsUIResource(0, 0, 0, 0);
_tabAreaInsets = UIDefaultsLookup.getInsets("JideTabbedPane.tabAreaInsets");
if (_tabAreaInsets == null) _tabAreaInsets = new InsetsUIResource(0, 0, 0, 0);
Insets insets = _tabPane.getContentBorderInsets();
if (insets == null || insets instanceof UIResource) {
_tabPane.setContentBorderInsets(UIDefaultsLookup.getInsets("JideTabbedPane.contentBorderInsets"));
}
_ignoreContentBorderInsetsIfNoTabs = UIDefaultsLookup.getBoolean("JideTabbedPane.ignoreContentBorderInsetsIfNoTabs");
_tabRunOverlay = UIDefaultsLookup.getInt("JideTabbedPane.tabRunOverlay");
_showIconOnTab = UIDefaultsLookup.getBoolean("JideTabbedPane.showIconOnTab");
_showCloseButtonOnTab = UIDefaultsLookup.getBoolean("JideTabbedPane.showCloseButtonOnTab");
_closeButtonAlignment = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonAlignment");
_gripperWidth = UIDefaultsLookup.getInt("Gripper.size");
_tabRectPadding = UIDefaultsLookup.getInt("JideTabbedPane.tabRectPadding");
_closeButtonMarginHorizon = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginHorizonal");
_closeButtonMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginVertical");
_textMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.textMarginVertical");
_noIconMargin = UIDefaultsLookup.getInt("JideTabbedPane.noIconMargin");
_iconMargin = UIDefaultsLookup.getInt("JideTabbedPane.iconMargin");
_textPadding = UIDefaultsLookup.getInt("JideTabbedPane.textPadding");
_buttonSize = UIDefaultsLookup.getInt("JideTabbedPane.buttonSize");
_buttonMargin = UIDefaultsLookup.getInt("JideTabbedPane.buttonMargin");
_fitStyleBoundSize = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleBoundSize");
_fitStyleFirstTabMargin = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleFirstTabMargin");
_fitStyleIconMinWidth = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleIconMinWidth");
_fitStyleTextMinWidth = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleTextMinWidth");
_compressedStyleNoIconRectSize = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleNoIconRectSize");
_compressedStyleIconMargin = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleIconMargin");
_compressedStyleCloseButtonMarginHorizon = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleCloseButtonMarginHorizontal");
_compressedStyleCloseButtonMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleCloseButtonMarginVertical");
_fixedStyleRectSize = UIDefaultsLookup.getInt("JideTabbedPane.fixedStyleRectSize");
_closeButtonMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMargin");
_gripLeftMargin = UIDefaultsLookup.getInt("JideTabbedPane.gripLeftMargin");
_closeButtonMarginSize = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginSize");
_closeButtonLeftMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonLeftMargin");
_closeButtonRightMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonRightMargin");
_defaultTabBorderShadowColor = UIDefaultsLookup.getColor("JideTabbedPane.defaultTabBorderShadowColor");
_alwaysShowLineBorder = UIDefaultsLookup.getBoolean("JideTabbedPane.alwaysShowLineBorder");
_showFocusIndicator = UIDefaultsLookup.getBoolean("JideTabbedPane.showFocusIndicator");
}
protected void uninstallDefaults() {
_painter = null;
_gripperPainter = null;
_highlight = null;
_lightHighlight = null;
_shadow = null;
_darkShadow = null;
_focus = null;
_inactiveTabForeground = null;
_selectedColor = null;
_tabInsets = null;
_selectedTabPadInsets = null;
_tabAreaInsets = null;
_defaultTabBorderShadowColor = null;
}
protected void installListeners() {
_tabPane.getModel().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (_tabPane != null) { // in case updateUI() was invoked, it could be null
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount() && _tabScroller != null && _tabScroller.closeButton != null) {
_tabScroller.closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex));
}
}
}
});
if (_propertyChangeListener == null) {
_propertyChangeListener = createPropertyChangeListener();
_tabPane.addPropertyChangeListener(_propertyChangeListener);
}
if (_tabChangeListener == null) {
_tabChangeListener = createChangeListener();
_tabPane.addChangeListener(_tabChangeListener);
}
if (_tabFocusListener == null) {
_tabFocusListener = createFocusListener();
_tabPane.addFocusListener(_tabFocusListener);
}
if (_mouseListener == null) {
_mouseListener = createMouseListener();
_tabPane.addMouseListener(_mouseListener);
}
if (_mousemotionListener == null) {
_mousemotionListener = createMouseMotionListener();
_tabPane.addMouseMotionListener(_mousemotionListener);
}
if (_mouseWheelListener == null) {
_mouseWheelListener = createMouseWheelListener();
_tabPane.addMouseWheelListener(_mouseWheelListener);
}
// PENDING(api) : See comment for ContainerHandler
if (_containerListener == null) {
_containerListener = new ContainerHandler();
_tabPane.addContainerListener(_containerListener);
if (_tabPane.getTabCount() > 0) {
htmlViews = createHTMLVector();
}
}
if (_componentListener == null) {
_componentListener = new ComponentHandler();
_tabPane.addComponentListener(_componentListener);
}
if (!_tabPane.isDragOverDisabled()) {
if (_dropListener == null) {
_dropListener = createDropListener();
_dt = new DropTarget(getTabPanel(), _dropListener);
}
}
}
protected DropListener createDropListener() {
return new DropListener();
}
protected void uninstallListeners() {
// PENDING(api): See comment for ContainerHandler
if (_containerListener != null) {
_tabPane.removeContainerListener(_containerListener);
_containerListener = null;
if (htmlViews != null) {
htmlViews.removeAllElements();
htmlViews = null;
}
}
if (_componentListener != null) {
_tabPane.removeComponentListener(_componentListener);
_componentListener = null;
}
if (_tabChangeListener != null) {
_tabPane.removeChangeListener(_tabChangeListener);
_tabChangeListener = null;
}
if (_tabFocusListener != null) {
_tabPane.removeFocusListener(_tabFocusListener);
_tabFocusListener = null;
}
if (_mouseListener != null) {
_tabPane.removeMouseListener(_mouseListener);
_mouseListener = null;
}
if (_mousemotionListener != null) {
_tabPane.removeMouseMotionListener(_mousemotionListener);
_mousemotionListener = null;
}
if (_mouseWheelListener != null) {
_tabPane.removeMouseWheelListener(_mouseWheelListener);
_mouseWheelListener = null;
}
if (_propertyChangeListener != null) {
_tabPane.removePropertyChangeListener(_propertyChangeListener);
_propertyChangeListener = null;
}
if (_dt != null && _dropListener != null) {
_dt.removeDropTargetListener(_dropListener);
_dropListener = null;
_dt = null;
getTabPanel().setDropTarget(null);
}
}
protected ChangeListener createChangeListener() {
return new TabSelectionHandler();
}
protected FocusListener createFocusListener() {
return new TabFocusListener();
}
protected PropertyChangeListener createPropertyChangeListener() {
return new PropertyChangeHandler();
}
protected void installKeyboardActions() {
InputMap km = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km);
km = getInputMap(JComponent.WHEN_FOCUSED);
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_FOCUSED, km);
ActionMap am = getActionMap();
SwingUtilities.replaceUIActionMap(_tabPane, am);
ensureCloseButtonCreated();
if (scrollableTabLayoutEnabled()) {
_tabScroller.scrollForwardButton.setAction(am.get("scrollTabsForwardAction"));
_tabScroller.scrollBackwardButton.setAction(am.get("scrollTabsBackwardAction"));
_tabScroller.listButton.setAction(am.get("scrollTabsListAction"));
Action action = _tabPane.getCloseAction();
updateButtonFromAction(_tabScroller.closeButton, action);
_tabScroller.closeButton.setAction(am.get("closeTabAction"));
}
}
InputMap getInputMap(int condition) {
if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) {
return (InputMap) UIDefaultsLookup.get("JideTabbedPane.ancestorInputMap");
}
else if (condition == JComponent.WHEN_FOCUSED) {
return (InputMap) UIDefaultsLookup.get("JideTabbedPane.focusInputMap");
}
return null;
}
ActionMap getActionMap() {
ActionMap map = (ActionMap) UIDefaultsLookup.get("JideTabbedPane.actionMap");
if (map == null) {
map = createActionMap();
if (map != null) {
UIManager.getLookAndFeelDefaults().put("JideTabbedPane.actionMap", map);
}
}
return map;
}
ActionMap createActionMap() {
ActionMap map = new ActionMapUIResource();
map.put("navigateNext", new NextAction());
map.put("navigatePrevious", new PreviousAction());
map.put("navigateRight", new RightAction());
map.put("navigateLeft", new LeftAction());
map.put("navigateUp", new UpAction());
map.put("navigateDown", new DownAction());
map.put("navigatePageUp", new PageUpAction());
map.put("navigatePageDown", new PageDownAction());
map.put("requestFocus", new RequestFocusAction());
map.put("requestFocusForVisibleComponent", new RequestFocusForVisibleAction());
map.put("setSelectedIndex", new SetSelectedIndexAction());
map.put("scrollTabsForwardAction", new ScrollTabsForwardAction());
map.put("scrollTabsBackwardAction", new ScrollTabsBackwardAction());
map.put("scrollTabsListAction", new ScrollTabsListAction());
map.put("closeTabAction", new CloseTabAction());
return map;
}
protected void uninstallKeyboardActions() {
SwingUtilities.replaceUIActionMap(_tabPane, null);
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_FOCUSED, null);
if (_closeButtons != null) {
for (int i = 0; i < _closeButtons.length; i++) {
_closeButtons[i] = null;
}
_closeButtons = null;
}
}
/**
* Reloads the mnemonics. This should be invoked when a mnemonic changes, when the title of a mnemonic changes, or
* when tabs are added/removed.
*/
protected void updateMnemonics() {
resetMnemonics();
for (int counter = _tabPane.getTabCount() - 1; counter >= 0; counter--) {
int mnemonic = _tabPane.getMnemonicAt(counter);
if (mnemonic > 0) {
addMnemonic(counter, mnemonic);
}
}
}
/**
* Resets the mnemonics bindings to an empty state.
*/
private void resetMnemonics() {
if (_mnemonicToIndexMap != null) {
_mnemonicToIndexMap.clear();
_mnemonicInputMap.clear();
}
}
/**
* Adds the specified mnemonic at the specified index.
* @param index the index
* @param mnemonic the mnemonic for the index
*/
private void addMnemonic(int index, int mnemonic) {
if (_mnemonicToIndexMap == null) {
initMnemonics();
}
_mnemonicInputMap.put(KeyStroke.getKeyStroke(mnemonic, Event.ALT_MASK), "setSelectedIndex");
_mnemonicToIndexMap.put(mnemonic, index);
}
/**
* Installs the state needed for mnemonics.
*/
private void initMnemonics() {
_mnemonicToIndexMap = new Hashtable();
_mnemonicInputMap = new InputMapUIResource();
_mnemonicInputMap.setParent(SwingUtilities.getUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, _mnemonicInputMap);
}
// Geometry
@Override
public Dimension getPreferredSize(JComponent c) {
// Default to LayoutManager's preferredLayoutSize
return null;
}
@Override
public Dimension getMinimumSize(JComponent c) {
// Default to LayoutManager's minimumLayoutSize
return null;
}
@Override
public Dimension getMaximumSize(JComponent c) {
// Default to LayoutManager's maximumLayoutSize
return null;
}
// UI Rendering
@Override
public void paint(Graphics g, JComponent c) {
int tc = _tabPane.getTabCount();
paintBackground(g, c);
if (tc == 0) {
return;
}
if (_tabCount != tc) {
_tabCount = tc;
updateMnemonics();
}
int selectedIndex = _tabPane.getSelectedIndex();
int tabPlacement = _tabPane.getTabPlacement();
ensureCurrentLayout();
// Paint tab area
// If scrollable tabs are enabled, the tab area will be
// painted by the scrollable tab panel instead.
//
if (!scrollableTabLayoutEnabled()) { // WRAP_TAB_LAYOUT
paintTabArea(g, tabPlacement, selectedIndex, c);
}
// Paint content border
// if (_tabPane.isTabShown())
paintContentBorder(g, tabPlacement, selectedIndex);
}
public void paintBackground(Graphics g, Component c) {
if (_tabPane.isOpaque()) {
int width = c.getWidth();
int height = c.getHeight();
g.setColor(_background);
g.fillRect(0, 0, width, height);
}
}
/**
* Paints the tabs in the tab area. Invoked by paint(). The graphics parameter must be a valid <code>Graphics</code>
* object. Tab placement may be either: <code>JTabbedPane.TOP</code>, <code>JTabbedPane.BOTTOM</code>,
* <code>JTabbedPane.LEFT</code>, or <code>JTabbedPane.RIGHT</code>. The selected index must be a valid tabbed pane
* tab index (0 to tab count - 1, inclusive) or -1 if no tab is currently selected. The handling of invalid
* parameters is unspecified.
*
* @param g the graphics object to use for rendering
* @param tabPlacement the placement for the tabs within the JTabbedPane
* @param selectedIndex the tab index of the selected component
* @param c the component
*/
protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex, Component c) {
if (!PAINT_TABAREA) {
return;
}
int tabCount = _tabPane.getTabCount();
Rectangle iconRect = new Rectangle(),
textRect = new Rectangle();
Rectangle rect = new Rectangle(0, 0, c.getWidth(), c.getHeight());
paintTabAreaBackground(g, rect, tabPlacement);
boolean leftToRight = tabPlacement == LEFT || tabPlacement == RIGHT || _tabPane.getComponentOrientation().isLeftToRight();
// Paint tabRuns of tabs from back to front
for (int i = _runCount - 1; i >= 0; i--) {
int start = _tabRuns[i];
int next = _tabRuns[(i == _runCount - 1) ? 0 : i + 1];
int end = (next != 0 ? next - 1 : tabCount - 1);
for (int j = start; j <= end; j++) {
if ((_rects[j].intersects(rect) || !leftToRight) && j != selectedIndex) {
paintTab(g, tabPlacement, _rects, j, iconRect, textRect);
}
}
}
// Paint selected tab if its in the front run
// since it may overlap other tabs
if (selectedIndex >= 0 && getRunForTab(tabCount, selectedIndex) == 0) {
if (_rects[selectedIndex].intersects(rect) || !leftToRight) {
paintTab(g, tabPlacement, _rects, selectedIndex, iconRect, textRect);
}
}
}
protected void paintTabAreaBackground(Graphics g, Rectangle rect, int tabPlacement) {
getPainter().paintTabAreaBackground(_tabPane, g, rect,
tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM ? SwingConstants.HORIZONTAL : SwingConstants.VERTICAL,
ThemePainter.STATE_DEFAULT);
}
protected void paintTab(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect) {
if (!PAINT_TAB) {
return;
}
Rectangle tabRect = new Rectangle(rects[tabIndex]);
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
tabRect.x += _tabScroller.viewport.getExpectedViewX();
}
int selectedIndex = _tabPane.getSelectedIndex();
boolean isSelected = selectedIndex == tabIndex;
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
paintTabBackground(g, tabPlacement, tabIndex, tabRect.x, tabRect.y,
tabRect.width, tabRect.height, isSelected);
Object savedHints = JideSwingUtilities.setupShapeAntialiasing(g);
paintTabBorder(g, tabPlacement, tabIndex, tabRect.x, tabRect.y,
tabRect.width, tabRect.height, isSelected);
JideSwingUtilities.restoreShapeAntialiasing(g, savedHints);
Icon icon = _tabPane.getIconForTab(tabIndex);
Rectangle tempTabRect = new Rectangle(tabRect);
if (_tabPane.isShowGripper()) {
if (leftToRight) {
tempTabRect.x += _gripperWidth;
}
tempTabRect.width -= _gripperWidth;
Rectangle gripperRect = new Rectangle(tabRect);
if (leftToRight) {
gripperRect.x += _gripLeftMargin;
}
else {
gripperRect.x = tabRect.x + tabRect.width - _gripLeftMargin - _gripperWidth;
}
gripperRect.width = _gripperWidth;
if (_gripperPainter != null) {
_gripperPainter.paint(_tabPane, g, gripperRect, SwingConstants.HORIZONTAL, isSelected ? ThemePainter.STATE_SELECTED : ThemePainter.STATE_DEFAULT);
}
else {
getPainter().paintGripper(_tabPane, g, gripperRect, SwingConstants.HORIZONTAL, isSelected ? ThemePainter.STATE_SELECTED : ThemePainter.STATE_DEFAULT);
}
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex)
&& (!_tabPane.isShowCloseButtonOnSelectedTab() || isSelected)) {
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int buttonWidth = _closeButtons[tabIndex].getPreferredSize().width + _closeButtonLeftMargin + _closeButtonRightMargin;
if (!(_closeButtonAlignment == SwingConstants.LEADING ^ leftToRight)) {
tempTabRect.x += buttonWidth;
}
tempTabRect.width -= buttonWidth;
}
else {
int buttonHeight = _closeButtons[tabIndex].getPreferredSize().height + _closeButtonLeftMargin + _closeButtonRightMargin;
if (_closeButtonAlignment == SwingConstants.LEADING) {
tempTabRect.y += buttonHeight;
tempTabRect.height -= buttonHeight;
}
else {
tempTabRect.height -= buttonHeight;
}
}
}
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
Font font;
if (isSelected && _tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (isSelected && _tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
FontMetrics metrics = g.getFontMetrics(font);
while (title == null || title.length() < 3)
title += " ";
layoutLabel(tabPlacement, metrics, tabIndex, title, icon,
tempTabRect, iconRect, textRect, isSelected);
if (!_isEditing || (!isSelected))
paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
paintIcon(g, tabPlacement, tabIndex, icon, iconRect, isSelected);
paintFocusIndicator(g, tabPlacement, rects, tabIndex,
iconRect, textRect, isSelected);
}
/* This method will create and return a polygon shape for the given tab rectangle
* which has been cropped at the specified crop line with a torn edge visual.
* e.g. A "File" tab which has cropped been cropped just after the "i":
* -------------
* | ..... |
* | . |
* | ... . |
* | . . |
* | . . |
* | . . |
* --------------
*
* The x, y arrays below define the pattern used to create a "torn" edge
* segment which is repeated to fill the edge of the tab.
* For tabs placed on TOP and BOTTOM, this righthand torn edge is created by
* line segments which are defined by coordinates obtained by
* subtracting xCropLen[i] from (tab.x + tab.width) and adding yCroplen[i]
* to (tab.y).
* For tabs placed on LEFT or RIGHT, the bottom torn edge is created by
* subtracting xCropLen[i] from (tab.y + tab.height) and adding yCropLen[i]
* to (tab.x).
*/
private int xCropLen[] = {1, 1, 0, 0, 1, 1, 2, 2};
private int yCropLen[] = {0, 3, 3, 6, 6, 9, 9, 12};
private static final int CROP_SEGMENT = 12;
/*
private Polygon createCroppedTabClip(int tabPlacement, Rectangle tabRect, int cropline) {
int rlen = 0;
int start = 0;
int end = 0;
int ostart = 0;
switch (tabPlacement) {
case LEFT:
case RIGHT:
rlen = tabRect.width;
start = tabRect.x;
end = tabRect.x + tabRect.width;
ostart = tabRect.y;
break;
case TOP:
case BOTTOM:
default:
rlen = tabRect.height;
start = tabRect.y;
end = tabRect.y + tabRect.height;
ostart = tabRect.x;
}
int rcnt = rlen / CROP_SEGMENT;
if (rlen % CROP_SEGMENT > 0) {
rcnt++;
}
int npts = 2 + (rcnt << 3);
int xp[] = new int[npts];
int yp[] = new int[npts];
int pcnt = 0;
xp[pcnt] = ostart;
yp[pcnt++] = end;
xp[pcnt] = ostart;
yp[pcnt++] = start;
for (int i = 0; i < rcnt; i++) {
for (int j = 0; j < xCropLen.length; j++) {
xp[pcnt] = cropline - xCropLen[j];
yp[pcnt] = start + (i * CROP_SEGMENT) + yCropLen[j];
if (yp[pcnt] >= end) {
yp[pcnt] = end;
pcnt++;
break;
}
pcnt++;
}
}
if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
return new Polygon(xp, yp, pcnt);
}
else { // LEFT or RIGHT
return new Polygon(yp, xp, pcnt);
}
}
*/
/* If tabLayoutPolicy == SCROLL_TAB_LAYOUT, this method will paint an edge
* indicating the tab is cropped in the viewport display
*/
@SuppressWarnings({"UnusedDeclaration"})
private void paintCroppedTabEdge(Graphics g, int tabPlacement, int tabIndex,
boolean isSelected,
int x, int y) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
int xx = x;
g.setColor(_shadow);
while (xx <= x + _rects[tabIndex].width) {
for (int i = 0; i < xCropLen.length; i += 2) {
g.drawLine(xx + yCropLen[i], y - xCropLen[i],
xx + yCropLen[i + 1] - 1, y - xCropLen[i + 1]);
}
xx += CROP_SEGMENT;
}
break;
case TOP:
case BOTTOM:
default:
int yy = y;
g.setColor(_shadow);
while (yy <= y + _rects[tabIndex].height) {
for (int i = 0; i < xCropLen.length; i += 2) {
g.drawLine(x - xCropLen[i], yy + yCropLen[i],
x - xCropLen[i + 1], yy + yCropLen[i + 1] - 1);
}
yy += CROP_SEGMENT;
}
}
}
protected void layoutLabel(int tabPlacement,
FontMetrics metrics, int tabIndex,
String title, Icon icon,
Rectangle tabRect, Rectangle iconRect,
Rectangle textRect, boolean isSelected) {
textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
View v = getTextViewForTab(tabIndex);
if (v != null) {
_tabPane.putClientProperty("html", v);
}
SwingUtilities.layoutCompoundLabel(_tabPane,
metrics, title, icon,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
SwingUtilities.TRAILING,
tabRect,
iconRect,
textRect,
_textIconGap);
_tabPane.putClientProperty("html", null);
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
// iconRect.x = tabRect.x + _iconMargin;
// textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding);
// iconRect.width = Math.min(iconRect.width, tabRect.width - _tabRectPadding);
// textRect.width = tabRect.width - _tabRectPadding - iconRect.width - (icon != null ? _textIconGap + _iconMargin : _noIconMargin);
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
if (!_tabPane.isShowCloseButtonOnSelectedTab()) {
if (!isSelected) {
iconRect.width = iconRect.width + _closeButtons[tabIndex].getPreferredSize().width + _closeButtonMarginHorizon;
textRect.width = 0;
}
}
}
}
else {// tabplacement is left or right
iconRect.y = tabRect.y + _iconMargin;
textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding);
iconRect.x = tabRect.x + 2;
textRect.x = tabRect.x + 2;
textRect.width = tabRect.width - _textMarginVertical;
textRect.height = tabRect.height - _tabRectPadding - iconRect.height - (icon != null ? _textIconGap + _iconMargin : _noIconMargin);
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
if (!_tabPane.isShowCloseButtonOnSelectedTab()) {
if (!isSelected) {
iconRect.height = iconRect.height + _closeButtons[tabIndex].getPreferredSize().height + _closeButtonMarginVertical;
textRect.height = 0;
}
}
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintIcon(Graphics g, int tabPlacement,
int tabIndex, Icon icon, Rectangle iconRect,
boolean isSelected) {
if (icon != null && iconRect.width >= icon.getIconWidth()) {
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
icon.paintIcon(_tabPane, g, iconRect.x, iconRect.y);
}
else {
if (iconRect.height < _rects[tabIndex].height - _gripperHeight) {
icon.paintIcon(_tabPane, g, iconRect.x, iconRect.y);
}
}
}
}
protected void paintText(Graphics g, int tabPlacement,
Font font, FontMetrics metrics, int tabIndex,
String title, Rectangle textRect,
boolean isSelected) {
Graphics2D g2d = (Graphics2D) g.create();
if (isSelected && _tabPane.isBoldActiveTab()) {
g2d.setFont(font.deriveFont(Font.BOLD));
}
else {
g2d.setFont(font);
}
String actualText = title;
if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
if (textRect.width <= 0)
return;
while (SwingUtilities.computeStringWidth(metrics, actualText) > textRect.width) {
actualText = actualText.substring(0, actualText.length() - 1);
}
if (!actualText.equals(title)) {
if (actualText.length() >= 2)
actualText = actualText.substring(0, actualText.length() - 2) + "..";
else
actualText = "";
}
}
else {
if (textRect.height <= 0)
return;
while (SwingUtilities.computeStringWidth(metrics, actualText) > textRect.height) {
actualText = actualText.substring(0, actualText.length() - 1);
}
if (!actualText.equals(title)) {
if (actualText.length() >= 2)
actualText = actualText.substring(0, actualText.length() - 2) + "..";
else
actualText = "";
}
}
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
v.paint(g2d, textRect);
}
else {
// plain text
int mnemIndex = _tabPane.getDisplayedMnemonicIndexAt(tabIndex);
JideTabbedPane.ColorProvider colorProvider = _tabPane.getTabColorProvider();
if (_tabPane.isEnabled() && _tabPane.isEnabledAt(tabIndex)) {
if (colorProvider != null) {
g2d.setColor(colorProvider.getForegroudAt(tabIndex));
}
else {
Color color = _tabPane.getForegroundAt(tabIndex);
if (isSelected && showFocusIndicator()) {
if (!(color instanceof ColorUIResource)) {
g2d.setColor(color);
}
else {
g2d.setColor(_activeTabForeground);
}
}
else {
if (!(color instanceof ColorUIResource)) {
g2d.setColor(color);
}
else {
g2d.setColor(_inactiveTabForeground);
}
}
}
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
}
else {// draw string from top to bottom
AffineTransform old = g2d.getTransform();
g2d.translate(textRect.x, textRect.y);
if (tabPlacement == RIGHT) {
g2d.rotate(Math.PI / 2);
g2d.translate(0, -textRect.width);
}
else {
g2d.rotate(-Math.PI / 2);
g2d.translate(-textRect.height + metrics.getHeight() / 2 + _rectSizeExtend, 0); // no idea why i need 7 here
}
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex, 0,
((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent());
g2d.setTransform(old);
}
}
else { // tab disabled
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
g2d.setColor(_tabPane.getBackgroundAt(tabIndex).brighter());
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
g2d.setColor(_tabPane.getBackgroundAt(tabIndex).darker());
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1);
}
else {// draw string from top to bottom
AffineTransform old = g2d.getTransform();
g2d.translate(textRect.x, textRect.y);
if (tabPlacement == RIGHT) {
g2d.rotate(Math.PI / 2);
g2d.translate(0, -textRect.width);
}
else {
g2d.rotate(-Math.PI / 2);
g2d.translate(-textRect.height + metrics.getHeight() / 2 + _rectSizeExtend, 0); // no idea why i need 7 here
}
g2d.setColor(_tabPane.getBackgroundAt(tabIndex).brighter());
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex,
0, ((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent());
g2d.setColor(_tabPane.getBackgroundAt(tabIndex).darker());
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex,
tabPlacement == RIGHT ? -1 : 1, ((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent() - 1);
g2d.setTransform(old);
}
}
}
g2d.dispose();
}
/**
* this function draws the border around each tab note that this function does now draw the background of the tab.
* that is done elsewhere
*
* @param g the Graphics instance
* @param tabPlacement the tab placement
* @param tabIndex the tab index
* @param x x
* @param y y
* @param w width
* @param h height
* @param isSelected if the tab is selected
*/
protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
if (!PAINT_TAB_BORDER) {
return;
}
switch (getTabShape()) {
case JideTabbedPane.SHAPE_BOX:
paintBoxTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_EXCEL:
paintExcelTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_WINDOWS:
paintWindowsTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_WINDOWS_SELECTED:
if (isSelected) {
paintWindowsTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
break;
case JideTabbedPane.SHAPE_VSNET:
paintVsnetTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_ROUNDED_VSNET:
paintRoundedVsnetTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_FLAT:
paintFlatTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_ROUNDED_FLAT:
paintRoundedFlatTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_OFFICE2003:
default:
paintOffice2003TabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
int tabShape = getTabShape();
if (tabShape == JideTabbedPane.SHAPE_WINDOWS) {
if (_mouseEnter && _tabPane.getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP
&& tabIndex == _indexMouseOver && !isSelected && _tabPane.isEnabledAt(_indexMouseOver)) {
paintTabBorderMouseOver(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
}
else if (tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
if (_mouseEnter && tabIndex == _indexMouseOver && !isSelected && _tabPane.isEnabledAt(_indexMouseOver)) {
paintTabBorderMouseOver(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
}
}
protected void paintOffice2003TabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:// when the tab on the left
y += 2;
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x, y + 3, x, y + h - 5);// left
g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom
// arc
g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom
g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + 2, y - 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + 3 + i, y - 2 - i, x + 3 + i, y - 2 - i);
}
g.drawLine(x + w - 1, y - w + 1, x + w - 1, y - w + 2);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 3, x + 1, y + h - 5);// left
g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom
g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc
g.drawLine(x + 3, y, x + 3, y - 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + 4 + i, y - 2 - i, x + 4 + i, y - 2 - i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 3, x, y + h - 5);// left
g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom
// arc
g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom
g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + 2, y - 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + 3 + i, y - 2 - i, x + 3 + i, y - 2 - i);
}
g.drawLine(x + w - 1, y - w + 1, x + w - 1, y - w + 2);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 3, x + 1, y + h - 6);// left
g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc
g.drawLine(x + 3, y, x + 3, y - 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + 4 + i, y - 2 - i, x + 4 + i, y - 2 - i);
}
g.setColor(getPainter().getControlDk());
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// bottom
// arc
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x, y + 3, x, y + h - 5);// left
g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom
// arc
g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom
g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + 2, y - 1);
g.drawLine(x + 3, y - 2, x + 3, y - 2);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 3, x + 1, y + h - 6);// left
g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc
g.drawLine(x + 3, y, x + 3, y - 1);
g.drawLine(x + 4, y - 2, x + 4, y - 2);
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);
}
}
}
break;
case RIGHT:
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom
// arc
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + w - 4 - i, y - i, x + w - 4 - i, y - i);
}
g.drawLine(x, y - w + 3, x, y - w + 4);
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 3);// right
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top arc
g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + w - 5 - i, y - i, x + w - 5 - i, y - i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom
// arc
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + w - 4 - i, y - i, x + w - 4 - i, y - i);
}
g.drawLine(x, y - w + 3, x, y - w + 4);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 4);// right
g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top
// arc
g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + w - 5 - i, y - i, x + w - 5 - i, y
- i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom
// arc
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom
// arc
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc
g.drawLine(x + w - 4, y, x + w - 4, y);// top arc
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 4);// right
g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top
// arc
g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1);
g.drawLine(x + w - 5, y, x + w - 5, y);
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom
// arc
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
}
}
}
break;
case BOTTOM:
if (leftToRight) {
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right
// arc
g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc
g.drawLine(x, y + h - 4, x, y + h - 4);// left arc
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + h - 2 - i, x + 2 - i, y + h
- 2 - i);
}
g.drawLine(x - h + 3, y, x - h + 4, y);
g.setColor(_selectColor2);
g.drawLine(x + 5, y + h - 2, x + w - 3, y + h - 2);// bottom
g.drawLine(x + w - 2, y, x + w - 2, y + h - 3);// right
g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left arc
g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left arc
g.drawLine(x, y + h - 5, x, y + h - 5);// left arc
for (int i = 3; i < h - 2; i++) {// left
g.drawLine(x + 2 - i, y + h - 3 - i, x + 2 - i, y + h
- 3 - i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right
// arc
g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc
g.drawLine(x, y + h - 4, x, y + h - 4);// left arc
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + h - 2 - i, x + 2 - i, y + h
- 2 - i);
}
g.drawLine(x - h + 3, y, x - h + 4, y);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left
// arc
g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left
// arc
g.drawLine(x, y + h - 5, x, y + h - 5);// left arc
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + h - 3 - i, x + 2 - i, y
+ h - 3 - i);
}
g.drawLine(x + 5, y + h - 2, x + w - 4, y + h - 2);// bottom
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2);
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y);// right
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right
// arc
g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc
g.drawLine(x, y + h - 4, x, y + h - 4);// left arc
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left
// arc
g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left
// arc
g.drawLine(x, y + h - 5, x, y + h - 5);// left arc
g.drawLine(x + 5, y + h - 2, x + w - 4, y + h - 2);// bottom
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2);
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y);// right
}
}
}
}
else {
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x, y + h - 3, x, y);// left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// left
// arc
g.drawLine(x + w - 6, y + h - 1, x + 2, y + h - 1);// bottom
g.drawLine(x + w - 4, y + h - 2, x + w - 5, y + h - 2);// right arc
g.drawLine(x + w - 2, y + h - 3, x + w - 3, y + h - 3);// right arc
g.drawLine(x + w - 1, y + h - 4, x + w - 1, y + h - 4);// right arc
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + h - 2 - i, x + w - 3 + i, y + h - 2 - i);
}
g.drawLine(x + w - 4 + h, y, x + w - 5 + h, y);
g.setColor(_selectColor2);
g.drawLine(x + w - 6, y + h - 2, x + 2, y + h - 2);// bottom
g.drawLine(x + 1, y, x + 1, y + h - 3);// left
g.drawLine(x + w - 4, y + h - 3, x + w - 5, y + h - 3);// right arc
g.drawLine(x + w - 2, y + h - 4, x + w - 3, y + h - 4);// right arc
g.drawLine(x + w - 1, y + h - 5, x + w - 1, y + h - 5);// right arc
for (int i = 3; i < h - 2; i++) {// right
g.drawLine(x + w - 3 + i, y + h - 3 - i, x + w - 3 + i, y + h - 3 - i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x, y + h - 3, x, y);// left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// left
// arc
g.drawLine(x + w - 6, y + h - 1, x + 2, y + h - 1);// bottom
g.drawLine(x + w - 4, y + h - 2, x + w - 5, y + h - 2);// right arc
g.drawLine(x + w - 2, y + h - 3, x + w - 3, y + h - 3);// right arc
g.drawLine(x + w - 1, y + h - 4, x + w - 1, y + h - 4);// right arc
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + h - 2 - i, x + w - 3 + i, y + h - 2 - i);
}
g.drawLine(x + w - 4 + h, y, x + w -5 + h, y);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 4, y + h - 3, x + w - 5, y + h - 3);// right
// arc
g.drawLine(x + w - 2, y + h - 4, x + w - 3, y + h - 4);// right
// arc
g.drawLine(x + w - 1, y + h - 5, x + w - 1, y + h - 5);// right arc
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + h - 3 - i, x + w - 3 + i, y + h - 3 - i);
}
g.drawLine(x + w - 6, y + h - 2, x + 3, y + h - 2);// bottom
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + w - 6, y + h - 1, x + 2, y + h - 1);// bottom
g.drawLine(x, y + h - 3, x, y);// left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// left
// arc
g.drawLine(x + w - 4, y + h - 2, x + w - 5, y + h - 2);// right arc
g.drawLine(x + w - 2, y + h - 3, x + w - 3, y + h - 3);// right arc
g.drawLine(x + w - 1, y + h - 4, x + w - 1, y + h - 4);// right arc
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 4, y + h - 3, x + w - 5, y + h - 3);// right
// arc
g.drawLine(x + w - 2, y + h - 4, x + w - 3, y + h - 4);// right
// arc
g.drawLine(x + w - 1, y + h - 5, x + w -1, y + h - 5);// right arc
g.drawLine(x + w - 6, y + h - 2, x + 3, y + h - 2);// bottom
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
}
}
}
}
break;
case TOP:
default:
if (leftToRight) {
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc
g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc
g.drawLine(x, y + 3, x, y + 3);
g.drawLine(x + 5, y, x + w - 3, y);// top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + 1 + i, x + 2 - i, y + 1 + i);
}
g.drawLine(x - h + 3, y + h - 1, x - h + 4, y + h - 1);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc
g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc
g.drawLine(x, y + 4, x, y + 4);
g.drawLine(x + 5, y + 1, x + w - 3, y + 1);// top
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + 2 + i, x + 2 - i, y + 2 + i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc
g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc
g.drawLine(x, y + 3, x, y + 3);
g.drawLine(x + 5, y, x + w - 3, y);// top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + 1 + i, x + 2 - i, y + 1 + i);
}
g.drawLine(x - h + 3, y + h - 1, x - h + 4, y + h - 1);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc
g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc
g.drawLine(x, y + 4, x, y + 4);
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + 2 + i, x + 2 - i, y + 2
+ i);
}
g.drawLine(x + 5, y + 1, x + w - 4, y + 1);// top
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 3, y + 1, x + w - 3, y + 1);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc
g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc
g.drawLine(x, y + 3, x, y + 3);
g.drawLine(x + 5, y, x + w - 3, y);// top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc
g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc
g.drawLine(x, y + 4, x, y + 4);
g.drawLine(x + 5, y + 1, x + w - 4, y + 1);// top
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 3, y + 1, x + w - 3, y + 1);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right
}
}
}
}
else {
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x + w - 4, y + 1, x + w - 5, y + 1);// right arc
g.drawLine(x + w - 2, y + 2, x + w - 3, y + 2);// right arc
g.drawLine(x + w - 1, y + 3, x + w - 1, y + 3);
g.drawLine(x + w - 6, y, x + 2, y);// top
g.drawLine(x + 1, y + 1, x + 1, y + 1);// left arc
g.drawLine(x, y + 2, x, y + h - 1);// left
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + 1 + i, x + w - 3 + i, y + 1 + i);
}
g.drawLine(x + w - 4 + h, y + h - 1, x + w - 5 + h, y + h - 1);
g.setColor(_selectColor2);
g.drawLine(x + w - 4, y + 2, x + w - 5, y + 2);// right arc
g.drawLine(x + w - 2, y + 3, x + w - 3, y + 3);// right arc
g.drawLine(x + w - 1, y + 4, x + w - 1, y + 4);
g.drawLine(x + w - 6, y + 1, x + 2, y + 1);// top
g.drawLine(x + 1, y + 2, x + 1, y + h - 1);// right
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + 2 + i, x + w - 3 + i, y + 2 + i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 4, y + 1, x + w - 5, y + 1);// right arc
g.drawLine(x + w - 2, y + 2, x + w - 3, y + 2);// right arc
g.drawLine(x + w - 1, y + 3, x + w - 1, y + 3);
g.drawLine(x + w - 6, y, x + 2, y);// top
g.drawLine(x + 1, y + 1, x + 1, y + 1);// left arc
g.drawLine(x, y + 2, x, y + h - 1);// left
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + 1 + i, x + w - 3 + i, y + 1 + i);
}
g.drawLine(x + w - 4 + h, y + h - 1, x + w - 5 + h, y + h - 1);//
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 4, y + 2, x + w - 5, y + 2);// right arc
g.drawLine(x + w - 2, y + 3, x + w - 3, y + 3);// right arc
g.drawLine(x + w - 1, y + 4, x + w - 1, y + 4);
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + 2 + i, x + w - 3 + i, y + 2 + i);
}
g.drawLine(x + w - 6, y + 1, x + 3, y + 1);// top
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + 1, x + 2, y + 1);
g.drawLine(x + 1, y + 2, x + 1, y + h - 1);// left
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + w - 4, y + 1, x + w - 5, y + 1);// right arc
g.drawLine(x + w - 2, y + 2, x + w - 3, y + 2);// right arc
g.drawLine(x + w - 1, y + 3, x + w - 1, y + 3);
g.drawLine(x + w - 6, y, x + 2, y);// top
g.drawLine(x + 1, y + 1, x + 1, y + 1);// left arc
g.drawLine(x, y + 2, x, y + h - 1);// left
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 4, y + 2, x + w - 5, y + 2);// right arc
g.drawLine(x + w - 2, y + 3, x + w - 3, y + 3);// right arc
g.drawLine(x + w - 1, y + 4, x + w - 1, y + 4);
g.drawLine(x + w - 6, y + 1, x + 3, y + 1);// top
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + 1, x + 2, y + 1);
g.drawLine(x + 1, y + 2, x + 1, y + h - 1);// left
}
}
}
}
}
}
protected void paintExcelTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + 5, x, y + h - 5);// left
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i);
}
if (_selectColor2 != null) {
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i);
}
}
if (_selectColor3 != null) {
g.setColor(_selectColor3);
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i);
}
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 5, x, y + h - 5);// left
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left
for (int i = 0, j = 0; i < w / 2; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i);
}
}
}
else if (tabIndex == _tabPane.getSelectedIndex() - 1) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 5, x, y + h - 5);// left
for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i);
}
for (int i = 0, j = 0; i < 5; i++, j = j + 2) {// bottom
g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left
for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point
for (int i = 0, j = 0; i < 5; i++, j = j + 2) {// bottom
g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i);
}
}
}
else if (tabIndex != _tabPane.getSelectedIndex() - 1) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 5, x, y + h - 5);// left
for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left
for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i);
}
}
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i);
}
if (_selectColor2 != null) {
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i);
}
}
if (_selectColor3 != null) {
g.setColor(_selectColor3);
g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i);
}
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a
// point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i);
}
}
}
else if (tabIndex == _tabPane.getSelectedIndex() - 1) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right
for (int i = 0, j = 0; i < 4; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i);
}
for (int i = 0, j = 0; i < 5; i++, j += 2) {// bottom
g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right
for (int i = 0, j = 0; i < 4; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point
for (int i = 0, j = 0; i < 5; i++, j += 2) {// bottom
g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i);
}
}
}
else if (tabIndex != _tabPane.getSelectedIndex() - 1) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right
for (int i = 0, j = 0; i < 4; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right
for (int i = 0, j = 0; i < 4; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i);
}
}
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 5, y + h - 1);// bottom
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + h - 1 - j, x + w - 4 - 1 + i, y + h - 2 - j);
}
if (_selectColor2 != null) {
g.setColor(_selectColor2);
g.drawLine(x + 5, y + h - 3, x + 5, y + h - 3);// bottom
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 4 - j, x + 4 - i, y + h - 5 - j);
}
}
if (_selectColor3 != null) {
g.setColor(_selectColor3);
g.drawLine(x + 5, y + h - 2, x + w - 6, y + h - 2);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j);
}
}
}
else {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 5, y + h - 1);// bottom
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + h - 1 - j, x + w - 4 - 1 + i, y + h - 2 - j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j);
}
}
}
else if (tabIndex == _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 6, y + h - 1);// bottom
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j);
}
for (int i = 0, j = 0; i < 5; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 1 - j, x + w - 5 + i, y + h - 2 - j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point
for (int i = 0, j = 0; i < 5; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j);
}
}
}
else if (tabIndex != _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 6, y + h - 1);// bottom
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 1 - j, x + w - 5 + i, y + h - 2 - j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j);
}
}
}
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 5, y, x + w - 5, y);// top
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j);
}
if (_selectColor2 != null) {
g.setColor(_selectColor2);
g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j);
}
}
if (_selectColor3 != null) {
g.setColor(_selectColor3);
g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j);
}
}
}
else {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y, x + w - 5, y);// top
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j);
}
}
}
else if (tabIndex == _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y, x + w - 5, y);// top
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j);
}
for (int i = 0, j = 0; i < 5; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point
for (int i = 0, j = 0; i < 5; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j);
}
}
}
else if (tabIndex != _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y, x + w - 5, y);// top
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j);
}
}
}
}
}
}
protected void paintWindowsTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
int colorTheme = getColorTheme();
switch (tabPlacement) {
case LEFT:
if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x - 2, y + 1, x - 2, y + h - 1);// left
g.drawLine(x - 1, y, x - 1, y);// top arc
g.drawLine(x, y - 1, x + w - 1, y - 1);// top
g.setColor(_selectColor2);
g.drawLine(x - 1, y + h, x - 1, y + h);// bottom arc
g.drawLine(x, y + h + 1, x, y + h + 1);// bottom arc
g.drawLine(x + 1, y + h, x + w - 1, y + h);// bottom
g.setColor(_selectColor3);
g.drawLine(x, y + h, x, y + h);// bottom arc
g.drawLine(x + 1, y + h + 1, x + w - 1, y + h + 1);// bottom
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 2, x, y + h - 3);// left
g.drawLine(x + 1, y + 1, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + w - 1, y);// top
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// bottom arc
g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc
g.drawLine(x + 3, y + h - 2, x + w - 1, y + h - 2);// bottom
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// bottom arc
g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 3, x, y + h - 2);// left
g.drawLine(x + 1, y + 2, x + 1, y + 2);// top arc
g.drawLine(x + 2, y + 1, x + w - 1, y + 1);// top
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc
g.drawLine(x + 2, y + h, x + 2, y + h);// bottom arc
g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc
g.drawLine(x + 3, y + h, x + w - 1, y + h);// bottom
}
}
}
else {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x - 2, y + 1, x - 2, y + h - 1);// left
g.drawLine(x - 1, y, x - 1, y);// top arc
g.drawLine(x, y - 1, x, y - 1);// top arc
g.drawLine(x - 1, y + h, x - 1, y + h);// bottom arc
g.drawLine(x, y + h + 1, x, y + h + 1);// bottom arc
g.setColor(_selectColor2);
g.drawLine(x - 1, y + 1, x - 1, y + h - 1);// left
g.drawLine(x, y, x, y + h);// left
g.setColor(_selectColor3);
g.drawLine(x + 1, y - 2, x + w - 1, y - 2);// top
g.drawLine(x + 1, y + h + 2, x + w - 1, y + h + 2);// bottom
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 2, x, y + h - 4);// left
g.drawLine(x + 1, y + 1, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + w - 1, y);// top
g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3);// bottom arc
g.drawLine(x + 2, y + h - 2, x + w - 1, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 4, x, y + h - 2);// left
g.drawLine(x + 1, y + 3, x + 1, y + 3);// top arc
g.drawLine(x + 2, y + 2, x + w - 1, y + 2);// top
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc
g.drawLine(x + 2, y + h, x + w - 1, y + h);// bottom
}
}
}
break;
case RIGHT:
if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y - 1, x, y - 1);// top
g.setColor(_selectColor2);
g.drawLine(x + w, y + 1, x + w, y + h - 1);// right
g.drawLine(x + w - 1, y + h, x, y + h);// bottom
g.setColor(_selectColor3);
g.drawLine(x + w, y, x + w, y);// top arc
g.drawLine(x + w + 1, y + 1, x + w + 1, y + h - 1);// right
g.drawLine(x + w, y + h, x + w, y + h);// bottom arc
g.drawLine(x + w - 1, y + h + 1, x, y + h + 1);// bottom
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 3, y, x, y);// top
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 3);// right
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom arc
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 3, y + 1, x, y + 1);// top
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 3, x + w - 2, y + h - 2);// right
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + 2);// top arc
g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 2);// right
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc
g.drawLine(x + w - 3, y + h, x, y + h);// bottom
}
}
}
else {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + w + 1, y + 1, x + w + 1, y + h - 1);// right
g.drawLine(x + w, y, x + w, y);// top arc
g.drawLine(x + w - 1, y - 1, x + w - 1, y - 1);// top arc
g.drawLine(x + w, y + h, x + w, y + h);// bottom arc
g.drawLine(x + w - 1, y + h + 1, x + w - 1, y + h + 1);// bottom arc
g.setColor(_selectColor2);
g.drawLine(x + w, y + 1, x + w, y + h - 1);// right
g.drawLine(x + w - 1, y, x + w - 1, y + h);// right
g.setColor(_selectColor3);
g.drawLine(x + w - 2, y - 2, x, y - 2);// top
g.drawLine(x + w - 2, y + h + 2, x, y + h + 2);// bottom
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 4);// right
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top arc
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom arc
g.drawLine(x + w - 3, y, x, y);// top
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2);// right
g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3);// top arc
g.drawLine(x + w - 3, y + 2, x, y + 2);// top
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc
g.drawLine(x + w - 3, y + h, x, y + h);// bottom
}
}
}
break;
case BOTTOM:
if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + h, x, y + h);// left arc
g.drawLine(x - 1, y + h - 1, x - 1, y);// left
g.setColor(_selectColor2);
g.drawLine(x + 1, y + h, x + w - 2, y + h);// bottom
g.drawLine(x + w - 1, y + h - 1, x + w - 1, y - 1);// right
g.setColor(_selectColor3);
g.drawLine(x + 1, y + h + 1, x + w - 2, y + h + 1);// bottom
g.drawLine(x + w - 1, y + h, x + w - 1, y + h);// right arc
g.drawLine(x + w, y + h - 1, x + w, y - 1);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + h - 2, x, y + h - 2);// left arc
g.drawLine(x - 1, y + h - 3, x - 1, y);// left
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 2, x + w - 4, y + h - 2);// bottom
g.drawLine(x + w - 3, y + h - 3, x + w - 3, y - 1);// right
g.setColor(_unselectColor3);
g.drawLine(x + 1, y + h - 1, x + w - 4, y + h - 1);// bottom
g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2);// right arc
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y - 1);// right
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + h - 2, x + w - 2, y + h - 2);// bottom
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
g.setColor(_unselectColor3);
g.drawLine(x + 3, y + h - 1, x + w - 2, y + h - 1);// bottom
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);// right arc
g.drawLine(x + w, y + h - 3, x + w, y);// right
}
}
}
else {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 1, y + h + 1, x + w, y + h + 1);// bottom
g.drawLine(x, y + h, x, y + h);// right arc
g.drawLine(x - 1, y + h - 1, x - 1, y + h - 1);// right arc
g.drawLine(x + w + 1, y + h, x + w + 1, y + h);// left arc
g.drawLine(x + w + 2, y + h - 1, x + w + 2, y + h - 1);// left arc
g.setColor(_selectColor2);
g.drawLine(x + 1, y + h, x + w, y + h);// bottom
g.drawLine(x, y + h - 1, x + w + 1, y + h - 1);// bottom
g.setColor(_selectColor3);
g.drawLine(x - 1, y + h - 2, x - 1, y);// left
g.drawLine(x + w + 2, y + h - 2, x + w + 2, y);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right arc
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y - 1);// right
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right arc
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y - 1);// right
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
}
}
}
break;
case TOP:
default:
if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y - 1, x, y - 1); // left arc
g.drawLine(x - 1, y, x - 1, y + h - 1);// left
g.drawLine(x + 1, y - 2, x + w + 1, y - 2);// top
g.setColor(_selectColor2);
g.drawLine(x + w + 2, y - 1, x + w + 2, y + h - 1);// right
g.setColor(_selectColor3);
g.drawLine(x + w + 2, y - 1, x + w + 2, y - 1);// right arc
g.drawLine(x + w + 3, y, x + w + 3, y + h - 1);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 3, y, x + w - 2, y); // top
g.setColor(_unselectColor2);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right
g.setColor(_unselectColor3);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc
g.drawLine(x + w, y + 2, x + w, y + h - 1);// right
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 3, y, x + w - 2, y); // top
g.setColor(_unselectColor2);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right
g.setColor(_unselectColor3);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc
g.drawLine(x + w, y + 2, x + w, y + h - 1);// right
}
}
}
else {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 1, y - 2, x + w, y - 2); // top
g.drawLine(x, y - 1, x, y - 1); // left arc
g.drawLine(x - 1, y, x - 1, y); // left arc
g.drawLine(x + w + 1, y - 1, x + w + 1, y - 1);// right arc
g.drawLine(x + w + 2, y, x + w + 2, y);// right arc
g.setColor(_selectColor2);
g.drawLine(x + 1, y - 1, x + w, y - 1);// top
g.drawLine(x, y, x + w + 1, y);// top
g.setColor(_selectColor3);
g.drawLine(x - 1, y + 1, x - 1, y + h - 1);// left
g.drawLine(x + w + 2, y + 1, x + w + 2, y + h - 1);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 3, y, x + w - 3, y); // top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 3, y, x + w - 3, y); // top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
}
}
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintTabBorderMouseOver(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS) {
switch (tabPlacement) {
case LEFT:
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 2;
}
g.setColor(_selectColor1);
g.drawLine(x, y + 4, x, y + h - 2);
g.drawLine(x + 1, y + 3, x + 1, y + 3);
g.drawLine(x + 2, y + 2, x + 2, y + 2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
g.drawLine(x + 2, y + h, x + 2, y + h);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 4, x + 1, y + h - 2);
g.drawLine(x + 2, y + 3, x + 2, y + h - 1);
break;
case RIGHT:
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 2;
}
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2);
g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3);
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 2);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w - 3, y + h, x + w - 3, y + h);
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 4, x + w - 2, y + h - 2);
g.drawLine(x + w - 3, y + 3, x + w - 3, y + h - 1);
break;
case BOTTOM:
g.setColor(_selectColor1);
g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);
g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3);
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y + h - 3);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + h - 2, x + w - 3, y + h - 2);
g.drawLine(x + 2, y + h - 3, x + w - 2, y + h - 3);
break;
case TOP:
default:
g.setColor(_selectColor1);
g.drawLine(x + 3, y, x + w - 3, y);
g.drawLine(x + 2, y + 1, x + 2, y + 1);
g.drawLine(x + 1, y + 2, x + 1, y + 2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + 2);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + 1, x + w - 3, y + 1);
g.drawLine(x + 2, y + 2, x + w - 2, y + 2);
}
}
else if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
switch (tabPlacement) {
case LEFT:
if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) {
if (tabIndex > _tabPane.getSelectedIndex()) {
y -= 2;
}
g.setColor(_selectColor1);
g.drawLine(x, y + 4, x, y + h - 2);
g.drawLine(x + 1, y + 3, x + 1, y + 3);
g.drawLine(x + 2, y + 2, x + 2, y + 2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
g.drawLine(x + 2, y + h, x + 2, y + h);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 4, x + 1, y + h - 2);
g.drawLine(x + 2, y + 3, x + 2, y + h - 1);
g.setColor(_selectColor3);
g.drawLine(x + 3, y + 2, x + w - 1, y + 2);
g.drawLine(x + 3, y + h, x + w - 1, y + h);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 1;
}
g.setColor(_selectColor1);
g.drawLine(x, y + 3, x, y + h - 2);// left
g.drawLine(x + 1, y + 2, x + 1, y + 2);// top arc
g.drawLine(x + 2, y + 1, x + w - 1, y + 1);// top
g.setColor(_selectColor2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc
g.drawLine(x + 2, y + h, x + 2, y + h);// bottom arc
g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom
g.setColor(_selectColor3);
g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc
g.drawLine(x + 3, y + h, x + w - 1, y + h);// bottom
}
break;
case RIGHT:
if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) {
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 2;
}
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2);
g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3);
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 2);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w - 3, y + h, x + w - 3, y + h);
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 4, x + w - 2, y + h - 2);
g.drawLine(x + w - 3, y + 3, x + w - 3, y + h - 1);
g.setColor(_selectColor3);
g.drawLine(x + w - 4, y + 2, x, y + 2);
g.drawLine(x + w - 4, y + h, x, y + h);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 1;
}
g.setColor(_selectColor3);
g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 2);// right
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc
g.drawLine(x + w - 3, y + h, x, y + h);// bottom
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 3, x + w - 2, y + h - 2);// right
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.setColor(_selectColor1);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + 2);// top arc
g.drawLine(x + w - 3, y + 1, x, y + 1);// top
}
break;
case BOTTOM:
if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) {
g.setColor(_selectColor1);
g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);
g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3);
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y + h - 3);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + h - 2, x + w - 3, y + h - 2);
g.drawLine(x + 2, y + h - 3, x + w - 2, y + h - 3);
g.setColor(_selectColor3);
g.drawLine(x + 1, y, x + 1, y + h - 4); // left
g.drawLine(x + w - 1, y, x + w - 1, y + h - 4);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
x = x - 2;
}
g.setColor(_selectColor3);
g.drawLine(x + 3, y + h - 1, x + w - 2, y + h - 1);// bottom
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);// right arc
g.drawLine(x + w, y + h - 3, x + w, y);// right
g.setColor(_selectColor1);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left
g.drawLine(x + 1, y + h - 3, x + 1, y);// left arc
g.setColor(_selectColor2);
g.drawLine(x + 3, y + h - 2, x + w - 2, y + h - 2);// bottom
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
}
break;
case TOP:
default:
if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) {
g.setColor(_selectColor1);
g.drawLine(x + 3, y, x + w - 3, y);
g.drawLine(x + 2, y + 1, x + 2, y + 1);
g.drawLine(x + 1, y + 2, x + 1, y + 2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + 2);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + 1, x + w - 3, y + 1);
g.drawLine(x + 2, y + 2, x + w - 2, y + 2);
g.setColor(_selectColor3);
g.drawLine(x + 1, y + 3, x + 1, y + h - 1); // left
g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 1);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
x = x - 1;
}
g.setColor(_selectColor1);
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 3, y, x + w - 2, y); // top
g.setColor(_selectColor2);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right
g.setColor(_selectColor3);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc
g.drawLine(x + w, y + 2, x + w, y + h - 1);// right
}
}
}
}
protected void paintVsnetTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 1, y);// top
g.drawLine(x, y, x, y + h - 2);// left
g.setColor(_selectColor2);
g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + 2, y + h - 2, x + w - 2, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x + 2, y, x + w - 2, y);// top
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 1, y);// top
g.setColor(_selectColor2);
g.drawLine(x + w - 1, y, x + w - 1, y + h - 2);// left
g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + 1, y + h - 2, x + w - 3, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x + 1, y, x + w - 3, y);// top
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x, y + h - 1); // left
g.setColor(_selectColor2);
g.drawLine(x, y + h - 1, x + w - 1, y + h - 1); // bottom
g.drawLine(x + w - 1, y, x + w - 1, y + h - 2); // right
}
else {
g.setColor(_unselectColor1);
if (leftToRight) {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
}
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + 1, x, y + h - 1); // left
g.drawLine(x, y, x + w - 1, y); // top
g.setColor(_selectColor2);
g.drawLine(x + w - 1, y, x + w - 1, y + h - 1); // right
}
else {
g.setColor(_unselectColor1);
if (leftToRight) {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
}
}
}
}
protected void paintRoundedVsnetTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 2, y, x + w - 1, y);// top
g.drawLine(x + 1, y + 1, x + 1, y + 1);// top-left
g.drawLine(x, y + 2, x, y + h - 3);// left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// bottom-left
g.drawLine(x + 2, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + 2, y + h - 2, x + w - 2, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x + 2, y + 1, x + w - 2, y + 1);// top
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 3, y);// top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top-left
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3);// left
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom-left
g.drawLine(x, y + h - 1, x + w - 3, y + h - 1);// bottom
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + 1, y + h - 2, x + w - 3, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x + 1, y + 1, x + w - 3, y + 1);// top
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x, y + h - 3); // left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2); // bottom-left
g.drawLine(x + 2, y + h - 1, x + w - 3, y + h - 1); // bottom
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2); // bottom-right
g.drawLine(x + w - 1, y, x + w - 1, y + h - 3); // right
}
else {
g.setColor(_unselectColor1);
if (leftToRight) {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
}
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + 2, x, y + h - 1); // left
g.drawLine(x, y + 2, x + 2, y); // top-left
g.drawLine(x + 2, y, x + w - 3, y); // top
g.drawLine(x + w - 3, y, x + w - 1, y + 2); // top-left
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1); // right
}
else {
g.setColor(_unselectColor1);
if (leftToRight) {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
}
}
}
}
protected void paintFlatTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawRect(x, y, w, h);
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawRect(x, y, w, h - 1);
}
else {
g.drawRect(x, y, w, h);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.drawRect(x, y, w, h);
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawRect(x - 1, y, w, h);
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawRect(x - 1, y, w, h - 1);
}
else {
g.drawRect(x - 1, y, w, h);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.drawRect(x - 1, y, w, h);
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawRect(x, y - 1, w, h);
}
else {
g.setColor(_unselectColor1);
g.drawRect(x, y - 1, w, h);
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawRect(x, y, w, h);
}
else {
g.setColor(_unselectColor1);
g.drawRect(x, y, w, h);
}
}
}
protected void paintRoundedFlatTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 2, y, x + w - 1, y);
g.drawLine(x + 2, y + h, x + w - 1, y + h);
g.drawLine(x, y + 2, x, y + h - 2);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 1, x + 1, y + 1);
// g.drawLine(x, y + 1, x, y + 1);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
// g.drawLine(x + 1, y + h, x + 1, y + h);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y, x + w - 1, y);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + 2, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x, y + 2, x, y + h - 3);
}
else {
g.drawLine(x + 2, y + h, x + w - 1, y + h);
g.drawLine(x, y + 2, x, y + h - 2);
}
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 1, x + 1, y + 1);
// g.drawLine(x, y + 1, x, y + 1);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x, y + h - 2, x, y + h - 2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
}
else {
g.drawLine(x, y + h - 1, x, y + h - 1);
g.drawLine(x + 1, y + h, x + 1, y + h);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y, x + w - 1, y);
g.drawLine(x + 2, y + h, x + w - 1, y + h);
g.drawLine(x, y + 2, x, y + h - 2);
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 1, x + 1, y + 1);
// g.drawLine(x, y + 1, x, y + 1);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
// g.drawLine(x + 1, y + h, x + 1, y + h);
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 3, y);
g.drawLine(x, y + h, x + w - 3, y + h);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2);
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
// g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y, x + w - 3, y);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x, y + h - 1, x + w - 3, y + h - 1);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3);
}
else {
g.drawLine(x, y + h, x + w - 3, y + h);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2);
}
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
// g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);
// g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
}
else {
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y, x + w - 3, y);
g.drawLine(x, y + h, x + w - 3, y + h);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2);
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
// g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
// g.drawLine(x + w - 2, y + h, x + w - 2, y + h);
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x, y + h - 3);
g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w, y, x + w, y + h - 3);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);
// g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y, x, y + h - 3);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + 2, y + h - 1, x + w - 3, y + h - 1);
g.drawLine(x + w - 1, y, x + w - 1, y + h - 3);
}
else {
g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w, y, x + w, y + h - 3);
}
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);
// g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
if (tabIndex == _tabPane.getTabCount() - 1) {
// g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);
}
else {
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y, x, y + h - 3);
g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w, y, x + w, y + h - 3);
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);
// g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);
}
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + h - 1, x, y + 2);
g.drawLine(x + 2, y, x + w - 2, y);
g.drawLine(x + w, y + 2, x + w, y + h - 1);
g.setColor(_selectColor2);
g.drawLine(x, y + 2, x + 2, y); // top-left
g.drawLine(x + w - 2, y, x + w, y + 2);
// g.drawLine(x + w, y + 1, x + w, y + 1);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + h - 1, x, y + 2);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + 2, y, x + w - 3, y);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);
}
else {
g.drawLine(x + 2, y, x + w - 2, y);
g.drawLine(x + w, y + 2, x + w, y + h - 1);
}
g.setColor(_unselectColor2);
g.drawLine(x, y + 2, x + 2, y); // top-left
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 3, y, x + w - 1, y + 2);
}
else {
g.drawLine(x + w - 2, y, x + w, y + 2);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + h - 1, x, y + 2);
g.drawLine(x + 2, y, x + w - 2, y);
g.drawLine(x + w, y + 2, x + w, y + h - 1);
g.setColor(_unselectColor2);
g.drawLine(x, y + 2, x + 2, y);
g.drawLine(x + w - 2, y, x + w, y + 2);
}
}
}
}
protected void paintBoxTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 2, y);// top
g.drawLine(x, y, x, y + h - 2);// left
g.setColor(_selectColor2);
g.drawLine(x + w - 1, y, x + w - 1, y + h - 1);// right
g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else {
if (tabIndex != _tabPane.getSelectedIndex() - 1) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
g.setColor(_unselectColor1);
g.drawLine(x + 2, y + h, x + w - 2, y + h);// bottom
g.setColor(_unselectColor2);
g.drawLine(x + 2, y + h + 1, x + w - 2, y + h + 1);// bottom
break;
case BOTTOM:
case TOP:
default:
if (leftToRight) {
g.setColor(_unselectColor1);
g.drawLine(x + w, y + 2, x + w, y + h - 2);// right
g.setColor(_unselectColor2);
g.drawLine(x + w + 1, y + 2, x + w + 1, y + h - 2);// right
}
else {
g.setColor(_unselectColor1);
g.drawLine(x, y + 2, x, y + h - 2);// right
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 2, x + 1, y + h - 2);// right
}
}
}
}
}
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
if (!PAINT_TAB_BACKGROUND) {
return;
}
switch (getTabShape()) {
case JideTabbedPane.SHAPE_BOX:
paintButtonTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_EXCEL:
paintExcelTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_WINDOWS:
paintDefaultTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_WINDOWS_SELECTED:
if (isSelected) {
paintDefaultTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
break;
case JideTabbedPane.SHAPE_VSNET:
case JideTabbedPane.SHAPE_ROUNDED_VSNET:
paintVsnetTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_FLAT:
case JideTabbedPane.SHAPE_ROUNDED_FLAT:
paintFlatTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_OFFICE2003:
default:
paintOffice2003TabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintOffice2003TabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (tabIndex != 0 && !isSelected) {
int xp[] = {x + w, x + 4, x + 2, x, x, x + 3, x + w};
int yp[] = {y, y, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {// tabIndex != 0
int xp[] = {x + w, x + 2, x, x, x + 3, x + w};
int yp[] = {y - w + 2 + 2, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case RIGHT:
if (tabIndex != 0 && !isSelected) {
int xp[] = {x, x + w - 4, x + w - 3, x + w - 1, x + w - 1, x + w - 3, x};
int yp[] = {y, y, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x + w - 3, x + w - 1, x + w - 1, x + w - 3, x};
int yp[] = {y - w + 2 + 2, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case BOTTOM:
if (leftToRight) {
int xp[] = {x - (tabIndex == 0 || isSelected ? h - 5 : 0), x, x + 4, x + w - 3, x + w - 1, x + w - 1};
int yp[] = {y, y + h - 5, y + h - 1, y + h - 1, y + h - 5, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x, x + 2, x + w - 5, x + w - 1, x + w - 1 + (tabIndex == 0 || isSelected ? h - 5 : 0)};
int yp[] = {y, y + h - 5, y + h - 1, y + h - 1, y + h - 5, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case TOP:
default:
if (leftToRight) {
int xp[] = {x - (tabIndex == 0 || isSelected ? h - 5 : 0), x, x + 4, x + w - 3, x + w - 1, x + w - 1};
int yp[] = {y + h, y + 3, y + 1, y + 1, y + 3, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x, x + 2, x + w - 5, x + w - 1, x + w - 1 + (tabIndex == 0 || isSelected ? h - 5 : 0)};
int yp[] = {y + h, y + 3, y + 1, y + 1, y + 3, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintExcelTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (!isSelected) {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
int xp[] = {x + w, x, x, x + w};
int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + w, x + 9, x, x, x + w};
int yp[] = {y + 8, y + 2, y + 6, y + h - 5, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
else {
int xp[] = {x + w, x, x, x + w};
int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case RIGHT:
if (!isSelected) {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
int xp[] = {x, x + w - 1, x + w - 1, x};
int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x + w - 10, x + w - 1, x + w - 1, x};
int yp[] = {y + 8, y + 2, y + 6, y + h - 5,
y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
else {
int xp[] = {x, x + w - 1, x + w - 1, x};
int yp[] = {y - 5, y + 5, y + h - 4, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case BOTTOM:
if (!isSelected) {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
int xp[] = {x - 5, x + 5, x + w - 5, x + w + 5};
int yp[] = {y, y + h - 1, y + h - 1, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + 7, x + 1, x + 5, x + w - 5, x + w + 5};
int yp[] = {y, y + h - 10, y + h - 1, y + h - 1, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
else {
int xp[] = {x - 5, x + 5, x + w - 5, x + w + 5};
int yp[] = {y, y + h - 1, y + h - 1, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case TOP:
default:
if (!isSelected) {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
int xp[] = {x - 6, x + 5, x + w - 5, x + w + 5};
int yp[] = {y + h, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + 7, x + 1, x + 6, x + w - 5, x + w + 5};
int yp[] = {y + h, y + 9, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
else {
int xp[] = {x - 6, x + 5, x + w - 5, x + w + 5};
int yp[] = {y + h, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintDefaultTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
switch (tabPlacement) {
case LEFT:
if (isSelected) {
x = x + 1;
int xp[] = {x + w, x, x - 2, x - 2, x + w};
int yp[] = {y - 1, y - 1, y + 1, y + h + 2, y + h + 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
if (tabIndex < _tabPane.getSelectedIndex()) {
y = y + 1;
int xp[] = {x + w, x + 2, x, x, x + w};
int yp[] = {y + 1, y + 1, y + 3, y + h - 1,
y + h - 1};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + w, x + 2, x, x, x + w};
int yp[] = {y + 1, y + 1, y + 3, y + h - 2,
y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
break;
case RIGHT:
if (isSelected) {
int xp[] = {x, x + w - 1, x + w, x + w, x};
int yp[] = {y - 1, y - 1, y + 1, y + h + 2, y + h + 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
if (tabIndex < _tabPane.getSelectedIndex()) {
y = y + 1;
int xp[] = {x, x + w - 3, x + w - 1, x + w - 1, x};
int yp[] = {y + 1, y + 1, y + 3, y + h - 1,
y + h - 1};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x + w - 2, x + w - 1, x + w - 1, x};
int yp[] = {y + 1, y + 1, y + 3, y + h - 2,
y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
break;
case BOTTOM:
if (isSelected) {
int xp[] = {x, x, x + 2, x + w + 2, x + w + 2};
int yp[] = {y + h, y, y - 2, y - 2, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + 1, x + 1, x + 1, x + w - 1, x + w - 1};
int yp[] = {y + h - 1, y + 2, y, y, y + h - 1};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case TOP:
default:
if (isSelected) {
int xp[] = {x, x, x + 2, x + w + 2, x + w + 2};
int yp[] = {y + h + 1, y, y - 2, y - 2, y + h + 1};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + 1, x + 1, x + 3, x + w - 1, x + w - 1};
int yp[] = {y + h, y + 2, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintTabBackgroundMouseOver(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected, Color backgroundUnselectedColorStart, Color backgroundUnselectedColorEnd) {
Graphics2D g2d = (Graphics2D) g;
Polygon polygon;
switch (tabPlacement) {
case LEFT:
if (tabIndex < _tabPane.getSelectedIndex()) {
int xp[] = {x + w, x + 2, x, x, x + 2, x + w};
int yp[] = {y + 2, y + 2, y + 4, y + h - 1, y + h,
y + h};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
}
else {// tabIndex > _tabPane.getSelectedIndex()
int xp[] = {x + w, x + 2, x, x, x + 2, x + w};
int yp[] = {y + 1, y + 1, y + 3, y + h - 3,
y + h - 2, y + h - 2};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
}
JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorStart, backgroundUnselectedColorEnd, false);
break;
case RIGHT:
if (tabIndex < _tabPane.getSelectedIndex()) {
int xp[] = {x, x + w - 3, x + w - 1, x + w - 1,
x + w - 3, x};
int yp[] = {y + 2, y + 2, y + 4, y + h - 1, y + h,
y + h};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x + w - 2, x + w - 1, x + w - 1,
x + w - 3, x};
int yp[] = {y + 1, y + 1, y + 3, y + h - 3,
y + h - 2, y + h - 2};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
}
JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorEnd, backgroundUnselectedColorStart, false);
break;
case BOTTOM:
int xp[] = {x + 1, x + 1, x + 1, x + w - 1, x + w - 1};
int yp[] = {y + h - 2, y + 2, y, y, y + h - 2};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorEnd, backgroundUnselectedColorStart, true);
break;
case TOP:
default:
int xp1[] = {x + 1, x + 1, x + 3, x + w - 1, x + w - 1};
int yp1[] = {y + h, y + 2, y, y, y + h};
int np1 = yp1.length;
polygon = new Polygon(xp1, yp1, np1);
JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorStart, backgroundUnselectedColorEnd, true);
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintVsnetTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
int xp[];
int yp[];
switch (tabPlacement) {
case LEFT:
xp = new int[]{x + 1, x + 1, x + w, x + w};
yp = new int[]{y + h - 1, y + 1, y + 1, y + h - 1};
break;
case RIGHT:
xp = new int[]{x, x, x + w - 1, x + w - 1};
yp = new int[]{y + h - 1, y + 1, y + 1, y + h - 1};
break;
case BOTTOM:
xp = new int[]{x + 1, x + 1, x + w - 1, x + w - 1};
yp = new int[]{y + h - 1, y, y, y + h - 1};
break;
case TOP:
default:
xp = new int[]{x + 1, x + 1, x + w - 1, x + w - 1};
yp = new int[]{y + h, y + 1, y + 1, y + h};
break;
}
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintFlatTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
switch (tabPlacement) {
case LEFT:
int xp1[] = {x + 1, x + 1, x + w, x + w};
int yp1[] = {y + h, y + 1, y + 1, y + h};
int np1 = yp1.length;
tabRegion = new Polygon(xp1, yp1, np1);
break;
case RIGHT:
int xp2[] = {x, x, x + w - 1, x + w - 1};
int yp2[] = {y + h, y + 1, y + 1, y + h};
int np2 = yp2.length;
tabRegion = new Polygon(xp2, yp2, np2);
break;
case BOTTOM:
int xp3[] = {x + 1, x + 1, x + w, x + w};
int yp3[] = {y + h - 1, y, y, y + h - 1};
int np3 = yp3.length;
tabRegion = new Polygon(xp3, yp3, np3);
break;
case TOP:
default:
int xp4[] = {x, x + 1, x + w, x + w};
int yp4[] = {y + h, y + 1, y + 1, y + h};
int np4 = yp4.length;
tabRegion = new Polygon(xp4, yp4, np4);
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintButtonTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
int xp[] = {x, x, x + w, x + w};
int yp[] = {y + h, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) {
int width = _tabPane.getWidth();
int height = _tabPane.getHeight();
Insets insets = _tabPane.getInsets();
int x = insets.left;
int y = insets.top;
int w = width - insets.right - insets.left;
int h = height - insets.top - insets.bottom;
int temp = -1;
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
x += calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
if (isTabLeadingComponentVisible()) {
if (lsize.width > calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth)) {
x = insets.left + lsize.width;
temp = _tabLeadingComponent.getSize().width;
}
}
if (isTabTrailingComponentVisible()) {
if (_maxTabWidth < tsize.width
&& temp < tsize.width) {
x = insets.left + tsize.width;
}
}
w -= (x - insets.left);
break;
case RIGHT:
w -= calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
break;
case BOTTOM:
h -= calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
break;
case TOP:
default:
y += calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
if (lsize.height > calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight)) {
y = insets.top + lsize.height;
temp = lsize.height;
}
}
if (isTabTrailingComponentVisible()) {
if (_maxTabHeight < tsize.height
&& temp < tsize.height) {
y = insets.top + tsize.height;
}
}
h -= (y - insets.top);
}
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
// Fill region behind content area
paintContentBorder(g, x, y, w, h);
switch (tabPlacement) {
case LEFT:
paintContentBorderLeftEdge(g, tabPlacement, selectedIndex, x, y, w, h);
break;
case RIGHT:
paintContentBorderRightEdge(g, tabPlacement, selectedIndex, x, y, w, h);
break;
case BOTTOM:
paintContentBorderBottomEdge(g, tabPlacement, selectedIndex, x, y, w, h);
break;
case TOP:
default:
paintContentBorderTopEdge(g, tabPlacement, selectedIndex, x, y, w, h);
break;
}
}
}
protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
}
protected void paintContentBorderRightEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
}
protected void paintContentBorder(Graphics g, int x, int y, int w, int h) {
if (!PAINT_CONTENT_BORDER) {
return;
}
if (_tabPane.isOpaque()) {
g.setColor(_tabBackground);
g.fillRect(x, y, w, h);
}
}
protected Color getBorderEdgeColor() {
if ("true".equals(SecurityUtils.getProperty("shadingtheme", "false"))) {
return _shadow;
}
else {
return _lightHighlight;
}
}
protected void paintContentBorderTopEdge(Graphics g, int tabPlacement,
int selectedIndex,
int x, int y, int w, int h) {
if (!PAINT_CONTENT_BORDER_EDGE) {
return;
}
if (selectedIndex < 0) {
return;
}
if (!_tabPane.isTabShown()) {
return;
}
Rectangle selRect = getTabBounds(selectedIndex, _calcRect);
g.setColor(getBorderEdgeColor());
// Draw unbroken line if tabs are not on TOP, OR
// selected tab is not in run adjacent to content, OR
// selected tab is not visible (SCROLL_TAB_LAYOUT)
//
if (tabPlacement != TOP || selectedIndex < 0 ||
/*(selRect.y + selRect.height + 1 < y) ||*/
(selRect.x < x || selRect.x > x + w)) {
g.drawLine(x, y, x + w - 1, y);
}
else {
// Break line to show visual connection to selected tab
g.drawLine(x, y, selRect.x, y);
if (!getBorderEdgeColor().equals(_lightHighlight)) {
if (selRect.x + selRect.width < x + w - 2) {
g.drawLine(selRect.x + selRect.width - 1, y,
selRect.x + selRect.width - 1, y);
g.drawLine(selRect.x + selRect.width, y, x + w - 1, y);
}
else {
g.drawLine(x + w - 2, y, x + w - 1, y);
}
}
else {
if (selRect.x + selRect.width < x + w - 2) {
g.setColor(_darkShadow);
g.drawLine(selRect.x + selRect.width - 1, y,
selRect.x + selRect.width - 1, y);
g.setColor(_lightHighlight);
g.drawLine(selRect.x + selRect.width, y, x + w - 1, y);
}
else {
g.setColor(_selectedColor == null ?
_tabPane.getBackground() : _selectedColor);
g.drawLine(x + w - 2, y, x + w - 1, y);
}
}
}
}
protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement,
int selectedIndex,
int x, int y, int w, int h) {
if (!PAINT_CONTENT_BORDER_EDGE) {
return;
}
if (selectedIndex < 0) {
return;
}
if (!_tabPane.isTabShown()) {
return;
}
Rectangle selRect = getTabBounds(selectedIndex, _calcRect);
// Draw unbroken line if tabs are not on BOTTOM, OR
// selected tab is not in run adjacent to content, OR
// selected tab is not visible (SCROLL_TAB_LAYOUT)
//
if (tabPlacement != BOTTOM || selectedIndex < 0 ||
/*(selRect.y - 1 > h) ||*/
(selRect.x < x || selRect.x > x + w)) {
g.setColor(getBorderEdgeColor());
g.drawLine(x, y + h - 1, x + w - 2, y + h - 1);
}
else {
if (!getBorderEdgeColor().equals(_lightHighlight)) {
g.setColor(getBorderEdgeColor());
g.drawLine(x, y + h - 1, selRect.x - 1, y + h - 1);
g.drawLine(selRect.x, y + h - 1, selRect.x, y + h - 1);
if (selRect.x + selRect.width < x + w - 2) {
g.drawLine(selRect.x + selRect.width - 1, y + h - 1, x + w - 2, y + h - 1); // dark line to the end
}
}
else {
// Break line to show visual connection to selected tab
g.setColor(_darkShadow); // dark line at the beginning
g.drawLine(x, y + h - 1, selRect.x - 1, y + h - 1);
g.setColor(_lightHighlight); // light line to meet with tab
// border
g.drawLine(selRect.x, y + h - 1, selRect.x, y + h - 1);
if (selRect.x + selRect.width < x + w - 2) {
g.setColor(_darkShadow);
g.drawLine(selRect.x + selRect.width - 1, y + h - 1, x + w - 2, y + h - 1); // dark line to the end
}
}
}
}
protected void ensureCurrentLayout() {
/*
* If tabPane doesn't have a peer yet, the validate() call will
* silently fail. We handle that by forcing a layout if tabPane
* is still invalid. See bug 4237677.
*/
if (!_tabPane.isValid()) {
TabbedPaneLayout layout = (TabbedPaneLayout) _tabPane.getLayout();
layout.calculateLayoutInfo();
}
}
private void updateCloseButtons() {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab()) {
for (int i = 0; i < _closeButtons.length; i++) {
if (_tabPane.isShowCloseButtonOnSelectedTab()) {
if (i != _tabPane.getSelectedIndex()) {
_closeButtons[i].setBounds(0, 0, 0, 0);
continue;
}
}
else {
if (i >= _rects.length) {
_closeButtons[i].setBounds(0, 0, 0, 0);
continue;
}
}
if (!_tabPane.isTabClosableAt(i)) {
_closeButtons[i].setBounds(0, 0, 0, 0);
continue;
}
Dimension size = _closeButtons[i].getPreferredSize();
Rectangle bounds;
if (_closeButtonAlignment == SwingConstants.TRAILING) {
if (_tabPane.getTabPlacement() == JideTabbedPane.TOP || _tabPane.getTabPlacement() == JideTabbedPane.BOTTOM) {
if (leftToRight) {
bounds = new Rectangle(_rects[i].x + _rects[i].width - size.width - _closeButtonRightMargin,
_rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height);
bounds.x -= getTabGap();
}
else {
bounds = new Rectangle(_rects[i].x + _closeButtonLeftMargin + getTabGap(), _rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height);
}
}
else /*if (_tabPane.getTabPlacement() == JideTabbedPane.LEFT || _tabPane.getTabPlacement() == JideTabbedPane.RIGHT)*/ {
bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2, _rects[i].y + _rects[i].height - size.height - _closeButtonRightMargin, size.width, size.height);
bounds.y -= getTabGap();
}
}
else {
if (_tabPane.getTabPlacement() == JideTabbedPane.TOP || _tabPane.getTabPlacement() == JideTabbedPane.BOTTOM) {
if (leftToRight) {
bounds = new Rectangle(_rects[i].x + _closeButtonLeftMargin + getTabGap(), _rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height);
}
else {
bounds = new Rectangle(_rects[i].x + _rects[i].width - size.width - _closeButtonRightMargin,
_rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height);
bounds.x -= getTabGap();
}
}
else if (_tabPane.getTabPlacement() == JideTabbedPane.LEFT) {
bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2, _rects[i].y + _closeButtonLeftMargin, size.width, size.height);
}
else /*if (_tabPane.getTabPlacement() == JideTabbedPane.RIGHT)*/ {
bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2 - 2, _rects[i].y + _closeButtonLeftMargin, size.width, size.height);
}
}
_closeButtons[i].setIndex(i);
if (!bounds.equals(_closeButtons[i].getBounds())) {
_closeButtons[i].setBounds(bounds);
}
if (_tabPane.getSelectedIndex() == i) {
_closeButtons[i].setBackground(_selectedColor == null ? _tabPane.getBackgroundAt(i) : _selectedColor);
}
else {
_closeButtons[i].setBackground(_tabPane.getBackgroundAt(i));
}
}
}
}
// TabbedPaneUI methods
/**
* Returns the bounds of the specified tab index. The bounds are with respect to the JTabbedPane's coordinate
* space.
*/
@Override
public Rectangle getTabBounds(JTabbedPane pane, int i) {
ensureCurrentLayout();
Rectangle tabRect = new Rectangle();
return getTabBounds(i, tabRect);
}
@Override
public int getTabRunCount(JTabbedPane pane) {
ensureCurrentLayout();
return _runCount;
}
/**
* Returns the tab index which intersects the specified point in the JTabbedPane's coordinate space.
*/
@Override
public int tabForCoordinate(JTabbedPane pane, int x, int y) {
ensureCurrentLayout();
Point p = new Point(x, y);
if (scrollableTabLayoutEnabled()) {
translatePointToTabPanel(x, y, p);
}
int tabCount = _tabPane.getTabCount();
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
p.x -= _tabScroller.viewport.getExpectedViewX();
}
for (int i = 0; i < tabCount; i++) {
if (_rects[i].contains(p.x, p.y)) {
return i;
}
}
return -1;
}
/**
* Returns the bounds of the specified tab in the coordinate space of the JTabbedPane component. This is required
* because the tab rects are by default defined in the coordinate space of the component where they are rendered,
* which could be the JTabbedPane (for WRAP_TAB_LAYOUT) or a ScrollableTabPanel (SCROLL_TAB_LAYOUT). This method
* should be used whenever the tab rectangle must be relative to the JTabbedPane itself and the result should be
* placed in a designated Rectangle object (rather than instantiating and returning a new Rectangle each time). The
* tab index parameter must be a valid tabbed pane tab index (0 to tab count - 1, inclusive). The destination
* rectangle parameter must be a valid <code>Rectangle</code> instance. The handling of invalid parameters is
* unspecified.
*
* @param tabIndex the index of the tab
* @param dest the rectangle where the result should be placed
* @return the resulting rectangle
*/
protected Rectangle getTabBounds(int tabIndex, Rectangle dest) {
if (_rects.length == 0) {
return null;
}
// to make the index is in bound.
if (tabIndex > _rects.length - 1) {
tabIndex = _rects.length - 1;
}
if (tabIndex < 0) {
tabIndex = 0;
}
dest.width = _rects[tabIndex].width;
dest.height = _rects[tabIndex].height;
if (scrollableTabLayoutEnabled()) { // SCROLL_TAB_LAYOUT
// Need to translate coordinates based on viewport location &
// view position
int tabPlacement = _tabPane.getTabPlacement();
Point vpp = _tabScroller.viewport.getLocation();
Point viewp = _tabScroller.viewport.getViewPosition();
dest.x = _rects[tabIndex].x + vpp.x - (((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) ? -_tabScroller.viewport.getExpectedViewX(): viewp.x);
dest.y = _rects[tabIndex].y + vpp.y - viewp.y;
}
else { // WRAP_TAB_LAYOUT
dest.x = _rects[tabIndex].x;
dest.y = _rects[tabIndex].y;
}
return dest;
}
/**
* Returns the tab index which intersects the specified point in the coordinate space of the component where the
* tabs are actually rendered, which could be the JTabbedPane (for WRAP_TAB_LAYOUT) or a ScrollableTabPanel
* (SCROLL_TAB_LAYOUT).
*
* @param x x value of the point
* @param y y value of the point
* @return the tab index in the point (x, y). -1 if no tab could be found.
*/
public int getTabAtLocation(int x, int y) {
ensureCurrentLayout();
int tabCount = _tabPane.getTabCount();
for (int i = 0; i < tabCount; i++) {
if (_rects[i].contains(x, y)) {
return i;
}
}
return -1;
}
/**
* Returns if the point resides in the empty tab area, which means it is in the tab area however no real tab contains
* that point.
*
* @param x x value of the point
* @param y y value of the point
* @return true if the point is in empty tab area. Otherwise false.
*/
public boolean isEmptyTabArea(int x, int y) {
int tabCount = _tabPane.getTabCount();
if (getTabAtLocation(x, y) >= 0 || tabCount <= 0) {
return false;
}
int tabPlacement = _tabPane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (_rects[0].contains(_rects[0].x + 1, y)) {
return true;
}
}
else {
if (_rects[0].contains(x, _rects[0].y + 1)) {
return true;
}
}
return false;
}
/*
* Returns the index of the tab closest to the passed in location, note that the returned tab may not contain the
* location x,y.
*/
private int getClosestTab(int x, int y) {
int min = 0;
int tabCount = Math.min(_rects.length, _tabPane.getTabCount());
int max = tabCount;
int tabPlacement = _tabPane.getTabPlacement();
boolean useX = (tabPlacement == TOP || tabPlacement == BOTTOM);
int want = (useX) ? x : y;
if (!_tabPane.getComponentOrientation().isLeftToRight()) {
want = x - _tabScroller.viewport.getExpectedViewX() - 1;
}
Rectangle[] rects = new Rectangle[_rects.length];
boolean needConvert = false;
if (!useX || _tabPane.getComponentOrientation().isLeftToRight()) {
System.arraycopy(_rects, 0, rects, 0, _rects.length);
}
else {
if (x == _tabScroller.viewport.getViewRect().width) {
return _tabScroller.leadingTabIndex;
}
needConvert = true;
for (int i = 0; i < _rects.length; i++) {
rects[i] = _rects[_rects.length - 1 - i];
}
}
while (min != max) {
int current = (max + min) >> 1;
int minLoc;
int maxLoc;
if (useX) {
minLoc = rects[current].x;
maxLoc = minLoc + rects[current].width;
}
else {
minLoc = rects[current].y;
maxLoc = minLoc + rects[current].height;
}
if (want < minLoc) {
max = current;
if (min == max) {
int tabIndex = Math.max(0, current - 1);
return needConvert ? rects.length - 1 - tabIndex : tabIndex;
}
}
else if (want >= maxLoc) {
min = current;
if (max - min <= 1) {
int tabIndex = Math.max(current + 1, tabCount - 1);
return needConvert ? rects.length - 1 - tabIndex : tabIndex;
}
}
else {
return needConvert ? rects.length - 1 - current : current;
}
}
return needConvert ? rects.length - 1 - min : min;
}
/*
* Returns a point which is translated from the specified point in the JTabbedPane's coordinate space to the
* coordinate space of the ScrollableTabPanel. This is used for SCROLL_TAB_LAYOUT ONLY.
*/
private Point translatePointToTabPanel(int srcx, int srcy, Point dest) {
Point vpp = _tabScroller.viewport.getLocation();
Point viewp = _tabScroller.viewport.getViewPosition();
dest.x = srcx - vpp.x + viewp.x;
dest.y = srcy - vpp.y + viewp.y;
return dest;
}
// VsnetJideTabbedPaneUI methods
protected Component getVisibleComponent() {
return visibleComponent;
}
protected void setVisibleComponent(Component component) {
if (visibleComponent != null && visibleComponent != component &&
visibleComponent.getParent() == _tabPane) {
visibleComponent.setVisible(false);
}
if (component != null && !component.isVisible()) {
component.setVisible(true);
}
visibleComponent = component;
}
protected void assureRectsCreated(int tabCount) {
int rectArrayLen = _rects.length;
if (tabCount != rectArrayLen) {
Rectangle[] tempRectArray = new Rectangle[tabCount];
System.arraycopy(_rects, 0, tempRectArray, 0,
Math.min(rectArrayLen, tabCount));
_rects = tempRectArray;
for (int rectIndex = rectArrayLen; rectIndex < tabCount; rectIndex++) {
_rects[rectIndex] = new Rectangle();
}
}
}
protected void expandTabRunsArray() {
int rectLen = _tabRuns.length;
int[] newArray = new int[rectLen + 10];
System.arraycopy(_tabRuns, 0, newArray, 0, _runCount);
_tabRuns = newArray;
}
protected int getRunForTab(int tabCount, int tabIndex) {
for (int i = 0; i < _runCount; i++) {
int first = _tabRuns[i];
int last = lastTabInRun(tabCount, i);
if (tabIndex >= first && tabIndex <= last) {
return i;
}
}
return 0;
}
protected int lastTabInRun(int tabCount, int run) {
if (_runCount == 1) {
return tabCount - 1;
}
int nextRun = (run == _runCount - 1 ? 0 : run + 1);
if (_tabRuns[nextRun] == 0) {
return tabCount - 1;
}
return _tabRuns[nextRun] - 1;
}
@SuppressWarnings({"UnusedDeclaration"})
protected int getTabRunOverlay(int tabPlacement) {
return _tabRunOverlay;
}
@SuppressWarnings({"UnusedDeclaration"})
protected int getTabRunIndent(int tabPlacement, int run) {
return 0;
}
@SuppressWarnings({"UnusedDeclaration"})
protected boolean shouldPadTabRun(int tabPlacement, int run) {
return _runCount > 1;
}
@SuppressWarnings({"UnusedDeclaration"})
protected boolean shouldRotateTabRuns(int tabPlacement) {
return true;
}
/**
* Returns the text View object required to render stylized text (HTML) for the specified tab or null if no
* specialized text rendering is needed for this tab. This is provided to support html rendering inside tabs.
*
* @param tabIndex the index of the tab
* @return the text view to render the tab's text or null if no specialized rendering is required
*/
protected View getTextViewForTab(int tabIndex) {
if (htmlViews != null && tabIndex < htmlViews.size()) {
return (View) htmlViews.elementAt(tabIndex);
}
return null;
}
protected int calculateTabHeight(int tabPlacement, int tabIndex, FontMetrics metrics) {
int height = 0;
if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
height += (int) v.getPreferredSpan(View.Y_AXIS);
}
else {
// plain text
height += metrics.getHeight();
}
Icon icon = _tabPane.getIconForTab(tabIndex);
Insets tabInsets = getTabInsets(tabPlacement, tabIndex);
if (icon != null) {
height = Math.max(height, icon.getIconHeight());
}
height += tabInsets.top + tabInsets.bottom + 2;
}
else {
Icon icon = _tabPane.getIconForTab(tabIndex);
Insets tabInsets = getTabInsets(tabPlacement, tabIndex);
height = tabInsets.top + tabInsets.bottom + 3;
if (icon != null) {
height += icon.getIconHeight() + _textIconGap;
}
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
height += (int) v.getPreferredSpan(View.X_AXIS);
}
else {
// plain text
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
height += SwingUtilities.computeStringWidth(metrics, title);
}
// for gripper
if (_tabPane.isShowGripper()) {
height += _gripperHeight;
}
if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex)) {
if (_tabPane.isShowCloseButtonOnSelectedTab()) {
if (_tabPane.getSelectedIndex() == tabIndex) {
height += _closeButtons[tabIndex].getPreferredSize().height + _closeButtonRightMargin + _closeButtonLeftMargin;
}
}
else {
height += _closeButtons[tabIndex].getPreferredSize().height + _closeButtonRightMargin + _closeButtonLeftMargin;
}
}
// height += _tabRectPadding;
}
return height;
}
protected int calculateMaxTabHeight(int tabPlacement) {
int tabCount = _tabPane.getTabCount();
int result = 0;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
result = Math.max(calculateTabHeight(tabPlacement, i, metrics), result);
}
return result;
}
protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
int width = 0;
if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
Icon icon = _tabPane.getIconForTab(tabIndex);
Insets tabInsets = getTabInsets(tabPlacement, tabIndex);
width = tabInsets.left + tabInsets.right + 3 + getTabGap();
if (icon != null) {
width += icon.getIconWidth() + _textIconGap;
}
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
width += (int) v.getPreferredSpan(View.X_AXIS);
}
else {
// plain text
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
while (title == null || title.length() < 3)
title += " ";
width += SwingUtilities.computeStringWidth(metrics, title);
}
// for gripper
if (_tabPane.isShowGripper()) {
width += _gripperWidth;
}
if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex)) {
if (_tabPane.isShowCloseButtonOnSelectedTab()) {
if (_tabPane.getSelectedIndex() == tabIndex) {
width += _closeButtons[tabIndex].getPreferredSize().width + _closeButtonRightMargin + _closeButtonLeftMargin;
}
}
else {
width += _closeButtons[tabIndex].getPreferredSize().width + _closeButtonRightMargin + _closeButtonLeftMargin;
}
}
// width += _tabRectPadding;
}
else {
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
width += (int) v.getPreferredSpan(View.Y_AXIS);
}
else {
// plain text
width += metrics.getHeight();
}
Icon icon = _tabPane.getIconForTab(tabIndex);
Insets tabInsets = getTabInsets(tabPlacement, tabIndex);
if (icon != null) {
width = Math.max(width, icon.getIconWidth());
}
width += tabInsets.left + tabInsets.right + 2;
}
return width;
}
protected int calculateMaxTabWidth(int tabPlacement) {
int tabCount = _tabPane.getTabCount();
int result = 0;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
result = Math.max(calculateTabWidth(tabPlacement, i, metrics), result);
}
return result;
}
protected int calculateTabAreaHeight(int tabPlacement, int horizRunCount, int maxTabHeight) {
if (!_tabPane.isTabShown()) {
return 0;
}
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int tabRunOverlay = getTabRunOverlay(tabPlacement);
return (horizRunCount > 0 ? horizRunCount * (maxTabHeight - tabRunOverlay) + tabRunOverlay + tabAreaInsets.top + tabAreaInsets.bottom : 0);
}
protected int calculateTabAreaWidth(int tabPlacement, int vertRunCount, int maxTabWidth) {
if (!_tabPane.isTabShown()) {
return 0;
}
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int tabRunOverlay = getTabRunOverlay(tabPlacement);
return (vertRunCount > 0 ? vertRunCount * (maxTabWidth - tabRunOverlay) + tabRunOverlay + tabAreaInsets.left + tabAreaInsets.right : 0);
}
@SuppressWarnings({"UnusedDeclaration"})
protected Insets getTabInsets(int tabPlacement, int tabIndex) {
rotateInsets(_tabInsets, _currentTabInsets, tabPlacement);
return _currentTabInsets;
}
protected Insets getSelectedTabPadInsets(int tabPlacement) {
rotateInsets(_selectedTabPadInsets, _currentPadInsets, tabPlacement);
return _currentPadInsets;
}
protected Insets getTabAreaInsets(int tabPlacement) {
rotateInsets(_tabAreaInsets, _currentTabAreaInsets, tabPlacement);
return _currentTabAreaInsets;
}
protected Insets getContentBorderInsets(int tabPlacement) {
rotateInsets(_tabPane.getContentBorderInsets(), _currentContentBorderInsets, tabPlacement);
if (_ignoreContentBorderInsetsIfNoTabs && !_tabPane.isTabShown())
return new Insets(0, 0, 0, 0);
else
return _currentContentBorderInsets;
}
protected FontMetrics getFontMetrics(int tab) {
Font font;
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex == tab && _tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (selectedIndex == tab && _tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
return _tabPane.getFontMetrics(font);
}
// Tab Navigation methods
protected void navigateSelectedTab(int direction) {
int tabPlacement = _tabPane.getTabPlacement();
int current = _tabPane.getSelectedIndex();
int tabCount = _tabPane.getTabCount();
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
// If we have no tabs then don't navigate.
if (tabCount <= 0) {
return;
}
int offset;
switch (tabPlacement) {
case NEXT:
selectNextTab(current);
break;
case PREVIOUS:
selectPreviousTab(current);
break;
case LEFT:
case RIGHT:
switch (direction) {
case NORTH:
selectPreviousTabInRun(current);
break;
case SOUTH:
selectNextTabInRun(current);
break;
case WEST:
offset = getTabRunOffset(tabPlacement, tabCount, current, false);
selectAdjacentRunTab(tabPlacement, current, offset);
break;
case EAST:
offset = getTabRunOffset(tabPlacement, tabCount, current, true);
selectAdjacentRunTab(tabPlacement, current, offset);
break;
default:
}
break;
case BOTTOM:
case TOP:
default:
switch (direction) {
case NORTH:
offset = getTabRunOffset(tabPlacement, tabCount, current, false);
selectAdjacentRunTab(tabPlacement, current, offset);
break;
case SOUTH:
offset = getTabRunOffset(tabPlacement, tabCount, current, true);
selectAdjacentRunTab(tabPlacement, current, offset);
break;
case EAST:
if (leftToRight) {
selectNextTabInRun(current);
}
else {
selectPreviousTabInRun(current);
}
break;
case WEST:
if (leftToRight) {
selectPreviousTabInRun(current);
}
else {
selectNextTabInRun(current);
}
break;
default:
}
}
}
protected void selectNextTabInRun(int current) {
int tabCount = _tabPane.getTabCount();
int tabIndex = getNextTabIndexInRun(tabCount, current);
while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) {
tabIndex = getNextTabIndexInRun(tabCount, tabIndex);
}
_tabPane.setSelectedIndex(tabIndex);
}
protected void selectPreviousTabInRun(int current) {
int tabCount = _tabPane.getTabCount();
int tabIndex = getPreviousTabIndexInRun(tabCount, current);
while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) {
tabIndex = getPreviousTabIndexInRun(tabCount, tabIndex);
}
_tabPane.setSelectedIndex(tabIndex);
}
protected void selectNextTab(int current) {
int tabIndex = getNextTabIndex(current);
while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) {
tabIndex = getNextTabIndex(tabIndex);
}
_tabPane.setSelectedIndex(tabIndex);
}
protected void selectPreviousTab(int current) {
int tabIndex = getPreviousTabIndex(current);
while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) {
tabIndex = getPreviousTabIndex(tabIndex);
}
_tabPane.setSelectedIndex(tabIndex);
}
protected void selectAdjacentRunTab(int tabPlacement,
int tabIndex, int offset) {
if (_runCount < 2) {
return;
}
int newIndex;
Rectangle r = _rects[tabIndex];
switch (tabPlacement) {
case LEFT:
case RIGHT:
newIndex = getTabAtLocation(r.x + (r.width >> 1) + offset,
r.y + (r.height >> 1));
break;
case BOTTOM:
case TOP:
default:
newIndex = getTabAtLocation(r.x + (r.width >> 1),
r.y + (r.height >> 1) + offset);
}
if (newIndex != -1) {
while (!_tabPane.isEnabledAt(newIndex) && newIndex != tabIndex) {
newIndex = getNextTabIndex(newIndex);
}
_tabPane.setSelectedIndex(newIndex);
}
}
protected int getTabRunOffset(int tabPlacement, int tabCount,
int tabIndex, boolean forward) {
int run = getRunForTab(tabCount, tabIndex);
int offset;
switch (tabPlacement) {
case LEFT: {
if (run == 0) {
offset = (forward ?
-(calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth) :
-_maxTabWidth);
}
else if (run == _runCount - 1) {
offset = (forward ?
_maxTabWidth :
calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth);
}
else {
offset = (forward ? _maxTabWidth : -_maxTabWidth);
}
break;
}
case RIGHT: {
if (run == 0) {
offset = (forward ?
_maxTabWidth :
calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth);
}
else if (run == _runCount - 1) {
offset = (forward ?
-(calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth) :
-_maxTabWidth);
}
else {
offset = (forward ? _maxTabWidth : -_maxTabWidth);
}
break;
}
case BOTTOM: {
if (run == 0) {
offset = (forward ?
_maxTabHeight :
calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight);
}
else if (run == _runCount - 1) {
offset = (forward ?
-(calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight) :
-_maxTabHeight);
}
else {
offset = (forward ? _maxTabHeight : -_maxTabHeight);
}
break;
}
case TOP:
default: {
if (run == 0) {
offset = (forward ?
-(calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight) :
-_maxTabHeight);
}
else if (run == _runCount - 1) {
offset = (forward ?
_maxTabHeight :
calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight);
}
else {
offset = (forward ? _maxTabHeight : -_maxTabHeight);
}
}
}
return offset;
}
protected int getPreviousTabIndex(int base) {
int tabIndex = (base - 1 >= 0 ? base - 1 : _tabPane.getTabCount() - 1);
return (tabIndex >= 0 ? tabIndex : 0);
}
protected int getNextTabIndex(int base) {
return (base + 1) % _tabPane.getTabCount();
}
protected int getNextTabIndexInRun(int tabCount, int base) {
if (_runCount < 2) {
return getNextTabIndex(base);
}
int currentRun = getRunForTab(tabCount, base);
int next = getNextTabIndex(base);
if (next == _tabRuns[getNextTabRun(currentRun)]) {
return _tabRuns[currentRun];
}
return next;
}
protected int getPreviousTabIndexInRun(int tabCount, int base) {
if (_runCount < 2) {
return getPreviousTabIndex(base);
}
int currentRun = getRunForTab(tabCount, base);
if (base == _tabRuns[currentRun]) {
int previous = _tabRuns[getNextTabRun(currentRun)] - 1;
return (previous != -1 ? previous : tabCount - 1);
}
return getPreviousTabIndex(base);
}
protected int getPreviousTabRun(int baseRun) {
int runIndex = (baseRun - 1 >= 0 ? baseRun - 1 : _runCount - 1);
return (runIndex >= 0 ? runIndex : 0);
}
protected int getNextTabRun(int baseRun) {
return (baseRun + 1) % _runCount;
}
public static void rotateInsets(Insets topInsets, Insets targetInsets, int targetPlacement) {
switch (targetPlacement) {
case LEFT:
targetInsets.top = topInsets.left;
targetInsets.left = topInsets.top;
targetInsets.bottom = topInsets.right;
targetInsets.right = topInsets.bottom;
break;
case BOTTOM:
targetInsets.top = topInsets.bottom;
targetInsets.left = topInsets.left;
targetInsets.bottom = topInsets.top;
targetInsets.right = topInsets.right;
break;
case RIGHT:
targetInsets.top = topInsets.left;
targetInsets.left = topInsets.bottom;
targetInsets.bottom = topInsets.right;
targetInsets.right = topInsets.top;
break;
case TOP:
default:
targetInsets.top = topInsets.top;
targetInsets.left = topInsets.left;
targetInsets.bottom = topInsets.bottom;
targetInsets.right = topInsets.right;
}
}
protected boolean requestFocusForVisibleComponent() {
Component visibleComponent = getVisibleComponent();
Component lastFocused = _tabPane.getLastFocusedComponent(visibleComponent);
if (lastFocused != null && lastFocused.requestFocusInWindow()) {
return true;
}
else if (visibleComponent != null && JideSwingUtilities.passesFocusabilityTest(visibleComponent)) { // visibleComponent.isFocusTraversable()) {
JideSwingUtilities.compositeRequestFocus(visibleComponent);
return true;
}
else if (visibleComponent instanceof JComponent) {
if (((JComponent) visibleComponent).requestDefaultFocus()) {
return true;
}
}
return false;
}
private static class RightAction extends AbstractAction {
private static final long serialVersionUID = -1759791760116532857L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(EAST);
}
}
private static class LeftAction extends AbstractAction {
private static final long serialVersionUID = 8670680299012169408L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(WEST);
}
}
private static class UpAction extends AbstractAction {
private static final long serialVersionUID = -6961702501242792445L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NORTH);
}
}
private static class DownAction extends AbstractAction {
private static final long serialVersionUID = -453174268282628886L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(SOUTH);
}
}
private static class NextAction extends AbstractAction {
private static final long serialVersionUID = -154035573464933924L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NEXT);
}
}
private static class PreviousAction extends AbstractAction {
private static final long serialVersionUID = 2095403667386334865L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(PREVIOUS);
}
}
private static class PageUpAction extends AbstractAction {
private static final long serialVersionUID = 1154273528778779166L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(WEST);
}
else {
ui.navigateSelectedTab(NORTH);
}
}
}
private static class PageDownAction extends AbstractAction {
private static final long serialVersionUID = 4895454480954468453L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(EAST);
}
else {
ui.navigateSelectedTab(SOUTH);
}
}
}
private static class RequestFocusAction extends AbstractAction {
private static final long serialVersionUID = 3791111435639724577L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (!pane.requestFocusInWindow()) {
pane.requestFocus();
}
}
}
private static class RequestFocusForVisibleAction extends AbstractAction {
private static final long serialVersionUID = 6677797853998039155L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.requestFocusForVisibleComponent();
}
}
/**
* Selects a tab in the JTabbedPane based on the String of the action command. The tab selected is based on the
* first tab that has a mnemonic matching the first character of the action command.
*/
private static class SetSelectedIndexAction extends AbstractAction {
private static final long serialVersionUID = 6216635910156115469L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (pane != null && (pane.getUI() instanceof BasicJideTabbedPaneUI)) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
String command = e.getActionCommand();
if (command != null && command.length() > 0) {
int mnemonic = (int) e.getActionCommand().charAt(0);
if (mnemonic >= 'a' && mnemonic <= 'z') {
mnemonic -= ('a' - 'A');
}
Integer index = (Integer) ui._mnemonicToIndexMap
.get(new Integer(mnemonic));
if (index != null && pane.isEnabledAt(index)) {
pane.setSelectedIndex(index);
}
}
}
}
}
protected TabCloseButton createNoFocusButton(int type) {
return new TabCloseButton(type);
}
private static class ScrollTabsForwardAction extends AbstractAction {
private static final long serialVersionUID = 8772616556895545931L;
public ScrollTabsForwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollForward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollForward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsBackwardAction extends AbstractAction {
private static final long serialVersionUID = -426408621939940046L;
public ScrollTabsBackwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollBackward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollBackward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsListAction extends AbstractAction {
private static final long serialVersionUID = 246103712600916771L;
public ScrollTabsListAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.showList"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
if (ui._tabScroller._popup != null && ui._tabScroller._popup.isPopupVisible()) {
ui._tabScroller._popup.hidePopupImmediately();
ui._tabScroller._popup = null;
}
else {
ui._tabScroller.createPopup(pane.getTabPlacement());
}
}
}
}
}
protected void stopOrCancelEditing() {
boolean isEditValid = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
isEditValid = _tabPane.getTabEditingValidator().isValid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (isEditValid)
_tabPane.stopTabEditing();
else
_tabPane.cancelTabEditing();
}
private static class CloseTabAction extends AbstractAction {
private static final long serialVersionUID = 7779678389793199733L;
public CloseTabAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.close"));
}
public void actionPerformed(ActionEvent e) {
JideTabbedPane pane;
Object src = e.getSource();
int index;
boolean closeSelected = false;
if (src instanceof JideTabbedPane) {
pane = (JideTabbedPane) src;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof JideTabbedPane) {
pane = (JideTabbedPane) ((TabCloseButton) src).getParent();
closeSelected = true;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof ScrollableTabPanel) {
pane = (JideTabbedPane) SwingUtilities.getAncestorOfClass(JideTabbedPane.class, (TabCloseButton) src);
closeSelected = false;
}
else {
return; // shouldn't happen
}
if (pane.isTabEditing()) {
((BasicJideTabbedPaneUI) pane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
}
ActionEvent e2 = e;
if (src instanceof TabCloseButton) {
index = ((TabCloseButton) src).getIndex();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
else if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
if (pane.getCloseAction() != null) {
pane.getCloseAction().actionPerformed(e2);
}
else {
if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
if (index >= 0)
pane.removeTabAt(index);
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else if (closeSelected) {
if (pane.getSelectedIndex() >= 0)
pane.removeTabAt(pane.getSelectedIndex());
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else {
int i = ((TabCloseButton) src).getIndex();
if (i != -1) {
int tabIndex = pane.getSelectedIndex();
pane.removeTabAt(i);
if (i < tabIndex) {
pane.setSelectedIndex(tabIndex - 1);
}
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
}
}
}
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabbedPaneLayout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
return calculateSize(false);
}
public Dimension minimumLayoutSize(Container parent) {
return calculateSize(true);
}
protected Dimension calculateSize(boolean minimum) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
Insets contentInsets = getContentBorderInsets(tabPlacement);
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
Dimension zeroSize = new Dimension(0, 0);
int height = contentInsets.top + contentInsets.bottom;
int width = contentInsets.left + contentInsets.right;
int cWidth = 0;
int cHeight = 0;
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
// Determine minimum size required to display largest
// child in each dimension
//
if (_tabPane.isShowTabContent()) {
for (int i = 0; i < _tabPane.getTabCount(); i++) {
Component component = _tabPane.getComponentAt(i);
if (component != null) {
Dimension size = zeroSize;
size = minimum ? component.getMinimumSize() :
component.getPreferredSize();
if (size != null) {
cHeight = Math.max(size.height, cHeight);
cWidth = Math.max(size.width, cWidth);
}
}
}
// Add content border insets to minimum size
width += cWidth;
height += cHeight;
}
int tabExtent;
// Calculate how much space the tabs will need, based on the
// minimum size required to display largest child + content border
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
height = Math.max(height, (minimum ? 0 : calculateMaxTabHeight(tabPlacement)) + tabAreaInsets.top + tabAreaInsets.bottom);
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.width, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.width, tabExtent);
}
width += tabExtent;
break;
case TOP:
case BOTTOM:
default:
if (_tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {
width = Math.max(width, (_tabPane.getTabCount() << 2) +
tabAreaInsets.left + tabAreaInsets.right);
}
else {
width = Math.max(width, (minimum ? 0 : calculateMaxTabWidth(tabPlacement)) +
tabAreaInsets.left + tabAreaInsets.right);
}
if (_tabPane.isTabShown()) {
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.height, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.height, tabExtent);
}
height += tabExtent;
}
}
}
return new Dimension(width + insets.left + insets.right,
height + insets.bottom + insets.top);
}
protected int preferredTabAreaHeight(int tabPlacement, int width) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int rows = 1;
int x = 0;
int maxTabHeight = calculateMaxTabHeight(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabWidth = calculateTabWidth(tabPlacement, i, metrics);
if (x != 0 && x + tabWidth > width) {
rows++;
x = 0;
}
x += tabWidth;
}
total = calculateTabAreaHeight(tabPlacement, rows, maxTabHeight);
}
return total;
}
protected int preferredTabAreaWidth(int tabPlacement, int height) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int columns = 1;
int y = 0;
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabHeight = calculateTabHeight(tabPlacement, i, metrics);
if (y != 0 && y + tabHeight > height) {
columns++;
y = 0;
}
y += tabHeight;
}
total = calculateTabAreaWidth(tabPlacement, columns, _maxTabWidth);
}
return total;
}
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
int cx, cy, cw, ch;
int totalTabWidth = 0;
int totalTabHeight = 0;
Insets contentInsets = getContentBorderInsets(tabPlacement);
Component selectedComponent = _tabPane.getComponentAt(selectedIndex);
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + totalTabWidth + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case RIGHT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case BOTTOM:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case TOP:
default:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + totalTabHeight + contentInsets.top;
}
cw = bounds.width - totalTabWidth -
insets.left - insets.right -
contentInsets.left - contentInsets.right;
ch = bounds.height - totalTabHeight -
insets.top - insets.bottom -
contentInsets.top - contentInsets.bottom;
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
child.setBounds(cx, cy, cw, ch);
}
}
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
public void calculateLayoutInfo() {
int tabCount = _tabPane.getTabCount();
assureRectsCreated(tabCount);
calculateTabRects(_tabPane.getTabPlacement(), tabCount);
}
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int selectedIndex = _tabPane.getSelectedIndex();
int tabRunOverlay;
int i, j;
int x, y;
int returnAt;
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
//
// Calculate bounds within which a tab run must fit
//
switch (tabPlacement) {
case LEFT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = size.width - insets.right - tabAreaInsets.right - _maxTabWidth;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case BOTTOM:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = size.height - insets.bottom - tabAreaInsets.bottom - _maxTabHeight;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
}
tabRunOverlay = getTabRunOverlay(tabPlacement);
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
// Run through tabs and partition them into runs
Rectangle rect;
for (i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabWidth = 0;
rect.x = x;
}
rect.width = calculateTabWidth(tabPlacement, i, metrics);
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
// Never move a TAB down a run if it is in the first column.
// Even if there isn't enough room, moving it to a fresh
// line won't help.
if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.x = x;
}
// Initialize y position in case there's just one run
rect.y = y;
rect.height = _maxTabHeight/* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabHeight = 0;
rect.y = y;
}
rect.height = calculateTabHeight(tabPlacement, i, metrics);
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
// Never move a TAB over a run if it is in the first run.
// Even if there isn't enough room, moving it to a fresh
// column won't help.
if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.y = y;
}
// Initialize x position in case there's just one column
rect.x = x;
rect.width = _maxTabWidth/* - 2 */;
}
if (i == selectedIndex) {
_selectedRun = _runCount - 1;
}
}
if (_runCount > 1) {
// Re-distribute tabs in case last run has leftover space
normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns ? y : x, returnAt);
_selectedRun = getRunForTab(tabCount, selectedIndex);
// Rotate run array so that selected run is first
if (shouldRotateTabRuns(tabPlacement)) {
rotateTabRuns(tabPlacement, _selectedRun);
}
}
// Step through runs from back to front to calculate
// tab y locations and to pad runs appropriately
for (i = _runCount - 1; i >= 0; i--) {
int start = _tabRuns[i];
int next = _tabRuns[i == (_runCount - 1) ? 0 : i + 1];
int end = (next != 0 ? next - 1 : tabCount - 1);
if (!verticalTabRuns) {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.y = y;
rect.x += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == BOTTOM) {
y -= (_maxTabHeight - tabRunOverlay);
}
else {
y += (_maxTabHeight - tabRunOverlay);
}
}
else {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.x = x;
rect.y += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == RIGHT) {
x -= (_maxTabWidth - tabRunOverlay);
}
else {
x += (_maxTabWidth - tabRunOverlay);
}
}
}
// Pad the selected tab so that it appears raised in front
padSelectedTab(tabPlacement, selectedIndex);
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right);
for (i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width;
}
}
}
/*
* Rotates the run-index array so that the selected run is run[0]
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void rotateTabRuns(int tabPlacement, int selectedRun) {
for (int i = 0; i < selectedRun; i++) {
int save = _tabRuns[0];
for (int j = 1; j < _runCount; j++) {
_tabRuns[j - 1] = _tabRuns[j];
}
_tabRuns[_runCount - 1] = save;
}
}
protected void normalizeTabRuns(int tabPlacement, int tabCount,
int start, int max) {
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
int run = _runCount - 1;
boolean keepAdjusting = true;
double weight = 1.25;
// At this point the tab runs are packed to fit as many
// tabs as possible, which can leave the last run with a lot
// of extra space (resulting in very fat tabs on the last run).
// So we'll attempt to distribute this extra space more evenly
// across the runs in order to make the runs look more consistent.
//
// Starting with the last run, determine whether the last tab in
// the previous run would fit (generously) in this run; if so,
// move tab to current run and shift tabs accordingly. Cycle
// through remaining runs using the same algorithm.
//
while (keepAdjusting) {
int last = lastTabInRun(tabCount, run);
int prevLast = lastTabInRun(tabCount, run - 1);
int end;
int prevLastLen;
if (!verticalTabRuns) {
end = _rects[last].x + _rects[last].width;
prevLastLen = (int) (_maxTabWidth * weight);
}
else {
end = _rects[last].y + _rects[last].height;
prevLastLen = (int) (_maxTabHeight * weight * 2);
}
// Check if the run has enough extra space to fit the last tab
// from the previous row...
if (max - end > prevLastLen) {
// Insert tab from previous row and shift rest over
_tabRuns[run] = prevLast;
if (!verticalTabRuns) {
_rects[prevLast].x = start;
}
else {
_rects[prevLast].y = start;
}
for (int i = prevLast + 1; i <= last; i++) {
if (!verticalTabRuns) {
_rects[i].x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_rects[i].y = _rects[i - 1].y + _rects[i - 1].height;
}
}
}
else if (run == _runCount - 1) {
// no more room left in last run, so we're done!
keepAdjusting = false;
}
if (run - 1 > 0) {
// check previous run next...
run -= 1;
}
else {
// check last run again...but require a higher ratio
// of extraspace-to-tabsize because we don't want to
// end up with too many tabs on the last run!
run = _runCount - 1;
weight += .25;
}
}
}
protected void padTabRun(int tabPlacement, int start, int end, int max) {
Rectangle lastRect = _rects[end];
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int runWidth = (lastRect.x + lastRect.width) - _rects[start].x;
int deltaWidth = max - (lastRect.x + lastRect.width);
float factor = (float) deltaWidth / (float) runWidth;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.x = _rects[j - 1].x + _rects[j - 1].width;
}
pastRect.width += Math.round((float) pastRect.width * factor);
}
lastRect.width = max - lastRect.x;
}
else {
int runHeight = (lastRect.y + lastRect.height) - _rects[start].y;
int deltaHeight = max - (lastRect.y + lastRect.height);
float factor = (float) deltaHeight / (float) runHeight;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.y = _rects[j - 1].y + _rects[j - 1].height;
}
pastRect.height += Math.round((float) pastRect.height * factor);
}
lastRect.height = max - lastRect.y;
}
}
protected void padSelectedTab(int tabPlacement, int selectedIndex) {
if (selectedIndex >= 0) {
Rectangle selRect = _rects[selectedIndex];
Insets padInsets = getSelectedTabPadInsets(tabPlacement);
selRect.x -= padInsets.left;
selRect.width += (padInsets.left + padInsets.right);
selRect.y -= padInsets.top;
selRect.height += (padInsets.top + padInsets.bottom);
}
}
}
protected TabSpaceAllocator tryTabSpacer = new TabSpaceAllocator();
protected class TabbedPaneScrollLayout extends TabbedPaneLayout {
@Override
protected int preferredTabAreaHeight(int tabPlacement, int width) {
return calculateMaxTabHeight(tabPlacement);
}
@Override
protected int preferredTabAreaWidth(int tabPlacement, int height) {
return calculateMaxTabWidth(tabPlacement);
}
@Override
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
JViewport viewport = null;
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
int tx, ty, tw, th; // tab area bounds
int cx, cy, cw, ch; // content area bounds
Insets contentInsets = getContentBorderInsets(tabPlacement);
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = insets.left;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
}
}
// calculate content area bounds
cx = tx + tw + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case RIGHT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount,
_maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = bounds.width - insets.right - tw;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
tx = bounds.width - insets.right - tw;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
tx = bounds.width - insets.right - tw;
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case BOTTOM:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = bounds.height - insets.bottom - th;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
break;
case TOP:
default:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = insets.top;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + th + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
}
// if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (tw < _rects[0].width + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
// else {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (th < _rects[0].height + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
if (child instanceof ScrollableTabViewport) {
viewport = (JViewport) child;
// Rectangle viewRect = viewport.getViewRect();
int vw = tw;
int vh = th;
int numberOfButtons = getNumberOfTabButtons();
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (totalTabHeight > th || isShowTabButtons()) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
// if (totalTabHeight - viewRect.y <= vh) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vh = totalTabHeight - viewRect.y;
// }
}
else {
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
}
if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) {
vh += getLayoutSize();
}
break;
case BOTTOM:
case TOP:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (isShowTabButtons() || !widthEnough) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Need to allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
// if (totalTabWidth - viewRect.x <= vw) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vw = totalTabWidth - viewRect.x;
// }
}
else {
// Allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
}
if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) {
vw += getLayoutSize();
if (!leftToRight) {
tx -= getLayoutSize();
}
}
break;
}
child.setBounds(tx, ty, vw, vh);
}
else if (child instanceof TabCloseButton) {
TabCloseButton scrollbutton = (TabCloseButton) child;
if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) {
Dimension bsize = scrollbutton.getPreferredSize();
int bx = 0;
int by = 0;
int bw = bsize.width;
int bh = bsize.height;
boolean visible = false;
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) {
int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
}
bx = tx + 2;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
bx = tx + 2;
}
}
if (isTabTrailingComponentVisible()) {
by = by - tsize.height;
}
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.width >= _rects[0].width) {
if (tabPlacement == LEFT) {
bx += lsize.width - _rects[0].width;
temp = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.width >= _rects[0].width
&& temp < tsize.width) {
if (tabPlacement == LEFT) {
bx += tsize.width - _rects[0].width;
}
}
}
break;
case TOP:
case BOTTOM:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (_tabPane.isTabShown() && (isShowTabButtons() || !widthEnough)) {
int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON
// NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
bx = insets.left - 5;
}
}
else {
visible = false;
bx = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (1 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
}
by = ((th - bsize.height) >> 1) + ty;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
visible = false;
bx = 0;
}
by = ((th - bsize.height) >> 1) + ty;
}
}
if (isTabTrailingComponentVisible()) {
bx -= tsize.width;
}
temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.height >= _rects[0].height) {
if (tabPlacement == TOP) {
by = ty + 2 + lsize.height - _rects[0].height;
temp = lsize.height;
}
else {
by = ty + 2;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.height >= _rects[0].height
&& temp < tsize.height) {
if (tabPlacement == TOP) {
by = ty + 2 + tsize.height - _rects[0].height;
}
else {
by = ty + 2;
}
}
}
}
child.setVisible(visible);
if (visible) {
child.setBounds(bx, by, bw, bh);
}
}
else {
scrollbutton.setBounds(0, 0, 0, 0);
}
}
else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) {
if (_tabPane.isShowTabContent()) {
// All content children...
child.setBounds(cx, cy, cw, ch);
}
else {
child.setBounds(0, 0, 0, 0);
}
}
}
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
}
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
if (!leftToRight && !verticalTabRuns && viewport != null && !viewport.getSize().equals(_tabPane.getSize())) {
int offset = _tabPane.getWidth() - viewport.getWidth();
for (Rectangle rect : _rects) {
rect.x -= offset;
}
}
updateCloseButtons();
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
@Override
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
int x = tabAreaInsets.left;
int y = tabAreaInsets.top;
//
// Calculate bounds within which a tab run must fit
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < lsize.width) {
_maxTabWidth = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < tsize.width) {
_maxTabWidth = tsize.width;
}
}
}
break;
case BOTTOM:
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < lsize.height) {
_maxTabHeight = lsize.height;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < tsize.height) {
_maxTabHeight = tsize.height;
}
}
}
}
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
_selectedRun = 0;
_runCount = 1;
// Run through tabs and lay them out in a single run
Rectangle rect;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_maxTabWidth = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.x = x + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.x = x;
}
}
rect.width = calculateTabWidth(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
rect.y = y;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < lsize.height) {
rect.y = y + lsize.height - _maxTabHeight - 2;
temp = lsize.height;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < tsize.height
&& temp < tsize.height) {
rect.y = y + tsize.height - _maxTabHeight - 2;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
rect.height = calculateMaxTabHeight(tabPlacement);///* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_maxTabHeight = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.y = y + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.y = y;
}
}
rect.height = calculateTabHeight(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
rect.x = x;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < lsize.width) {
rect.x = x + lsize.width - _maxTabWidth - 2;
temp = lsize.width;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < tsize.width
&& temp < tsize.width) {
rect.x = x + tsize.width - _maxTabWidth - 2;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
rect.width = calculateMaxTabWidth(tabPlacement)/* - 2 */;
}
}
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right) - _tabScroller.viewport.getLocation().x;
if (isTabLeadingComponentVisible()) {
rightMargin -= lsize.width;
}
int offset = 0;
if (isTabTrailingComponentVisible()) {
offset += tsize.width;
}
for (int i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width - offset + tabAreaInsets.left;
// if(i == tabCount - 1) {
// _rects[i].width += getLeftMargin();
// _rects[i].x -= getLeftMargin();
// }
}
}
ensureCurrentRects(getLeftMargin(), tabCount);
}
}
protected void ensureCurrentRects(int leftMargin, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
int totalWidth = 0;
int totalHeight = 0;
boolean verticalTabRuns = (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT);
boolean ltr = _tabPane.getComponentOrientation().isLeftToRight();
if (tabCount == 0) {
return;
}
Rectangle r = _rects[tabCount - 1];
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (verticalTabRuns) {
totalHeight = r.y + r.height;
if (_tabLeadingComponent != null) {
totalHeight -= lsize.height;
}
}
else {
// totalWidth = r.x + r.width;
for (Rectangle rect : _rects) {
totalWidth += rect.width;
}
if (ltr) {
totalWidth += _rects[0].x;
}
else {
totalWidth += size.width - _rects[0].x - _rects[0].width - _tabScroller.viewport.getLocation().x;
}
if (_tabLeadingComponent != null) {
totalWidth -= lsize.width;
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {// LayOut Style is Size to Fix
if (verticalTabRuns) {
int availHeight;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom - leftMargin - getTabRightPadding();// give the first tab extra space
}
else {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom;
}
if (_tabPane.isShowCloseButton()) {
availHeight -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availHeight = availHeight - lsize.height;
}
if (isTabTrailingComponentVisible()) {
availHeight = availHeight - tsize.height;
}
int numberOfButtons = getNumberOfTabButtons();
availHeight -= _buttonSize * numberOfButtons;
if (totalHeight > availHeight) { // shrink is necessary
// calculate each tab width
int tabHeight = availHeight / tabCount;
totalHeight = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
_rects[k].height = tabHeight;
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
tabRect.y = totalHeight + leftMargin;// give the first tab extra space
}
else {
tabRect.y = totalHeight;
}
totalHeight += tabRect.height;
}
}
}
else {
int availWidth;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right - leftMargin - getTabRightPadding();
}
else {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right;
}
if (_tabPane.isShowCloseButton()) {
availWidth -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availWidth -= lsize.width;
}
if (isTabTrailingComponentVisible()) {
availWidth -= tsize.width;
}
int numberOfButtons = getNumberOfTabButtons();
availWidth -= _buttonSize * numberOfButtons;
if (totalWidth > availWidth) { // shrink is necessary
// calculate each tab width
int tabWidth = availWidth / tabCount;
int gripperWidth = _tabPane.isShowGripper() ? _gripperWidth
: 0;
if (tabWidth < _textIconGap + _fitStyleTextMinWidth
+ _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleIconMinWidth + gripperWidth) // cannot
// hold any text but can hold an icon
tabWidth = _fitStyleIconMinWidth + gripperWidth;
if (tabWidth < _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleFirstTabMargin + gripperWidth) // cannot
// hold any icon but gripper
tabWidth = _fitStyleFirstTabMargin + gripperWidth;
tryTabSpacer.reArrange(_rects, insets, availWidth);
}
totalWidth = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
if (ltr) {
tabRect.x = totalWidth + leftMargin;// give the first tab extra space when the style is not box style
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width + leftMargin;// give the first tab extra space when the style is not box style
}
}
else {
if (ltr) {
tabRect.x = totalWidth;
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width;
}
}
totalWidth += tabRect.width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIXED) {// LayOut Style is Fix
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
_rects[k].height = _fixedStyleRectSize;// + _rectSizeExtend * 2;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].height += _closeButtons[k].getPreferredSize().height;
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
_rects[k].width = _fixedStyleRectSize;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].width += _closeButtons[k].getPreferredSize().width;
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED) {// LayOut Style is Compressed
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab() && !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].height = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].height = icon.getIconHeight() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].height = _rects[k].height + _closeButtons[k].getPreferredSize().height + _compressedStyleCloseButtonMarginVertical;
}
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab()
&& !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].width = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].width = icon.getIconWidth() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].width = _rects[k].width + _closeButtons[k].getPreferredSize().width + _compressedStyleCloseButtonMarginHorizon;
}
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
totalWidth += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalWidth += lsize.width;
}
}
else {
totalHeight += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalHeight += tsize.height;
}
}
_tabScroller.tabPanel.setPreferredSize(new Dimension(totalWidth, totalHeight));
}
protected class ActivateTabAction extends AbstractAction {
int _tabIndex;
private static final long serialVersionUID = 3270152106579039554L;
public ActivateTabAction(String name, Icon icon, int tabIndex) {
super(name, icon);
_tabIndex = tabIndex;
}
public void actionPerformed(ActionEvent e) {
_tabPane.setSelectedIndex(_tabIndex);
}
}
protected ListCellRenderer getTabListCellRenderer() {
return _tabPane.getTabListCellRenderer();
}
public class ScrollableTabSupport implements ChangeListener {
public ScrollableTabViewport viewport;
public ScrollableTabPanel tabPanel;
public TabCloseButton scrollForwardButton;
public TabCloseButton scrollBackwardButton;
public TabCloseButton listButton;
public TabCloseButton closeButton;
public int leadingTabIndex;
private Point tabViewPosition = new Point(0, 0);
public JidePopup _popup;
@SuppressWarnings({"UnusedDeclaration"})
ScrollableTabSupport(int tabPlacement) {
viewport = new ScrollableTabViewport();
tabPanel = new ScrollableTabPanel();
viewport.setView(tabPanel);
viewport.addChangeListener(this);
scrollForwardButton = createNoFocusButton(TabCloseButton.EAST_BUTTON);
scrollForwardButton.setName(BUTTON_NAME_SCROLL_FORWARD);
scrollBackwardButton = createNoFocusButton(TabCloseButton.WEST_BUTTON);
scrollBackwardButton.setName(BUTTON_NAME_SCROLL_BACKWARD);
scrollForwardButton.setBackground(viewport.getBackground());
scrollBackwardButton.setBackground(viewport.getBackground());
listButton = createNoFocusButton(TabCloseButton.LIST_BUTTON);
listButton.setName(BUTTON_NAME_TAB_LIST);
listButton.setBackground(viewport.getBackground());
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName(BUTTON_NAME_CLOSE);
closeButton.setBackground(viewport.getBackground());
}
public void createPopupMenu(int tabPlacement) {
JPopupMenu popup = new JPopupMenu();
int totalCount = _tabPane.getTabCount();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
for (int i = 0; i < totalCount; i++) {
if (_tabPane.isEnabledAt(i)) {
JMenuItem item;
popup.add(item = new JCheckBoxMenuItem(new ActivateTabAction(_tabPane.getTitleAt(i), _tabPane.getIconForTab(i), i)));
item.setToolTipText(_tabPane.getToolTipTextAt(i));
item.setSelected(selectedIndex == i);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
}
}
Dimension preferredSize = popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
switch (tabPlacement) {
case TOP:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y + bounds.height);
break;
case BOTTOM:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y - preferredSize.height);
break;
case LEFT:
popup.show(_tabPane, bounds.x + bounds.width, bounds.y + bounds.height - preferredSize.height);
break;
case RIGHT:
popup.show(_tabPane, bounds.x - preferredSize.width, bounds.y + bounds.height - preferredSize.height);
break;
}
}
public void createPopup(int tabPlacement) {
final JList list = new JList() {
// override this method to disallow deselect by ctrl-click
@Override
public void removeSelectionInterval(int index0, int index1) {
super.removeSelectionInterval(index0, index1);
if (getSelectedIndex() == -1) {
setSelectedIndex(index0);
}
}
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension preferredScrollableViewportSize = super.getPreferredScrollableViewportSize();
if (preferredScrollableViewportSize.width < 150) {
preferredScrollableViewportSize.width = 150;
}
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredScrollableViewportSize.width >= screenWidth) {
preferredScrollableViewportSize.width = screenWidth;
}
return preferredScrollableViewportSize;
}
@Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredSize.width >= screenWidth) {
preferredSize.width = screenWidth;
}
return preferredSize;
}
};
new Sticky(list);
list.setBackground(_tabListBackground);
JScrollPane scroller = new JScrollPane(list);
scroller.setBorder(BorderFactory.createEmptyBorder());
scroller.getViewport().setOpaque(false);
scroller.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(_tabListBackground);
panel.setOpaque(true);
panel.add(scroller);
panel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
if (_popup != null) {
if (_popup.isPopupVisible()) {
_popup.hidePopupImmediately();
}
_popup = null;
}
_popup = com.jidesoft.popup.JidePopupFactory.getSharedInstance().createPopup();
_popup.setPopupBorder(BorderFactory.createLineBorder(_darkShadow));
_popup.add(panel);
_popup.addExcludedComponent(listButton);
_popup.setDefaultFocusComponent(list);
DefaultListModel listModel = new DefaultListModel();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
int totalCount = _tabPane.getTabCount();
for (int i = 0; i < totalCount; i++) {
listModel.addElement(_tabPane);
}
list.setCellRenderer(getTabListCellRenderer());
list.setModel(listModel);
list.setSelectedIndex(selectedIndex);
list.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
componentSelected(list);
}
}
public void keyReleased(KeyEvent e) {
}
});
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
componentSelected(list);
}
});
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Insets insets = panel.getInsets();
int max = (PortingUtils.getLocalScreenSize(_tabPane).height - insets.top - insets.bottom) / list.getCellBounds(0, 0).height;
if (listModel.getSize() > max) {
list.setVisibleRowCount(max);
}
else {
list.setVisibleRowCount(listModel.getSize());
}
_popup.setOwner(_tabPane);
_popup.removeExcludedComponent(_tabPane);
Dimension size = _popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
Point p = listButton.getLocationOnScreen();
bounds.x = p.x;
bounds.y = p.y;
int x;
int y;
switch (tabPlacement) {
case TOP:
default:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y + bounds.height + 2;
break;
case BOTTOM:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y - size.height - 2;
break;
case LEFT:
x = bounds.x + bounds.width + 2;
y = bounds.y + bounds.height - size.height;
break;
case RIGHT:
x = bounds.x - size.width - 2;
y = bounds.y + bounds.height - size.height;
break;
}
Rectangle screenBounds = PortingUtils.getScreenBounds(_tabPane);
int right = x + size.width + 3;
int bottom = y + size.height + 3;
if (right > screenBounds.x + screenBounds.width) {
x -= right - screenBounds.x - screenBounds.width; // move left so that the whole popup can fit in
}
if (x < screenBounds.x) {
x = screenBounds.x; // move right so that the whole popup can fit in
}
if (bottom > screenBounds.height) {
y -= bottom - screenBounds.height;
}
if (y < screenBounds.y) {
y = screenBounds.y;
}
_popup.showPopup(x, y);
}
private void componentSelected(JList list) {
int tabIndex = list.getSelectedIndex();
if (tabIndex != -1 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
Runnable runnable = new Runnable() {
public void run() {
_tabPane.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
Runnable runnable = new Runnable() {
public void run() {
if (lastFocused != null) {
lastFocused.requestFocus();
}
else if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocus();
}
}
};
SwingUtilities.invokeLater(runnable);
}
});
}
else {
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
Runnable runnable = new Runnable() {
public void run() {
lastFocused.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
else {
Container container;
if (comp instanceof Container) {
container = (Container) comp;
}
else {
container = comp.getFocusCycleRootAncestor();
}
FocusTraversalPolicy traversalPolicy = container.getFocusTraversalPolicy();
Component focusComponent;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(container);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(container);
}
}
else if (comp instanceof Container) {
// not sure if it is correct
focusComponent = findFocusableComponent((Container) comp);
}
else {
focusComponent = comp;
}
if (focusComponent != null) {
final Component theComponent = focusComponent;
Runnable runnable = new Runnable() {
public void run() {
theComponent.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
}
}
ensureActiveTabIsVisible(false);
_popup.hidePopupImmediately();
_popup = null;
}
}
private Component findFocusableComponent(Container parent) {
FocusTraversalPolicy traversalPolicy = parent.getFocusTraversalPolicy();
Component focusComponent = null;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(parent);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(parent);
}
}
if (focusComponent != null) {
return focusComponent;
}
int i = 0;
while (i < parent.getComponentCount()) {
Component comp = parent.getComponent(i);
if (comp instanceof Container) {
focusComponent = findFocusableComponent((Container) comp);
if (focusComponent != null) {
return focusComponent;
}
}
else if (comp.isFocusable()) {
return comp;
}
i++;
}
if (parent.isFocusable()) {
return parent;
}
return null;
}
public void scrollForward(int tabPlacement) {
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (viewRect.width >= viewSize.width - viewRect.x) {
return; // no room left to scroll
}
}
else { // tabPlacement == LEFT || tabPlacement == RIGHT
if (viewRect.height >= viewSize.height - viewRect.y) {
return;
}
}
setLeadingTabIndex(tabPlacement, leadingTabIndex + 1);
}
public void scrollBackward(int tabPlacement) {
setLeadingTabIndex(tabPlacement, leadingTabIndex > 0 ? leadingTabIndex - 1 : 0);
}
public void setLeadingTabIndex(int tabPlacement, int index) {
// make sure the index is in range
if (index < 0 || index >= _tabPane.getTabCount()) {
return;
}
leadingTabIndex = index;
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
switch (tabPlacement) {
case TOP:
case BOTTOM:
tabViewPosition.y = 0;
if (_tabPane.getComponentOrientation().isLeftToRight()) {
tabViewPosition.x = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].x;
}
else {
tabViewPosition.x = (_rects.length <= 0 || leadingTabIndex == 0) ? 0 : _rects[0].x - _rects[leadingTabIndex].x + (_rects[0].width - _rects[leadingTabIndex].width) + 25;
}
if ((viewSize.width - tabViewPosition.x) < viewRect.width) {
tabViewPosition.x = viewSize.width - viewRect.width;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewSize.width - tabViewPosition.x,
// viewRect.height);
// System.out.println("setExtendedSize: " + extentSize);
// viewport.setExtentSize(extentSize);
}
break;
case LEFT:
case RIGHT:
tabViewPosition.x = 0;
tabViewPosition.y = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].y;
if ((viewSize.height - tabViewPosition.y) < viewRect.height) {
tabViewPosition.y = viewSize.height - viewRect.height;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewRect.width,
// viewSize.height - tabViewPosition.y);
// viewport.setExtentSize(extentSize);
}
break;
}
viewport.setViewPosition(tabViewPosition);
_tabPane.repaint();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight() && tabViewPosition.x == 0) {
// In current workaround, tabViewPosition set to 0 cannot trigger state change event
stateChanged(new ChangeEvent(viewport));
}
}
public void stateChanged(ChangeEvent e) {
if (_tabPane == null) return;
ensureCurrentLayout();
JViewport viewport = (JViewport) e.getSource();
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Rectangle vpRect = viewport.getBounds();
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
leadingTabIndex = getClosestTab(viewRect.x + viewRect.width, viewRect.y + viewRect.height);
if (leadingTabIndex < 0) {
leadingTabIndex = 0;
}
}
else {
leadingTabIndex = getClosestTab(viewRect.x, viewRect.y);
}
// If the tab isn't right aligned, adjust it.
if (leadingTabIndex < _rects.length && leadingTabIndex >= _rects.length) {
switch (tabPlacement) {
case TOP:
case BOTTOM:
if (_rects[leadingTabIndex].x < viewRect.x) {
leadingTabIndex++;
}
break;
case LEFT:
case RIGHT:
if (_rects[leadingTabIndex].y < viewRect.y) {
leadingTabIndex++;
}
break;
}
}
Insets contentInsets = getContentBorderInsets(tabPlacement);
int checkX;
switch (tabPlacement) {
case LEFT:
_tabPane.repaint(vpRect.x + vpRect.width, vpRect.y, contentInsets.left, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case RIGHT:
_tabPane.repaint(vpRect.x - contentInsets.right, vpRect.y, contentInsets.right, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case BOTTOM:
_tabPane.repaint(vpRect.x, vpRect.y - contentInsets.bottom, vpRect.width, contentInsets.bottom);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
break;
case TOP:
default:
_tabPane.repaint(vpRect.x, vpRect.y + vpRect.height, vpRect.width, contentInsets.top);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
}
if (SystemInfo.isJdk15Above()) {
_tabPane.setComponentZOrder(_tabScroller.scrollForwardButton, 0);
_tabPane.setComponentZOrder(_tabScroller.scrollBackwardButton, 0);
}
_tabScroller.scrollForwardButton.repaint();
_tabScroller.scrollBackwardButton.repaint();
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount()) {
closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex));
}
}
@Override
public String toString() {
return "viewport.viewSize=" + viewport.getViewSize() + "\n" +
"viewport.viewRectangle=" + viewport.getViewRect() + "\n" +
"leadingTabIndex=" + leadingTabIndex + "\n" +
"tabViewPosition=" + tabViewPosition;
}
}
public class ScrollableTabViewport extends JViewport implements UIResource {
int _expectViewX = 0;
boolean _protectView = false;
public ScrollableTabViewport() {
super();
setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
setOpaque(false);
setLayout(new ViewportLayout() {
private static final long serialVersionUID = -1069760662716244442L;
@Override
public void layoutContainer(Container parent) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
_protectView = true;
}
try {
super.layoutContainer(parent);
}
finally {
_protectView = false;
}
}
});
}
/**
* Gets the background color of this component.
*
* @return this component's background color; if this component does not have a background color, the background
* color of its parent is returned
*/
@Override
public Color getBackground() {
return UIDefaultsLookup.getColor("JideTabbedPane.background");
}
// workaround for swing bug
@Override
public void setViewPosition(Point p) {
int oldX = _expectViewX;
_expectViewX = p.x;
super.setViewPosition(p); // to trigger state change event, so the adjustment for RTL need to be done at ScrollableTabPanel#setBounds()
if (_protectView) {
_expectViewX = oldX;
Point savedPosition = new Point(oldX, p.y);
super.setViewPosition(savedPosition);
}
}
public int getExpectedViewX() {
return _expectViewX;
}
}
public class ScrollableTabPanel extends JPanel implements UIResource {
public ScrollableTabPanel() {
setLayout(null);
}
@Override
public boolean isOpaque() {
return false;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_tabPane.isOpaque()) {
if (getTabShape() == JideTabbedPane.SHAPE_BOX) {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"));
}
else {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground"));
}
g.fillRect(0, 0, getWidth(), getHeight());
}
paintTabArea(g, _tabPane.getTabPlacement(), _tabPane.getSelectedIndex(), this);
}
// workaround for swing bug
@Override
public void scrollRectToVisible(Rectangle aRect) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
int startX = aRect.x + _tabScroller.viewport.getExpectedViewX();
if (startX < 0) {
int i;
for (i = _tabScroller.leadingTabIndex; i < _rects.length; i++) {
startX += _rects[i].width;
if (startX >= 0) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.min(i + 1, _rects.length - 1));
}
else if (startX > aRect.x + aRect.width) {
int i;
for (i = _tabScroller.leadingTabIndex - 1; i >= 0; i--) {
startX -= _rects[i].width;
if (startX <= aRect.x + aRect.width) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.max(i, 0));
}
return;
}
super.scrollRectToVisible(aRect);
}
// workaround for swing bug
@Override
public void setBounds(int x, int y, int width, int height) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
super.setBounds(0, y, width, height);
return;
}
super.setBounds(x, y, width, height);
}
// workaround for swing bug
// http://developer.java.sun.com/developer/bugParade/bugs/4668865.html
@Override
public void setToolTipText(String text) {
_tabPane.setToolTipText(text);
}
@Override
public String getToolTipText() {
return _tabPane.getToolTipText();
}
@Override
public String getToolTipText(MouseEvent event) {
return _tabPane.getToolTipText(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public Point getToolTipLocation(MouseEvent event) {
return _tabPane.getToolTipLocation(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public JToolTip createToolTip() {
return _tabPane.createToolTip();
}
}
protected Color _closeButtonSelectedColor = new Color(255, 162, 165);
protected Color _closeButtonColor = Color.BLACK;
protected Color _popupColor = Color.BLACK;
/**
* Close button on the tab.
*/
public class TabCloseButton extends JButton implements MouseMotionListener, MouseListener, UIResource {
public static final int CLOSE_BUTTON = 0;
public static final int EAST_BUTTON = 1;
public static final int WEST_BUTTON = 2;
public static final int NORTH_BUTTON = 3;
public static final int SOUTH_BUTTON = 4;
public static final int LIST_BUTTON = 5;
private int _type;
private int _index = -1;
private boolean _mouseOver = false;
private boolean _mousePressed = false;
/**
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
@Override
public void updateUI() {
super.updateUI();
setMargin(new Insets(0, 0, 0, 0));
setBorder(BorderFactory.createEmptyBorder());
setFocusPainted(false);
setFocusable(false);
setRequestFocusEnabled(false);
String name = getName();
if (name != null) setToolTipText(getResourceString(name));
}
public TabCloseButton() {
this(CLOSE_BUTTON);
}
public TabCloseButton(int type) {
addMouseMotionListener(this);
addMouseListener(this);
setFocusPainted(false);
setFocusable(false);
setType(type);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(5, 5);
}
public int getIndex() {
return _index;
}
public void setIndex(int index) {
_index = index;
}
@Override
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
@Override
protected void paintComponent(Graphics g) {
if (!isEnabled()) {
setMouseOver(false);
setMousePressed(false);
}
if (isMouseOver() && isMousePressed()) {
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
else if (isMouseOver()) {
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
g.setColor(UIDefaultsLookup.getColor("controlShadow").darker());
int centerX = getWidth() >> 1;
int centerY = getHeight() >> 1;
int type = getType();
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
if (type == EAST_BUTTON) {
type = WEST_BUTTON;
}
else if (type == WEST_BUTTON) {
type = EAST_BUTTON;
}
}
switch (type) {
case CLOSE_BUTTON:
if (isEnabled()) {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX - 4, centerY - 3, centerX + 2, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
g.drawLine(centerX + 2, centerY - 3, centerX - 4, centerY + 3);
}
else {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
}
break;
case EAST_BUTTON:
//
// |
// ||
// |||
// ||||
// ||||*
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX + 2, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 3, y - 3, x - 3, y + 3);
g.drawLine(x - 2, y - 2, x - 2, y + 2);
g.drawLine(x - 1, y - 1, x - 1, y + 1);
g.drawLine(x, y, x, y);
}
else {
g.drawLine(x - 4, y - 4, x, y);
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
else {
int x = centerX + 3, y = centerY - 2; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 7, y + 1, x - 1, y + 1);
g.drawLine(x - 6, y + 2, x - 2, y + 2);
g.drawLine(x - 5, y + 3, x - 3, y + 3);
g.drawLine(x - 4, y + 4, x - 4, y + 4);
}
else {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 8, y, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
}
break;
case WEST_BUTTON: {
//
// |
// ||
// |||
// ||||
// *||||
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX - 3, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x, y);
g.drawLine(x + 1, y - 1, x + 1, y + 1);
g.drawLine(x + 2, y - 2, x + 2, y + 2);
g.drawLine(x + 3, y - 3, x + 3, y + 3);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
else {
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x, y, x + 4, y + 4);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
}
else {
int x = centerX - 5, y = centerY + 3; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x + 8, y);
g.drawLine(x + 1, y - 1, x + 7, y - 1);
g.drawLine(x + 2, y - 2, x + 6, y - 2);
g.drawLine(x + 3, y - 3, x + 5, y - 3);
g.drawLine(x + 4, y - 4, x + 4, y - 4);
}
else {
g.drawLine(x, y, x + 8, y);
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x + 8, y, x + 4, y - 4);
}
}
}
break;
}
case LIST_BUTTON: {
int x = centerX + 2, y = centerY; // start point. mark as
// * above
g.drawLine(x - 6, y - 4, x - 6, y + 4);
g.drawLine(x + 1, y - 4, x + 1, y + 4);
g.drawLine(x - 6, y - 4, x + 1, y - 4);
g.drawLine(x - 4, y - 2, x - 1, y - 2);
g.drawLine(x - 4, y, x - 1, y);
g.drawLine(x - 4, y + 2, x - 1, y + 2);
g.drawLine(x - 6, y + 4, x + 1, y + 4);
break;
}
}
}
@Override
public boolean isFocusable() {
return false;
}
@Override
public void requestFocus() {
}
@Override
public boolean isOpaque() {
return false;
}
public boolean scrollsForward() {
return getType() == EAST_BUTTON || getType() == SOUTH_BUTTON;
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
setMousePressed(false);
}
public void mousePressed(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(true);
repaint();
}
public void mouseReleased(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(false);
setMouseOver(false);
}
public void mouseEntered(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseExited(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(false);
setMousePressed(false);
repaint();
_tabScroller.tabPanel.repaint();
}
public int getType() {
return _type;
}
public void setType(int type) {
_type = type;
}
public boolean isMouseOver() {
return _mouseOver;
}
public void setMouseOver(boolean mouseOver) {
_mouseOver = mouseOver;
}
public boolean isMousePressed() {
return _mousePressed;
}
public void setMousePressed(boolean mousePressed) {
_mousePressed = mousePressed;
}
}
// Controller: event listeners
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class PropertyChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
String name = e.getPropertyName();
if ("mnemonicAt".equals(name)) {
updateMnemonics();
pane.repaint();
}
else if ("displayedMnemonicIndexAt".equals(name)) {
pane.repaint();
}
else if (name.equals("indexForTitle")) {
int index = (Integer) e.getNewValue();
String title = getCurrentDisplayTitleAt(_tabPane, index);
if (BasicHTML.isHTMLString(title)) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(_tabPane, title);
htmlViews.setElementAt(v, index);
}
}
else {
if (htmlViews != null && htmlViews.elementAt(index) != null) {
htmlViews.setElementAt(null, index);
}
}
updateMnemonics();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(
_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(false);
}
}
else if (name.equals("tabLayoutPolicy")) {
_tabPane.updateUI();
}
else if (name.equals("closeTabAction")) {
updateCloseAction();
}
else if (name.equals(JideTabbedPane.PROPERTY_DRAG_OVER_DISABLED)) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_COLOR_PROVIDER)) {
_tabPane.repaint();
}
else if (name.equals("locale")) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.BOLDACTIVETAB_PROPERTY)) {
getTabPanel().invalidate();
_tabPane.invalidate();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_LEADING_COMPONENT)) {
ensureCurrentLayout();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(false);
_tabPane.remove(_tabLeadingComponent);
}
_tabLeadingComponent = (Component) e.getNewValue();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(true);
_tabPane.add(_tabLeadingComponent);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_TRAILING_COMPONENT)) {
ensureCurrentLayout();
if (_tabTrailingComponent != null) {
_tabTrailingComponent.setVisible(false);
_tabPane.remove(_tabTrailingComponent);
}
_tabTrailingComponent = (Component) e.getNewValue();
if (_tabTrailingComponent != null) {
_tabPane.add(_tabTrailingComponent);
_tabTrailingComponent.setVisible(true);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.SHRINK_TAB_PROPERTY) ||
name.equals(JideTabbedPane.HIDE_IF_ONE_TAB_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_AREA_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_CONTENT_PROPERTY) ||
name.equals(JideTabbedPane.BOX_STYLE_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.TAB_CLOSABLE_PROPERTY) ||
name.equals(JideTabbedPane.PROPERTY_TAB_SHAPE) ||
name.equals(JideTabbedPane.PROPERTY_COLOR_THEME) ||
name.equals(JideTabbedPane.PROPERTY_TAB_RESIZE_MODE) ||
name.equals(JideTabbedPane.SHOW_TAB_BUTTONS_PROPERTY)) {
if ((name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY))
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
ensureCloseButtonCreated();
}
_tabPane.updateUI();
}
else if (name.equals("__index_to_remove__")) {
setVisibleComponent(null);
}
}
}
protected void updateCloseAction() {
ensureCloseButtonCreated();
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabSelectionHandler implements ChangeListener {
public void stateChanged(ChangeEvent e) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
ensureCloseButtonCreated();
Runnable runnable = new Runnable() {
public void run() {
ensureActiveTabIsVisible(false);
}
};
SwingUtilities.invokeLater(runnable);
}
}
public class TabFocusListener implements FocusListener {
public void focusGained(FocusEvent e) {
repaintSelectedTab();
}
public void focusLost(FocusEvent e) {
repaintSelectedTab();
}
private void repaintSelectedTab() {
if (_tabPane.getTabCount() > 0) {
Rectangle rect = getTabBounds(_tabPane, _tabPane.getSelectedIndex());
if (rect != null) {
_tabPane.repaint(rect);
}
}
}
}
public class MouseMotionHandler extends MouseMotionAdapter {
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class MouseHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isMiddleMouseButton(e)) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
Action action = getActionMap().get("closeTabAction");
if (action != null && tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex) && _tabPane.isCloseTabOnMouseMiddleButton() && _tabPane.isTabClosableAt(tabIndex)) {
ActionEvent event = new ActionEvent(_tabPane, tabIndex, "middleMouseButtonClicked");
action.actionPerformed(event);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isLeftMouseButton(e) || _tabPane.isRightClickSelect()) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
_tabPane.processMouseSelection(tabIndex, e);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else if (_tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
});
}
else {
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else {
// first try to find a default component.
boolean foundInTab = JideSwingUtilities.compositeRequestFocus(comp);
if (!foundInTab) { // && !_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
if (!isTabEditing())
startEditing(e); // start editing tab
}
}
public class MouseWheelHandler implements MouseWheelListener {
public void mouseWheelMoved(MouseWheelEvent e) {
if (_tabPane.isScrollSelectedTabOnWheel()) {
// set selected tab to the currently selected tab plus the wheel rotation but between
// 0 and tabCount-1
_tabPane.setSelectedIndex(
Math.min(_tabPane.getTabCount() - 1, Math.max(0, _tabPane.getSelectedIndex() + e.getWheelRotation())));
}
else if (scrollableTabLayoutEnabled() && e.getWheelRotation() != 0) {
if (e.getWheelRotation() > 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollForward(_tabPane.getTabPlacement());
}
}
else if (e.getWheelRotation() < 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollBackward(_tabPane.getTabPlacement());
}
}
}
}
}
private class ComponentHandler implements ComponentListener {
public void componentResized(ComponentEvent e) {
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
/* GES 2/3/99:
The container listener code was added to support HTML
rendering of tab titles.
Ideally, we would be able to listen for property changes
when a tab is added or its text modified. At the moment
there are no such events because the Beans spec doesn't
allow 'indexed' property changes (i.e. tab 2's text changed
from A to B).
In order to get around this, we listen for tabs to be added
or removed by listening for the container events. we then
queue up a runnable (so the component has a chance to complete
the add) which checks the tab title of the new component to see
if it requires HTML rendering.
The Views (one per tab title requiring HTML rendering) are
stored in the htmlViews Vector, which is only allocated after
the first time we run into an HTML tab. Note that this vector
is kept in step with the number of pages, and nulls are added
for those pages whose tab title do not require HTML rendering.
This makes it easy for the paint and layout code to tell
whether to invoke the HTML engine without having to check
the string during time-sensitive operations.
When we have added a way to listen for tab additions and
changes to tab text, this code should be removed and
replaced by something which uses that. */
private class ContainerHandler implements ContainerListener {
public void componentAdded(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
int index = tp.indexOfComponent(child);
String title = getCurrentDisplayTitleAt(tp, index);
boolean isHTML = BasicHTML.isHTMLString(title);
if (isHTML) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(tp, title);
htmlViews.insertElementAt(v, index);
}
}
else { // Not HTML
if (htmlViews != null) { // Add placeholder
htmlViews.insertElementAt(null, index);
} // else nada!
}
if (_tabPane.isTabEditing()) {
+ if (index <= _tabPane.getEditingTabIndex()) {
+ ((BasicJideTabbedPaneUI) _tabPane.getUI())._editingTab ++;
+ }
+ ensureCloseButtonCreated();
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
}
public void componentRemoved(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
// NOTE 4/15/2002 (joutwate):
// This fix is implemented using client properties since there is
// currently no IndexPropertyChangeEvent. Once
// IndexPropertyChangeEvents have been added this code should be
// modified to use it.
Integer index =
(Integer) tp.getClientProperty("__index_to_remove__");
if (index != null) {
if (htmlViews != null && htmlViews.size() > index) {
htmlViews.removeElementAt(index);
}
tp.putClientProperty("__index_to_remove__", null);
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
// ensureActiveTabIsVisible(true);
}
}
private Vector createHTMLVector() {
Vector htmlViews = new Vector();
int count = _tabPane.getTabCount();
if (count > 0) {
for (int i = 0; i < count; i++) {
String title = getCurrentDisplayTitleAt(_tabPane, i);
if (BasicHTML.isHTMLString(title)) {
htmlViews.addElement(BasicHTML.createHTMLView(_tabPane, title));
}
else {
htmlViews.addElement(null);
}
}
}
return htmlViews;
}
@Override
public Component getTabPanel() {
if (scrollableTabLayoutEnabled())
return _tabScroller.tabPanel;
else
return _tabPane;
}
static class AbstractTab {
int width;
int id;
public void copy(AbstractTab tab) {
this.width = tab.width;
this.id = tab.id;
}
}
public static class TabSpaceAllocator {
static final int startOffset = 4;
private Insets insets = null;
static final int tabWidth = 24;
static final int textIconGap = 8;
private AbstractTab tabs[];
private void setInsets(Insets insets) {
this.insets = (Insets) insets.clone();
}
private void init(Rectangle rects[], Insets insets) {
setInsets(insets);
tabs = new AbstractTab[rects.length];
// fill up internal datastructure
for (int i = 0; i < rects.length; i++) {
tabs[i] = new AbstractTab();
tabs[i].id = i;
tabs[i].width = rects[i].width;
}
tabSort();
}
private void bestfit(AbstractTab tabs[], int freeWidth, int startTab) {
int tabCount = tabs.length;
int worstWidth;
int currentTabWidth;
int initialPos;
currentTabWidth = tabs[startTab].width;
initialPos = startTab;
if (startTab == tabCount - 1) {
// directly fill as worst case
tabs[startTab].width = freeWidth;
return;
}
worstWidth = freeWidth / (tabCount - startTab);
while (currentTabWidth < worstWidth) {
freeWidth -= currentTabWidth;
if (++startTab < tabCount - 1) {
currentTabWidth = tabs[startTab].width;
}
else {
tabs[startTab].width = worstWidth;
return;
}
}
if (startTab == initialPos) {
// didn't find anything smaller
for (int i = startTab; i < tabCount; i++) {
tabs[i].width = worstWidth;
}
}
else if (startTab < tabCount - 1) {
bestfit(tabs, freeWidth, startTab);
}
}
// bubble sort for now
private void tabSort() {
int tabCount = tabs.length;
AbstractTab tempTab = new AbstractTab();
for (int i = 0; i < tabCount - 1; i++) {
for (int j = i + 1; j < tabCount; j++) {
if (tabs[i].width > tabs[j].width) {
tempTab.copy(tabs[j]);
tabs[j].copy(tabs[i]);
tabs[i].copy(tempTab);
}
}
}
}
// directly modify the rects
private void outpush(Rectangle rects[]) {
for (AbstractTab tab : tabs) {
rects[tab.id].width = tab.width;
}
rects[0].x = startOffset;
for (int i = 1; i < rects.length; i++) {
rects[i].x = rects[i - 1].x + rects[i - 1].width;
}
}
public void reArrange(Rectangle rects[], Insets insets, int totalAvailableSpace) {
init(rects, insets);
bestfit(tabs, totalAvailableSpace, 0);
outpush(rects);
clearup();
}
private void clearup() {
for (int i = 0; i < tabs.length; i++) {
tabs[i] = null;
}
tabs = null;
}
}
@Override
public void ensureActiveTabIsVisible(boolean scrollLeft) {
if (_tabPane == null || _tabPane.getWidth() == 0) {
return;
}
if (scrollableTabLayoutEnabled()) {
ensureCurrentLayout();
if (scrollLeft && _rects.length > 0) {
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
_tabScroller.tabPanel.scrollRectToVisible(_rects[0]);
}
else {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
}
int index = _tabPane.getSelectedIndex();
if ((!scrollLeft || index != 0) && index < _rects.length && index != -1) {
if (index == 0) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
else {
if (index == _rects.length - 1) { // last one, scroll to the end
Rectangle lastRect = _rects[index];
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && _tabPane.getComponentOrientation().isLeftToRight()) {
lastRect.width = _tabScroller.tabPanel.getWidth() - lastRect.x;
}
_tabScroller.tabPanel.scrollRectToVisible(lastRect);
}
else {
_tabScroller.tabPanel.scrollRectToVisible(_rects[index]);
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.tabPanel.getParent().doLayout();
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabPane.revalidate();
_tabPane.repaintTabAreaAndContentBorder();
}
else {
_tabPane.repaint();
}
}
}
protected boolean isShowCloseButtonOnTab() {
if (_tabPane.isUseDefaultShowCloseButtonOnTab()) {
return _showCloseButtonOnTab;
}
else return _tabPane.isShowCloseButtonOnTab();
}
protected boolean isShowCloseButton() {
return _tabPane.isShowCloseButton();
}
public void ensureCloseButtonCreated() {
if (isShowCloseButton() && isShowCloseButtonOnTab() && scrollableTabLayoutEnabled()) {
if (_closeButtons == null) {
_closeButtons = new TabCloseButton[_tabPane.getTabCount()];
}
else if (_closeButtons.length > _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0, temp.length);
for (int i = temp.length; i < _closeButtons.length; i++) {
TabCloseButton tabCloseButton = _closeButtons[i];
_tabScroller.tabPanel.remove(tabCloseButton);
}
_closeButtons = temp;
}
else if (_closeButtons.length < _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0,
_closeButtons.length);
_closeButtons = temp;
}
ActionMap am = getActionMap();
for (int i = 0; i < _closeButtons.length; i++) {
TabCloseButton closeButton = _closeButtons[i];
if (closeButton == null) {
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName("JideTabbedPane.close");
_closeButtons[i] = closeButton;
closeButton.setBounds(0, 0, 0, 0);
Action action = _tabPane.getCloseAction();
closeButton.setAction(am.get("closeTabAction"));
updateButtonFromAction(closeButton, action);
_tabScroller.tabPanel.add(closeButton);
}
closeButton.setIndex(i);
}
}
}
private void updateButtonFromAction(TabCloseButton closeButton, Action action) {
if (action == null) {
return;
}
closeButton.setEnabled(action.isEnabled());
Object desc = action.getValue(Action.SHORT_DESCRIPTION);
if (desc instanceof String) {
closeButton.setToolTipText((String) desc);
}
Object icon = action.getValue(Action.SMALL_ICON);
if (icon instanceof Icon) {
closeButton.setIcon((Icon) icon);
}
}
protected boolean isShowTabButtons() {
return _tabPane.getTabCount() != 0 && _tabPane.isShowTabArea() && _tabPane.isShowTabButtons();
}
protected boolean isShrinkTabs() {
return _tabPane.getTabCount() != 0 && _tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT;
}
protected TabEditor _tabEditor;
protected boolean _isEditing;
protected int _editingTab = -1;
protected String _oldValue;
protected String _oldPrefix;
protected String _oldPostfix;
// mtf - changed
protected Component _originalFocusComponent;
@Override
public boolean isTabEditing() {
return _isEditing;
}
protected TabEditor createDefaultTabEditor() {
final TabEditor editor = new TabEditor();
editor.getDocument().addDocumentListener(this);
editor.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
return true;
}
public boolean shouldYieldFocus(JComponent input) {
boolean shouldStopEditing = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
shouldStopEditing = _tabPane.getTabEditingValidator().alertIfInvalid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (shouldStopEditing && _tabPane != null && _tabPane.isTabEditing()) {
_tabPane.stopTabEditing();
}
return shouldStopEditing;
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_originalFocusComponent = e.getOppositeComponent();
}
@Override
public void focusLost(FocusEvent e) {
}
});
editor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editor.transferFocus();
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (_isEditing && (e.getKeyCode() == KeyEvent.VK_ESCAPE)) {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldValue);
}
_tabPane.cancelTabEditing();
}
}
});
editor.setFont(_tabPane.getFont());
return editor;
}
@Override
public void stopTabEditing() {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
cancelTabEditing();
}
@Override
public void cancelTabEditing() {
if (_tabEditor != null) {
_isEditing = false;
((Container) getTabPanel()).remove(_tabEditor);
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
Rectangle tabRect = _tabPane.getBoundsAt(_editingTab);
getTabPanel().repaint(tabRect.x, tabRect.y,
tabRect.width, tabRect.height);
}
else {
getTabPanel().repaint();
}
if (_originalFocusComponent != null)
_originalFocusComponent.requestFocus(); // InWindow();
else
_tabPane.requestFocusForVisibleComponent();
_editingTab = -1;
_oldValue = null;
_tabPane.doLayout();
}
}
@Override
public boolean editTabAt(int tabIndex) {
if (_isEditing) {
return false;
}
// _tabPane.popupSelectedIndex(tabIndex);
if (_tabEditor == null)
_tabEditor = createDefaultTabEditor();
if (_tabEditor != null) {
prepareEditor(_tabEditor, tabIndex);
((Container) getTabPanel()).add(_tabEditor);
resizeEditor(tabIndex);
_editingTab = tabIndex;
_isEditing = true;
_tabEditor.requestFocusInWindow();
_tabEditor.selectAll();
return true;
}
return false;
}
@Override
public int getEditingTabIndex() {
return _editingTab;
}
protected void prepareEditor(TabEditor e, int tabIndex) {
Font font;
if (_tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (_tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
e.setFont(font);
_oldValue = _tabPane.getTitleAt(tabIndex);
if (_oldValue.startsWith("<HTML>") && _oldValue.endsWith("/HTML>")) {
_oldPrefix = "<HTML>";
_oldPostfix = "</HTML>";
String title = _oldValue.substring("<HTML>".length(), _oldValue.length() - "</HTML>".length());
if (title.startsWith("<B>") && title.endsWith("/B>")) {
title = title.substring("<B>".length(), title.length() - "</B>".length());
_oldPrefix += "<B>";
_oldPostfix = "</B>" + _oldPostfix;
}
e.setText(title);
}
else {
_oldPrefix = "";
_oldPostfix = "";
e.setText(_oldValue);
}
e.selectAll();
e.setForeground(_tabPane.getForegroundAt(tabIndex));
}
protected Rectangle getTabsTextBoundsAt(int tabIndex) {
Rectangle tabRect = _tabPane.getBoundsAt(tabIndex);
Rectangle iconRect = new Rectangle(),
textRect = new Rectangle();
if (tabRect.width < 200) // random max size;
tabRect.width = 200;
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
while (title == null || title.length() < 3)
title += " ";
Icon icon = _tabPane.getIconForTab(tabIndex);
Font font = _tabPane.getFont();
if (tabIndex == _tabPane.getSelectedIndex() && _tabPane.isBoldActiveTab()) {
font = font.deriveFont(Font.BOLD);
}
SwingUtilities.layoutCompoundLabel(_tabPane, _tabPane.getGraphics().getFontMetrics(font), title, icon,
SwingUtilities.CENTER, SwingUtilities.CENTER,
SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect,
iconRect, textRect, icon == null ? 0 : _textIconGap);
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
iconRect.x = tabRect.x + _iconMargin;
textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding);
textRect.width += 2;
}
else {
iconRect.y = tabRect.y + _iconMargin;
textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding);
iconRect.x = tabRect.x + 2;
textRect.x = tabRect.x + 2;
textRect.height += 2;
}
return textRect;
}
private void updateTab() {
if (_isEditing) {
resizeEditor(getEditingTabIndex());
}
}
public void insertUpdate(DocumentEvent e) {
updateTab();
}
public void removeUpdate(DocumentEvent e) {
updateTab();
}
public void changedUpdate(DocumentEvent e) {
updateTab();
}
protected void resizeEditor(int tabIndex) {
// note - this should use the logic of label paint text so that the text overlays exactly.
Rectangle tabsTextBoundsAt = getTabsTextBoundsAt(tabIndex);
if (tabsTextBoundsAt.isEmpty()) {
tabsTextBoundsAt = new Rectangle(14, 3); // note - 14 should be the font height but...
}
tabsTextBoundsAt.x = tabsTextBoundsAt.x - _tabEditor.getBorder().getBorderInsets(_tabEditor).left;
tabsTextBoundsAt.width = +tabsTextBoundsAt.width +
_tabEditor.getBorder().getBorderInsets(_tabEditor).left +
_tabEditor.getBorder().getBorderInsets(_tabEditor).right;
tabsTextBoundsAt.y = tabsTextBoundsAt.y - _tabEditor.getBorder().getBorderInsets(_tabEditor).top;
tabsTextBoundsAt.height = tabsTextBoundsAt.height +
_tabEditor.getBorder().getBorderInsets(_tabEditor).top +
_tabEditor.getBorder().getBorderInsets(_tabEditor).bottom;
_tabEditor.setBounds(SwingUtilities.convertRectangle(_tabPane, tabsTextBoundsAt, getTabPanel()));
_tabEditor.invalidate();
_tabEditor.validate();
// getTabPanel().invalidate();
// getTabPanel().validate();
// getTabPanel().repaint();
// getTabPanel().doLayout();
_tabPane.doLayout();
// mtf - note - this is an exteme repaint but we need to paint any content borders
getTabPanel().getParent().getParent().repaint();
}
protected String getCurrentDisplayTitleAt(JideTabbedPane tp, int index) {
String returnTitle = tp.getDisplayTitleAt(index);
if ((_isEditing) && (index == _editingTab))
returnTitle = _tabEditor.getText();
return returnTitle;
}
protected class TabEditor extends JTextField implements UIResource {
TabEditor() {
setOpaque(false);
// setBorder(BorderFactory.createEmptyBorder());
setBorder(BorderFactory
.createCompoundBorder(new PartialLineBorder(Color.BLACK, 1, true),
BorderFactory.createEmptyBorder(0, 2, 0, 2)));
}
public boolean stopEditing() {
return true;
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Composite orgComposite = g2.getComposite();
Color orgColor = g2.getColor();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.70f));
Object o = JideSwingUtilities.setupShapeAntialiasing(g);
g2.setColor(getBackground());
g.fillRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 1, 1);
JideSwingUtilities.restoreShapeAntialiasing(g, o);
g2.setColor(orgColor);
g2.setComposite(orgComposite);
super.paintComponent(g);
}
}
public void startEditing(MouseEvent e) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (!e.isPopupTrigger() && tabIndex >= 0
&& _tabPane.isEnabledAt(tabIndex)
&& _tabPane.isTabEditingAllowed() && (e.getClickCount() == 2)) {
boolean shouldEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldEdit = _tabPane.getTabEditingValidator().shouldStartEdit(tabIndex, e);
if (shouldEdit) {
e.consume();
_tabPane.editTabAt(tabIndex);
}
}
if (e.getClickCount() == 1) {
if (_tabPane.isTabEditing()) {
boolean shouldStopEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldStopEdit = _tabPane.getTabEditingValidator().alertIfInvalid(tabIndex, _oldPrefix + _tabEditor.getText() + _oldPostfix);
if (shouldStopEdit)
_tabPane.stopTabEditing();
}
}
}
public ThemePainter getPainter() {
return _painter;
}
private class DragOverTimer extends Timer implements ActionListener {
private int _index;
private static final long serialVersionUID = -2529347876574638854L;
public DragOverTimer(int index) {
super(500, null);
_index = index;
addActionListener(this);
setRepeats(false);
}
public void actionPerformed(ActionEvent e) {
if (_tabPane.getTabCount() == 0) {
return;
}
if (_index == _tabPane.getSelectedIndex()) {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
_tabPane.repaint(getTabBounds(_tabPane, _index));
}
}
else {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
}
_tabPane.setSelectedIndex(_index);
}
stop();
}
}
private class DropListener implements DropTargetListener {
private DragOverTimer _timer;
int _index = -1;
public DropListener() {
}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
if (!_tabPane.isEnabled()) {
return;
}
int tabIndex = getTabAtLocation(dtde.getLocation().x, dtde.getLocation().y);
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex()) {
// selected already, do nothing
}
else if (tabIndex == _index) {
// same tab, timer has started
}
else {
stopTimer();
startTimer(tabIndex);
_index = tabIndex; // save the index
}
}
else {
stopTimer();
}
dtde.rejectDrag();
}
private void startTimer(int tabIndex) {
_timer = new DragOverTimer(tabIndex);
_timer.start();
}
private void stopTimer() {
if (_timer != null) {
_timer.stop();
_timer = null;
_index = -1;
}
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dte) {
stopTimer();
}
public void drop(DropTargetDropEvent dtde) {
stopTimer();
}
}
protected void paintFocusIndicator(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect,
boolean isSelected) {
Rectangle tabRect = new Rectangle(rects[tabIndex]);
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
tabRect.x += _tabScroller.viewport.getExpectedViewX();
}
if (_tabPane.hasFocus() && isSelected) {
int x, y, w, h;
g.setColor(_focus);
switch (tabPlacement) {
case LEFT:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case RIGHT:
x = tabRect.x + 2;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case BOTTOM:
x = tabRect.x + 3;
y = tabRect.y + 2;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
break;
case TOP:
default:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
}
BasicGraphicsUtils.drawDashedRect(g, x, y, w, h);
}
}
protected boolean isRoundedCorner() {
return "true".equals(SecurityUtils.getProperty("shadingtheme", "false"));
}
protected int getTabShape() {
return _tabPane.getTabShape();
}
protected int getTabResizeMode() {
return _tabPane.getTabResizeMode();
}
protected int getColorTheme() {
return _tabPane.getColorTheme();
}
// for debug purpose
final protected boolean PAINT_TAB = true;
final protected boolean PAINT_TAB_BORDER = true;
final protected boolean PAINT_TAB_BACKGROUND = true;
final protected boolean PAINT_TABAREA = true;
final protected boolean PAINT_CONTENT_BORDER = true;
final protected boolean PAINT_CONTENT_BORDER_EDGE = true;
protected int getLeftMargin() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return OFFICE2003_LEFT_MARGIN;
}
else if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else {
return DEFAULT_LEFT_MARGIN;
}
}
protected int getTabGap() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return 4;
}
else {
return 0;
}
}
protected int getLayoutSize() {
int tabShape = getTabShape();
if (tabShape == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else if (tabShape == JideTabbedPane.SHAPE_ECLIPSE3X) {
return 15;
}
else if (_tabPane.getTabShape() == JideTabbedPane.SHAPE_FLAT || _tabPane.getTabShape() == JideTabbedPane.SHAPE_ROUNDED_FLAT) {
return 2;
}
else if (tabShape == JideTabbedPane.SHAPE_WINDOWS
|| tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return 6;
}
else {
return 0;
}
}
protected int getTabRightPadding() {
if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return 4;
}
else {
return 0;
}
}
protected MouseListener createMouseListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseHandler();
}
else {
return new MouseHandler();
}
}
protected MouseWheelListener createMouseWheelListener() {
return new MouseWheelHandler();
}
protected MouseMotionListener createMouseMotionListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseMotionHandler();
}
else {
return new MouseMotionHandler();
}
}
public class DefaultMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class DefaultMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
}
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
public class RolloverMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class RolloverMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
protected boolean isTabLeadingComponentVisible() {
return _tabPane.isTabShown() && _tabLeadingComponent != null && _tabLeadingComponent.isVisible();
}
protected boolean isTabTrailingComponentVisible() {
return _tabPane.isTabShown() && _tabTrailingComponent != null && _tabTrailingComponent.isVisible();
}
protected boolean isTabTopVisible(int tabPlacement) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement));
case TOP:
case BOTTOM:
default:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement));
}
}
protected boolean showFocusIndicator() {
return _tabPane.hasFocusComponent() && _showFocusIndicator;
}
private int getNumberOfTabButtons() {
int numberOfButtons = (!isShowTabButtons() || isShrinkTabs()) ? 1 : 4;
if (!isShowCloseButton() || isShowCloseButtonOnTab()) {
numberOfButtons--;
}
return numberOfButtons;
}
/**
* Gets the resource string used in DocumentPane. Subclass can override it to provide their own strings.
*
* @param key the resource key
* @return the localized string.
*/
protected String getResourceString(String key) {
return Resource.getResourceBundle(_tabPane != null ? _tabPane.getLocale() : Locale.getDefault()).getString(key);
}
}
| true | true | protected boolean requestFocusForVisibleComponent() {
Component visibleComponent = getVisibleComponent();
Component lastFocused = _tabPane.getLastFocusedComponent(visibleComponent);
if (lastFocused != null && lastFocused.requestFocusInWindow()) {
return true;
}
else if (visibleComponent != null && JideSwingUtilities.passesFocusabilityTest(visibleComponent)) { // visibleComponent.isFocusTraversable()) {
JideSwingUtilities.compositeRequestFocus(visibleComponent);
return true;
}
else if (visibleComponent instanceof JComponent) {
if (((JComponent) visibleComponent).requestDefaultFocus()) {
return true;
}
}
return false;
}
private static class RightAction extends AbstractAction {
private static final long serialVersionUID = -1759791760116532857L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(EAST);
}
}
private static class LeftAction extends AbstractAction {
private static final long serialVersionUID = 8670680299012169408L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(WEST);
}
}
private static class UpAction extends AbstractAction {
private static final long serialVersionUID = -6961702501242792445L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NORTH);
}
}
private static class DownAction extends AbstractAction {
private static final long serialVersionUID = -453174268282628886L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(SOUTH);
}
}
private static class NextAction extends AbstractAction {
private static final long serialVersionUID = -154035573464933924L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NEXT);
}
}
private static class PreviousAction extends AbstractAction {
private static final long serialVersionUID = 2095403667386334865L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(PREVIOUS);
}
}
private static class PageUpAction extends AbstractAction {
private static final long serialVersionUID = 1154273528778779166L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(WEST);
}
else {
ui.navigateSelectedTab(NORTH);
}
}
}
private static class PageDownAction extends AbstractAction {
private static final long serialVersionUID = 4895454480954468453L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(EAST);
}
else {
ui.navigateSelectedTab(SOUTH);
}
}
}
private static class RequestFocusAction extends AbstractAction {
private static final long serialVersionUID = 3791111435639724577L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (!pane.requestFocusInWindow()) {
pane.requestFocus();
}
}
}
private static class RequestFocusForVisibleAction extends AbstractAction {
private static final long serialVersionUID = 6677797853998039155L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.requestFocusForVisibleComponent();
}
}
/**
* Selects a tab in the JTabbedPane based on the String of the action command. The tab selected is based on the
* first tab that has a mnemonic matching the first character of the action command.
*/
private static class SetSelectedIndexAction extends AbstractAction {
private static final long serialVersionUID = 6216635910156115469L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (pane != null && (pane.getUI() instanceof BasicJideTabbedPaneUI)) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
String command = e.getActionCommand();
if (command != null && command.length() > 0) {
int mnemonic = (int) e.getActionCommand().charAt(0);
if (mnemonic >= 'a' && mnemonic <= 'z') {
mnemonic -= ('a' - 'A');
}
Integer index = (Integer) ui._mnemonicToIndexMap
.get(new Integer(mnemonic));
if (index != null && pane.isEnabledAt(index)) {
pane.setSelectedIndex(index);
}
}
}
}
}
protected TabCloseButton createNoFocusButton(int type) {
return new TabCloseButton(type);
}
private static class ScrollTabsForwardAction extends AbstractAction {
private static final long serialVersionUID = 8772616556895545931L;
public ScrollTabsForwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollForward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollForward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsBackwardAction extends AbstractAction {
private static final long serialVersionUID = -426408621939940046L;
public ScrollTabsBackwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollBackward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollBackward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsListAction extends AbstractAction {
private static final long serialVersionUID = 246103712600916771L;
public ScrollTabsListAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.showList"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
if (ui._tabScroller._popup != null && ui._tabScroller._popup.isPopupVisible()) {
ui._tabScroller._popup.hidePopupImmediately();
ui._tabScroller._popup = null;
}
else {
ui._tabScroller.createPopup(pane.getTabPlacement());
}
}
}
}
}
protected void stopOrCancelEditing() {
boolean isEditValid = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
isEditValid = _tabPane.getTabEditingValidator().isValid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (isEditValid)
_tabPane.stopTabEditing();
else
_tabPane.cancelTabEditing();
}
private static class CloseTabAction extends AbstractAction {
private static final long serialVersionUID = 7779678389793199733L;
public CloseTabAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.close"));
}
public void actionPerformed(ActionEvent e) {
JideTabbedPane pane;
Object src = e.getSource();
int index;
boolean closeSelected = false;
if (src instanceof JideTabbedPane) {
pane = (JideTabbedPane) src;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof JideTabbedPane) {
pane = (JideTabbedPane) ((TabCloseButton) src).getParent();
closeSelected = true;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof ScrollableTabPanel) {
pane = (JideTabbedPane) SwingUtilities.getAncestorOfClass(JideTabbedPane.class, (TabCloseButton) src);
closeSelected = false;
}
else {
return; // shouldn't happen
}
if (pane.isTabEditing()) {
((BasicJideTabbedPaneUI) pane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
}
ActionEvent e2 = e;
if (src instanceof TabCloseButton) {
index = ((TabCloseButton) src).getIndex();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
else if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
if (pane.getCloseAction() != null) {
pane.getCloseAction().actionPerformed(e2);
}
else {
if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
if (index >= 0)
pane.removeTabAt(index);
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else if (closeSelected) {
if (pane.getSelectedIndex() >= 0)
pane.removeTabAt(pane.getSelectedIndex());
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else {
int i = ((TabCloseButton) src).getIndex();
if (i != -1) {
int tabIndex = pane.getSelectedIndex();
pane.removeTabAt(i);
if (i < tabIndex) {
pane.setSelectedIndex(tabIndex - 1);
}
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
}
}
}
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabbedPaneLayout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
return calculateSize(false);
}
public Dimension minimumLayoutSize(Container parent) {
return calculateSize(true);
}
protected Dimension calculateSize(boolean minimum) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
Insets contentInsets = getContentBorderInsets(tabPlacement);
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
Dimension zeroSize = new Dimension(0, 0);
int height = contentInsets.top + contentInsets.bottom;
int width = contentInsets.left + contentInsets.right;
int cWidth = 0;
int cHeight = 0;
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
// Determine minimum size required to display largest
// child in each dimension
//
if (_tabPane.isShowTabContent()) {
for (int i = 0; i < _tabPane.getTabCount(); i++) {
Component component = _tabPane.getComponentAt(i);
if (component != null) {
Dimension size = zeroSize;
size = minimum ? component.getMinimumSize() :
component.getPreferredSize();
if (size != null) {
cHeight = Math.max(size.height, cHeight);
cWidth = Math.max(size.width, cWidth);
}
}
}
// Add content border insets to minimum size
width += cWidth;
height += cHeight;
}
int tabExtent;
// Calculate how much space the tabs will need, based on the
// minimum size required to display largest child + content border
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
height = Math.max(height, (minimum ? 0 : calculateMaxTabHeight(tabPlacement)) + tabAreaInsets.top + tabAreaInsets.bottom);
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.width, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.width, tabExtent);
}
width += tabExtent;
break;
case TOP:
case BOTTOM:
default:
if (_tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {
width = Math.max(width, (_tabPane.getTabCount() << 2) +
tabAreaInsets.left + tabAreaInsets.right);
}
else {
width = Math.max(width, (minimum ? 0 : calculateMaxTabWidth(tabPlacement)) +
tabAreaInsets.left + tabAreaInsets.right);
}
if (_tabPane.isTabShown()) {
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.height, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.height, tabExtent);
}
height += tabExtent;
}
}
}
return new Dimension(width + insets.left + insets.right,
height + insets.bottom + insets.top);
}
protected int preferredTabAreaHeight(int tabPlacement, int width) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int rows = 1;
int x = 0;
int maxTabHeight = calculateMaxTabHeight(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabWidth = calculateTabWidth(tabPlacement, i, metrics);
if (x != 0 && x + tabWidth > width) {
rows++;
x = 0;
}
x += tabWidth;
}
total = calculateTabAreaHeight(tabPlacement, rows, maxTabHeight);
}
return total;
}
protected int preferredTabAreaWidth(int tabPlacement, int height) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int columns = 1;
int y = 0;
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabHeight = calculateTabHeight(tabPlacement, i, metrics);
if (y != 0 && y + tabHeight > height) {
columns++;
y = 0;
}
y += tabHeight;
}
total = calculateTabAreaWidth(tabPlacement, columns, _maxTabWidth);
}
return total;
}
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
int cx, cy, cw, ch;
int totalTabWidth = 0;
int totalTabHeight = 0;
Insets contentInsets = getContentBorderInsets(tabPlacement);
Component selectedComponent = _tabPane.getComponentAt(selectedIndex);
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + totalTabWidth + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case RIGHT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case BOTTOM:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case TOP:
default:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + totalTabHeight + contentInsets.top;
}
cw = bounds.width - totalTabWidth -
insets.left - insets.right -
contentInsets.left - contentInsets.right;
ch = bounds.height - totalTabHeight -
insets.top - insets.bottom -
contentInsets.top - contentInsets.bottom;
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
child.setBounds(cx, cy, cw, ch);
}
}
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
public void calculateLayoutInfo() {
int tabCount = _tabPane.getTabCount();
assureRectsCreated(tabCount);
calculateTabRects(_tabPane.getTabPlacement(), tabCount);
}
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int selectedIndex = _tabPane.getSelectedIndex();
int tabRunOverlay;
int i, j;
int x, y;
int returnAt;
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
//
// Calculate bounds within which a tab run must fit
//
switch (tabPlacement) {
case LEFT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = size.width - insets.right - tabAreaInsets.right - _maxTabWidth;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case BOTTOM:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = size.height - insets.bottom - tabAreaInsets.bottom - _maxTabHeight;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
}
tabRunOverlay = getTabRunOverlay(tabPlacement);
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
// Run through tabs and partition them into runs
Rectangle rect;
for (i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabWidth = 0;
rect.x = x;
}
rect.width = calculateTabWidth(tabPlacement, i, metrics);
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
// Never move a TAB down a run if it is in the first column.
// Even if there isn't enough room, moving it to a fresh
// line won't help.
if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.x = x;
}
// Initialize y position in case there's just one run
rect.y = y;
rect.height = _maxTabHeight/* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabHeight = 0;
rect.y = y;
}
rect.height = calculateTabHeight(tabPlacement, i, metrics);
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
// Never move a TAB over a run if it is in the first run.
// Even if there isn't enough room, moving it to a fresh
// column won't help.
if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.y = y;
}
// Initialize x position in case there's just one column
rect.x = x;
rect.width = _maxTabWidth/* - 2 */;
}
if (i == selectedIndex) {
_selectedRun = _runCount - 1;
}
}
if (_runCount > 1) {
// Re-distribute tabs in case last run has leftover space
normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns ? y : x, returnAt);
_selectedRun = getRunForTab(tabCount, selectedIndex);
// Rotate run array so that selected run is first
if (shouldRotateTabRuns(tabPlacement)) {
rotateTabRuns(tabPlacement, _selectedRun);
}
}
// Step through runs from back to front to calculate
// tab y locations and to pad runs appropriately
for (i = _runCount - 1; i >= 0; i--) {
int start = _tabRuns[i];
int next = _tabRuns[i == (_runCount - 1) ? 0 : i + 1];
int end = (next != 0 ? next - 1 : tabCount - 1);
if (!verticalTabRuns) {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.y = y;
rect.x += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == BOTTOM) {
y -= (_maxTabHeight - tabRunOverlay);
}
else {
y += (_maxTabHeight - tabRunOverlay);
}
}
else {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.x = x;
rect.y += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == RIGHT) {
x -= (_maxTabWidth - tabRunOverlay);
}
else {
x += (_maxTabWidth - tabRunOverlay);
}
}
}
// Pad the selected tab so that it appears raised in front
padSelectedTab(tabPlacement, selectedIndex);
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right);
for (i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width;
}
}
}
/*
* Rotates the run-index array so that the selected run is run[0]
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void rotateTabRuns(int tabPlacement, int selectedRun) {
for (int i = 0; i < selectedRun; i++) {
int save = _tabRuns[0];
for (int j = 1; j < _runCount; j++) {
_tabRuns[j - 1] = _tabRuns[j];
}
_tabRuns[_runCount - 1] = save;
}
}
protected void normalizeTabRuns(int tabPlacement, int tabCount,
int start, int max) {
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
int run = _runCount - 1;
boolean keepAdjusting = true;
double weight = 1.25;
// At this point the tab runs are packed to fit as many
// tabs as possible, which can leave the last run with a lot
// of extra space (resulting in very fat tabs on the last run).
// So we'll attempt to distribute this extra space more evenly
// across the runs in order to make the runs look more consistent.
//
// Starting with the last run, determine whether the last tab in
// the previous run would fit (generously) in this run; if so,
// move tab to current run and shift tabs accordingly. Cycle
// through remaining runs using the same algorithm.
//
while (keepAdjusting) {
int last = lastTabInRun(tabCount, run);
int prevLast = lastTabInRun(tabCount, run - 1);
int end;
int prevLastLen;
if (!verticalTabRuns) {
end = _rects[last].x + _rects[last].width;
prevLastLen = (int) (_maxTabWidth * weight);
}
else {
end = _rects[last].y + _rects[last].height;
prevLastLen = (int) (_maxTabHeight * weight * 2);
}
// Check if the run has enough extra space to fit the last tab
// from the previous row...
if (max - end > prevLastLen) {
// Insert tab from previous row and shift rest over
_tabRuns[run] = prevLast;
if (!verticalTabRuns) {
_rects[prevLast].x = start;
}
else {
_rects[prevLast].y = start;
}
for (int i = prevLast + 1; i <= last; i++) {
if (!verticalTabRuns) {
_rects[i].x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_rects[i].y = _rects[i - 1].y + _rects[i - 1].height;
}
}
}
else if (run == _runCount - 1) {
// no more room left in last run, so we're done!
keepAdjusting = false;
}
if (run - 1 > 0) {
// check previous run next...
run -= 1;
}
else {
// check last run again...but require a higher ratio
// of extraspace-to-tabsize because we don't want to
// end up with too many tabs on the last run!
run = _runCount - 1;
weight += .25;
}
}
}
protected void padTabRun(int tabPlacement, int start, int end, int max) {
Rectangle lastRect = _rects[end];
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int runWidth = (lastRect.x + lastRect.width) - _rects[start].x;
int deltaWidth = max - (lastRect.x + lastRect.width);
float factor = (float) deltaWidth / (float) runWidth;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.x = _rects[j - 1].x + _rects[j - 1].width;
}
pastRect.width += Math.round((float) pastRect.width * factor);
}
lastRect.width = max - lastRect.x;
}
else {
int runHeight = (lastRect.y + lastRect.height) - _rects[start].y;
int deltaHeight = max - (lastRect.y + lastRect.height);
float factor = (float) deltaHeight / (float) runHeight;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.y = _rects[j - 1].y + _rects[j - 1].height;
}
pastRect.height += Math.round((float) pastRect.height * factor);
}
lastRect.height = max - lastRect.y;
}
}
protected void padSelectedTab(int tabPlacement, int selectedIndex) {
if (selectedIndex >= 0) {
Rectangle selRect = _rects[selectedIndex];
Insets padInsets = getSelectedTabPadInsets(tabPlacement);
selRect.x -= padInsets.left;
selRect.width += (padInsets.left + padInsets.right);
selRect.y -= padInsets.top;
selRect.height += (padInsets.top + padInsets.bottom);
}
}
}
protected TabSpaceAllocator tryTabSpacer = new TabSpaceAllocator();
protected class TabbedPaneScrollLayout extends TabbedPaneLayout {
@Override
protected int preferredTabAreaHeight(int tabPlacement, int width) {
return calculateMaxTabHeight(tabPlacement);
}
@Override
protected int preferredTabAreaWidth(int tabPlacement, int height) {
return calculateMaxTabWidth(tabPlacement);
}
@Override
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
JViewport viewport = null;
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
int tx, ty, tw, th; // tab area bounds
int cx, cy, cw, ch; // content area bounds
Insets contentInsets = getContentBorderInsets(tabPlacement);
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = insets.left;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
}
}
// calculate content area bounds
cx = tx + tw + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case RIGHT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount,
_maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = bounds.width - insets.right - tw;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
tx = bounds.width - insets.right - tw;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
tx = bounds.width - insets.right - tw;
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case BOTTOM:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = bounds.height - insets.bottom - th;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
break;
case TOP:
default:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = insets.top;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + th + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
}
// if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (tw < _rects[0].width + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
// else {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (th < _rects[0].height + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
if (child instanceof ScrollableTabViewport) {
viewport = (JViewport) child;
// Rectangle viewRect = viewport.getViewRect();
int vw = tw;
int vh = th;
int numberOfButtons = getNumberOfTabButtons();
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (totalTabHeight > th || isShowTabButtons()) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
// if (totalTabHeight - viewRect.y <= vh) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vh = totalTabHeight - viewRect.y;
// }
}
else {
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
}
if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) {
vh += getLayoutSize();
}
break;
case BOTTOM:
case TOP:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (isShowTabButtons() || !widthEnough) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Need to allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
// if (totalTabWidth - viewRect.x <= vw) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vw = totalTabWidth - viewRect.x;
// }
}
else {
// Allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
}
if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) {
vw += getLayoutSize();
if (!leftToRight) {
tx -= getLayoutSize();
}
}
break;
}
child.setBounds(tx, ty, vw, vh);
}
else if (child instanceof TabCloseButton) {
TabCloseButton scrollbutton = (TabCloseButton) child;
if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) {
Dimension bsize = scrollbutton.getPreferredSize();
int bx = 0;
int by = 0;
int bw = bsize.width;
int bh = bsize.height;
boolean visible = false;
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) {
int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
}
bx = tx + 2;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
bx = tx + 2;
}
}
if (isTabTrailingComponentVisible()) {
by = by - tsize.height;
}
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.width >= _rects[0].width) {
if (tabPlacement == LEFT) {
bx += lsize.width - _rects[0].width;
temp = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.width >= _rects[0].width
&& temp < tsize.width) {
if (tabPlacement == LEFT) {
bx += tsize.width - _rects[0].width;
}
}
}
break;
case TOP:
case BOTTOM:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (_tabPane.isTabShown() && (isShowTabButtons() || !widthEnough)) {
int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON
// NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
bx = insets.left - 5;
}
}
else {
visible = false;
bx = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (1 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
}
by = ((th - bsize.height) >> 1) + ty;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
visible = false;
bx = 0;
}
by = ((th - bsize.height) >> 1) + ty;
}
}
if (isTabTrailingComponentVisible()) {
bx -= tsize.width;
}
temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.height >= _rects[0].height) {
if (tabPlacement == TOP) {
by = ty + 2 + lsize.height - _rects[0].height;
temp = lsize.height;
}
else {
by = ty + 2;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.height >= _rects[0].height
&& temp < tsize.height) {
if (tabPlacement == TOP) {
by = ty + 2 + tsize.height - _rects[0].height;
}
else {
by = ty + 2;
}
}
}
}
child.setVisible(visible);
if (visible) {
child.setBounds(bx, by, bw, bh);
}
}
else {
scrollbutton.setBounds(0, 0, 0, 0);
}
}
else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) {
if (_tabPane.isShowTabContent()) {
// All content children...
child.setBounds(cx, cy, cw, ch);
}
else {
child.setBounds(0, 0, 0, 0);
}
}
}
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
}
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
if (!leftToRight && !verticalTabRuns && viewport != null && !viewport.getSize().equals(_tabPane.getSize())) {
int offset = _tabPane.getWidth() - viewport.getWidth();
for (Rectangle rect : _rects) {
rect.x -= offset;
}
}
updateCloseButtons();
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
@Override
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
int x = tabAreaInsets.left;
int y = tabAreaInsets.top;
//
// Calculate bounds within which a tab run must fit
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < lsize.width) {
_maxTabWidth = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < tsize.width) {
_maxTabWidth = tsize.width;
}
}
}
break;
case BOTTOM:
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < lsize.height) {
_maxTabHeight = lsize.height;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < tsize.height) {
_maxTabHeight = tsize.height;
}
}
}
}
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
_selectedRun = 0;
_runCount = 1;
// Run through tabs and lay them out in a single run
Rectangle rect;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_maxTabWidth = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.x = x + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.x = x;
}
}
rect.width = calculateTabWidth(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
rect.y = y;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < lsize.height) {
rect.y = y + lsize.height - _maxTabHeight - 2;
temp = lsize.height;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < tsize.height
&& temp < tsize.height) {
rect.y = y + tsize.height - _maxTabHeight - 2;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
rect.height = calculateMaxTabHeight(tabPlacement);///* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_maxTabHeight = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.y = y + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.y = y;
}
}
rect.height = calculateTabHeight(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
rect.x = x;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < lsize.width) {
rect.x = x + lsize.width - _maxTabWidth - 2;
temp = lsize.width;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < tsize.width
&& temp < tsize.width) {
rect.x = x + tsize.width - _maxTabWidth - 2;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
rect.width = calculateMaxTabWidth(tabPlacement)/* - 2 */;
}
}
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right) - _tabScroller.viewport.getLocation().x;
if (isTabLeadingComponentVisible()) {
rightMargin -= lsize.width;
}
int offset = 0;
if (isTabTrailingComponentVisible()) {
offset += tsize.width;
}
for (int i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width - offset + tabAreaInsets.left;
// if(i == tabCount - 1) {
// _rects[i].width += getLeftMargin();
// _rects[i].x -= getLeftMargin();
// }
}
}
ensureCurrentRects(getLeftMargin(), tabCount);
}
}
protected void ensureCurrentRects(int leftMargin, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
int totalWidth = 0;
int totalHeight = 0;
boolean verticalTabRuns = (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT);
boolean ltr = _tabPane.getComponentOrientation().isLeftToRight();
if (tabCount == 0) {
return;
}
Rectangle r = _rects[tabCount - 1];
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (verticalTabRuns) {
totalHeight = r.y + r.height;
if (_tabLeadingComponent != null) {
totalHeight -= lsize.height;
}
}
else {
// totalWidth = r.x + r.width;
for (Rectangle rect : _rects) {
totalWidth += rect.width;
}
if (ltr) {
totalWidth += _rects[0].x;
}
else {
totalWidth += size.width - _rects[0].x - _rects[0].width - _tabScroller.viewport.getLocation().x;
}
if (_tabLeadingComponent != null) {
totalWidth -= lsize.width;
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {// LayOut Style is Size to Fix
if (verticalTabRuns) {
int availHeight;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom - leftMargin - getTabRightPadding();// give the first tab extra space
}
else {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom;
}
if (_tabPane.isShowCloseButton()) {
availHeight -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availHeight = availHeight - lsize.height;
}
if (isTabTrailingComponentVisible()) {
availHeight = availHeight - tsize.height;
}
int numberOfButtons = getNumberOfTabButtons();
availHeight -= _buttonSize * numberOfButtons;
if (totalHeight > availHeight) { // shrink is necessary
// calculate each tab width
int tabHeight = availHeight / tabCount;
totalHeight = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
_rects[k].height = tabHeight;
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
tabRect.y = totalHeight + leftMargin;// give the first tab extra space
}
else {
tabRect.y = totalHeight;
}
totalHeight += tabRect.height;
}
}
}
else {
int availWidth;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right - leftMargin - getTabRightPadding();
}
else {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right;
}
if (_tabPane.isShowCloseButton()) {
availWidth -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availWidth -= lsize.width;
}
if (isTabTrailingComponentVisible()) {
availWidth -= tsize.width;
}
int numberOfButtons = getNumberOfTabButtons();
availWidth -= _buttonSize * numberOfButtons;
if (totalWidth > availWidth) { // shrink is necessary
// calculate each tab width
int tabWidth = availWidth / tabCount;
int gripperWidth = _tabPane.isShowGripper() ? _gripperWidth
: 0;
if (tabWidth < _textIconGap + _fitStyleTextMinWidth
+ _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleIconMinWidth + gripperWidth) // cannot
// hold any text but can hold an icon
tabWidth = _fitStyleIconMinWidth + gripperWidth;
if (tabWidth < _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleFirstTabMargin + gripperWidth) // cannot
// hold any icon but gripper
tabWidth = _fitStyleFirstTabMargin + gripperWidth;
tryTabSpacer.reArrange(_rects, insets, availWidth);
}
totalWidth = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
if (ltr) {
tabRect.x = totalWidth + leftMargin;// give the first tab extra space when the style is not box style
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width + leftMargin;// give the first tab extra space when the style is not box style
}
}
else {
if (ltr) {
tabRect.x = totalWidth;
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width;
}
}
totalWidth += tabRect.width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIXED) {// LayOut Style is Fix
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
_rects[k].height = _fixedStyleRectSize;// + _rectSizeExtend * 2;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].height += _closeButtons[k].getPreferredSize().height;
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
_rects[k].width = _fixedStyleRectSize;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].width += _closeButtons[k].getPreferredSize().width;
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED) {// LayOut Style is Compressed
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab() && !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].height = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].height = icon.getIconHeight() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].height = _rects[k].height + _closeButtons[k].getPreferredSize().height + _compressedStyleCloseButtonMarginVertical;
}
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab()
&& !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].width = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].width = icon.getIconWidth() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].width = _rects[k].width + _closeButtons[k].getPreferredSize().width + _compressedStyleCloseButtonMarginHorizon;
}
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
totalWidth += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalWidth += lsize.width;
}
}
else {
totalHeight += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalHeight += tsize.height;
}
}
_tabScroller.tabPanel.setPreferredSize(new Dimension(totalWidth, totalHeight));
}
protected class ActivateTabAction extends AbstractAction {
int _tabIndex;
private static final long serialVersionUID = 3270152106579039554L;
public ActivateTabAction(String name, Icon icon, int tabIndex) {
super(name, icon);
_tabIndex = tabIndex;
}
public void actionPerformed(ActionEvent e) {
_tabPane.setSelectedIndex(_tabIndex);
}
}
protected ListCellRenderer getTabListCellRenderer() {
return _tabPane.getTabListCellRenderer();
}
public class ScrollableTabSupport implements ChangeListener {
public ScrollableTabViewport viewport;
public ScrollableTabPanel tabPanel;
public TabCloseButton scrollForwardButton;
public TabCloseButton scrollBackwardButton;
public TabCloseButton listButton;
public TabCloseButton closeButton;
public int leadingTabIndex;
private Point tabViewPosition = new Point(0, 0);
public JidePopup _popup;
@SuppressWarnings({"UnusedDeclaration"})
ScrollableTabSupport(int tabPlacement) {
viewport = new ScrollableTabViewport();
tabPanel = new ScrollableTabPanel();
viewport.setView(tabPanel);
viewport.addChangeListener(this);
scrollForwardButton = createNoFocusButton(TabCloseButton.EAST_BUTTON);
scrollForwardButton.setName(BUTTON_NAME_SCROLL_FORWARD);
scrollBackwardButton = createNoFocusButton(TabCloseButton.WEST_BUTTON);
scrollBackwardButton.setName(BUTTON_NAME_SCROLL_BACKWARD);
scrollForwardButton.setBackground(viewport.getBackground());
scrollBackwardButton.setBackground(viewport.getBackground());
listButton = createNoFocusButton(TabCloseButton.LIST_BUTTON);
listButton.setName(BUTTON_NAME_TAB_LIST);
listButton.setBackground(viewport.getBackground());
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName(BUTTON_NAME_CLOSE);
closeButton.setBackground(viewport.getBackground());
}
public void createPopupMenu(int tabPlacement) {
JPopupMenu popup = new JPopupMenu();
int totalCount = _tabPane.getTabCount();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
for (int i = 0; i < totalCount; i++) {
if (_tabPane.isEnabledAt(i)) {
JMenuItem item;
popup.add(item = new JCheckBoxMenuItem(new ActivateTabAction(_tabPane.getTitleAt(i), _tabPane.getIconForTab(i), i)));
item.setToolTipText(_tabPane.getToolTipTextAt(i));
item.setSelected(selectedIndex == i);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
}
}
Dimension preferredSize = popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
switch (tabPlacement) {
case TOP:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y + bounds.height);
break;
case BOTTOM:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y - preferredSize.height);
break;
case LEFT:
popup.show(_tabPane, bounds.x + bounds.width, bounds.y + bounds.height - preferredSize.height);
break;
case RIGHT:
popup.show(_tabPane, bounds.x - preferredSize.width, bounds.y + bounds.height - preferredSize.height);
break;
}
}
public void createPopup(int tabPlacement) {
final JList list = new JList() {
// override this method to disallow deselect by ctrl-click
@Override
public void removeSelectionInterval(int index0, int index1) {
super.removeSelectionInterval(index0, index1);
if (getSelectedIndex() == -1) {
setSelectedIndex(index0);
}
}
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension preferredScrollableViewportSize = super.getPreferredScrollableViewportSize();
if (preferredScrollableViewportSize.width < 150) {
preferredScrollableViewportSize.width = 150;
}
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredScrollableViewportSize.width >= screenWidth) {
preferredScrollableViewportSize.width = screenWidth;
}
return preferredScrollableViewportSize;
}
@Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredSize.width >= screenWidth) {
preferredSize.width = screenWidth;
}
return preferredSize;
}
};
new Sticky(list);
list.setBackground(_tabListBackground);
JScrollPane scroller = new JScrollPane(list);
scroller.setBorder(BorderFactory.createEmptyBorder());
scroller.getViewport().setOpaque(false);
scroller.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(_tabListBackground);
panel.setOpaque(true);
panel.add(scroller);
panel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
if (_popup != null) {
if (_popup.isPopupVisible()) {
_popup.hidePopupImmediately();
}
_popup = null;
}
_popup = com.jidesoft.popup.JidePopupFactory.getSharedInstance().createPopup();
_popup.setPopupBorder(BorderFactory.createLineBorder(_darkShadow));
_popup.add(panel);
_popup.addExcludedComponent(listButton);
_popup.setDefaultFocusComponent(list);
DefaultListModel listModel = new DefaultListModel();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
int totalCount = _tabPane.getTabCount();
for (int i = 0; i < totalCount; i++) {
listModel.addElement(_tabPane);
}
list.setCellRenderer(getTabListCellRenderer());
list.setModel(listModel);
list.setSelectedIndex(selectedIndex);
list.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
componentSelected(list);
}
}
public void keyReleased(KeyEvent e) {
}
});
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
componentSelected(list);
}
});
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Insets insets = panel.getInsets();
int max = (PortingUtils.getLocalScreenSize(_tabPane).height - insets.top - insets.bottom) / list.getCellBounds(0, 0).height;
if (listModel.getSize() > max) {
list.setVisibleRowCount(max);
}
else {
list.setVisibleRowCount(listModel.getSize());
}
_popup.setOwner(_tabPane);
_popup.removeExcludedComponent(_tabPane);
Dimension size = _popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
Point p = listButton.getLocationOnScreen();
bounds.x = p.x;
bounds.y = p.y;
int x;
int y;
switch (tabPlacement) {
case TOP:
default:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y + bounds.height + 2;
break;
case BOTTOM:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y - size.height - 2;
break;
case LEFT:
x = bounds.x + bounds.width + 2;
y = bounds.y + bounds.height - size.height;
break;
case RIGHT:
x = bounds.x - size.width - 2;
y = bounds.y + bounds.height - size.height;
break;
}
Rectangle screenBounds = PortingUtils.getScreenBounds(_tabPane);
int right = x + size.width + 3;
int bottom = y + size.height + 3;
if (right > screenBounds.x + screenBounds.width) {
x -= right - screenBounds.x - screenBounds.width; // move left so that the whole popup can fit in
}
if (x < screenBounds.x) {
x = screenBounds.x; // move right so that the whole popup can fit in
}
if (bottom > screenBounds.height) {
y -= bottom - screenBounds.height;
}
if (y < screenBounds.y) {
y = screenBounds.y;
}
_popup.showPopup(x, y);
}
private void componentSelected(JList list) {
int tabIndex = list.getSelectedIndex();
if (tabIndex != -1 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
Runnable runnable = new Runnable() {
public void run() {
_tabPane.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
Runnable runnable = new Runnable() {
public void run() {
if (lastFocused != null) {
lastFocused.requestFocus();
}
else if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocus();
}
}
};
SwingUtilities.invokeLater(runnable);
}
});
}
else {
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
Runnable runnable = new Runnable() {
public void run() {
lastFocused.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
else {
Container container;
if (comp instanceof Container) {
container = (Container) comp;
}
else {
container = comp.getFocusCycleRootAncestor();
}
FocusTraversalPolicy traversalPolicy = container.getFocusTraversalPolicy();
Component focusComponent;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(container);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(container);
}
}
else if (comp instanceof Container) {
// not sure if it is correct
focusComponent = findFocusableComponent((Container) comp);
}
else {
focusComponent = comp;
}
if (focusComponent != null) {
final Component theComponent = focusComponent;
Runnable runnable = new Runnable() {
public void run() {
theComponent.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
}
}
ensureActiveTabIsVisible(false);
_popup.hidePopupImmediately();
_popup = null;
}
}
private Component findFocusableComponent(Container parent) {
FocusTraversalPolicy traversalPolicy = parent.getFocusTraversalPolicy();
Component focusComponent = null;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(parent);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(parent);
}
}
if (focusComponent != null) {
return focusComponent;
}
int i = 0;
while (i < parent.getComponentCount()) {
Component comp = parent.getComponent(i);
if (comp instanceof Container) {
focusComponent = findFocusableComponent((Container) comp);
if (focusComponent != null) {
return focusComponent;
}
}
else if (comp.isFocusable()) {
return comp;
}
i++;
}
if (parent.isFocusable()) {
return parent;
}
return null;
}
public void scrollForward(int tabPlacement) {
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (viewRect.width >= viewSize.width - viewRect.x) {
return; // no room left to scroll
}
}
else { // tabPlacement == LEFT || tabPlacement == RIGHT
if (viewRect.height >= viewSize.height - viewRect.y) {
return;
}
}
setLeadingTabIndex(tabPlacement, leadingTabIndex + 1);
}
public void scrollBackward(int tabPlacement) {
setLeadingTabIndex(tabPlacement, leadingTabIndex > 0 ? leadingTabIndex - 1 : 0);
}
public void setLeadingTabIndex(int tabPlacement, int index) {
// make sure the index is in range
if (index < 0 || index >= _tabPane.getTabCount()) {
return;
}
leadingTabIndex = index;
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
switch (tabPlacement) {
case TOP:
case BOTTOM:
tabViewPosition.y = 0;
if (_tabPane.getComponentOrientation().isLeftToRight()) {
tabViewPosition.x = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].x;
}
else {
tabViewPosition.x = (_rects.length <= 0 || leadingTabIndex == 0) ? 0 : _rects[0].x - _rects[leadingTabIndex].x + (_rects[0].width - _rects[leadingTabIndex].width) + 25;
}
if ((viewSize.width - tabViewPosition.x) < viewRect.width) {
tabViewPosition.x = viewSize.width - viewRect.width;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewSize.width - tabViewPosition.x,
// viewRect.height);
// System.out.println("setExtendedSize: " + extentSize);
// viewport.setExtentSize(extentSize);
}
break;
case LEFT:
case RIGHT:
tabViewPosition.x = 0;
tabViewPosition.y = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].y;
if ((viewSize.height - tabViewPosition.y) < viewRect.height) {
tabViewPosition.y = viewSize.height - viewRect.height;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewRect.width,
// viewSize.height - tabViewPosition.y);
// viewport.setExtentSize(extentSize);
}
break;
}
viewport.setViewPosition(tabViewPosition);
_tabPane.repaint();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight() && tabViewPosition.x == 0) {
// In current workaround, tabViewPosition set to 0 cannot trigger state change event
stateChanged(new ChangeEvent(viewport));
}
}
public void stateChanged(ChangeEvent e) {
if (_tabPane == null) return;
ensureCurrentLayout();
JViewport viewport = (JViewport) e.getSource();
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Rectangle vpRect = viewport.getBounds();
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
leadingTabIndex = getClosestTab(viewRect.x + viewRect.width, viewRect.y + viewRect.height);
if (leadingTabIndex < 0) {
leadingTabIndex = 0;
}
}
else {
leadingTabIndex = getClosestTab(viewRect.x, viewRect.y);
}
// If the tab isn't right aligned, adjust it.
if (leadingTabIndex < _rects.length && leadingTabIndex >= _rects.length) {
switch (tabPlacement) {
case TOP:
case BOTTOM:
if (_rects[leadingTabIndex].x < viewRect.x) {
leadingTabIndex++;
}
break;
case LEFT:
case RIGHT:
if (_rects[leadingTabIndex].y < viewRect.y) {
leadingTabIndex++;
}
break;
}
}
Insets contentInsets = getContentBorderInsets(tabPlacement);
int checkX;
switch (tabPlacement) {
case LEFT:
_tabPane.repaint(vpRect.x + vpRect.width, vpRect.y, contentInsets.left, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case RIGHT:
_tabPane.repaint(vpRect.x - contentInsets.right, vpRect.y, contentInsets.right, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case BOTTOM:
_tabPane.repaint(vpRect.x, vpRect.y - contentInsets.bottom, vpRect.width, contentInsets.bottom);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
break;
case TOP:
default:
_tabPane.repaint(vpRect.x, vpRect.y + vpRect.height, vpRect.width, contentInsets.top);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
}
if (SystemInfo.isJdk15Above()) {
_tabPane.setComponentZOrder(_tabScroller.scrollForwardButton, 0);
_tabPane.setComponentZOrder(_tabScroller.scrollBackwardButton, 0);
}
_tabScroller.scrollForwardButton.repaint();
_tabScroller.scrollBackwardButton.repaint();
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount()) {
closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex));
}
}
@Override
public String toString() {
return "viewport.viewSize=" + viewport.getViewSize() + "\n" +
"viewport.viewRectangle=" + viewport.getViewRect() + "\n" +
"leadingTabIndex=" + leadingTabIndex + "\n" +
"tabViewPosition=" + tabViewPosition;
}
}
public class ScrollableTabViewport extends JViewport implements UIResource {
int _expectViewX = 0;
boolean _protectView = false;
public ScrollableTabViewport() {
super();
setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
setOpaque(false);
setLayout(new ViewportLayout() {
private static final long serialVersionUID = -1069760662716244442L;
@Override
public void layoutContainer(Container parent) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
_protectView = true;
}
try {
super.layoutContainer(parent);
}
finally {
_protectView = false;
}
}
});
}
/**
* Gets the background color of this component.
*
* @return this component's background color; if this component does not have a background color, the background
* color of its parent is returned
*/
@Override
public Color getBackground() {
return UIDefaultsLookup.getColor("JideTabbedPane.background");
}
// workaround for swing bug
@Override
public void setViewPosition(Point p) {
int oldX = _expectViewX;
_expectViewX = p.x;
super.setViewPosition(p); // to trigger state change event, so the adjustment for RTL need to be done at ScrollableTabPanel#setBounds()
if (_protectView) {
_expectViewX = oldX;
Point savedPosition = new Point(oldX, p.y);
super.setViewPosition(savedPosition);
}
}
public int getExpectedViewX() {
return _expectViewX;
}
}
public class ScrollableTabPanel extends JPanel implements UIResource {
public ScrollableTabPanel() {
setLayout(null);
}
@Override
public boolean isOpaque() {
return false;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_tabPane.isOpaque()) {
if (getTabShape() == JideTabbedPane.SHAPE_BOX) {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"));
}
else {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground"));
}
g.fillRect(0, 0, getWidth(), getHeight());
}
paintTabArea(g, _tabPane.getTabPlacement(), _tabPane.getSelectedIndex(), this);
}
// workaround for swing bug
@Override
public void scrollRectToVisible(Rectangle aRect) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
int startX = aRect.x + _tabScroller.viewport.getExpectedViewX();
if (startX < 0) {
int i;
for (i = _tabScroller.leadingTabIndex; i < _rects.length; i++) {
startX += _rects[i].width;
if (startX >= 0) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.min(i + 1, _rects.length - 1));
}
else if (startX > aRect.x + aRect.width) {
int i;
for (i = _tabScroller.leadingTabIndex - 1; i >= 0; i--) {
startX -= _rects[i].width;
if (startX <= aRect.x + aRect.width) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.max(i, 0));
}
return;
}
super.scrollRectToVisible(aRect);
}
// workaround for swing bug
@Override
public void setBounds(int x, int y, int width, int height) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
super.setBounds(0, y, width, height);
return;
}
super.setBounds(x, y, width, height);
}
// workaround for swing bug
// http://developer.java.sun.com/developer/bugParade/bugs/4668865.html
@Override
public void setToolTipText(String text) {
_tabPane.setToolTipText(text);
}
@Override
public String getToolTipText() {
return _tabPane.getToolTipText();
}
@Override
public String getToolTipText(MouseEvent event) {
return _tabPane.getToolTipText(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public Point getToolTipLocation(MouseEvent event) {
return _tabPane.getToolTipLocation(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public JToolTip createToolTip() {
return _tabPane.createToolTip();
}
}
protected Color _closeButtonSelectedColor = new Color(255, 162, 165);
protected Color _closeButtonColor = Color.BLACK;
protected Color _popupColor = Color.BLACK;
/**
* Close button on the tab.
*/
public class TabCloseButton extends JButton implements MouseMotionListener, MouseListener, UIResource {
public static final int CLOSE_BUTTON = 0;
public static final int EAST_BUTTON = 1;
public static final int WEST_BUTTON = 2;
public static final int NORTH_BUTTON = 3;
public static final int SOUTH_BUTTON = 4;
public static final int LIST_BUTTON = 5;
private int _type;
private int _index = -1;
private boolean _mouseOver = false;
private boolean _mousePressed = false;
/**
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
@Override
public void updateUI() {
super.updateUI();
setMargin(new Insets(0, 0, 0, 0));
setBorder(BorderFactory.createEmptyBorder());
setFocusPainted(false);
setFocusable(false);
setRequestFocusEnabled(false);
String name = getName();
if (name != null) setToolTipText(getResourceString(name));
}
public TabCloseButton() {
this(CLOSE_BUTTON);
}
public TabCloseButton(int type) {
addMouseMotionListener(this);
addMouseListener(this);
setFocusPainted(false);
setFocusable(false);
setType(type);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(5, 5);
}
public int getIndex() {
return _index;
}
public void setIndex(int index) {
_index = index;
}
@Override
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
@Override
protected void paintComponent(Graphics g) {
if (!isEnabled()) {
setMouseOver(false);
setMousePressed(false);
}
if (isMouseOver() && isMousePressed()) {
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
else if (isMouseOver()) {
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
g.setColor(UIDefaultsLookup.getColor("controlShadow").darker());
int centerX = getWidth() >> 1;
int centerY = getHeight() >> 1;
int type = getType();
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
if (type == EAST_BUTTON) {
type = WEST_BUTTON;
}
else if (type == WEST_BUTTON) {
type = EAST_BUTTON;
}
}
switch (type) {
case CLOSE_BUTTON:
if (isEnabled()) {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX - 4, centerY - 3, centerX + 2, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
g.drawLine(centerX + 2, centerY - 3, centerX - 4, centerY + 3);
}
else {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
}
break;
case EAST_BUTTON:
//
// |
// ||
// |||
// ||||
// ||||*
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX + 2, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 3, y - 3, x - 3, y + 3);
g.drawLine(x - 2, y - 2, x - 2, y + 2);
g.drawLine(x - 1, y - 1, x - 1, y + 1);
g.drawLine(x, y, x, y);
}
else {
g.drawLine(x - 4, y - 4, x, y);
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
else {
int x = centerX + 3, y = centerY - 2; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 7, y + 1, x - 1, y + 1);
g.drawLine(x - 6, y + 2, x - 2, y + 2);
g.drawLine(x - 5, y + 3, x - 3, y + 3);
g.drawLine(x - 4, y + 4, x - 4, y + 4);
}
else {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 8, y, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
}
break;
case WEST_BUTTON: {
//
// |
// ||
// |||
// ||||
// *||||
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX - 3, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x, y);
g.drawLine(x + 1, y - 1, x + 1, y + 1);
g.drawLine(x + 2, y - 2, x + 2, y + 2);
g.drawLine(x + 3, y - 3, x + 3, y + 3);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
else {
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x, y, x + 4, y + 4);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
}
else {
int x = centerX - 5, y = centerY + 3; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x + 8, y);
g.drawLine(x + 1, y - 1, x + 7, y - 1);
g.drawLine(x + 2, y - 2, x + 6, y - 2);
g.drawLine(x + 3, y - 3, x + 5, y - 3);
g.drawLine(x + 4, y - 4, x + 4, y - 4);
}
else {
g.drawLine(x, y, x + 8, y);
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x + 8, y, x + 4, y - 4);
}
}
}
break;
}
case LIST_BUTTON: {
int x = centerX + 2, y = centerY; // start point. mark as
// * above
g.drawLine(x - 6, y - 4, x - 6, y + 4);
g.drawLine(x + 1, y - 4, x + 1, y + 4);
g.drawLine(x - 6, y - 4, x + 1, y - 4);
g.drawLine(x - 4, y - 2, x - 1, y - 2);
g.drawLine(x - 4, y, x - 1, y);
g.drawLine(x - 4, y + 2, x - 1, y + 2);
g.drawLine(x - 6, y + 4, x + 1, y + 4);
break;
}
}
}
@Override
public boolean isFocusable() {
return false;
}
@Override
public void requestFocus() {
}
@Override
public boolean isOpaque() {
return false;
}
public boolean scrollsForward() {
return getType() == EAST_BUTTON || getType() == SOUTH_BUTTON;
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
setMousePressed(false);
}
public void mousePressed(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(true);
repaint();
}
public void mouseReleased(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(false);
setMouseOver(false);
}
public void mouseEntered(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseExited(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(false);
setMousePressed(false);
repaint();
_tabScroller.tabPanel.repaint();
}
public int getType() {
return _type;
}
public void setType(int type) {
_type = type;
}
public boolean isMouseOver() {
return _mouseOver;
}
public void setMouseOver(boolean mouseOver) {
_mouseOver = mouseOver;
}
public boolean isMousePressed() {
return _mousePressed;
}
public void setMousePressed(boolean mousePressed) {
_mousePressed = mousePressed;
}
}
// Controller: event listeners
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class PropertyChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
String name = e.getPropertyName();
if ("mnemonicAt".equals(name)) {
updateMnemonics();
pane.repaint();
}
else if ("displayedMnemonicIndexAt".equals(name)) {
pane.repaint();
}
else if (name.equals("indexForTitle")) {
int index = (Integer) e.getNewValue();
String title = getCurrentDisplayTitleAt(_tabPane, index);
if (BasicHTML.isHTMLString(title)) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(_tabPane, title);
htmlViews.setElementAt(v, index);
}
}
else {
if (htmlViews != null && htmlViews.elementAt(index) != null) {
htmlViews.setElementAt(null, index);
}
}
updateMnemonics();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(
_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(false);
}
}
else if (name.equals("tabLayoutPolicy")) {
_tabPane.updateUI();
}
else if (name.equals("closeTabAction")) {
updateCloseAction();
}
else if (name.equals(JideTabbedPane.PROPERTY_DRAG_OVER_DISABLED)) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_COLOR_PROVIDER)) {
_tabPane.repaint();
}
else if (name.equals("locale")) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.BOLDACTIVETAB_PROPERTY)) {
getTabPanel().invalidate();
_tabPane.invalidate();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_LEADING_COMPONENT)) {
ensureCurrentLayout();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(false);
_tabPane.remove(_tabLeadingComponent);
}
_tabLeadingComponent = (Component) e.getNewValue();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(true);
_tabPane.add(_tabLeadingComponent);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_TRAILING_COMPONENT)) {
ensureCurrentLayout();
if (_tabTrailingComponent != null) {
_tabTrailingComponent.setVisible(false);
_tabPane.remove(_tabTrailingComponent);
}
_tabTrailingComponent = (Component) e.getNewValue();
if (_tabTrailingComponent != null) {
_tabPane.add(_tabTrailingComponent);
_tabTrailingComponent.setVisible(true);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.SHRINK_TAB_PROPERTY) ||
name.equals(JideTabbedPane.HIDE_IF_ONE_TAB_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_AREA_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_CONTENT_PROPERTY) ||
name.equals(JideTabbedPane.BOX_STYLE_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.TAB_CLOSABLE_PROPERTY) ||
name.equals(JideTabbedPane.PROPERTY_TAB_SHAPE) ||
name.equals(JideTabbedPane.PROPERTY_COLOR_THEME) ||
name.equals(JideTabbedPane.PROPERTY_TAB_RESIZE_MODE) ||
name.equals(JideTabbedPane.SHOW_TAB_BUTTONS_PROPERTY)) {
if ((name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY))
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
ensureCloseButtonCreated();
}
_tabPane.updateUI();
}
else if (name.equals("__index_to_remove__")) {
setVisibleComponent(null);
}
}
}
protected void updateCloseAction() {
ensureCloseButtonCreated();
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabSelectionHandler implements ChangeListener {
public void stateChanged(ChangeEvent e) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
ensureCloseButtonCreated();
Runnable runnable = new Runnable() {
public void run() {
ensureActiveTabIsVisible(false);
}
};
SwingUtilities.invokeLater(runnable);
}
}
public class TabFocusListener implements FocusListener {
public void focusGained(FocusEvent e) {
repaintSelectedTab();
}
public void focusLost(FocusEvent e) {
repaintSelectedTab();
}
private void repaintSelectedTab() {
if (_tabPane.getTabCount() > 0) {
Rectangle rect = getTabBounds(_tabPane, _tabPane.getSelectedIndex());
if (rect != null) {
_tabPane.repaint(rect);
}
}
}
}
public class MouseMotionHandler extends MouseMotionAdapter {
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class MouseHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isMiddleMouseButton(e)) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
Action action = getActionMap().get("closeTabAction");
if (action != null && tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex) && _tabPane.isCloseTabOnMouseMiddleButton() && _tabPane.isTabClosableAt(tabIndex)) {
ActionEvent event = new ActionEvent(_tabPane, tabIndex, "middleMouseButtonClicked");
action.actionPerformed(event);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isLeftMouseButton(e) || _tabPane.isRightClickSelect()) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
_tabPane.processMouseSelection(tabIndex, e);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else if (_tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
});
}
else {
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else {
// first try to find a default component.
boolean foundInTab = JideSwingUtilities.compositeRequestFocus(comp);
if (!foundInTab) { // && !_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
if (!isTabEditing())
startEditing(e); // start editing tab
}
}
public class MouseWheelHandler implements MouseWheelListener {
public void mouseWheelMoved(MouseWheelEvent e) {
if (_tabPane.isScrollSelectedTabOnWheel()) {
// set selected tab to the currently selected tab plus the wheel rotation but between
// 0 and tabCount-1
_tabPane.setSelectedIndex(
Math.min(_tabPane.getTabCount() - 1, Math.max(0, _tabPane.getSelectedIndex() + e.getWheelRotation())));
}
else if (scrollableTabLayoutEnabled() && e.getWheelRotation() != 0) {
if (e.getWheelRotation() > 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollForward(_tabPane.getTabPlacement());
}
}
else if (e.getWheelRotation() < 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollBackward(_tabPane.getTabPlacement());
}
}
}
}
}
private class ComponentHandler implements ComponentListener {
public void componentResized(ComponentEvent e) {
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
/* GES 2/3/99:
The container listener code was added to support HTML
rendering of tab titles.
Ideally, we would be able to listen for property changes
when a tab is added or its text modified. At the moment
there are no such events because the Beans spec doesn't
allow 'indexed' property changes (i.e. tab 2's text changed
from A to B).
In order to get around this, we listen for tabs to be added
or removed by listening for the container events. we then
queue up a runnable (so the component has a chance to complete
the add) which checks the tab title of the new component to see
if it requires HTML rendering.
The Views (one per tab title requiring HTML rendering) are
stored in the htmlViews Vector, which is only allocated after
the first time we run into an HTML tab. Note that this vector
is kept in step with the number of pages, and nulls are added
for those pages whose tab title do not require HTML rendering.
This makes it easy for the paint and layout code to tell
whether to invoke the HTML engine without having to check
the string during time-sensitive operations.
When we have added a way to listen for tab additions and
changes to tab text, this code should be removed and
replaced by something which uses that. */
private class ContainerHandler implements ContainerListener {
public void componentAdded(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
int index = tp.indexOfComponent(child);
String title = getCurrentDisplayTitleAt(tp, index);
boolean isHTML = BasicHTML.isHTMLString(title);
if (isHTML) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(tp, title);
htmlViews.insertElementAt(v, index);
}
}
else { // Not HTML
if (htmlViews != null) { // Add placeholder
htmlViews.insertElementAt(null, index);
} // else nada!
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
}
public void componentRemoved(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
// NOTE 4/15/2002 (joutwate):
// This fix is implemented using client properties since there is
// currently no IndexPropertyChangeEvent. Once
// IndexPropertyChangeEvents have been added this code should be
// modified to use it.
Integer index =
(Integer) tp.getClientProperty("__index_to_remove__");
if (index != null) {
if (htmlViews != null && htmlViews.size() > index) {
htmlViews.removeElementAt(index);
}
tp.putClientProperty("__index_to_remove__", null);
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
// ensureActiveTabIsVisible(true);
}
}
private Vector createHTMLVector() {
Vector htmlViews = new Vector();
int count = _tabPane.getTabCount();
if (count > 0) {
for (int i = 0; i < count; i++) {
String title = getCurrentDisplayTitleAt(_tabPane, i);
if (BasicHTML.isHTMLString(title)) {
htmlViews.addElement(BasicHTML.createHTMLView(_tabPane, title));
}
else {
htmlViews.addElement(null);
}
}
}
return htmlViews;
}
@Override
public Component getTabPanel() {
if (scrollableTabLayoutEnabled())
return _tabScroller.tabPanel;
else
return _tabPane;
}
static class AbstractTab {
int width;
int id;
public void copy(AbstractTab tab) {
this.width = tab.width;
this.id = tab.id;
}
}
public static class TabSpaceAllocator {
static final int startOffset = 4;
private Insets insets = null;
static final int tabWidth = 24;
static final int textIconGap = 8;
private AbstractTab tabs[];
private void setInsets(Insets insets) {
this.insets = (Insets) insets.clone();
}
private void init(Rectangle rects[], Insets insets) {
setInsets(insets);
tabs = new AbstractTab[rects.length];
// fill up internal datastructure
for (int i = 0; i < rects.length; i++) {
tabs[i] = new AbstractTab();
tabs[i].id = i;
tabs[i].width = rects[i].width;
}
tabSort();
}
private void bestfit(AbstractTab tabs[], int freeWidth, int startTab) {
int tabCount = tabs.length;
int worstWidth;
int currentTabWidth;
int initialPos;
currentTabWidth = tabs[startTab].width;
initialPos = startTab;
if (startTab == tabCount - 1) {
// directly fill as worst case
tabs[startTab].width = freeWidth;
return;
}
worstWidth = freeWidth / (tabCount - startTab);
while (currentTabWidth < worstWidth) {
freeWidth -= currentTabWidth;
if (++startTab < tabCount - 1) {
currentTabWidth = tabs[startTab].width;
}
else {
tabs[startTab].width = worstWidth;
return;
}
}
if (startTab == initialPos) {
// didn't find anything smaller
for (int i = startTab; i < tabCount; i++) {
tabs[i].width = worstWidth;
}
}
else if (startTab < tabCount - 1) {
bestfit(tabs, freeWidth, startTab);
}
}
// bubble sort for now
private void tabSort() {
int tabCount = tabs.length;
AbstractTab tempTab = new AbstractTab();
for (int i = 0; i < tabCount - 1; i++) {
for (int j = i + 1; j < tabCount; j++) {
if (tabs[i].width > tabs[j].width) {
tempTab.copy(tabs[j]);
tabs[j].copy(tabs[i]);
tabs[i].copy(tempTab);
}
}
}
}
// directly modify the rects
private void outpush(Rectangle rects[]) {
for (AbstractTab tab : tabs) {
rects[tab.id].width = tab.width;
}
rects[0].x = startOffset;
for (int i = 1; i < rects.length; i++) {
rects[i].x = rects[i - 1].x + rects[i - 1].width;
}
}
public void reArrange(Rectangle rects[], Insets insets, int totalAvailableSpace) {
init(rects, insets);
bestfit(tabs, totalAvailableSpace, 0);
outpush(rects);
clearup();
}
private void clearup() {
for (int i = 0; i < tabs.length; i++) {
tabs[i] = null;
}
tabs = null;
}
}
@Override
public void ensureActiveTabIsVisible(boolean scrollLeft) {
if (_tabPane == null || _tabPane.getWidth() == 0) {
return;
}
if (scrollableTabLayoutEnabled()) {
ensureCurrentLayout();
if (scrollLeft && _rects.length > 0) {
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
_tabScroller.tabPanel.scrollRectToVisible(_rects[0]);
}
else {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
}
int index = _tabPane.getSelectedIndex();
if ((!scrollLeft || index != 0) && index < _rects.length && index != -1) {
if (index == 0) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
else {
if (index == _rects.length - 1) { // last one, scroll to the end
Rectangle lastRect = _rects[index];
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && _tabPane.getComponentOrientation().isLeftToRight()) {
lastRect.width = _tabScroller.tabPanel.getWidth() - lastRect.x;
}
_tabScroller.tabPanel.scrollRectToVisible(lastRect);
}
else {
_tabScroller.tabPanel.scrollRectToVisible(_rects[index]);
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.tabPanel.getParent().doLayout();
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabPane.revalidate();
_tabPane.repaintTabAreaAndContentBorder();
}
else {
_tabPane.repaint();
}
}
}
protected boolean isShowCloseButtonOnTab() {
if (_tabPane.isUseDefaultShowCloseButtonOnTab()) {
return _showCloseButtonOnTab;
}
else return _tabPane.isShowCloseButtonOnTab();
}
protected boolean isShowCloseButton() {
return _tabPane.isShowCloseButton();
}
public void ensureCloseButtonCreated() {
if (isShowCloseButton() && isShowCloseButtonOnTab() && scrollableTabLayoutEnabled()) {
if (_closeButtons == null) {
_closeButtons = new TabCloseButton[_tabPane.getTabCount()];
}
else if (_closeButtons.length > _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0, temp.length);
for (int i = temp.length; i < _closeButtons.length; i++) {
TabCloseButton tabCloseButton = _closeButtons[i];
_tabScroller.tabPanel.remove(tabCloseButton);
}
_closeButtons = temp;
}
else if (_closeButtons.length < _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0,
_closeButtons.length);
_closeButtons = temp;
}
ActionMap am = getActionMap();
for (int i = 0; i < _closeButtons.length; i++) {
TabCloseButton closeButton = _closeButtons[i];
if (closeButton == null) {
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName("JideTabbedPane.close");
_closeButtons[i] = closeButton;
closeButton.setBounds(0, 0, 0, 0);
Action action = _tabPane.getCloseAction();
closeButton.setAction(am.get("closeTabAction"));
updateButtonFromAction(closeButton, action);
_tabScroller.tabPanel.add(closeButton);
}
closeButton.setIndex(i);
}
}
}
private void updateButtonFromAction(TabCloseButton closeButton, Action action) {
if (action == null) {
return;
}
closeButton.setEnabled(action.isEnabled());
Object desc = action.getValue(Action.SHORT_DESCRIPTION);
if (desc instanceof String) {
closeButton.setToolTipText((String) desc);
}
Object icon = action.getValue(Action.SMALL_ICON);
if (icon instanceof Icon) {
closeButton.setIcon((Icon) icon);
}
}
protected boolean isShowTabButtons() {
return _tabPane.getTabCount() != 0 && _tabPane.isShowTabArea() && _tabPane.isShowTabButtons();
}
protected boolean isShrinkTabs() {
return _tabPane.getTabCount() != 0 && _tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT;
}
protected TabEditor _tabEditor;
protected boolean _isEditing;
protected int _editingTab = -1;
protected String _oldValue;
protected String _oldPrefix;
protected String _oldPostfix;
// mtf - changed
protected Component _originalFocusComponent;
@Override
public boolean isTabEditing() {
return _isEditing;
}
protected TabEditor createDefaultTabEditor() {
final TabEditor editor = new TabEditor();
editor.getDocument().addDocumentListener(this);
editor.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
return true;
}
public boolean shouldYieldFocus(JComponent input) {
boolean shouldStopEditing = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
shouldStopEditing = _tabPane.getTabEditingValidator().alertIfInvalid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (shouldStopEditing && _tabPane != null && _tabPane.isTabEditing()) {
_tabPane.stopTabEditing();
}
return shouldStopEditing;
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_originalFocusComponent = e.getOppositeComponent();
}
@Override
public void focusLost(FocusEvent e) {
}
});
editor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editor.transferFocus();
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (_isEditing && (e.getKeyCode() == KeyEvent.VK_ESCAPE)) {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldValue);
}
_tabPane.cancelTabEditing();
}
}
});
editor.setFont(_tabPane.getFont());
return editor;
}
@Override
public void stopTabEditing() {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
cancelTabEditing();
}
@Override
public void cancelTabEditing() {
if (_tabEditor != null) {
_isEditing = false;
((Container) getTabPanel()).remove(_tabEditor);
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
Rectangle tabRect = _tabPane.getBoundsAt(_editingTab);
getTabPanel().repaint(tabRect.x, tabRect.y,
tabRect.width, tabRect.height);
}
else {
getTabPanel().repaint();
}
if (_originalFocusComponent != null)
_originalFocusComponent.requestFocus(); // InWindow();
else
_tabPane.requestFocusForVisibleComponent();
_editingTab = -1;
_oldValue = null;
_tabPane.doLayout();
}
}
@Override
public boolean editTabAt(int tabIndex) {
if (_isEditing) {
return false;
}
// _tabPane.popupSelectedIndex(tabIndex);
if (_tabEditor == null)
_tabEditor = createDefaultTabEditor();
if (_tabEditor != null) {
prepareEditor(_tabEditor, tabIndex);
((Container) getTabPanel()).add(_tabEditor);
resizeEditor(tabIndex);
_editingTab = tabIndex;
_isEditing = true;
_tabEditor.requestFocusInWindow();
_tabEditor.selectAll();
return true;
}
return false;
}
@Override
public int getEditingTabIndex() {
return _editingTab;
}
protected void prepareEditor(TabEditor e, int tabIndex) {
Font font;
if (_tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (_tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
e.setFont(font);
_oldValue = _tabPane.getTitleAt(tabIndex);
if (_oldValue.startsWith("<HTML>") && _oldValue.endsWith("/HTML>")) {
_oldPrefix = "<HTML>";
_oldPostfix = "</HTML>";
String title = _oldValue.substring("<HTML>".length(), _oldValue.length() - "</HTML>".length());
if (title.startsWith("<B>") && title.endsWith("/B>")) {
title = title.substring("<B>".length(), title.length() - "</B>".length());
_oldPrefix += "<B>";
_oldPostfix = "</B>" + _oldPostfix;
}
e.setText(title);
}
else {
_oldPrefix = "";
_oldPostfix = "";
e.setText(_oldValue);
}
e.selectAll();
e.setForeground(_tabPane.getForegroundAt(tabIndex));
}
protected Rectangle getTabsTextBoundsAt(int tabIndex) {
Rectangle tabRect = _tabPane.getBoundsAt(tabIndex);
Rectangle iconRect = new Rectangle(),
textRect = new Rectangle();
if (tabRect.width < 200) // random max size;
tabRect.width = 200;
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
while (title == null || title.length() < 3)
title += " ";
Icon icon = _tabPane.getIconForTab(tabIndex);
Font font = _tabPane.getFont();
if (tabIndex == _tabPane.getSelectedIndex() && _tabPane.isBoldActiveTab()) {
font = font.deriveFont(Font.BOLD);
}
SwingUtilities.layoutCompoundLabel(_tabPane, _tabPane.getGraphics().getFontMetrics(font), title, icon,
SwingUtilities.CENTER, SwingUtilities.CENTER,
SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect,
iconRect, textRect, icon == null ? 0 : _textIconGap);
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
iconRect.x = tabRect.x + _iconMargin;
textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding);
textRect.width += 2;
}
else {
iconRect.y = tabRect.y + _iconMargin;
textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding);
iconRect.x = tabRect.x + 2;
textRect.x = tabRect.x + 2;
textRect.height += 2;
}
return textRect;
}
private void updateTab() {
if (_isEditing) {
resizeEditor(getEditingTabIndex());
}
}
public void insertUpdate(DocumentEvent e) {
updateTab();
}
public void removeUpdate(DocumentEvent e) {
updateTab();
}
public void changedUpdate(DocumentEvent e) {
updateTab();
}
protected void resizeEditor(int tabIndex) {
// note - this should use the logic of label paint text so that the text overlays exactly.
Rectangle tabsTextBoundsAt = getTabsTextBoundsAt(tabIndex);
if (tabsTextBoundsAt.isEmpty()) {
tabsTextBoundsAt = new Rectangle(14, 3); // note - 14 should be the font height but...
}
tabsTextBoundsAt.x = tabsTextBoundsAt.x - _tabEditor.getBorder().getBorderInsets(_tabEditor).left;
tabsTextBoundsAt.width = +tabsTextBoundsAt.width +
_tabEditor.getBorder().getBorderInsets(_tabEditor).left +
_tabEditor.getBorder().getBorderInsets(_tabEditor).right;
tabsTextBoundsAt.y = tabsTextBoundsAt.y - _tabEditor.getBorder().getBorderInsets(_tabEditor).top;
tabsTextBoundsAt.height = tabsTextBoundsAt.height +
_tabEditor.getBorder().getBorderInsets(_tabEditor).top +
_tabEditor.getBorder().getBorderInsets(_tabEditor).bottom;
_tabEditor.setBounds(SwingUtilities.convertRectangle(_tabPane, tabsTextBoundsAt, getTabPanel()));
_tabEditor.invalidate();
_tabEditor.validate();
// getTabPanel().invalidate();
// getTabPanel().validate();
// getTabPanel().repaint();
// getTabPanel().doLayout();
_tabPane.doLayout();
// mtf - note - this is an exteme repaint but we need to paint any content borders
getTabPanel().getParent().getParent().repaint();
}
protected String getCurrentDisplayTitleAt(JideTabbedPane tp, int index) {
String returnTitle = tp.getDisplayTitleAt(index);
if ((_isEditing) && (index == _editingTab))
returnTitle = _tabEditor.getText();
return returnTitle;
}
protected class TabEditor extends JTextField implements UIResource {
TabEditor() {
setOpaque(false);
// setBorder(BorderFactory.createEmptyBorder());
setBorder(BorderFactory
.createCompoundBorder(new PartialLineBorder(Color.BLACK, 1, true),
BorderFactory.createEmptyBorder(0, 2, 0, 2)));
}
public boolean stopEditing() {
return true;
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Composite orgComposite = g2.getComposite();
Color orgColor = g2.getColor();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.70f));
Object o = JideSwingUtilities.setupShapeAntialiasing(g);
g2.setColor(getBackground());
g.fillRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 1, 1);
JideSwingUtilities.restoreShapeAntialiasing(g, o);
g2.setColor(orgColor);
g2.setComposite(orgComposite);
super.paintComponent(g);
}
}
public void startEditing(MouseEvent e) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (!e.isPopupTrigger() && tabIndex >= 0
&& _tabPane.isEnabledAt(tabIndex)
&& _tabPane.isTabEditingAllowed() && (e.getClickCount() == 2)) {
boolean shouldEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldEdit = _tabPane.getTabEditingValidator().shouldStartEdit(tabIndex, e);
if (shouldEdit) {
e.consume();
_tabPane.editTabAt(tabIndex);
}
}
if (e.getClickCount() == 1) {
if (_tabPane.isTabEditing()) {
boolean shouldStopEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldStopEdit = _tabPane.getTabEditingValidator().alertIfInvalid(tabIndex, _oldPrefix + _tabEditor.getText() + _oldPostfix);
if (shouldStopEdit)
_tabPane.stopTabEditing();
}
}
}
public ThemePainter getPainter() {
return _painter;
}
private class DragOverTimer extends Timer implements ActionListener {
private int _index;
private static final long serialVersionUID = -2529347876574638854L;
public DragOverTimer(int index) {
super(500, null);
_index = index;
addActionListener(this);
setRepeats(false);
}
public void actionPerformed(ActionEvent e) {
if (_tabPane.getTabCount() == 0) {
return;
}
if (_index == _tabPane.getSelectedIndex()) {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
_tabPane.repaint(getTabBounds(_tabPane, _index));
}
}
else {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
}
_tabPane.setSelectedIndex(_index);
}
stop();
}
}
private class DropListener implements DropTargetListener {
private DragOverTimer _timer;
int _index = -1;
public DropListener() {
}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
if (!_tabPane.isEnabled()) {
return;
}
int tabIndex = getTabAtLocation(dtde.getLocation().x, dtde.getLocation().y);
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex()) {
// selected already, do nothing
}
else if (tabIndex == _index) {
// same tab, timer has started
}
else {
stopTimer();
startTimer(tabIndex);
_index = tabIndex; // save the index
}
}
else {
stopTimer();
}
dtde.rejectDrag();
}
private void startTimer(int tabIndex) {
_timer = new DragOverTimer(tabIndex);
_timer.start();
}
private void stopTimer() {
if (_timer != null) {
_timer.stop();
_timer = null;
_index = -1;
}
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dte) {
stopTimer();
}
public void drop(DropTargetDropEvent dtde) {
stopTimer();
}
}
protected void paintFocusIndicator(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect,
boolean isSelected) {
Rectangle tabRect = new Rectangle(rects[tabIndex]);
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
tabRect.x += _tabScroller.viewport.getExpectedViewX();
}
if (_tabPane.hasFocus() && isSelected) {
int x, y, w, h;
g.setColor(_focus);
switch (tabPlacement) {
case LEFT:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case RIGHT:
x = tabRect.x + 2;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case BOTTOM:
x = tabRect.x + 3;
y = tabRect.y + 2;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
break;
case TOP:
default:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
}
BasicGraphicsUtils.drawDashedRect(g, x, y, w, h);
}
}
protected boolean isRoundedCorner() {
return "true".equals(SecurityUtils.getProperty("shadingtheme", "false"));
}
protected int getTabShape() {
return _tabPane.getTabShape();
}
protected int getTabResizeMode() {
return _tabPane.getTabResizeMode();
}
protected int getColorTheme() {
return _tabPane.getColorTheme();
}
// for debug purpose
final protected boolean PAINT_TAB = true;
final protected boolean PAINT_TAB_BORDER = true;
final protected boolean PAINT_TAB_BACKGROUND = true;
final protected boolean PAINT_TABAREA = true;
final protected boolean PAINT_CONTENT_BORDER = true;
final protected boolean PAINT_CONTENT_BORDER_EDGE = true;
protected int getLeftMargin() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return OFFICE2003_LEFT_MARGIN;
}
else if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else {
return DEFAULT_LEFT_MARGIN;
}
}
protected int getTabGap() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return 4;
}
else {
return 0;
}
}
protected int getLayoutSize() {
int tabShape = getTabShape();
if (tabShape == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else if (tabShape == JideTabbedPane.SHAPE_ECLIPSE3X) {
return 15;
}
else if (_tabPane.getTabShape() == JideTabbedPane.SHAPE_FLAT || _tabPane.getTabShape() == JideTabbedPane.SHAPE_ROUNDED_FLAT) {
return 2;
}
else if (tabShape == JideTabbedPane.SHAPE_WINDOWS
|| tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return 6;
}
else {
return 0;
}
}
protected int getTabRightPadding() {
if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return 4;
}
else {
return 0;
}
}
protected MouseListener createMouseListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseHandler();
}
else {
return new MouseHandler();
}
}
protected MouseWheelListener createMouseWheelListener() {
return new MouseWheelHandler();
}
protected MouseMotionListener createMouseMotionListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseMotionHandler();
}
else {
return new MouseMotionHandler();
}
}
public class DefaultMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class DefaultMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
}
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
public class RolloverMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class RolloverMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
protected boolean isTabLeadingComponentVisible() {
return _tabPane.isTabShown() && _tabLeadingComponent != null && _tabLeadingComponent.isVisible();
}
protected boolean isTabTrailingComponentVisible() {
return _tabPane.isTabShown() && _tabTrailingComponent != null && _tabTrailingComponent.isVisible();
}
protected boolean isTabTopVisible(int tabPlacement) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement));
case TOP:
case BOTTOM:
default:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement));
}
}
protected boolean showFocusIndicator() {
return _tabPane.hasFocusComponent() && _showFocusIndicator;
}
private int getNumberOfTabButtons() {
int numberOfButtons = (!isShowTabButtons() || isShrinkTabs()) ? 1 : 4;
if (!isShowCloseButton() || isShowCloseButtonOnTab()) {
numberOfButtons--;
}
return numberOfButtons;
}
/**
* Gets the resource string used in DocumentPane. Subclass can override it to provide their own strings.
*
* @param key the resource key
* @return the localized string.
*/
protected String getResourceString(String key) {
return Resource.getResourceBundle(_tabPane != null ? _tabPane.getLocale() : Locale.getDefault()).getString(key);
}
}
| protected boolean requestFocusForVisibleComponent() {
Component visibleComponent = getVisibleComponent();
Component lastFocused = _tabPane.getLastFocusedComponent(visibleComponent);
if (lastFocused != null && lastFocused.requestFocusInWindow()) {
return true;
}
else if (visibleComponent != null && JideSwingUtilities.passesFocusabilityTest(visibleComponent)) { // visibleComponent.isFocusTraversable()) {
JideSwingUtilities.compositeRequestFocus(visibleComponent);
return true;
}
else if (visibleComponent instanceof JComponent) {
if (((JComponent) visibleComponent).requestDefaultFocus()) {
return true;
}
}
return false;
}
private static class RightAction extends AbstractAction {
private static final long serialVersionUID = -1759791760116532857L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(EAST);
}
}
private static class LeftAction extends AbstractAction {
private static final long serialVersionUID = 8670680299012169408L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(WEST);
}
}
private static class UpAction extends AbstractAction {
private static final long serialVersionUID = -6961702501242792445L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NORTH);
}
}
private static class DownAction extends AbstractAction {
private static final long serialVersionUID = -453174268282628886L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(SOUTH);
}
}
private static class NextAction extends AbstractAction {
private static final long serialVersionUID = -154035573464933924L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NEXT);
}
}
private static class PreviousAction extends AbstractAction {
private static final long serialVersionUID = 2095403667386334865L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(PREVIOUS);
}
}
private static class PageUpAction extends AbstractAction {
private static final long serialVersionUID = 1154273528778779166L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(WEST);
}
else {
ui.navigateSelectedTab(NORTH);
}
}
}
private static class PageDownAction extends AbstractAction {
private static final long serialVersionUID = 4895454480954468453L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(EAST);
}
else {
ui.navigateSelectedTab(SOUTH);
}
}
}
private static class RequestFocusAction extends AbstractAction {
private static final long serialVersionUID = 3791111435639724577L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (!pane.requestFocusInWindow()) {
pane.requestFocus();
}
}
}
private static class RequestFocusForVisibleAction extends AbstractAction {
private static final long serialVersionUID = 6677797853998039155L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.requestFocusForVisibleComponent();
}
}
/**
* Selects a tab in the JTabbedPane based on the String of the action command. The tab selected is based on the
* first tab that has a mnemonic matching the first character of the action command.
*/
private static class SetSelectedIndexAction extends AbstractAction {
private static final long serialVersionUID = 6216635910156115469L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (pane != null && (pane.getUI() instanceof BasicJideTabbedPaneUI)) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
String command = e.getActionCommand();
if (command != null && command.length() > 0) {
int mnemonic = (int) e.getActionCommand().charAt(0);
if (mnemonic >= 'a' && mnemonic <= 'z') {
mnemonic -= ('a' - 'A');
}
Integer index = (Integer) ui._mnemonicToIndexMap
.get(new Integer(mnemonic));
if (index != null && pane.isEnabledAt(index)) {
pane.setSelectedIndex(index);
}
}
}
}
}
protected TabCloseButton createNoFocusButton(int type) {
return new TabCloseButton(type);
}
private static class ScrollTabsForwardAction extends AbstractAction {
private static final long serialVersionUID = 8772616556895545931L;
public ScrollTabsForwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollForward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollForward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsBackwardAction extends AbstractAction {
private static final long serialVersionUID = -426408621939940046L;
public ScrollTabsBackwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollBackward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollBackward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsListAction extends AbstractAction {
private static final long serialVersionUID = 246103712600916771L;
public ScrollTabsListAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.showList"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
if (ui._tabScroller._popup != null && ui._tabScroller._popup.isPopupVisible()) {
ui._tabScroller._popup.hidePopupImmediately();
ui._tabScroller._popup = null;
}
else {
ui._tabScroller.createPopup(pane.getTabPlacement());
}
}
}
}
}
protected void stopOrCancelEditing() {
boolean isEditValid = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
isEditValid = _tabPane.getTabEditingValidator().isValid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (isEditValid)
_tabPane.stopTabEditing();
else
_tabPane.cancelTabEditing();
}
private static class CloseTabAction extends AbstractAction {
private static final long serialVersionUID = 7779678389793199733L;
public CloseTabAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.close"));
}
public void actionPerformed(ActionEvent e) {
JideTabbedPane pane;
Object src = e.getSource();
int index;
boolean closeSelected = false;
if (src instanceof JideTabbedPane) {
pane = (JideTabbedPane) src;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof JideTabbedPane) {
pane = (JideTabbedPane) ((TabCloseButton) src).getParent();
closeSelected = true;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof ScrollableTabPanel) {
pane = (JideTabbedPane) SwingUtilities.getAncestorOfClass(JideTabbedPane.class, (TabCloseButton) src);
closeSelected = false;
}
else {
return; // shouldn't happen
}
if (pane.isTabEditing()) {
((BasicJideTabbedPaneUI) pane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
}
ActionEvent e2 = e;
if (src instanceof TabCloseButton) {
index = ((TabCloseButton) src).getIndex();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
else if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
if (pane.getCloseAction() != null) {
pane.getCloseAction().actionPerformed(e2);
}
else {
if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
if (index >= 0)
pane.removeTabAt(index);
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else if (closeSelected) {
if (pane.getSelectedIndex() >= 0)
pane.removeTabAt(pane.getSelectedIndex());
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else {
int i = ((TabCloseButton) src).getIndex();
if (i != -1) {
int tabIndex = pane.getSelectedIndex();
pane.removeTabAt(i);
if (i < tabIndex) {
pane.setSelectedIndex(tabIndex - 1);
}
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
}
}
}
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabbedPaneLayout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
return calculateSize(false);
}
public Dimension minimumLayoutSize(Container parent) {
return calculateSize(true);
}
protected Dimension calculateSize(boolean minimum) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
Insets contentInsets = getContentBorderInsets(tabPlacement);
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
Dimension zeroSize = new Dimension(0, 0);
int height = contentInsets.top + contentInsets.bottom;
int width = contentInsets.left + contentInsets.right;
int cWidth = 0;
int cHeight = 0;
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
// Determine minimum size required to display largest
// child in each dimension
//
if (_tabPane.isShowTabContent()) {
for (int i = 0; i < _tabPane.getTabCount(); i++) {
Component component = _tabPane.getComponentAt(i);
if (component != null) {
Dimension size = zeroSize;
size = minimum ? component.getMinimumSize() :
component.getPreferredSize();
if (size != null) {
cHeight = Math.max(size.height, cHeight);
cWidth = Math.max(size.width, cWidth);
}
}
}
// Add content border insets to minimum size
width += cWidth;
height += cHeight;
}
int tabExtent;
// Calculate how much space the tabs will need, based on the
// minimum size required to display largest child + content border
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
height = Math.max(height, (minimum ? 0 : calculateMaxTabHeight(tabPlacement)) + tabAreaInsets.top + tabAreaInsets.bottom);
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.width, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.width, tabExtent);
}
width += tabExtent;
break;
case TOP:
case BOTTOM:
default:
if (_tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {
width = Math.max(width, (_tabPane.getTabCount() << 2) +
tabAreaInsets.left + tabAreaInsets.right);
}
else {
width = Math.max(width, (minimum ? 0 : calculateMaxTabWidth(tabPlacement)) +
tabAreaInsets.left + tabAreaInsets.right);
}
if (_tabPane.isTabShown()) {
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.height, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.height, tabExtent);
}
height += tabExtent;
}
}
}
return new Dimension(width + insets.left + insets.right,
height + insets.bottom + insets.top);
}
protected int preferredTabAreaHeight(int tabPlacement, int width) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int rows = 1;
int x = 0;
int maxTabHeight = calculateMaxTabHeight(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabWidth = calculateTabWidth(tabPlacement, i, metrics);
if (x != 0 && x + tabWidth > width) {
rows++;
x = 0;
}
x += tabWidth;
}
total = calculateTabAreaHeight(tabPlacement, rows, maxTabHeight);
}
return total;
}
protected int preferredTabAreaWidth(int tabPlacement, int height) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int columns = 1;
int y = 0;
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabHeight = calculateTabHeight(tabPlacement, i, metrics);
if (y != 0 && y + tabHeight > height) {
columns++;
y = 0;
}
y += tabHeight;
}
total = calculateTabAreaWidth(tabPlacement, columns, _maxTabWidth);
}
return total;
}
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
int cx, cy, cw, ch;
int totalTabWidth = 0;
int totalTabHeight = 0;
Insets contentInsets = getContentBorderInsets(tabPlacement);
Component selectedComponent = _tabPane.getComponentAt(selectedIndex);
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + totalTabWidth + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case RIGHT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case BOTTOM:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case TOP:
default:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + totalTabHeight + contentInsets.top;
}
cw = bounds.width - totalTabWidth -
insets.left - insets.right -
contentInsets.left - contentInsets.right;
ch = bounds.height - totalTabHeight -
insets.top - insets.bottom -
contentInsets.top - contentInsets.bottom;
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
child.setBounds(cx, cy, cw, ch);
}
}
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
public void calculateLayoutInfo() {
int tabCount = _tabPane.getTabCount();
assureRectsCreated(tabCount);
calculateTabRects(_tabPane.getTabPlacement(), tabCount);
}
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int selectedIndex = _tabPane.getSelectedIndex();
int tabRunOverlay;
int i, j;
int x, y;
int returnAt;
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
//
// Calculate bounds within which a tab run must fit
//
switch (tabPlacement) {
case LEFT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = size.width - insets.right - tabAreaInsets.right - _maxTabWidth;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case BOTTOM:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = size.height - insets.bottom - tabAreaInsets.bottom - _maxTabHeight;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
}
tabRunOverlay = getTabRunOverlay(tabPlacement);
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
// Run through tabs and partition them into runs
Rectangle rect;
for (i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabWidth = 0;
rect.x = x;
}
rect.width = calculateTabWidth(tabPlacement, i, metrics);
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
// Never move a TAB down a run if it is in the first column.
// Even if there isn't enough room, moving it to a fresh
// line won't help.
if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.x = x;
}
// Initialize y position in case there's just one run
rect.y = y;
rect.height = _maxTabHeight/* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabHeight = 0;
rect.y = y;
}
rect.height = calculateTabHeight(tabPlacement, i, metrics);
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
// Never move a TAB over a run if it is in the first run.
// Even if there isn't enough room, moving it to a fresh
// column won't help.
if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.y = y;
}
// Initialize x position in case there's just one column
rect.x = x;
rect.width = _maxTabWidth/* - 2 */;
}
if (i == selectedIndex) {
_selectedRun = _runCount - 1;
}
}
if (_runCount > 1) {
// Re-distribute tabs in case last run has leftover space
normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns ? y : x, returnAt);
_selectedRun = getRunForTab(tabCount, selectedIndex);
// Rotate run array so that selected run is first
if (shouldRotateTabRuns(tabPlacement)) {
rotateTabRuns(tabPlacement, _selectedRun);
}
}
// Step through runs from back to front to calculate
// tab y locations and to pad runs appropriately
for (i = _runCount - 1; i >= 0; i--) {
int start = _tabRuns[i];
int next = _tabRuns[i == (_runCount - 1) ? 0 : i + 1];
int end = (next != 0 ? next - 1 : tabCount - 1);
if (!verticalTabRuns) {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.y = y;
rect.x += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == BOTTOM) {
y -= (_maxTabHeight - tabRunOverlay);
}
else {
y += (_maxTabHeight - tabRunOverlay);
}
}
else {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.x = x;
rect.y += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == RIGHT) {
x -= (_maxTabWidth - tabRunOverlay);
}
else {
x += (_maxTabWidth - tabRunOverlay);
}
}
}
// Pad the selected tab so that it appears raised in front
padSelectedTab(tabPlacement, selectedIndex);
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right);
for (i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width;
}
}
}
/*
* Rotates the run-index array so that the selected run is run[0]
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void rotateTabRuns(int tabPlacement, int selectedRun) {
for (int i = 0; i < selectedRun; i++) {
int save = _tabRuns[0];
for (int j = 1; j < _runCount; j++) {
_tabRuns[j - 1] = _tabRuns[j];
}
_tabRuns[_runCount - 1] = save;
}
}
protected void normalizeTabRuns(int tabPlacement, int tabCount,
int start, int max) {
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
int run = _runCount - 1;
boolean keepAdjusting = true;
double weight = 1.25;
// At this point the tab runs are packed to fit as many
// tabs as possible, which can leave the last run with a lot
// of extra space (resulting in very fat tabs on the last run).
// So we'll attempt to distribute this extra space more evenly
// across the runs in order to make the runs look more consistent.
//
// Starting with the last run, determine whether the last tab in
// the previous run would fit (generously) in this run; if so,
// move tab to current run and shift tabs accordingly. Cycle
// through remaining runs using the same algorithm.
//
while (keepAdjusting) {
int last = lastTabInRun(tabCount, run);
int prevLast = lastTabInRun(tabCount, run - 1);
int end;
int prevLastLen;
if (!verticalTabRuns) {
end = _rects[last].x + _rects[last].width;
prevLastLen = (int) (_maxTabWidth * weight);
}
else {
end = _rects[last].y + _rects[last].height;
prevLastLen = (int) (_maxTabHeight * weight * 2);
}
// Check if the run has enough extra space to fit the last tab
// from the previous row...
if (max - end > prevLastLen) {
// Insert tab from previous row and shift rest over
_tabRuns[run] = prevLast;
if (!verticalTabRuns) {
_rects[prevLast].x = start;
}
else {
_rects[prevLast].y = start;
}
for (int i = prevLast + 1; i <= last; i++) {
if (!verticalTabRuns) {
_rects[i].x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_rects[i].y = _rects[i - 1].y + _rects[i - 1].height;
}
}
}
else if (run == _runCount - 1) {
// no more room left in last run, so we're done!
keepAdjusting = false;
}
if (run - 1 > 0) {
// check previous run next...
run -= 1;
}
else {
// check last run again...but require a higher ratio
// of extraspace-to-tabsize because we don't want to
// end up with too many tabs on the last run!
run = _runCount - 1;
weight += .25;
}
}
}
protected void padTabRun(int tabPlacement, int start, int end, int max) {
Rectangle lastRect = _rects[end];
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int runWidth = (lastRect.x + lastRect.width) - _rects[start].x;
int deltaWidth = max - (lastRect.x + lastRect.width);
float factor = (float) deltaWidth / (float) runWidth;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.x = _rects[j - 1].x + _rects[j - 1].width;
}
pastRect.width += Math.round((float) pastRect.width * factor);
}
lastRect.width = max - lastRect.x;
}
else {
int runHeight = (lastRect.y + lastRect.height) - _rects[start].y;
int deltaHeight = max - (lastRect.y + lastRect.height);
float factor = (float) deltaHeight / (float) runHeight;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.y = _rects[j - 1].y + _rects[j - 1].height;
}
pastRect.height += Math.round((float) pastRect.height * factor);
}
lastRect.height = max - lastRect.y;
}
}
protected void padSelectedTab(int tabPlacement, int selectedIndex) {
if (selectedIndex >= 0) {
Rectangle selRect = _rects[selectedIndex];
Insets padInsets = getSelectedTabPadInsets(tabPlacement);
selRect.x -= padInsets.left;
selRect.width += (padInsets.left + padInsets.right);
selRect.y -= padInsets.top;
selRect.height += (padInsets.top + padInsets.bottom);
}
}
}
protected TabSpaceAllocator tryTabSpacer = new TabSpaceAllocator();
protected class TabbedPaneScrollLayout extends TabbedPaneLayout {
@Override
protected int preferredTabAreaHeight(int tabPlacement, int width) {
return calculateMaxTabHeight(tabPlacement);
}
@Override
protected int preferredTabAreaWidth(int tabPlacement, int height) {
return calculateMaxTabWidth(tabPlacement);
}
@Override
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
JViewport viewport = null;
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
int tx, ty, tw, th; // tab area bounds
int cx, cy, cw, ch; // content area bounds
Insets contentInsets = getContentBorderInsets(tabPlacement);
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = insets.left;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
}
}
// calculate content area bounds
cx = tx + tw + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case RIGHT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount,
_maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = bounds.width - insets.right - tw;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
tx = bounds.width - insets.right - tw;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
tx = bounds.width - insets.right - tw;
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case BOTTOM:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = bounds.height - insets.bottom - th;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
break;
case TOP:
default:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = insets.top;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + th + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
}
// if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (tw < _rects[0].width + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
// else {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (th < _rects[0].height + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
if (child instanceof ScrollableTabViewport) {
viewport = (JViewport) child;
// Rectangle viewRect = viewport.getViewRect();
int vw = tw;
int vh = th;
int numberOfButtons = getNumberOfTabButtons();
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (totalTabHeight > th || isShowTabButtons()) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
// if (totalTabHeight - viewRect.y <= vh) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vh = totalTabHeight - viewRect.y;
// }
}
else {
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
}
if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) {
vh += getLayoutSize();
}
break;
case BOTTOM:
case TOP:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (isShowTabButtons() || !widthEnough) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Need to allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
// if (totalTabWidth - viewRect.x <= vw) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vw = totalTabWidth - viewRect.x;
// }
}
else {
// Allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
}
if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) {
vw += getLayoutSize();
if (!leftToRight) {
tx -= getLayoutSize();
}
}
break;
}
child.setBounds(tx, ty, vw, vh);
}
else if (child instanceof TabCloseButton) {
TabCloseButton scrollbutton = (TabCloseButton) child;
if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) {
Dimension bsize = scrollbutton.getPreferredSize();
int bx = 0;
int by = 0;
int bw = bsize.width;
int bh = bsize.height;
boolean visible = false;
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) {
int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
}
bx = tx + 2;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
bx = tx + 2;
}
}
if (isTabTrailingComponentVisible()) {
by = by - tsize.height;
}
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.width >= _rects[0].width) {
if (tabPlacement == LEFT) {
bx += lsize.width - _rects[0].width;
temp = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.width >= _rects[0].width
&& temp < tsize.width) {
if (tabPlacement == LEFT) {
bx += tsize.width - _rects[0].width;
}
}
}
break;
case TOP:
case BOTTOM:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (_tabPane.isTabShown() && (isShowTabButtons() || !widthEnough)) {
int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON
// NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
bx = insets.left - 5;
}
}
else {
visible = false;
bx = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (1 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
}
by = ((th - bsize.height) >> 1) + ty;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
visible = false;
bx = 0;
}
by = ((th - bsize.height) >> 1) + ty;
}
}
if (isTabTrailingComponentVisible()) {
bx -= tsize.width;
}
temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.height >= _rects[0].height) {
if (tabPlacement == TOP) {
by = ty + 2 + lsize.height - _rects[0].height;
temp = lsize.height;
}
else {
by = ty + 2;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.height >= _rects[0].height
&& temp < tsize.height) {
if (tabPlacement == TOP) {
by = ty + 2 + tsize.height - _rects[0].height;
}
else {
by = ty + 2;
}
}
}
}
child.setVisible(visible);
if (visible) {
child.setBounds(bx, by, bw, bh);
}
}
else {
scrollbutton.setBounds(0, 0, 0, 0);
}
}
else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) {
if (_tabPane.isShowTabContent()) {
// All content children...
child.setBounds(cx, cy, cw, ch);
}
else {
child.setBounds(0, 0, 0, 0);
}
}
}
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
}
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
if (!leftToRight && !verticalTabRuns && viewport != null && !viewport.getSize().equals(_tabPane.getSize())) {
int offset = _tabPane.getWidth() - viewport.getWidth();
for (Rectangle rect : _rects) {
rect.x -= offset;
}
}
updateCloseButtons();
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
@Override
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
int x = tabAreaInsets.left;
int y = tabAreaInsets.top;
//
// Calculate bounds within which a tab run must fit
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < lsize.width) {
_maxTabWidth = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < tsize.width) {
_maxTabWidth = tsize.width;
}
}
}
break;
case BOTTOM:
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < lsize.height) {
_maxTabHeight = lsize.height;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < tsize.height) {
_maxTabHeight = tsize.height;
}
}
}
}
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
_selectedRun = 0;
_runCount = 1;
// Run through tabs and lay them out in a single run
Rectangle rect;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_maxTabWidth = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.x = x + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.x = x;
}
}
rect.width = calculateTabWidth(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
rect.y = y;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < lsize.height) {
rect.y = y + lsize.height - _maxTabHeight - 2;
temp = lsize.height;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < tsize.height
&& temp < tsize.height) {
rect.y = y + tsize.height - _maxTabHeight - 2;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
rect.height = calculateMaxTabHeight(tabPlacement);///* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_maxTabHeight = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.y = y + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.y = y;
}
}
rect.height = calculateTabHeight(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
rect.x = x;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < lsize.width) {
rect.x = x + lsize.width - _maxTabWidth - 2;
temp = lsize.width;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < tsize.width
&& temp < tsize.width) {
rect.x = x + tsize.width - _maxTabWidth - 2;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
rect.width = calculateMaxTabWidth(tabPlacement)/* - 2 */;
}
}
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right) - _tabScroller.viewport.getLocation().x;
if (isTabLeadingComponentVisible()) {
rightMargin -= lsize.width;
}
int offset = 0;
if (isTabTrailingComponentVisible()) {
offset += tsize.width;
}
for (int i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width - offset + tabAreaInsets.left;
// if(i == tabCount - 1) {
// _rects[i].width += getLeftMargin();
// _rects[i].x -= getLeftMargin();
// }
}
}
ensureCurrentRects(getLeftMargin(), tabCount);
}
}
protected void ensureCurrentRects(int leftMargin, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
int totalWidth = 0;
int totalHeight = 0;
boolean verticalTabRuns = (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT);
boolean ltr = _tabPane.getComponentOrientation().isLeftToRight();
if (tabCount == 0) {
return;
}
Rectangle r = _rects[tabCount - 1];
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (verticalTabRuns) {
totalHeight = r.y + r.height;
if (_tabLeadingComponent != null) {
totalHeight -= lsize.height;
}
}
else {
// totalWidth = r.x + r.width;
for (Rectangle rect : _rects) {
totalWidth += rect.width;
}
if (ltr) {
totalWidth += _rects[0].x;
}
else {
totalWidth += size.width - _rects[0].x - _rects[0].width - _tabScroller.viewport.getLocation().x;
}
if (_tabLeadingComponent != null) {
totalWidth -= lsize.width;
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {// LayOut Style is Size to Fix
if (verticalTabRuns) {
int availHeight;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom - leftMargin - getTabRightPadding();// give the first tab extra space
}
else {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom;
}
if (_tabPane.isShowCloseButton()) {
availHeight -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availHeight = availHeight - lsize.height;
}
if (isTabTrailingComponentVisible()) {
availHeight = availHeight - tsize.height;
}
int numberOfButtons = getNumberOfTabButtons();
availHeight -= _buttonSize * numberOfButtons;
if (totalHeight > availHeight) { // shrink is necessary
// calculate each tab width
int tabHeight = availHeight / tabCount;
totalHeight = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
_rects[k].height = tabHeight;
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
tabRect.y = totalHeight + leftMargin;// give the first tab extra space
}
else {
tabRect.y = totalHeight;
}
totalHeight += tabRect.height;
}
}
}
else {
int availWidth;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right - leftMargin - getTabRightPadding();
}
else {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right;
}
if (_tabPane.isShowCloseButton()) {
availWidth -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availWidth -= lsize.width;
}
if (isTabTrailingComponentVisible()) {
availWidth -= tsize.width;
}
int numberOfButtons = getNumberOfTabButtons();
availWidth -= _buttonSize * numberOfButtons;
if (totalWidth > availWidth) { // shrink is necessary
// calculate each tab width
int tabWidth = availWidth / tabCount;
int gripperWidth = _tabPane.isShowGripper() ? _gripperWidth
: 0;
if (tabWidth < _textIconGap + _fitStyleTextMinWidth
+ _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleIconMinWidth + gripperWidth) // cannot
// hold any text but can hold an icon
tabWidth = _fitStyleIconMinWidth + gripperWidth;
if (tabWidth < _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleFirstTabMargin + gripperWidth) // cannot
// hold any icon but gripper
tabWidth = _fitStyleFirstTabMargin + gripperWidth;
tryTabSpacer.reArrange(_rects, insets, availWidth);
}
totalWidth = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
if (ltr) {
tabRect.x = totalWidth + leftMargin;// give the first tab extra space when the style is not box style
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width + leftMargin;// give the first tab extra space when the style is not box style
}
}
else {
if (ltr) {
tabRect.x = totalWidth;
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width;
}
}
totalWidth += tabRect.width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIXED) {// LayOut Style is Fix
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
_rects[k].height = _fixedStyleRectSize;// + _rectSizeExtend * 2;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].height += _closeButtons[k].getPreferredSize().height;
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
_rects[k].width = _fixedStyleRectSize;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].width += _closeButtons[k].getPreferredSize().width;
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED) {// LayOut Style is Compressed
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab() && !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].height = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].height = icon.getIconHeight() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].height = _rects[k].height + _closeButtons[k].getPreferredSize().height + _compressedStyleCloseButtonMarginVertical;
}
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab()
&& !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].width = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].width = icon.getIconWidth() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].width = _rects[k].width + _closeButtons[k].getPreferredSize().width + _compressedStyleCloseButtonMarginHorizon;
}
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
totalWidth += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalWidth += lsize.width;
}
}
else {
totalHeight += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalHeight += tsize.height;
}
}
_tabScroller.tabPanel.setPreferredSize(new Dimension(totalWidth, totalHeight));
}
protected class ActivateTabAction extends AbstractAction {
int _tabIndex;
private static final long serialVersionUID = 3270152106579039554L;
public ActivateTabAction(String name, Icon icon, int tabIndex) {
super(name, icon);
_tabIndex = tabIndex;
}
public void actionPerformed(ActionEvent e) {
_tabPane.setSelectedIndex(_tabIndex);
}
}
protected ListCellRenderer getTabListCellRenderer() {
return _tabPane.getTabListCellRenderer();
}
public class ScrollableTabSupport implements ChangeListener {
public ScrollableTabViewport viewport;
public ScrollableTabPanel tabPanel;
public TabCloseButton scrollForwardButton;
public TabCloseButton scrollBackwardButton;
public TabCloseButton listButton;
public TabCloseButton closeButton;
public int leadingTabIndex;
private Point tabViewPosition = new Point(0, 0);
public JidePopup _popup;
@SuppressWarnings({"UnusedDeclaration"})
ScrollableTabSupport(int tabPlacement) {
viewport = new ScrollableTabViewport();
tabPanel = new ScrollableTabPanel();
viewport.setView(tabPanel);
viewport.addChangeListener(this);
scrollForwardButton = createNoFocusButton(TabCloseButton.EAST_BUTTON);
scrollForwardButton.setName(BUTTON_NAME_SCROLL_FORWARD);
scrollBackwardButton = createNoFocusButton(TabCloseButton.WEST_BUTTON);
scrollBackwardButton.setName(BUTTON_NAME_SCROLL_BACKWARD);
scrollForwardButton.setBackground(viewport.getBackground());
scrollBackwardButton.setBackground(viewport.getBackground());
listButton = createNoFocusButton(TabCloseButton.LIST_BUTTON);
listButton.setName(BUTTON_NAME_TAB_LIST);
listButton.setBackground(viewport.getBackground());
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName(BUTTON_NAME_CLOSE);
closeButton.setBackground(viewport.getBackground());
}
public void createPopupMenu(int tabPlacement) {
JPopupMenu popup = new JPopupMenu();
int totalCount = _tabPane.getTabCount();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
for (int i = 0; i < totalCount; i++) {
if (_tabPane.isEnabledAt(i)) {
JMenuItem item;
popup.add(item = new JCheckBoxMenuItem(new ActivateTabAction(_tabPane.getTitleAt(i), _tabPane.getIconForTab(i), i)));
item.setToolTipText(_tabPane.getToolTipTextAt(i));
item.setSelected(selectedIndex == i);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
}
}
Dimension preferredSize = popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
switch (tabPlacement) {
case TOP:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y + bounds.height);
break;
case BOTTOM:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y - preferredSize.height);
break;
case LEFT:
popup.show(_tabPane, bounds.x + bounds.width, bounds.y + bounds.height - preferredSize.height);
break;
case RIGHT:
popup.show(_tabPane, bounds.x - preferredSize.width, bounds.y + bounds.height - preferredSize.height);
break;
}
}
public void createPopup(int tabPlacement) {
final JList list = new JList() {
// override this method to disallow deselect by ctrl-click
@Override
public void removeSelectionInterval(int index0, int index1) {
super.removeSelectionInterval(index0, index1);
if (getSelectedIndex() == -1) {
setSelectedIndex(index0);
}
}
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension preferredScrollableViewportSize = super.getPreferredScrollableViewportSize();
if (preferredScrollableViewportSize.width < 150) {
preferredScrollableViewportSize.width = 150;
}
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredScrollableViewportSize.width >= screenWidth) {
preferredScrollableViewportSize.width = screenWidth;
}
return preferredScrollableViewportSize;
}
@Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredSize.width >= screenWidth) {
preferredSize.width = screenWidth;
}
return preferredSize;
}
};
new Sticky(list);
list.setBackground(_tabListBackground);
JScrollPane scroller = new JScrollPane(list);
scroller.setBorder(BorderFactory.createEmptyBorder());
scroller.getViewport().setOpaque(false);
scroller.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(_tabListBackground);
panel.setOpaque(true);
panel.add(scroller);
panel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
if (_popup != null) {
if (_popup.isPopupVisible()) {
_popup.hidePopupImmediately();
}
_popup = null;
}
_popup = com.jidesoft.popup.JidePopupFactory.getSharedInstance().createPopup();
_popup.setPopupBorder(BorderFactory.createLineBorder(_darkShadow));
_popup.add(panel);
_popup.addExcludedComponent(listButton);
_popup.setDefaultFocusComponent(list);
DefaultListModel listModel = new DefaultListModel();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
int totalCount = _tabPane.getTabCount();
for (int i = 0; i < totalCount; i++) {
listModel.addElement(_tabPane);
}
list.setCellRenderer(getTabListCellRenderer());
list.setModel(listModel);
list.setSelectedIndex(selectedIndex);
list.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
componentSelected(list);
}
}
public void keyReleased(KeyEvent e) {
}
});
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
componentSelected(list);
}
});
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Insets insets = panel.getInsets();
int max = (PortingUtils.getLocalScreenSize(_tabPane).height - insets.top - insets.bottom) / list.getCellBounds(0, 0).height;
if (listModel.getSize() > max) {
list.setVisibleRowCount(max);
}
else {
list.setVisibleRowCount(listModel.getSize());
}
_popup.setOwner(_tabPane);
_popup.removeExcludedComponent(_tabPane);
Dimension size = _popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
Point p = listButton.getLocationOnScreen();
bounds.x = p.x;
bounds.y = p.y;
int x;
int y;
switch (tabPlacement) {
case TOP:
default:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y + bounds.height + 2;
break;
case BOTTOM:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y - size.height - 2;
break;
case LEFT:
x = bounds.x + bounds.width + 2;
y = bounds.y + bounds.height - size.height;
break;
case RIGHT:
x = bounds.x - size.width - 2;
y = bounds.y + bounds.height - size.height;
break;
}
Rectangle screenBounds = PortingUtils.getScreenBounds(_tabPane);
int right = x + size.width + 3;
int bottom = y + size.height + 3;
if (right > screenBounds.x + screenBounds.width) {
x -= right - screenBounds.x - screenBounds.width; // move left so that the whole popup can fit in
}
if (x < screenBounds.x) {
x = screenBounds.x; // move right so that the whole popup can fit in
}
if (bottom > screenBounds.height) {
y -= bottom - screenBounds.height;
}
if (y < screenBounds.y) {
y = screenBounds.y;
}
_popup.showPopup(x, y);
}
private void componentSelected(JList list) {
int tabIndex = list.getSelectedIndex();
if (tabIndex != -1 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
Runnable runnable = new Runnable() {
public void run() {
_tabPane.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
Runnable runnable = new Runnable() {
public void run() {
if (lastFocused != null) {
lastFocused.requestFocus();
}
else if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocus();
}
}
};
SwingUtilities.invokeLater(runnable);
}
});
}
else {
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
Runnable runnable = new Runnable() {
public void run() {
lastFocused.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
else {
Container container;
if (comp instanceof Container) {
container = (Container) comp;
}
else {
container = comp.getFocusCycleRootAncestor();
}
FocusTraversalPolicy traversalPolicy = container.getFocusTraversalPolicy();
Component focusComponent;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(container);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(container);
}
}
else if (comp instanceof Container) {
// not sure if it is correct
focusComponent = findFocusableComponent((Container) comp);
}
else {
focusComponent = comp;
}
if (focusComponent != null) {
final Component theComponent = focusComponent;
Runnable runnable = new Runnable() {
public void run() {
theComponent.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
}
}
ensureActiveTabIsVisible(false);
_popup.hidePopupImmediately();
_popup = null;
}
}
private Component findFocusableComponent(Container parent) {
FocusTraversalPolicy traversalPolicy = parent.getFocusTraversalPolicy();
Component focusComponent = null;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(parent);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(parent);
}
}
if (focusComponent != null) {
return focusComponent;
}
int i = 0;
while (i < parent.getComponentCount()) {
Component comp = parent.getComponent(i);
if (comp instanceof Container) {
focusComponent = findFocusableComponent((Container) comp);
if (focusComponent != null) {
return focusComponent;
}
}
else if (comp.isFocusable()) {
return comp;
}
i++;
}
if (parent.isFocusable()) {
return parent;
}
return null;
}
public void scrollForward(int tabPlacement) {
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (viewRect.width >= viewSize.width - viewRect.x) {
return; // no room left to scroll
}
}
else { // tabPlacement == LEFT || tabPlacement == RIGHT
if (viewRect.height >= viewSize.height - viewRect.y) {
return;
}
}
setLeadingTabIndex(tabPlacement, leadingTabIndex + 1);
}
public void scrollBackward(int tabPlacement) {
setLeadingTabIndex(tabPlacement, leadingTabIndex > 0 ? leadingTabIndex - 1 : 0);
}
public void setLeadingTabIndex(int tabPlacement, int index) {
// make sure the index is in range
if (index < 0 || index >= _tabPane.getTabCount()) {
return;
}
leadingTabIndex = index;
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
switch (tabPlacement) {
case TOP:
case BOTTOM:
tabViewPosition.y = 0;
if (_tabPane.getComponentOrientation().isLeftToRight()) {
tabViewPosition.x = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].x;
}
else {
tabViewPosition.x = (_rects.length <= 0 || leadingTabIndex == 0) ? 0 : _rects[0].x - _rects[leadingTabIndex].x + (_rects[0].width - _rects[leadingTabIndex].width) + 25;
}
if ((viewSize.width - tabViewPosition.x) < viewRect.width) {
tabViewPosition.x = viewSize.width - viewRect.width;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewSize.width - tabViewPosition.x,
// viewRect.height);
// System.out.println("setExtendedSize: " + extentSize);
// viewport.setExtentSize(extentSize);
}
break;
case LEFT:
case RIGHT:
tabViewPosition.x = 0;
tabViewPosition.y = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].y;
if ((viewSize.height - tabViewPosition.y) < viewRect.height) {
tabViewPosition.y = viewSize.height - viewRect.height;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewRect.width,
// viewSize.height - tabViewPosition.y);
// viewport.setExtentSize(extentSize);
}
break;
}
viewport.setViewPosition(tabViewPosition);
_tabPane.repaint();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight() && tabViewPosition.x == 0) {
// In current workaround, tabViewPosition set to 0 cannot trigger state change event
stateChanged(new ChangeEvent(viewport));
}
}
public void stateChanged(ChangeEvent e) {
if (_tabPane == null) return;
ensureCurrentLayout();
JViewport viewport = (JViewport) e.getSource();
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Rectangle vpRect = viewport.getBounds();
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
leadingTabIndex = getClosestTab(viewRect.x + viewRect.width, viewRect.y + viewRect.height);
if (leadingTabIndex < 0) {
leadingTabIndex = 0;
}
}
else {
leadingTabIndex = getClosestTab(viewRect.x, viewRect.y);
}
// If the tab isn't right aligned, adjust it.
if (leadingTabIndex < _rects.length && leadingTabIndex >= _rects.length) {
switch (tabPlacement) {
case TOP:
case BOTTOM:
if (_rects[leadingTabIndex].x < viewRect.x) {
leadingTabIndex++;
}
break;
case LEFT:
case RIGHT:
if (_rects[leadingTabIndex].y < viewRect.y) {
leadingTabIndex++;
}
break;
}
}
Insets contentInsets = getContentBorderInsets(tabPlacement);
int checkX;
switch (tabPlacement) {
case LEFT:
_tabPane.repaint(vpRect.x + vpRect.width, vpRect.y, contentInsets.left, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case RIGHT:
_tabPane.repaint(vpRect.x - contentInsets.right, vpRect.y, contentInsets.right, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case BOTTOM:
_tabPane.repaint(vpRect.x, vpRect.y - contentInsets.bottom, vpRect.width, contentInsets.bottom);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
break;
case TOP:
default:
_tabPane.repaint(vpRect.x, vpRect.y + vpRect.height, vpRect.width, contentInsets.top);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
}
if (SystemInfo.isJdk15Above()) {
_tabPane.setComponentZOrder(_tabScroller.scrollForwardButton, 0);
_tabPane.setComponentZOrder(_tabScroller.scrollBackwardButton, 0);
}
_tabScroller.scrollForwardButton.repaint();
_tabScroller.scrollBackwardButton.repaint();
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount()) {
closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex));
}
}
@Override
public String toString() {
return "viewport.viewSize=" + viewport.getViewSize() + "\n" +
"viewport.viewRectangle=" + viewport.getViewRect() + "\n" +
"leadingTabIndex=" + leadingTabIndex + "\n" +
"tabViewPosition=" + tabViewPosition;
}
}
public class ScrollableTabViewport extends JViewport implements UIResource {
int _expectViewX = 0;
boolean _protectView = false;
public ScrollableTabViewport() {
super();
setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
setOpaque(false);
setLayout(new ViewportLayout() {
private static final long serialVersionUID = -1069760662716244442L;
@Override
public void layoutContainer(Container parent) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
_protectView = true;
}
try {
super.layoutContainer(parent);
}
finally {
_protectView = false;
}
}
});
}
/**
* Gets the background color of this component.
*
* @return this component's background color; if this component does not have a background color, the background
* color of its parent is returned
*/
@Override
public Color getBackground() {
return UIDefaultsLookup.getColor("JideTabbedPane.background");
}
// workaround for swing bug
@Override
public void setViewPosition(Point p) {
int oldX = _expectViewX;
_expectViewX = p.x;
super.setViewPosition(p); // to trigger state change event, so the adjustment for RTL need to be done at ScrollableTabPanel#setBounds()
if (_protectView) {
_expectViewX = oldX;
Point savedPosition = new Point(oldX, p.y);
super.setViewPosition(savedPosition);
}
}
public int getExpectedViewX() {
return _expectViewX;
}
}
public class ScrollableTabPanel extends JPanel implements UIResource {
public ScrollableTabPanel() {
setLayout(null);
}
@Override
public boolean isOpaque() {
return false;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_tabPane.isOpaque()) {
if (getTabShape() == JideTabbedPane.SHAPE_BOX) {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"));
}
else {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground"));
}
g.fillRect(0, 0, getWidth(), getHeight());
}
paintTabArea(g, _tabPane.getTabPlacement(), _tabPane.getSelectedIndex(), this);
}
// workaround for swing bug
@Override
public void scrollRectToVisible(Rectangle aRect) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
int startX = aRect.x + _tabScroller.viewport.getExpectedViewX();
if (startX < 0) {
int i;
for (i = _tabScroller.leadingTabIndex; i < _rects.length; i++) {
startX += _rects[i].width;
if (startX >= 0) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.min(i + 1, _rects.length - 1));
}
else if (startX > aRect.x + aRect.width) {
int i;
for (i = _tabScroller.leadingTabIndex - 1; i >= 0; i--) {
startX -= _rects[i].width;
if (startX <= aRect.x + aRect.width) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.max(i, 0));
}
return;
}
super.scrollRectToVisible(aRect);
}
// workaround for swing bug
@Override
public void setBounds(int x, int y, int width, int height) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
super.setBounds(0, y, width, height);
return;
}
super.setBounds(x, y, width, height);
}
// workaround for swing bug
// http://developer.java.sun.com/developer/bugParade/bugs/4668865.html
@Override
public void setToolTipText(String text) {
_tabPane.setToolTipText(text);
}
@Override
public String getToolTipText() {
return _tabPane.getToolTipText();
}
@Override
public String getToolTipText(MouseEvent event) {
return _tabPane.getToolTipText(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public Point getToolTipLocation(MouseEvent event) {
return _tabPane.getToolTipLocation(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public JToolTip createToolTip() {
return _tabPane.createToolTip();
}
}
protected Color _closeButtonSelectedColor = new Color(255, 162, 165);
protected Color _closeButtonColor = Color.BLACK;
protected Color _popupColor = Color.BLACK;
/**
* Close button on the tab.
*/
public class TabCloseButton extends JButton implements MouseMotionListener, MouseListener, UIResource {
public static final int CLOSE_BUTTON = 0;
public static final int EAST_BUTTON = 1;
public static final int WEST_BUTTON = 2;
public static final int NORTH_BUTTON = 3;
public static final int SOUTH_BUTTON = 4;
public static final int LIST_BUTTON = 5;
private int _type;
private int _index = -1;
private boolean _mouseOver = false;
private boolean _mousePressed = false;
/**
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
@Override
public void updateUI() {
super.updateUI();
setMargin(new Insets(0, 0, 0, 0));
setBorder(BorderFactory.createEmptyBorder());
setFocusPainted(false);
setFocusable(false);
setRequestFocusEnabled(false);
String name = getName();
if (name != null) setToolTipText(getResourceString(name));
}
public TabCloseButton() {
this(CLOSE_BUTTON);
}
public TabCloseButton(int type) {
addMouseMotionListener(this);
addMouseListener(this);
setFocusPainted(false);
setFocusable(false);
setType(type);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(5, 5);
}
public int getIndex() {
return _index;
}
public void setIndex(int index) {
_index = index;
}
@Override
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
@Override
protected void paintComponent(Graphics g) {
if (!isEnabled()) {
setMouseOver(false);
setMousePressed(false);
}
if (isMouseOver() && isMousePressed()) {
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
else if (isMouseOver()) {
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
g.setColor(UIDefaultsLookup.getColor("controlShadow").darker());
int centerX = getWidth() >> 1;
int centerY = getHeight() >> 1;
int type = getType();
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
if (type == EAST_BUTTON) {
type = WEST_BUTTON;
}
else if (type == WEST_BUTTON) {
type = EAST_BUTTON;
}
}
switch (type) {
case CLOSE_BUTTON:
if (isEnabled()) {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX - 4, centerY - 3, centerX + 2, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
g.drawLine(centerX + 2, centerY - 3, centerX - 4, centerY + 3);
}
else {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
}
break;
case EAST_BUTTON:
//
// |
// ||
// |||
// ||||
// ||||*
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX + 2, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 3, y - 3, x - 3, y + 3);
g.drawLine(x - 2, y - 2, x - 2, y + 2);
g.drawLine(x - 1, y - 1, x - 1, y + 1);
g.drawLine(x, y, x, y);
}
else {
g.drawLine(x - 4, y - 4, x, y);
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
else {
int x = centerX + 3, y = centerY - 2; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 7, y + 1, x - 1, y + 1);
g.drawLine(x - 6, y + 2, x - 2, y + 2);
g.drawLine(x - 5, y + 3, x - 3, y + 3);
g.drawLine(x - 4, y + 4, x - 4, y + 4);
}
else {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 8, y, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
}
break;
case WEST_BUTTON: {
//
// |
// ||
// |||
// ||||
// *||||
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX - 3, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x, y);
g.drawLine(x + 1, y - 1, x + 1, y + 1);
g.drawLine(x + 2, y - 2, x + 2, y + 2);
g.drawLine(x + 3, y - 3, x + 3, y + 3);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
else {
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x, y, x + 4, y + 4);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
}
else {
int x = centerX - 5, y = centerY + 3; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x + 8, y);
g.drawLine(x + 1, y - 1, x + 7, y - 1);
g.drawLine(x + 2, y - 2, x + 6, y - 2);
g.drawLine(x + 3, y - 3, x + 5, y - 3);
g.drawLine(x + 4, y - 4, x + 4, y - 4);
}
else {
g.drawLine(x, y, x + 8, y);
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x + 8, y, x + 4, y - 4);
}
}
}
break;
}
case LIST_BUTTON: {
int x = centerX + 2, y = centerY; // start point. mark as
// * above
g.drawLine(x - 6, y - 4, x - 6, y + 4);
g.drawLine(x + 1, y - 4, x + 1, y + 4);
g.drawLine(x - 6, y - 4, x + 1, y - 4);
g.drawLine(x - 4, y - 2, x - 1, y - 2);
g.drawLine(x - 4, y, x - 1, y);
g.drawLine(x - 4, y + 2, x - 1, y + 2);
g.drawLine(x - 6, y + 4, x + 1, y + 4);
break;
}
}
}
@Override
public boolean isFocusable() {
return false;
}
@Override
public void requestFocus() {
}
@Override
public boolean isOpaque() {
return false;
}
public boolean scrollsForward() {
return getType() == EAST_BUTTON || getType() == SOUTH_BUTTON;
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
setMousePressed(false);
}
public void mousePressed(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(true);
repaint();
}
public void mouseReleased(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(false);
setMouseOver(false);
}
public void mouseEntered(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseExited(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(false);
setMousePressed(false);
repaint();
_tabScroller.tabPanel.repaint();
}
public int getType() {
return _type;
}
public void setType(int type) {
_type = type;
}
public boolean isMouseOver() {
return _mouseOver;
}
public void setMouseOver(boolean mouseOver) {
_mouseOver = mouseOver;
}
public boolean isMousePressed() {
return _mousePressed;
}
public void setMousePressed(boolean mousePressed) {
_mousePressed = mousePressed;
}
}
// Controller: event listeners
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class PropertyChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
String name = e.getPropertyName();
if ("mnemonicAt".equals(name)) {
updateMnemonics();
pane.repaint();
}
else if ("displayedMnemonicIndexAt".equals(name)) {
pane.repaint();
}
else if (name.equals("indexForTitle")) {
int index = (Integer) e.getNewValue();
String title = getCurrentDisplayTitleAt(_tabPane, index);
if (BasicHTML.isHTMLString(title)) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(_tabPane, title);
htmlViews.setElementAt(v, index);
}
}
else {
if (htmlViews != null && htmlViews.elementAt(index) != null) {
htmlViews.setElementAt(null, index);
}
}
updateMnemonics();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(
_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(false);
}
}
else if (name.equals("tabLayoutPolicy")) {
_tabPane.updateUI();
}
else if (name.equals("closeTabAction")) {
updateCloseAction();
}
else if (name.equals(JideTabbedPane.PROPERTY_DRAG_OVER_DISABLED)) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_COLOR_PROVIDER)) {
_tabPane.repaint();
}
else if (name.equals("locale")) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.BOLDACTIVETAB_PROPERTY)) {
getTabPanel().invalidate();
_tabPane.invalidate();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_LEADING_COMPONENT)) {
ensureCurrentLayout();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(false);
_tabPane.remove(_tabLeadingComponent);
}
_tabLeadingComponent = (Component) e.getNewValue();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(true);
_tabPane.add(_tabLeadingComponent);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_TRAILING_COMPONENT)) {
ensureCurrentLayout();
if (_tabTrailingComponent != null) {
_tabTrailingComponent.setVisible(false);
_tabPane.remove(_tabTrailingComponent);
}
_tabTrailingComponent = (Component) e.getNewValue();
if (_tabTrailingComponent != null) {
_tabPane.add(_tabTrailingComponent);
_tabTrailingComponent.setVisible(true);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.SHRINK_TAB_PROPERTY) ||
name.equals(JideTabbedPane.HIDE_IF_ONE_TAB_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_AREA_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_CONTENT_PROPERTY) ||
name.equals(JideTabbedPane.BOX_STYLE_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.TAB_CLOSABLE_PROPERTY) ||
name.equals(JideTabbedPane.PROPERTY_TAB_SHAPE) ||
name.equals(JideTabbedPane.PROPERTY_COLOR_THEME) ||
name.equals(JideTabbedPane.PROPERTY_TAB_RESIZE_MODE) ||
name.equals(JideTabbedPane.SHOW_TAB_BUTTONS_PROPERTY)) {
if ((name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY))
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
ensureCloseButtonCreated();
}
_tabPane.updateUI();
}
else if (name.equals("__index_to_remove__")) {
setVisibleComponent(null);
}
}
}
protected void updateCloseAction() {
ensureCloseButtonCreated();
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabSelectionHandler implements ChangeListener {
public void stateChanged(ChangeEvent e) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
ensureCloseButtonCreated();
Runnable runnable = new Runnable() {
public void run() {
ensureActiveTabIsVisible(false);
}
};
SwingUtilities.invokeLater(runnable);
}
}
public class TabFocusListener implements FocusListener {
public void focusGained(FocusEvent e) {
repaintSelectedTab();
}
public void focusLost(FocusEvent e) {
repaintSelectedTab();
}
private void repaintSelectedTab() {
if (_tabPane.getTabCount() > 0) {
Rectangle rect = getTabBounds(_tabPane, _tabPane.getSelectedIndex());
if (rect != null) {
_tabPane.repaint(rect);
}
}
}
}
public class MouseMotionHandler extends MouseMotionAdapter {
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class MouseHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isMiddleMouseButton(e)) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
Action action = getActionMap().get("closeTabAction");
if (action != null && tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex) && _tabPane.isCloseTabOnMouseMiddleButton() && _tabPane.isTabClosableAt(tabIndex)) {
ActionEvent event = new ActionEvent(_tabPane, tabIndex, "middleMouseButtonClicked");
action.actionPerformed(event);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isLeftMouseButton(e) || _tabPane.isRightClickSelect()) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
_tabPane.processMouseSelection(tabIndex, e);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else if (_tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
});
}
else {
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else {
// first try to find a default component.
boolean foundInTab = JideSwingUtilities.compositeRequestFocus(comp);
if (!foundInTab) { // && !_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
if (!isTabEditing())
startEditing(e); // start editing tab
}
}
public class MouseWheelHandler implements MouseWheelListener {
public void mouseWheelMoved(MouseWheelEvent e) {
if (_tabPane.isScrollSelectedTabOnWheel()) {
// set selected tab to the currently selected tab plus the wheel rotation but between
// 0 and tabCount-1
_tabPane.setSelectedIndex(
Math.min(_tabPane.getTabCount() - 1, Math.max(0, _tabPane.getSelectedIndex() + e.getWheelRotation())));
}
else if (scrollableTabLayoutEnabled() && e.getWheelRotation() != 0) {
if (e.getWheelRotation() > 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollForward(_tabPane.getTabPlacement());
}
}
else if (e.getWheelRotation() < 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollBackward(_tabPane.getTabPlacement());
}
}
}
}
}
private class ComponentHandler implements ComponentListener {
public void componentResized(ComponentEvent e) {
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
/* GES 2/3/99:
The container listener code was added to support HTML
rendering of tab titles.
Ideally, we would be able to listen for property changes
when a tab is added or its text modified. At the moment
there are no such events because the Beans spec doesn't
allow 'indexed' property changes (i.e. tab 2's text changed
from A to B).
In order to get around this, we listen for tabs to be added
or removed by listening for the container events. we then
queue up a runnable (so the component has a chance to complete
the add) which checks the tab title of the new component to see
if it requires HTML rendering.
The Views (one per tab title requiring HTML rendering) are
stored in the htmlViews Vector, which is only allocated after
the first time we run into an HTML tab. Note that this vector
is kept in step with the number of pages, and nulls are added
for those pages whose tab title do not require HTML rendering.
This makes it easy for the paint and layout code to tell
whether to invoke the HTML engine without having to check
the string during time-sensitive operations.
When we have added a way to listen for tab additions and
changes to tab text, this code should be removed and
replaced by something which uses that. */
private class ContainerHandler implements ContainerListener {
public void componentAdded(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
int index = tp.indexOfComponent(child);
String title = getCurrentDisplayTitleAt(tp, index);
boolean isHTML = BasicHTML.isHTMLString(title);
if (isHTML) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(tp, title);
htmlViews.insertElementAt(v, index);
}
}
else { // Not HTML
if (htmlViews != null) { // Add placeholder
htmlViews.insertElementAt(null, index);
} // else nada!
}
if (_tabPane.isTabEditing()) {
if (index <= _tabPane.getEditingTabIndex()) {
((BasicJideTabbedPaneUI) _tabPane.getUI())._editingTab ++;
}
ensureCloseButtonCreated();
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
}
public void componentRemoved(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
// NOTE 4/15/2002 (joutwate):
// This fix is implemented using client properties since there is
// currently no IndexPropertyChangeEvent. Once
// IndexPropertyChangeEvents have been added this code should be
// modified to use it.
Integer index =
(Integer) tp.getClientProperty("__index_to_remove__");
if (index != null) {
if (htmlViews != null && htmlViews.size() > index) {
htmlViews.removeElementAt(index);
}
tp.putClientProperty("__index_to_remove__", null);
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
// ensureActiveTabIsVisible(true);
}
}
private Vector createHTMLVector() {
Vector htmlViews = new Vector();
int count = _tabPane.getTabCount();
if (count > 0) {
for (int i = 0; i < count; i++) {
String title = getCurrentDisplayTitleAt(_tabPane, i);
if (BasicHTML.isHTMLString(title)) {
htmlViews.addElement(BasicHTML.createHTMLView(_tabPane, title));
}
else {
htmlViews.addElement(null);
}
}
}
return htmlViews;
}
@Override
public Component getTabPanel() {
if (scrollableTabLayoutEnabled())
return _tabScroller.tabPanel;
else
return _tabPane;
}
static class AbstractTab {
int width;
int id;
public void copy(AbstractTab tab) {
this.width = tab.width;
this.id = tab.id;
}
}
public static class TabSpaceAllocator {
static final int startOffset = 4;
private Insets insets = null;
static final int tabWidth = 24;
static final int textIconGap = 8;
private AbstractTab tabs[];
private void setInsets(Insets insets) {
this.insets = (Insets) insets.clone();
}
private void init(Rectangle rects[], Insets insets) {
setInsets(insets);
tabs = new AbstractTab[rects.length];
// fill up internal datastructure
for (int i = 0; i < rects.length; i++) {
tabs[i] = new AbstractTab();
tabs[i].id = i;
tabs[i].width = rects[i].width;
}
tabSort();
}
private void bestfit(AbstractTab tabs[], int freeWidth, int startTab) {
int tabCount = tabs.length;
int worstWidth;
int currentTabWidth;
int initialPos;
currentTabWidth = tabs[startTab].width;
initialPos = startTab;
if (startTab == tabCount - 1) {
// directly fill as worst case
tabs[startTab].width = freeWidth;
return;
}
worstWidth = freeWidth / (tabCount - startTab);
while (currentTabWidth < worstWidth) {
freeWidth -= currentTabWidth;
if (++startTab < tabCount - 1) {
currentTabWidth = tabs[startTab].width;
}
else {
tabs[startTab].width = worstWidth;
return;
}
}
if (startTab == initialPos) {
// didn't find anything smaller
for (int i = startTab; i < tabCount; i++) {
tabs[i].width = worstWidth;
}
}
else if (startTab < tabCount - 1) {
bestfit(tabs, freeWidth, startTab);
}
}
// bubble sort for now
private void tabSort() {
int tabCount = tabs.length;
AbstractTab tempTab = new AbstractTab();
for (int i = 0; i < tabCount - 1; i++) {
for (int j = i + 1; j < tabCount; j++) {
if (tabs[i].width > tabs[j].width) {
tempTab.copy(tabs[j]);
tabs[j].copy(tabs[i]);
tabs[i].copy(tempTab);
}
}
}
}
// directly modify the rects
private void outpush(Rectangle rects[]) {
for (AbstractTab tab : tabs) {
rects[tab.id].width = tab.width;
}
rects[0].x = startOffset;
for (int i = 1; i < rects.length; i++) {
rects[i].x = rects[i - 1].x + rects[i - 1].width;
}
}
public void reArrange(Rectangle rects[], Insets insets, int totalAvailableSpace) {
init(rects, insets);
bestfit(tabs, totalAvailableSpace, 0);
outpush(rects);
clearup();
}
private void clearup() {
for (int i = 0; i < tabs.length; i++) {
tabs[i] = null;
}
tabs = null;
}
}
@Override
public void ensureActiveTabIsVisible(boolean scrollLeft) {
if (_tabPane == null || _tabPane.getWidth() == 0) {
return;
}
if (scrollableTabLayoutEnabled()) {
ensureCurrentLayout();
if (scrollLeft && _rects.length > 0) {
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
_tabScroller.tabPanel.scrollRectToVisible(_rects[0]);
}
else {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
}
int index = _tabPane.getSelectedIndex();
if ((!scrollLeft || index != 0) && index < _rects.length && index != -1) {
if (index == 0) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
else {
if (index == _rects.length - 1) { // last one, scroll to the end
Rectangle lastRect = _rects[index];
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && _tabPane.getComponentOrientation().isLeftToRight()) {
lastRect.width = _tabScroller.tabPanel.getWidth() - lastRect.x;
}
_tabScroller.tabPanel.scrollRectToVisible(lastRect);
}
else {
_tabScroller.tabPanel.scrollRectToVisible(_rects[index]);
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.tabPanel.getParent().doLayout();
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabPane.revalidate();
_tabPane.repaintTabAreaAndContentBorder();
}
else {
_tabPane.repaint();
}
}
}
protected boolean isShowCloseButtonOnTab() {
if (_tabPane.isUseDefaultShowCloseButtonOnTab()) {
return _showCloseButtonOnTab;
}
else return _tabPane.isShowCloseButtonOnTab();
}
protected boolean isShowCloseButton() {
return _tabPane.isShowCloseButton();
}
public void ensureCloseButtonCreated() {
if (isShowCloseButton() && isShowCloseButtonOnTab() && scrollableTabLayoutEnabled()) {
if (_closeButtons == null) {
_closeButtons = new TabCloseButton[_tabPane.getTabCount()];
}
else if (_closeButtons.length > _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0, temp.length);
for (int i = temp.length; i < _closeButtons.length; i++) {
TabCloseButton tabCloseButton = _closeButtons[i];
_tabScroller.tabPanel.remove(tabCloseButton);
}
_closeButtons = temp;
}
else if (_closeButtons.length < _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0,
_closeButtons.length);
_closeButtons = temp;
}
ActionMap am = getActionMap();
for (int i = 0; i < _closeButtons.length; i++) {
TabCloseButton closeButton = _closeButtons[i];
if (closeButton == null) {
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName("JideTabbedPane.close");
_closeButtons[i] = closeButton;
closeButton.setBounds(0, 0, 0, 0);
Action action = _tabPane.getCloseAction();
closeButton.setAction(am.get("closeTabAction"));
updateButtonFromAction(closeButton, action);
_tabScroller.tabPanel.add(closeButton);
}
closeButton.setIndex(i);
}
}
}
private void updateButtonFromAction(TabCloseButton closeButton, Action action) {
if (action == null) {
return;
}
closeButton.setEnabled(action.isEnabled());
Object desc = action.getValue(Action.SHORT_DESCRIPTION);
if (desc instanceof String) {
closeButton.setToolTipText((String) desc);
}
Object icon = action.getValue(Action.SMALL_ICON);
if (icon instanceof Icon) {
closeButton.setIcon((Icon) icon);
}
}
protected boolean isShowTabButtons() {
return _tabPane.getTabCount() != 0 && _tabPane.isShowTabArea() && _tabPane.isShowTabButtons();
}
protected boolean isShrinkTabs() {
return _tabPane.getTabCount() != 0 && _tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT;
}
protected TabEditor _tabEditor;
protected boolean _isEditing;
protected int _editingTab = -1;
protected String _oldValue;
protected String _oldPrefix;
protected String _oldPostfix;
// mtf - changed
protected Component _originalFocusComponent;
@Override
public boolean isTabEditing() {
return _isEditing;
}
protected TabEditor createDefaultTabEditor() {
final TabEditor editor = new TabEditor();
editor.getDocument().addDocumentListener(this);
editor.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
return true;
}
public boolean shouldYieldFocus(JComponent input) {
boolean shouldStopEditing = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
shouldStopEditing = _tabPane.getTabEditingValidator().alertIfInvalid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (shouldStopEditing && _tabPane != null && _tabPane.isTabEditing()) {
_tabPane.stopTabEditing();
}
return shouldStopEditing;
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_originalFocusComponent = e.getOppositeComponent();
}
@Override
public void focusLost(FocusEvent e) {
}
});
editor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editor.transferFocus();
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (_isEditing && (e.getKeyCode() == KeyEvent.VK_ESCAPE)) {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldValue);
}
_tabPane.cancelTabEditing();
}
}
});
editor.setFont(_tabPane.getFont());
return editor;
}
@Override
public void stopTabEditing() {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
cancelTabEditing();
}
@Override
public void cancelTabEditing() {
if (_tabEditor != null) {
_isEditing = false;
((Container) getTabPanel()).remove(_tabEditor);
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
Rectangle tabRect = _tabPane.getBoundsAt(_editingTab);
getTabPanel().repaint(tabRect.x, tabRect.y,
tabRect.width, tabRect.height);
}
else {
getTabPanel().repaint();
}
if (_originalFocusComponent != null)
_originalFocusComponent.requestFocus(); // InWindow();
else
_tabPane.requestFocusForVisibleComponent();
_editingTab = -1;
_oldValue = null;
_tabPane.doLayout();
}
}
@Override
public boolean editTabAt(int tabIndex) {
if (_isEditing) {
return false;
}
// _tabPane.popupSelectedIndex(tabIndex);
if (_tabEditor == null)
_tabEditor = createDefaultTabEditor();
if (_tabEditor != null) {
prepareEditor(_tabEditor, tabIndex);
((Container) getTabPanel()).add(_tabEditor);
resizeEditor(tabIndex);
_editingTab = tabIndex;
_isEditing = true;
_tabEditor.requestFocusInWindow();
_tabEditor.selectAll();
return true;
}
return false;
}
@Override
public int getEditingTabIndex() {
return _editingTab;
}
protected void prepareEditor(TabEditor e, int tabIndex) {
Font font;
if (_tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (_tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
e.setFont(font);
_oldValue = _tabPane.getTitleAt(tabIndex);
if (_oldValue.startsWith("<HTML>") && _oldValue.endsWith("/HTML>")) {
_oldPrefix = "<HTML>";
_oldPostfix = "</HTML>";
String title = _oldValue.substring("<HTML>".length(), _oldValue.length() - "</HTML>".length());
if (title.startsWith("<B>") && title.endsWith("/B>")) {
title = title.substring("<B>".length(), title.length() - "</B>".length());
_oldPrefix += "<B>";
_oldPostfix = "</B>" + _oldPostfix;
}
e.setText(title);
}
else {
_oldPrefix = "";
_oldPostfix = "";
e.setText(_oldValue);
}
e.selectAll();
e.setForeground(_tabPane.getForegroundAt(tabIndex));
}
protected Rectangle getTabsTextBoundsAt(int tabIndex) {
Rectangle tabRect = _tabPane.getBoundsAt(tabIndex);
Rectangle iconRect = new Rectangle(),
textRect = new Rectangle();
if (tabRect.width < 200) // random max size;
tabRect.width = 200;
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
while (title == null || title.length() < 3)
title += " ";
Icon icon = _tabPane.getIconForTab(tabIndex);
Font font = _tabPane.getFont();
if (tabIndex == _tabPane.getSelectedIndex() && _tabPane.isBoldActiveTab()) {
font = font.deriveFont(Font.BOLD);
}
SwingUtilities.layoutCompoundLabel(_tabPane, _tabPane.getGraphics().getFontMetrics(font), title, icon,
SwingUtilities.CENTER, SwingUtilities.CENTER,
SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect,
iconRect, textRect, icon == null ? 0 : _textIconGap);
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
iconRect.x = tabRect.x + _iconMargin;
textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding);
textRect.width += 2;
}
else {
iconRect.y = tabRect.y + _iconMargin;
textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding);
iconRect.x = tabRect.x + 2;
textRect.x = tabRect.x + 2;
textRect.height += 2;
}
return textRect;
}
private void updateTab() {
if (_isEditing) {
resizeEditor(getEditingTabIndex());
}
}
public void insertUpdate(DocumentEvent e) {
updateTab();
}
public void removeUpdate(DocumentEvent e) {
updateTab();
}
public void changedUpdate(DocumentEvent e) {
updateTab();
}
protected void resizeEditor(int tabIndex) {
// note - this should use the logic of label paint text so that the text overlays exactly.
Rectangle tabsTextBoundsAt = getTabsTextBoundsAt(tabIndex);
if (tabsTextBoundsAt.isEmpty()) {
tabsTextBoundsAt = new Rectangle(14, 3); // note - 14 should be the font height but...
}
tabsTextBoundsAt.x = tabsTextBoundsAt.x - _tabEditor.getBorder().getBorderInsets(_tabEditor).left;
tabsTextBoundsAt.width = +tabsTextBoundsAt.width +
_tabEditor.getBorder().getBorderInsets(_tabEditor).left +
_tabEditor.getBorder().getBorderInsets(_tabEditor).right;
tabsTextBoundsAt.y = tabsTextBoundsAt.y - _tabEditor.getBorder().getBorderInsets(_tabEditor).top;
tabsTextBoundsAt.height = tabsTextBoundsAt.height +
_tabEditor.getBorder().getBorderInsets(_tabEditor).top +
_tabEditor.getBorder().getBorderInsets(_tabEditor).bottom;
_tabEditor.setBounds(SwingUtilities.convertRectangle(_tabPane, tabsTextBoundsAt, getTabPanel()));
_tabEditor.invalidate();
_tabEditor.validate();
// getTabPanel().invalidate();
// getTabPanel().validate();
// getTabPanel().repaint();
// getTabPanel().doLayout();
_tabPane.doLayout();
// mtf - note - this is an exteme repaint but we need to paint any content borders
getTabPanel().getParent().getParent().repaint();
}
protected String getCurrentDisplayTitleAt(JideTabbedPane tp, int index) {
String returnTitle = tp.getDisplayTitleAt(index);
if ((_isEditing) && (index == _editingTab))
returnTitle = _tabEditor.getText();
return returnTitle;
}
protected class TabEditor extends JTextField implements UIResource {
TabEditor() {
setOpaque(false);
// setBorder(BorderFactory.createEmptyBorder());
setBorder(BorderFactory
.createCompoundBorder(new PartialLineBorder(Color.BLACK, 1, true),
BorderFactory.createEmptyBorder(0, 2, 0, 2)));
}
public boolean stopEditing() {
return true;
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Composite orgComposite = g2.getComposite();
Color orgColor = g2.getColor();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.70f));
Object o = JideSwingUtilities.setupShapeAntialiasing(g);
g2.setColor(getBackground());
g.fillRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 1, 1);
JideSwingUtilities.restoreShapeAntialiasing(g, o);
g2.setColor(orgColor);
g2.setComposite(orgComposite);
super.paintComponent(g);
}
}
public void startEditing(MouseEvent e) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (!e.isPopupTrigger() && tabIndex >= 0
&& _tabPane.isEnabledAt(tabIndex)
&& _tabPane.isTabEditingAllowed() && (e.getClickCount() == 2)) {
boolean shouldEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldEdit = _tabPane.getTabEditingValidator().shouldStartEdit(tabIndex, e);
if (shouldEdit) {
e.consume();
_tabPane.editTabAt(tabIndex);
}
}
if (e.getClickCount() == 1) {
if (_tabPane.isTabEditing()) {
boolean shouldStopEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldStopEdit = _tabPane.getTabEditingValidator().alertIfInvalid(tabIndex, _oldPrefix + _tabEditor.getText() + _oldPostfix);
if (shouldStopEdit)
_tabPane.stopTabEditing();
}
}
}
public ThemePainter getPainter() {
return _painter;
}
private class DragOverTimer extends Timer implements ActionListener {
private int _index;
private static final long serialVersionUID = -2529347876574638854L;
public DragOverTimer(int index) {
super(500, null);
_index = index;
addActionListener(this);
setRepeats(false);
}
public void actionPerformed(ActionEvent e) {
if (_tabPane.getTabCount() == 0) {
return;
}
if (_index == _tabPane.getSelectedIndex()) {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
_tabPane.repaint(getTabBounds(_tabPane, _index));
}
}
else {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
}
_tabPane.setSelectedIndex(_index);
}
stop();
}
}
private class DropListener implements DropTargetListener {
private DragOverTimer _timer;
int _index = -1;
public DropListener() {
}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
if (!_tabPane.isEnabled()) {
return;
}
int tabIndex = getTabAtLocation(dtde.getLocation().x, dtde.getLocation().y);
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex()) {
// selected already, do nothing
}
else if (tabIndex == _index) {
// same tab, timer has started
}
else {
stopTimer();
startTimer(tabIndex);
_index = tabIndex; // save the index
}
}
else {
stopTimer();
}
dtde.rejectDrag();
}
private void startTimer(int tabIndex) {
_timer = new DragOverTimer(tabIndex);
_timer.start();
}
private void stopTimer() {
if (_timer != null) {
_timer.stop();
_timer = null;
_index = -1;
}
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dte) {
stopTimer();
}
public void drop(DropTargetDropEvent dtde) {
stopTimer();
}
}
protected void paintFocusIndicator(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect,
boolean isSelected) {
Rectangle tabRect = new Rectangle(rects[tabIndex]);
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
tabRect.x += _tabScroller.viewport.getExpectedViewX();
}
if (_tabPane.hasFocus() && isSelected) {
int x, y, w, h;
g.setColor(_focus);
switch (tabPlacement) {
case LEFT:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case RIGHT:
x = tabRect.x + 2;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case BOTTOM:
x = tabRect.x + 3;
y = tabRect.y + 2;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
break;
case TOP:
default:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
}
BasicGraphicsUtils.drawDashedRect(g, x, y, w, h);
}
}
protected boolean isRoundedCorner() {
return "true".equals(SecurityUtils.getProperty("shadingtheme", "false"));
}
protected int getTabShape() {
return _tabPane.getTabShape();
}
protected int getTabResizeMode() {
return _tabPane.getTabResizeMode();
}
protected int getColorTheme() {
return _tabPane.getColorTheme();
}
// for debug purpose
final protected boolean PAINT_TAB = true;
final protected boolean PAINT_TAB_BORDER = true;
final protected boolean PAINT_TAB_BACKGROUND = true;
final protected boolean PAINT_TABAREA = true;
final protected boolean PAINT_CONTENT_BORDER = true;
final protected boolean PAINT_CONTENT_BORDER_EDGE = true;
protected int getLeftMargin() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return OFFICE2003_LEFT_MARGIN;
}
else if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else {
return DEFAULT_LEFT_MARGIN;
}
}
protected int getTabGap() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return 4;
}
else {
return 0;
}
}
protected int getLayoutSize() {
int tabShape = getTabShape();
if (tabShape == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else if (tabShape == JideTabbedPane.SHAPE_ECLIPSE3X) {
return 15;
}
else if (_tabPane.getTabShape() == JideTabbedPane.SHAPE_FLAT || _tabPane.getTabShape() == JideTabbedPane.SHAPE_ROUNDED_FLAT) {
return 2;
}
else if (tabShape == JideTabbedPane.SHAPE_WINDOWS
|| tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return 6;
}
else {
return 0;
}
}
protected int getTabRightPadding() {
if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return 4;
}
else {
return 0;
}
}
protected MouseListener createMouseListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseHandler();
}
else {
return new MouseHandler();
}
}
protected MouseWheelListener createMouseWheelListener() {
return new MouseWheelHandler();
}
protected MouseMotionListener createMouseMotionListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseMotionHandler();
}
else {
return new MouseMotionHandler();
}
}
public class DefaultMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class DefaultMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
}
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
public class RolloverMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class RolloverMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
protected boolean isTabLeadingComponentVisible() {
return _tabPane.isTabShown() && _tabLeadingComponent != null && _tabLeadingComponent.isVisible();
}
protected boolean isTabTrailingComponentVisible() {
return _tabPane.isTabShown() && _tabTrailingComponent != null && _tabTrailingComponent.isVisible();
}
protected boolean isTabTopVisible(int tabPlacement) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement));
case TOP:
case BOTTOM:
default:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement));
}
}
protected boolean showFocusIndicator() {
return _tabPane.hasFocusComponent() && _showFocusIndicator;
}
private int getNumberOfTabButtons() {
int numberOfButtons = (!isShowTabButtons() || isShrinkTabs()) ? 1 : 4;
if (!isShowCloseButton() || isShowCloseButtonOnTab()) {
numberOfButtons--;
}
return numberOfButtons;
}
/**
* Gets the resource string used in DocumentPane. Subclass can override it to provide their own strings.
*
* @param key the resource key
* @return the localized string.
*/
protected String getResourceString(String key) {
return Resource.getResourceBundle(_tabPane != null ? _tabPane.getLocale() : Locale.getDefault()).getString(key);
}
}
|
diff --git a/src/gd/app/cli/CommandLineInterface.java b/src/gd/app/cli/CommandLineInterface.java
index 99f83bd..610d4ab 100644
--- a/src/gd/app/cli/CommandLineInterface.java
+++ b/src/gd/app/cli/CommandLineInterface.java
@@ -1,201 +1,201 @@
package gd.app.cli;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import gd.app.model.Table;
import gd.util.ImageFrame;
import gd.util.ArgsManager;
import gd.app.util.todot.GraphvizCmd;
import gd.app.util.todot.ToDotUtil;
import gd.app.util.todot.ToDotUtilException;
import gd.hibernate.util.HibernateUtil;
/**
* Command Line Interface class, this class contains the main function to
* compile the command line program.
*
* @author Clément Sipieter <[email protected]>
* @version 0.1
*/
public class CommandLineInterface
{
private static final String TITLE = "db2graph";
private static String username = "";
private static String password = "";
private static String db_name = null;
private static String sgbd_type = null;
private static String host = "";
private static String port = null;
private static String output = null;
private static boolean opt_show = false;
private static GraphvizCmd gv_cmd = GraphvizCmd.DOT;
/**
* Main
*
* @param args
* see --help.
*/
public static void main(String[] args) {
Session session = null;
String dot = "";
String dir = System.getProperty("user.dir") + "/";
manageParams(args);
try {
session = HibernateUtil.openSession(sgbd_type, host, db_name,
username, password, port);
Criteria c = session.createCriteria(Table.class);
dot = ToDotUtil.convertToDot(c.list(), db_name);
if (output == null && !opt_show) {
System.out.println(dot);
} else {
String racine_file = (output == null) ? "out" : output
.substring(0, output.lastIndexOf('.'));
String url_dot_file = dir + racine_file + ".dot";
// Write a dot file
BufferedWriter bw = new BufferedWriter(new FileWriter(
url_dot_file));
bw.write(dot);
bw.close();
// Generate a png image from the dot file
// @todo treat other image format
String url_image = dir + output;
if (output != null) {
// System call to graphviz
if (ToDotUtil.dotToSvg(gv_cmd, url_dot_file, url_image) != 0)
System.err
.println("Erreur lors de la génération du svg.");
}
if (opt_show) {
String png_image = dir + racine_file + ".png";
// System call to graphviz
if (ToDotUtil.dotToPng(gv_cmd, url_dot_file, png_image) != 0)
System.err
.println("Erreur lors de la génération du png.");
new ImageFrame(png_image, TITLE);
}
}
session.close();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
}
}
private static void manageParams(String args[])
{
ArgsManager param_manager = new ArgsManager(args);
String arg;
try
{
while ((arg = param_manager.getNextParam()) != null)
{
if (!ArgsManager.isAnOptionName(arg))
{
if (sgbd_type == null)
{
sgbd_type = ArgsManager.getOptionName(arg);
}
else
{
db_name = ArgsManager.getOptionName(arg);
}
}
else
{
String param = ArgsManager.getOptionName(arg);
// @todo manage this next line width ArgsManager
String value = "";
if (!param.equals("show") && !param.equals("help"))
{
value = param_manager.getNextParam();
if (value == null)
throw new Exception("wrong option : " + param);
else if (ArgsManager.isAnOptionName(value))
throw new Exception("wrong value for " + param
+ " option");
}
if (param.equals("host") || param.equals("h"))
host = value;
else if (param.equals("user") || param.equals("u"))
username = value;
else if (param.equals("password") || param.equals("p"))
password = value;
else if (param.equals("dbname"))
db_name = value;
else if (param.equals("sgbd_type"))
{
}
else if (param.equals("port"))
port = value;
else if (param.equals("cmd") || param.equals("c"))
gv_cmd = GraphvizCmd.getInstance(value);
- else if (param.equals("output"))
+ else if (param.equals("output") || param.equals("o"))
output = value;
else if (param.equals("show"))
opt_show = true;
else if (param.equals("help"))
{
printHelp();
System.exit(0);
}
else
throw new Exception("wrong option : " + arg);
}
}
if (sgbd_type == null || db_name == null)
throw new Exception("Bad usage");
}
catch (Exception e)
{
System.err.println(e.getMessage());
printHelp();
System.exit(1);
}
}
private static void printHelp()
{
System.out.println("Usage:\n" + "gd [OPTION...] SGBD_NAME DATABASE_NAME\n"
+ "\n" + "Options:\n" + " -u, --user <USERNAME>\n"
+ " use this username.\n" + " -p, --password [PASSWORD]\n"
+ " use this password.\n" + " -h, --host <HOST>\n"
+ " use this host.\n" + " --port <PORT>\n"
+ " use this port.\n" + " -o, --output <FILE_NAME>\n"
+ " generate an png image width graphviz\n"
+ " -c, --cmd <GRAPHVIZ_CMD>\n"
+ " choose your graphviz command (man graphviz).\n"
+ " --show \n"
+ " open a window with graph representation.\n" + " --help\n"
+ " print this message.\n" + "\n");
}
}
| true | true | private static void manageParams(String args[])
{
ArgsManager param_manager = new ArgsManager(args);
String arg;
try
{
while ((arg = param_manager.getNextParam()) != null)
{
if (!ArgsManager.isAnOptionName(arg))
{
if (sgbd_type == null)
{
sgbd_type = ArgsManager.getOptionName(arg);
}
else
{
db_name = ArgsManager.getOptionName(arg);
}
}
else
{
String param = ArgsManager.getOptionName(arg);
// @todo manage this next line width ArgsManager
String value = "";
if (!param.equals("show") && !param.equals("help"))
{
value = param_manager.getNextParam();
if (value == null)
throw new Exception("wrong option : " + param);
else if (ArgsManager.isAnOptionName(value))
throw new Exception("wrong value for " + param
+ " option");
}
if (param.equals("host") || param.equals("h"))
host = value;
else if (param.equals("user") || param.equals("u"))
username = value;
else if (param.equals("password") || param.equals("p"))
password = value;
else if (param.equals("dbname"))
db_name = value;
else if (param.equals("sgbd_type"))
{
}
else if (param.equals("port"))
port = value;
else if (param.equals("cmd") || param.equals("c"))
gv_cmd = GraphvizCmd.getInstance(value);
else if (param.equals("output"))
output = value;
else if (param.equals("show"))
opt_show = true;
else if (param.equals("help"))
{
printHelp();
System.exit(0);
}
else
throw new Exception("wrong option : " + arg);
}
}
if (sgbd_type == null || db_name == null)
throw new Exception("Bad usage");
}
catch (Exception e)
{
System.err.println(e.getMessage());
printHelp();
System.exit(1);
}
}
| private static void manageParams(String args[])
{
ArgsManager param_manager = new ArgsManager(args);
String arg;
try
{
while ((arg = param_manager.getNextParam()) != null)
{
if (!ArgsManager.isAnOptionName(arg))
{
if (sgbd_type == null)
{
sgbd_type = ArgsManager.getOptionName(arg);
}
else
{
db_name = ArgsManager.getOptionName(arg);
}
}
else
{
String param = ArgsManager.getOptionName(arg);
// @todo manage this next line width ArgsManager
String value = "";
if (!param.equals("show") && !param.equals("help"))
{
value = param_manager.getNextParam();
if (value == null)
throw new Exception("wrong option : " + param);
else if (ArgsManager.isAnOptionName(value))
throw new Exception("wrong value for " + param
+ " option");
}
if (param.equals("host") || param.equals("h"))
host = value;
else if (param.equals("user") || param.equals("u"))
username = value;
else if (param.equals("password") || param.equals("p"))
password = value;
else if (param.equals("dbname"))
db_name = value;
else if (param.equals("sgbd_type"))
{
}
else if (param.equals("port"))
port = value;
else if (param.equals("cmd") || param.equals("c"))
gv_cmd = GraphvizCmd.getInstance(value);
else if (param.equals("output") || param.equals("o"))
output = value;
else if (param.equals("show"))
opt_show = true;
else if (param.equals("help"))
{
printHelp();
System.exit(0);
}
else
throw new Exception("wrong option : " + arg);
}
}
if (sgbd_type == null || db_name == null)
throw new Exception("Bad usage");
}
catch (Exception e)
{
System.err.println(e.getMessage());
printHelp();
System.exit(1);
}
}
|
diff --git a/java/src/client/com/dgrid/transport/DGridHibernateTransport.java b/java/src/client/com/dgrid/transport/DGridHibernateTransport.java
index 1babb42..87a9799 100644
--- a/java/src/client/com/dgrid/transport/DGridHibernateTransport.java
+++ b/java/src/client/com/dgrid/transport/DGridHibernateTransport.java
@@ -1,418 +1,418 @@
package com.dgrid.transport;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.ObjectRetrievalFailureException;
import com.dgrid.dao.GenericDAO;
import com.dgrid.dao.ObjectQueryDAO;
import com.dgrid.dao.model.HostSetting;
import com.dgrid.dao.model.JobletLogEntry;
import com.dgrid.dao.model.SystemSetting;
import com.dgrid.errors.TransportException;
import com.dgrid.gen.Constants;
import com.dgrid.gen.Host;
import com.dgrid.gen.InvalidApiKey;
import com.dgrid.gen.InvalidHost;
import com.dgrid.gen.InvalidJobId;
import com.dgrid.gen.InvalidJobletId;
import com.dgrid.gen.JOB_CALLBACK_TYPES;
import com.dgrid.gen.JOB_STATUS;
import com.dgrid.gen.Job;
import com.dgrid.gen.Joblet;
import com.dgrid.gen.JobletResult;
import com.dgrid.gen.NoHostAvailable;
import com.dgrid.gen.NoWorkAvailable;
import com.dgrid.service.DGridSyncJobService;
import com.dgrid.service.DGridTransport;
import com.dgrid.util.ApiCallbackTypes;
import com.dgrid.util.io.HostnameDiscovery;
import com.facebook.thrift.TException;
public class DGridHibernateTransport implements DGridTransport {
private Log log = LogFactory.getLog(getClass());
private GenericDAO dao;
private ObjectQueryDAO queryDAO;
private DGridSyncJobService syncJobService;
private DGridTransport self;
private String apiKey;
private static final String[] jobStatusTypes = new String[] { null,
"saved", "received", "queued", "processing", "completed", "failed" };
private Random random = new SecureRandom();
private String hostname;
public void setGenericDAO(GenericDAO dao) {
this.dao = dao;
}
public void setObjectQueryDAO(ObjectQueryDAO dao) {
this.queryDAO = dao;
}
public void setSyncJobService(DGridSyncJobService service) {
this.syncJobService = service;
}
public void setTransport(DGridTransport transport) {
this.self = transport;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public void setEndpoint(String endpoint) {
}
public void setPort(int port) {
}
public void init() {
log.trace("init()");
this.hostname = HostnameDiscovery.getHostname();
}
public void completeJoblet(int jobletId, JobletResult result,
String logMessage) throws TransportException, InvalidApiKey,
InvalidJobletId {
log.trace("completeJoblet()");
Joblet joblet = readJoblet(jobletId);
joblet.setStatus(result.getStatus());
dao.update(joblet);
result.setJoblet(joblet);
result.setTimeCreated(System.currentTimeMillis());
dao.create(result);
if ((logMessage != null) && (logMessage.length() > 0)) {
JobletLogEntry log = new JobletLogEntry(0, joblet, logMessage);
dao.create(log);
}
// count joblets still in received/queued/processing
Criteria crit = queryDAO.createCriteria(Joblet.class);
crit.add(Restrictions.eq("jobId", joblet.getJobId()));
crit.add(Restrictions.or(
Restrictions.eq("status", JOB_STATUS.RECEIVED), Restrictions
.or(Restrictions.eq("status", JOB_STATUS.QUEUED),
Restrictions
.eq("status", JOB_STATUS.PROCESSING))));
crit.setProjection(Projections.rowCount());
int active = ((Integer) crit.list().get(0)).intValue();
if (active == 0) {
// update any saved joblets to received
Query query = queryDAO
.createQuery("update Joblet set status = ? where (jobId = ? and status = ?)");
query.setInteger(0, JOB_STATUS.RECEIVED);
query.setInteger(1, joblet.getJobId());
query.setInteger(2, JOB_STATUS.SAVED);
active = query.executeUpdate();
}
if (active == 0) {
// provision callback
Job job = (Job) dao.read(Job.class, joblet.getJobId());
// look for failures
Criteria failures = queryDAO.createCriteria(Joblet.class);
failures.add(Restrictions.eq("jobId", job.getId()));
failures.add(Restrictions.eq("status", JOB_STATUS.FAILED));
failures.setProjection(Projections.rowCount());
int failureCount = ((Integer) failures.list().get(0)).intValue();
int jobStatus = (failureCount == 0) ? JOB_STATUS.COMPLETED
: JOB_STATUS.FAILED;
// update job
job.setStatus(jobStatus);
job = (Job) dao.update(job);
if ((job.getCallbackType() != 0)
&& (job.getCallbackType() != JOB_CALLBACK_TYPES.NONE)) {
Map<String, String> params = new HashMap<String, String>();
params.put("jobId", Integer.toString(job.getId()));
params.put("jobStatus", jobStatusTypes[jobStatus]);
params.put("callbackType", ApiCallbackTypes
.getStringCallbackType(job.getCallbackType()));
params.put("callbackAddress", job.getCallbackAddress());
Joblet callback = new Joblet(0, System.currentTimeMillis(), 0,
0, job.getSubmitter(), 2, Constants.CALLBACK_JOBLET,
- "Callback for job # ", params, null,
+ "Callback for job # ", params, job.getCallbackContent(),
JOB_STATUS.RECEIVED);
try {
self.submitJoblet(callback, 0, JOB_CALLBACK_TYPES.NONE,
null, null);
} catch (InvalidJobId e) {
log.error("InvalidJobId called while submitting callback!",
e);
}
}
}
}
public Host getHostByName(String hostname) throws TransportException,
InvalidApiKey, InvalidHost {
log.trace("getHostByName()");
Criteria crit = queryDAO.createCriteria(Host.class);
crit.add(Restrictions.eq("hostname", hostname));
Host host = (Host) crit.uniqueResult();
if (host == null) {
throw new InvalidHost();
}
return host;
}
public String getHostSetting(int hostid, String name, String defaultValue)
throws TransportException, InvalidApiKey, InvalidHost {
log.trace("getHostSetting()");
Criteria crit = queryDAO.createCriteria(HostSetting.class);
crit.createCriteria("host").add(Restrictions.eq("id", hostid));
crit.add(Restrictions.eq("name", name));
HostSetting setting = (HostSetting) crit.uniqueResult();
String value = defaultValue;
if (setting == null) {
Host host = readHost(hostid);
setting = new HostSetting(0, System.currentTimeMillis(), name,
value, null, host);
setting = (HostSetting) dao.create(setting);
} else {
value = setting.getValue();
}
return value;
}
public String getSetting(String name, String defaultValue)
throws TransportException, InvalidApiKey {
log.trace("getSetting()");
Criteria crit = queryDAO.createCriteria(SystemSetting.class);
crit.add(Restrictions.eq("name", name));
int size = crit.list().size();
SystemSetting ss = (SystemSetting) crit.uniqueResult();
String value = defaultValue;
if (ss == null) {
ss = new SystemSetting(0, System.currentTimeMillis(), name,
defaultValue, null);
ss = (SystemSetting) dao.create(ss);
} else {
value = ss.getValue();
}
return value;
}
public Job getJob(int jobId) throws TransportException, InvalidApiKey,
InvalidJobId {
log.trace("getJob()");
try {
return (Job) dao.read(Job.class, jobId);
} catch (ObjectRetrievalFailureException e) {
throw new InvalidJobId();
}
}
public int getJobletQueueSize() throws TransportException, InvalidApiKey {
log.trace("getJobletQueueSize()");
Criteria crit = queryDAO.createCriteria(Joblet.class);
crit.add(Restrictions.eq("status", JOB_STATUS.RECEIVED));
crit.setProjection(Projections.rowCount());
return ((Integer) crit.list().get(0)).intValue();
}
public JobletResult getJobletResult(int jobletId)
throws TransportException, InvalidApiKey, InvalidJobletId {
log.trace("getJobletResult()");
Criteria crit = queryDAO.createCriteria(JobletResult.class);
crit.createCriteria("joblet").add(Restrictions.eq("id", jobletId));
JobletResult jr = (JobletResult) crit.uniqueResult();
if (jr == null)
throw new InvalidJobletId();
return jr;
}
public List<JobletResult> getResults(int jobId) throws TransportException,
InvalidApiKey, InvalidJobId {
log.trace("getResults()");
Criteria crit = queryDAO.createCriteria(JobletResult.class);
crit.createCriteria("joblet").add(Restrictions.eq("jobId", jobId));
crit.addOrder(Order.asc("timeCreated"));
return crit.list();
}
public Joblet getWork() throws TransportException, InvalidApiKey,
InvalidHost, NoWorkAvailable {
log.trace("getWork()");
Host host = getHostByName(this.hostname);
Criteria crit = queryDAO.createCriteria(Joblet.class);
crit.add(Restrictions.eq("status", JOB_STATUS.RECEIVED));
crit.add(Restrictions.or(Restrictions.eq("hostId", host.getId()),
Restrictions.or(Restrictions.isNull("hostId"), Restrictions.eq(
"hostId", 0))));
crit.addOrder(Order.desc("hostId"));
crit.addOrder(Order.desc("priority"));
crit.addOrder(Order.asc("timeCreated"));
crit.setMaxResults(1);
crit.setLockMode(LockMode.UPGRADE);
Joblet joblet = (Joblet) crit.uniqueResult();
if (joblet == null)
throw new NoWorkAvailable();
joblet.setStatus(JOB_STATUS.QUEUED);
joblet.setHostId(host.getId());
dao.update(joblet);
return joblet;
}
public JobletResult gridExecute(Joblet joblet, int retries)
throws InvalidApiKey, TransportException, NoHostAvailable {
log.trace("gridExecute()");
// want to pick a random host
Criteria crit = queryDAO.createCriteria(Host.class);
int size = crit.list().size();
int hostNumber = random.nextInt(size);
Host host = (Host) crit.list().get(hostNumber);
try {
JobletResult result = syncJobService.gridExecute(
host.getHostname(), joblet);
return result;
} catch (TException e) {
log.error("TException calling gridExecute()", e);
throw new TransportException(e);
}
}
public void log(int jobletId, int jobletStatus, String message)
throws TransportException, InvalidApiKey, InvalidJobletId {
log.trace("log()");
Joblet joblet = readJoblet(jobletId);
JobletLogEntry entry = new JobletLogEntry(0, joblet, message);
dao.create(entry);
if (jobletStatus != joblet.getStatus()) {
joblet.setStatus(jobletStatus);
dao.update(joblet);
}
}
public Host registerHost(String hostname) throws TransportException,
InvalidApiKey, InvalidHost {
log.trace("registerHost()");
Host host = null;
try {
host = getHostByName(hostname);
} catch (InvalidHost ih) {
host = new Host(0, hostname, new HashMap<String, String>());
host = (Host) dao.create(host);
}
return host;
}
public void releaseJoblet(int jobletId) throws InvalidApiKey,
TransportException, InvalidJobletId {
log.trace("releaseJoblet()");
Criteria crit = queryDAO.createCriteria(Joblet.class);
crit.add(Restrictions.eq("id", jobletId));
crit.add(Restrictions.or(Restrictions.eq("status", JOB_STATUS.QUEUED),
Restrictions.eq("status", JOB_STATUS.PROCESSING)));
crit.setLockMode(LockMode.UPGRADE);
Joblet joblet = (Joblet) crit.uniqueResult();
if (joblet == null)
throw new InvalidJobletId();
joblet.setStatus(JOB_STATUS.RECEIVED);
dao.update(joblet);
}
public void setHostFacts(int hostid, Map<String, String> facts)
throws TransportException, InvalidApiKey, InvalidHost {
log.trace("setHostFacts()");
Host host = null;
try {
host = (Host) dao.read(Host.class, hostid);
} catch (ObjectRetrievalFailureException e) {
throw new InvalidHost();
}
Map<String, String> oldFacts = host.getFacts();
if (oldFacts == null) {
oldFacts = new HashMap<String, String>();
} else {
oldFacts.putAll(facts);
}
Set<Entry<String, String>> entries = oldFacts.entrySet();
for (Entry<String, String> entry : entries) {
if (entry.getValue().length() > 500) {
oldFacts
.put(entry.getKey(), entry.getValue().substring(0, 499));
}
}
dao.update(host);
}
public int submitJob(Job job) throws TransportException, InvalidApiKey {
log.trace("submitJob()");
List<Joblet> joblets = new LinkedList<Joblet>();
for (Joblet joblet : job.getJoblets()) {
joblet.setJobId(0);
joblet.setTimeCreated(System.currentTimeMillis());
Joblet j = (Joblet) dao.create(joblet);
joblets.add(j);
}
job.setJoblets(joblets);
job = (Job) dao.create(job);
return job.getId();
}
public int submitJoblet(Joblet joblet, int jobId, int callbackType,
String callbackAddress, String callbackContent)
throws TransportException, InvalidApiKey, InvalidJobId {
log.trace("submitJoblet()");
Job job = null;
if (jobId != 0) {
try {
job = (Job) dao.read(Job.class, jobId);
} catch (ObjectRetrievalFailureException e) {
throw new InvalidJobId();
}
} else {
List<Joblet> joblets = new LinkedList<Joblet>();
job = new Job(0, System.currentTimeMillis(), joblet.getSubmitter(),
null, joblets, callbackType, callbackAddress,
callbackContent, JOB_STATUS.RECEIVED);
job = (Job) dao.create(job);
}
job.getJoblets().add(joblet);
joblet.setJobId(job.getId());
joblet.setTimeCreated(System.currentTimeMillis());
joblet = (Joblet) dao.create(joblet);
dao.update(job);
return joblet.getId();
}
private Joblet readJoblet(int id) throws InvalidJobletId {
log.trace("readJoblet()");
try {
return (Joblet) dao.read(Joblet.class, id);
} catch (ObjectRetrievalFailureException e) {
throw new InvalidJobletId();
}
}
private Host readHost(int id) throws InvalidHost {
log.trace("readHost()");
try {
return (Host) dao.read(Host.class, id);
} catch (ObjectRetrievalFailureException e) {
throw new InvalidHost();
}
}
}
| true | true | public void completeJoblet(int jobletId, JobletResult result,
String logMessage) throws TransportException, InvalidApiKey,
InvalidJobletId {
log.trace("completeJoblet()");
Joblet joblet = readJoblet(jobletId);
joblet.setStatus(result.getStatus());
dao.update(joblet);
result.setJoblet(joblet);
result.setTimeCreated(System.currentTimeMillis());
dao.create(result);
if ((logMessage != null) && (logMessage.length() > 0)) {
JobletLogEntry log = new JobletLogEntry(0, joblet, logMessage);
dao.create(log);
}
// count joblets still in received/queued/processing
Criteria crit = queryDAO.createCriteria(Joblet.class);
crit.add(Restrictions.eq("jobId", joblet.getJobId()));
crit.add(Restrictions.or(
Restrictions.eq("status", JOB_STATUS.RECEIVED), Restrictions
.or(Restrictions.eq("status", JOB_STATUS.QUEUED),
Restrictions
.eq("status", JOB_STATUS.PROCESSING))));
crit.setProjection(Projections.rowCount());
int active = ((Integer) crit.list().get(0)).intValue();
if (active == 0) {
// update any saved joblets to received
Query query = queryDAO
.createQuery("update Joblet set status = ? where (jobId = ? and status = ?)");
query.setInteger(0, JOB_STATUS.RECEIVED);
query.setInteger(1, joblet.getJobId());
query.setInteger(2, JOB_STATUS.SAVED);
active = query.executeUpdate();
}
if (active == 0) {
// provision callback
Job job = (Job) dao.read(Job.class, joblet.getJobId());
// look for failures
Criteria failures = queryDAO.createCriteria(Joblet.class);
failures.add(Restrictions.eq("jobId", job.getId()));
failures.add(Restrictions.eq("status", JOB_STATUS.FAILED));
failures.setProjection(Projections.rowCount());
int failureCount = ((Integer) failures.list().get(0)).intValue();
int jobStatus = (failureCount == 0) ? JOB_STATUS.COMPLETED
: JOB_STATUS.FAILED;
// update job
job.setStatus(jobStatus);
job = (Job) dao.update(job);
if ((job.getCallbackType() != 0)
&& (job.getCallbackType() != JOB_CALLBACK_TYPES.NONE)) {
Map<String, String> params = new HashMap<String, String>();
params.put("jobId", Integer.toString(job.getId()));
params.put("jobStatus", jobStatusTypes[jobStatus]);
params.put("callbackType", ApiCallbackTypes
.getStringCallbackType(job.getCallbackType()));
params.put("callbackAddress", job.getCallbackAddress());
Joblet callback = new Joblet(0, System.currentTimeMillis(), 0,
0, job.getSubmitter(), 2, Constants.CALLBACK_JOBLET,
"Callback for job # ", params, null,
JOB_STATUS.RECEIVED);
try {
self.submitJoblet(callback, 0, JOB_CALLBACK_TYPES.NONE,
null, null);
} catch (InvalidJobId e) {
log.error("InvalidJobId called while submitting callback!",
e);
}
}
}
}
| public void completeJoblet(int jobletId, JobletResult result,
String logMessage) throws TransportException, InvalidApiKey,
InvalidJobletId {
log.trace("completeJoblet()");
Joblet joblet = readJoblet(jobletId);
joblet.setStatus(result.getStatus());
dao.update(joblet);
result.setJoblet(joblet);
result.setTimeCreated(System.currentTimeMillis());
dao.create(result);
if ((logMessage != null) && (logMessage.length() > 0)) {
JobletLogEntry log = new JobletLogEntry(0, joblet, logMessage);
dao.create(log);
}
// count joblets still in received/queued/processing
Criteria crit = queryDAO.createCriteria(Joblet.class);
crit.add(Restrictions.eq("jobId", joblet.getJobId()));
crit.add(Restrictions.or(
Restrictions.eq("status", JOB_STATUS.RECEIVED), Restrictions
.or(Restrictions.eq("status", JOB_STATUS.QUEUED),
Restrictions
.eq("status", JOB_STATUS.PROCESSING))));
crit.setProjection(Projections.rowCount());
int active = ((Integer) crit.list().get(0)).intValue();
if (active == 0) {
// update any saved joblets to received
Query query = queryDAO
.createQuery("update Joblet set status = ? where (jobId = ? and status = ?)");
query.setInteger(0, JOB_STATUS.RECEIVED);
query.setInteger(1, joblet.getJobId());
query.setInteger(2, JOB_STATUS.SAVED);
active = query.executeUpdate();
}
if (active == 0) {
// provision callback
Job job = (Job) dao.read(Job.class, joblet.getJobId());
// look for failures
Criteria failures = queryDAO.createCriteria(Joblet.class);
failures.add(Restrictions.eq("jobId", job.getId()));
failures.add(Restrictions.eq("status", JOB_STATUS.FAILED));
failures.setProjection(Projections.rowCount());
int failureCount = ((Integer) failures.list().get(0)).intValue();
int jobStatus = (failureCount == 0) ? JOB_STATUS.COMPLETED
: JOB_STATUS.FAILED;
// update job
job.setStatus(jobStatus);
job = (Job) dao.update(job);
if ((job.getCallbackType() != 0)
&& (job.getCallbackType() != JOB_CALLBACK_TYPES.NONE)) {
Map<String, String> params = new HashMap<String, String>();
params.put("jobId", Integer.toString(job.getId()));
params.put("jobStatus", jobStatusTypes[jobStatus]);
params.put("callbackType", ApiCallbackTypes
.getStringCallbackType(job.getCallbackType()));
params.put("callbackAddress", job.getCallbackAddress());
Joblet callback = new Joblet(0, System.currentTimeMillis(), 0,
0, job.getSubmitter(), 2, Constants.CALLBACK_JOBLET,
"Callback for job # ", params, job.getCallbackContent(),
JOB_STATUS.RECEIVED);
try {
self.submitJoblet(callback, 0, JOB_CALLBACK_TYPES.NONE,
null, null);
} catch (InvalidJobId e) {
log.error("InvalidJobId called while submitting callback!",
e);
}
}
}
}
|
diff --git a/modules/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/TagsGet.java b/modules/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/TagsGet.java
index 0c1f9cbc..37b23abd 100644
--- a/modules/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/TagsGet.java
+++ b/modules/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/TagsGet.java
@@ -1,43 +1,43 @@
/* 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.activiti.rest.api.cycle;
import java.util.List;
import java.util.Map;
import org.activiti.rest.util.ActivitiRequest;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.Status;
/**
* @author Nils Preusker ([email protected])
*/
public class TagsGet extends ActivitiCycleWebScript {
@Override
void execute(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
String connectorId = req.getString("connectorId");
- String repositoryNodeId = req.getString("repositoryNodeId");
+ String repositoryNodeId = req.getString("nodeId");
String tag = req.getString("tag");
List<String> tags;
if (connectorId != null && repositoryNodeId != null) {
tags = tagService.getTags(connectorId, repositoryNodeId);
} else {
tags = tagService.getSimiliarTagNames(tag != null ? tag : "");
}
model.put("tags", tags);
}
}
| true | true | void execute(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
String connectorId = req.getString("connectorId");
String repositoryNodeId = req.getString("repositoryNodeId");
String tag = req.getString("tag");
List<String> tags;
if (connectorId != null && repositoryNodeId != null) {
tags = tagService.getTags(connectorId, repositoryNodeId);
} else {
tags = tagService.getSimiliarTagNames(tag != null ? tag : "");
}
model.put("tags", tags);
}
| void execute(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
String connectorId = req.getString("connectorId");
String repositoryNodeId = req.getString("nodeId");
String tag = req.getString("tag");
List<String> tags;
if (connectorId != null && repositoryNodeId != null) {
tags = tagService.getTags(connectorId, repositoryNodeId);
} else {
tags = tagService.getSimiliarTagNames(tag != null ? tag : "");
}
model.put("tags", tags);
}
|
diff --git a/GitHubTest/src/com/gingbear/githubtest/WifiChange.java b/GitHubTest/src/com/gingbear/githubtest/WifiChange.java
index 2d97f3e..5b298e6 100644
--- a/GitHubTest/src/com/gingbear/githubtest/WifiChange.java
+++ b/GitHubTest/src/com/gingbear/githubtest/WifiChange.java
@@ -1,75 +1,75 @@
package com.gingbear.githubtest;
import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
public class WifiChange {
static public String check(Intent intent){
String action = intent.getAction();
// BroadcastReceiver が Wifi の ON/OFF を検知して起動されたら
// if(action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)){
// WifiManager wifi = (WifiManager)getSystemService(WIFI_SERVICE);
// // Wifi が ON になったら OFF
// wifi.setWifiEnabled(false);
// 任意のタイミングで ON/OFF の状態を取得したい場合 wifi.isWifiEnabled(); で取得する
// Wifi の状態を取得
switch (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)){
case WifiManager.WIFI_STATE_DISABLING:
return "0:WIFI_STATE_DISABLING";
case WifiManager.WIFI_STATE_DISABLED:
return "1:WIFI_STATE_DISABLED";
case WifiManager.WIFI_STATE_ENABLING:
return "3:WIFI_STATE_ENABLING";
case WifiManager.WIFI_STATE_ENABLED:
return "4:WIFI_STATE_ENABLED";
case WifiManager.WIFI_STATE_UNKNOWN:
return "5:WIFI_STATE_UNKNOWN";
default:
return "wifi error";
}
// }
// return "non";
}
static public String change(Activity activity){
Intent intent = activity.getIntent();
// String action = intent.getAction();
// BroadcastReceiver がネットワークへの接続を検知して起動されたら
// if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
ConnectivityManager cm = (ConnectivityManager)activity.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
- if((ni!=null) && (ni.isConnected() && (ni.getType() == ConnectivityManager.TYPE_WIFI))){
+ if((ni!=null) && (ni.isConnected())){
switch (ni.getType() ){
case ConnectivityManager.TYPE_WIFI:
return "1:TYPE_WIFI";
case ConnectivityManager.TYPE_MOBILE:
return "0:TYPE_MOBILE";
case ConnectivityManager.TYPE_MOBILE_DUN:
return "4:TYPE_MOBILE_DUN";
case ConnectivityManager.TYPE_MOBILE_HIPRI:
return "5:TYPE_MOBILE_HIPRI";
case ConnectivityManager.TYPE_MOBILE_MMS:
return "2:TYPE_MOBILE_MMS";
case ConnectivityManager.TYPE_MOBILE_SUPL:
return "3:TYPE_MOBILE_SUPL";
case ConnectivityManager.TYPE_WIMAX:
return "6:TYPE_WIMAX";
default:
return "connect error";
}
// Wifi に接続中!TYPE_MOBILE だったらモバイルネットワークに接続中ということになる
}else{
// WifiManager wifi = (WifiManager)getSystemService(WIFI_SERVICE);
// // Wifi に接続してなかったら Wifi を OFF
// wifi.setWifiEnabled(false);
return "not connect";
}
// }
// return "non";
}
}
| true | true | static public String change(Activity activity){
Intent intent = activity.getIntent();
// String action = intent.getAction();
// BroadcastReceiver がネットワークへの接続を検知して起動されたら
// if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
ConnectivityManager cm = (ConnectivityManager)activity.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if((ni!=null) && (ni.isConnected() && (ni.getType() == ConnectivityManager.TYPE_WIFI))){
switch (ni.getType() ){
case ConnectivityManager.TYPE_WIFI:
return "1:TYPE_WIFI";
case ConnectivityManager.TYPE_MOBILE:
return "0:TYPE_MOBILE";
case ConnectivityManager.TYPE_MOBILE_DUN:
return "4:TYPE_MOBILE_DUN";
case ConnectivityManager.TYPE_MOBILE_HIPRI:
return "5:TYPE_MOBILE_HIPRI";
case ConnectivityManager.TYPE_MOBILE_MMS:
return "2:TYPE_MOBILE_MMS";
case ConnectivityManager.TYPE_MOBILE_SUPL:
return "3:TYPE_MOBILE_SUPL";
case ConnectivityManager.TYPE_WIMAX:
return "6:TYPE_WIMAX";
default:
return "connect error";
}
// Wifi に接続中!TYPE_MOBILE だったらモバイルネットワークに接続中ということになる
}else{
// WifiManager wifi = (WifiManager)getSystemService(WIFI_SERVICE);
// // Wifi に接続してなかったら Wifi を OFF
// wifi.setWifiEnabled(false);
return "not connect";
}
// }
// return "non";
}
| static public String change(Activity activity){
Intent intent = activity.getIntent();
// String action = intent.getAction();
// BroadcastReceiver がネットワークへの接続を検知して起動されたら
// if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
ConnectivityManager cm = (ConnectivityManager)activity.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if((ni!=null) && (ni.isConnected())){
switch (ni.getType() ){
case ConnectivityManager.TYPE_WIFI:
return "1:TYPE_WIFI";
case ConnectivityManager.TYPE_MOBILE:
return "0:TYPE_MOBILE";
case ConnectivityManager.TYPE_MOBILE_DUN:
return "4:TYPE_MOBILE_DUN";
case ConnectivityManager.TYPE_MOBILE_HIPRI:
return "5:TYPE_MOBILE_HIPRI";
case ConnectivityManager.TYPE_MOBILE_MMS:
return "2:TYPE_MOBILE_MMS";
case ConnectivityManager.TYPE_MOBILE_SUPL:
return "3:TYPE_MOBILE_SUPL";
case ConnectivityManager.TYPE_WIMAX:
return "6:TYPE_WIMAX";
default:
return "connect error";
}
// Wifi に接続中!TYPE_MOBILE だったらモバイルネットワークに接続中ということになる
}else{
// WifiManager wifi = (WifiManager)getSystemService(WIFI_SERVICE);
// // Wifi に接続してなかったら Wifi を OFF
// wifi.setWifiEnabled(false);
return "not connect";
}
// }
// return "non";
}
|
diff --git a/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/associations/collection/unidirectional/CollectionUnidirectionalTest.java b/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/associations/collection/unidirectional/CollectionUnidirectionalTest.java
index afa3a60eb..eee6448c6 100644
--- a/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/associations/collection/unidirectional/CollectionUnidirectionalTest.java
+++ b/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/associations/collection/unidirectional/CollectionUnidirectionalTest.java
@@ -1,104 +1,104 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat, Inc. and/or its affiliates or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat, Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ogm.test.associations.collection.unidirectional;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.ogm.test.simpleentity.OgmTestCase;
/**
* @author Emmanuel Bernard
*/
public class CollectionUnidirectionalTest extends OgmTestCase {
public void testUnidirectionalCollection() throws Exception {
final Session session = openSession();
Transaction transaction = session.beginTransaction();
SnowFlake sf = new SnowFlake();
sf.setDescription( "Snowflake 1" );
session.save( sf );
SnowFlake sf2 = new SnowFlake();
- sf.setDescription( "Snowflake 2" );
+ sf2.setDescription( "Snowflake 2" );
session.save( sf2 );
Cloud cloud = new Cloud();
cloud.setLength( 23 );
cloud.getProducedSnowFlakes().add( sf );
cloud.getProducedSnowFlakes().add( sf2 );
session.persist( cloud );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 2, cloud.getProducedSnowFlakes().size() );
final SnowFlake removedSf = cloud.getProducedSnowFlakes().iterator().next();
SnowFlake sf3 = new SnowFlake();
sf3.setDescription( "Snowflake 3" );
session.persist( sf3 );
cloud.getProducedSnowFlakes().remove( removedSf );
cloud.getProducedSnowFlakes().add( sf3 );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 2, cloud.getProducedSnowFlakes().size() );
boolean present = false;
for ( SnowFlake current : cloud.getProducedSnowFlakes() ) {
if ( current.getDescription().equals( removedSf.getDescription() ) ) {
present = true;
}
}
assertFalse( "flake not removed", present );
for ( SnowFlake current : cloud.getProducedSnowFlakes() ) {
session.delete( current );
}
session.delete( session.load( SnowFlake.class, removedSf.getId() ) );
cloud.getProducedSnowFlakes().clear();
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 0, cloud.getProducedSnowFlakes().size() );
session.delete( cloud );
transaction.commit();
session.close();
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Cloud.class,
SnowFlake.class
};
}
}
| true | true | public void testUnidirectionalCollection() throws Exception {
final Session session = openSession();
Transaction transaction = session.beginTransaction();
SnowFlake sf = new SnowFlake();
sf.setDescription( "Snowflake 1" );
session.save( sf );
SnowFlake sf2 = new SnowFlake();
sf.setDescription( "Snowflake 2" );
session.save( sf2 );
Cloud cloud = new Cloud();
cloud.setLength( 23 );
cloud.getProducedSnowFlakes().add( sf );
cloud.getProducedSnowFlakes().add( sf2 );
session.persist( cloud );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 2, cloud.getProducedSnowFlakes().size() );
final SnowFlake removedSf = cloud.getProducedSnowFlakes().iterator().next();
SnowFlake sf3 = new SnowFlake();
sf3.setDescription( "Snowflake 3" );
session.persist( sf3 );
cloud.getProducedSnowFlakes().remove( removedSf );
cloud.getProducedSnowFlakes().add( sf3 );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 2, cloud.getProducedSnowFlakes().size() );
boolean present = false;
for ( SnowFlake current : cloud.getProducedSnowFlakes() ) {
if ( current.getDescription().equals( removedSf.getDescription() ) ) {
present = true;
}
}
assertFalse( "flake not removed", present );
for ( SnowFlake current : cloud.getProducedSnowFlakes() ) {
session.delete( current );
}
session.delete( session.load( SnowFlake.class, removedSf.getId() ) );
cloud.getProducedSnowFlakes().clear();
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 0, cloud.getProducedSnowFlakes().size() );
session.delete( cloud );
transaction.commit();
session.close();
}
| public void testUnidirectionalCollection() throws Exception {
final Session session = openSession();
Transaction transaction = session.beginTransaction();
SnowFlake sf = new SnowFlake();
sf.setDescription( "Snowflake 1" );
session.save( sf );
SnowFlake sf2 = new SnowFlake();
sf2.setDescription( "Snowflake 2" );
session.save( sf2 );
Cloud cloud = new Cloud();
cloud.setLength( 23 );
cloud.getProducedSnowFlakes().add( sf );
cloud.getProducedSnowFlakes().add( sf2 );
session.persist( cloud );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 2, cloud.getProducedSnowFlakes().size() );
final SnowFlake removedSf = cloud.getProducedSnowFlakes().iterator().next();
SnowFlake sf3 = new SnowFlake();
sf3.setDescription( "Snowflake 3" );
session.persist( sf3 );
cloud.getProducedSnowFlakes().remove( removedSf );
cloud.getProducedSnowFlakes().add( sf3 );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 2, cloud.getProducedSnowFlakes().size() );
boolean present = false;
for ( SnowFlake current : cloud.getProducedSnowFlakes() ) {
if ( current.getDescription().equals( removedSf.getDescription() ) ) {
present = true;
}
}
assertFalse( "flake not removed", present );
for ( SnowFlake current : cloud.getProducedSnowFlakes() ) {
session.delete( current );
}
session.delete( session.load( SnowFlake.class, removedSf.getId() ) );
cloud.getProducedSnowFlakes().clear();
transaction.commit();
session.clear();
transaction = session.beginTransaction();
cloud = (Cloud) session.get( Cloud.class, cloud.getId() );
assertNotNull( cloud.getProducedSnowFlakes() );
assertEquals( 0, cloud.getProducedSnowFlakes().size() );
session.delete( cloud );
transaction.commit();
session.close();
}
|
diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/NovaException.java b/src/main/java/org/dasein/cloud/openstack/nova/os/NovaException.java
index 9db2f7d..aaa4fdc 100644
--- a/src/main/java/org/dasein/cloud/openstack/nova/os/NovaException.java
+++ b/src/main/java/org/dasein/cloud/openstack/nova/os/NovaException.java
@@ -1,120 +1,128 @@
/**
* Copyright (C) 2009-2013 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.openstack.nova.os;
import org.dasein.cloud.CloudErrorType;
import org.dasein.cloud.CloudException;
import org.json.JSONException;
import org.json.JSONObject;
public class NovaException extends CloudException {
private static final long serialVersionUID = -9188123825416917437L;
static public class ExceptionItems {
public CloudErrorType type;
public int code;
public String message;
public String details;
}
// //{"badRequest": {"message": "AddressLimitExceeded: Address quota exceeded. You cannot allocate any more addresses", "code": 400}}
static public ExceptionItems parseException(int code, String json) {
ExceptionItems items = new ExceptionItems();
items.code = code;
items.type = CloudErrorType.GENERAL;
items.message = "unknown";
- items.details = "The cloud provided an error code without explanation";
+ items.details = "The cloud returned an error code with explanation: ";
if( json != null ) {
try {
JSONObject ob = new JSONObject(json);
if( code == 400 && ob.has("badRequest") ) {
ob = ob.getJSONObject("badRequest");
}
if( code == 413 && ob.has("overLimit") ) {
ob = ob.getJSONObject("overLimit");
}
if( ob.has("message") ) {
items.message = ob.getString("message");
if( items.message == null ) {
items.message = "unknown";
}
else {
items.message = items.message.trim();
}
}
if (items.message.equals("unknown")) {
String[] names = JSONObject.getNames(ob);
for (String key : names) {
- if (key.contains("Error")) {
- items.message = ob.getString(key);
+ if (key.contains("Error") || key.contains("Fault")) {
+ try {
+ JSONObject msg = ob.getJSONObject(key);
+ if (msg.has("message") && !msg.isNull("message")) {
+ items.message = msg.getString("message");
+ }
+ }
+ catch (JSONException e) {
+ items.message = ob.getString(key);
+ }
}
}
}
if( ob.has("details") ) {
- items.details = ob.getString("details");
+ items.details = items.details + ob.getString("details");
}
else {
- items.details = "[" + code + "] " + items.message;
+ items.details = items.details + "[" + code + "] " + items.message;
}
String t = items.message.toLowerCase().trim();
if( code == 413 ) {
items.type = CloudErrorType.THROTTLING;
}
else if( t.startsWith("addresslimitexceeded") || t.startsWith("ramlimitexceeded")) {
items.type = CloudErrorType.QUOTA;
}
else if( t.equals("unauthorized") ) {
items.type = CloudErrorType.AUTHENTICATION;
}
else if( t.equals("serviceunavailable") ) {
items.type = CloudErrorType.CAPACITY;
}
else if( t.equals("badrequest") || t.equals("badmediatype") || t.equals("badmethod") || t.equals("notimplemented") ) {
items.type = CloudErrorType.COMMUNICATION;
}
else if( t.equals("overlimit") ) {
items.type = CloudErrorType.QUOTA;
}
else if( t.equals("servercapacityunavailable") ) {
items.type = CloudErrorType.CAPACITY;
}
else if( t.equals("itemnotfound") ) {
return null;
}
}
catch( JSONException e ) {
NovaOpenStack.getLogger(NovaException.class, "std").warn("parseException(): Invalid JSON in cloud response: " + json);
items.details = json;
}
}
return items;
}
public NovaException(ExceptionItems items) {
super(items.type, items.code, items.message, items.details);
}
public NovaException(CloudErrorType type, int code, String message, String details) {
super(type, code, message, details);
}
}
| false | true | static public ExceptionItems parseException(int code, String json) {
ExceptionItems items = new ExceptionItems();
items.code = code;
items.type = CloudErrorType.GENERAL;
items.message = "unknown";
items.details = "The cloud provided an error code without explanation";
if( json != null ) {
try {
JSONObject ob = new JSONObject(json);
if( code == 400 && ob.has("badRequest") ) {
ob = ob.getJSONObject("badRequest");
}
if( code == 413 && ob.has("overLimit") ) {
ob = ob.getJSONObject("overLimit");
}
if( ob.has("message") ) {
items.message = ob.getString("message");
if( items.message == null ) {
items.message = "unknown";
}
else {
items.message = items.message.trim();
}
}
if (items.message.equals("unknown")) {
String[] names = JSONObject.getNames(ob);
for (String key : names) {
if (key.contains("Error")) {
items.message = ob.getString(key);
}
}
}
if( ob.has("details") ) {
items.details = ob.getString("details");
}
else {
items.details = "[" + code + "] " + items.message;
}
String t = items.message.toLowerCase().trim();
if( code == 413 ) {
items.type = CloudErrorType.THROTTLING;
}
else if( t.startsWith("addresslimitexceeded") || t.startsWith("ramlimitexceeded")) {
items.type = CloudErrorType.QUOTA;
}
else if( t.equals("unauthorized") ) {
items.type = CloudErrorType.AUTHENTICATION;
}
else if( t.equals("serviceunavailable") ) {
items.type = CloudErrorType.CAPACITY;
}
else if( t.equals("badrequest") || t.equals("badmediatype") || t.equals("badmethod") || t.equals("notimplemented") ) {
items.type = CloudErrorType.COMMUNICATION;
}
else if( t.equals("overlimit") ) {
items.type = CloudErrorType.QUOTA;
}
else if( t.equals("servercapacityunavailable") ) {
items.type = CloudErrorType.CAPACITY;
}
else if( t.equals("itemnotfound") ) {
return null;
}
}
catch( JSONException e ) {
NovaOpenStack.getLogger(NovaException.class, "std").warn("parseException(): Invalid JSON in cloud response: " + json);
items.details = json;
}
}
return items;
}
| static public ExceptionItems parseException(int code, String json) {
ExceptionItems items = new ExceptionItems();
items.code = code;
items.type = CloudErrorType.GENERAL;
items.message = "unknown";
items.details = "The cloud returned an error code with explanation: ";
if( json != null ) {
try {
JSONObject ob = new JSONObject(json);
if( code == 400 && ob.has("badRequest") ) {
ob = ob.getJSONObject("badRequest");
}
if( code == 413 && ob.has("overLimit") ) {
ob = ob.getJSONObject("overLimit");
}
if( ob.has("message") ) {
items.message = ob.getString("message");
if( items.message == null ) {
items.message = "unknown";
}
else {
items.message = items.message.trim();
}
}
if (items.message.equals("unknown")) {
String[] names = JSONObject.getNames(ob);
for (String key : names) {
if (key.contains("Error") || key.contains("Fault")) {
try {
JSONObject msg = ob.getJSONObject(key);
if (msg.has("message") && !msg.isNull("message")) {
items.message = msg.getString("message");
}
}
catch (JSONException e) {
items.message = ob.getString(key);
}
}
}
}
if( ob.has("details") ) {
items.details = items.details + ob.getString("details");
}
else {
items.details = items.details + "[" + code + "] " + items.message;
}
String t = items.message.toLowerCase().trim();
if( code == 413 ) {
items.type = CloudErrorType.THROTTLING;
}
else if( t.startsWith("addresslimitexceeded") || t.startsWith("ramlimitexceeded")) {
items.type = CloudErrorType.QUOTA;
}
else if( t.equals("unauthorized") ) {
items.type = CloudErrorType.AUTHENTICATION;
}
else if( t.equals("serviceunavailable") ) {
items.type = CloudErrorType.CAPACITY;
}
else if( t.equals("badrequest") || t.equals("badmediatype") || t.equals("badmethod") || t.equals("notimplemented") ) {
items.type = CloudErrorType.COMMUNICATION;
}
else if( t.equals("overlimit") ) {
items.type = CloudErrorType.QUOTA;
}
else if( t.equals("servercapacityunavailable") ) {
items.type = CloudErrorType.CAPACITY;
}
else if( t.equals("itemnotfound") ) {
return null;
}
}
catch( JSONException e ) {
NovaOpenStack.getLogger(NovaException.class, "std").warn("parseException(): Invalid JSON in cloud response: " + json);
items.details = json;
}
}
return items;
}
|
diff --git a/components/patient-update-listeners/src/main/java/org/phenotips/listeners/MeasurementAgeUpdater.java b/components/patient-update-listeners/src/main/java/org/phenotips/listeners/MeasurementAgeUpdater.java
index 801605ae7..1f00b24c1 100644
--- a/components/patient-update-listeners/src/main/java/org/phenotips/listeners/MeasurementAgeUpdater.java
+++ b/components/patient-update-listeners/src/main/java/org/phenotips/listeners/MeasurementAgeUpdater.java
@@ -1,105 +1,109 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.phenotips.listeners;
import org.phenotips.Constants;
import org.xwiki.bridge.event.DocumentCreatingEvent;
import org.xwiki.bridge.event.DocumentUpdatingEvent;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.event.Event;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.inject.Named;
import javax.inject.Singleton;
import org.joda.time.DateTime;
import org.joda.time.Months;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
/**
* Update the Age property whenever the birth date or measurement date properties are changed.
*
* @version $Id$
*/
@Component
@Named("measurement-age-updater")
@Singleton
public class MeasurementAgeUpdater implements EventListener
{
/** The name of the XProperty holding the age at the time of measurement, which will be updated by this listener. */
private static final String AGE_PROPERTY_NAME = "age";
/** The name of the XProperty holding the date when the measurement occurred. */
private static final String DATE_PROPERTY_NAME = "date";
@Override
public String getName()
{
return "measurement-age-updater";
}
@Override
public List<Event> getEvents()
{
// The list of events this listener listens to
return Arrays.<Event> asList(new DocumentCreatingEvent(), new DocumentUpdatingEvent());
}
@Override
public void onEvent(Event event, Object source, Object data)
{
XWikiDocument doc = (XWikiDocument) source;
BaseObject patientRecordObj = doc.getXObject(new DocumentReference(
doc.getDocumentReference().getRoot().getName(), Constants.CODE_SPACE, "PatientClass"));
if (patientRecordObj == null) {
return;
}
Date birthDate = patientRecordObj.getDateValue("date_of_birth");
if (birthDate == null) {
return;
}
List<BaseObject> objects = doc.getXObjects(new DocumentReference(
doc.getDocumentReference().getRoot().getName(), Constants.CODE_SPACE, "MeasurementsClass"));
if (objects == null || objects.isEmpty()) {
return;
}
for (BaseObject measurement : objects) {
if (measurement == null) {
continue;
+ } else if ("birth".equals(measurement.getStringValue("type"))) {
+ measurement.setIntValue(AGE_PROPERTY_NAME, 0);
+ measurement.removeField(DATE_PROPERTY_NAME);
+ continue;
}
Date measurementDate = measurement.getDateValue(DATE_PROPERTY_NAME);
if (measurementDate == null) {
measurement.removeField(AGE_PROPERTY_NAME);
} else {
int age = Months.monthsBetween(new DateTime(birthDate), new DateTime(measurementDate)).getMonths();
measurement.setIntValue(AGE_PROPERTY_NAME, age);
}
}
}
}
| true | true | public void onEvent(Event event, Object source, Object data)
{
XWikiDocument doc = (XWikiDocument) source;
BaseObject patientRecordObj = doc.getXObject(new DocumentReference(
doc.getDocumentReference().getRoot().getName(), Constants.CODE_SPACE, "PatientClass"));
if (patientRecordObj == null) {
return;
}
Date birthDate = patientRecordObj.getDateValue("date_of_birth");
if (birthDate == null) {
return;
}
List<BaseObject> objects = doc.getXObjects(new DocumentReference(
doc.getDocumentReference().getRoot().getName(), Constants.CODE_SPACE, "MeasurementsClass"));
if (objects == null || objects.isEmpty()) {
return;
}
for (BaseObject measurement : objects) {
if (measurement == null) {
continue;
}
Date measurementDate = measurement.getDateValue(DATE_PROPERTY_NAME);
if (measurementDate == null) {
measurement.removeField(AGE_PROPERTY_NAME);
} else {
int age = Months.monthsBetween(new DateTime(birthDate), new DateTime(measurementDate)).getMonths();
measurement.setIntValue(AGE_PROPERTY_NAME, age);
}
}
}
| public void onEvent(Event event, Object source, Object data)
{
XWikiDocument doc = (XWikiDocument) source;
BaseObject patientRecordObj = doc.getXObject(new DocumentReference(
doc.getDocumentReference().getRoot().getName(), Constants.CODE_SPACE, "PatientClass"));
if (patientRecordObj == null) {
return;
}
Date birthDate = patientRecordObj.getDateValue("date_of_birth");
if (birthDate == null) {
return;
}
List<BaseObject> objects = doc.getXObjects(new DocumentReference(
doc.getDocumentReference().getRoot().getName(), Constants.CODE_SPACE, "MeasurementsClass"));
if (objects == null || objects.isEmpty()) {
return;
}
for (BaseObject measurement : objects) {
if (measurement == null) {
continue;
} else if ("birth".equals(measurement.getStringValue("type"))) {
measurement.setIntValue(AGE_PROPERTY_NAME, 0);
measurement.removeField(DATE_PROPERTY_NAME);
continue;
}
Date measurementDate = measurement.getDateValue(DATE_PROPERTY_NAME);
if (measurementDate == null) {
measurement.removeField(AGE_PROPERTY_NAME);
} else {
int age = Months.monthsBetween(new DateTime(birthDate), new DateTime(measurementDate)).getMonths();
measurement.setIntValue(AGE_PROPERTY_NAME, age);
}
}
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/EnvServlet.java b/GAE/src/org/waterforpeople/mapping/app/web/EnvServlet.java
index 2c7892e77..0a0dd3fe4 100644
--- a/GAE/src/org/waterforpeople/mapping/app/web/EnvServlet.java
+++ b/GAE/src/org/waterforpeople/mapping/app/web/EnvServlet.java
@@ -1,125 +1,125 @@
/*
* Copyright (C) 2013 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.app.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.json.JSONArray;
import org.json.JSONObject;
import org.waterforpeople.mapping.app.web.rest.security.AppRole;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.common.util.PropertyUtil;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.gis.geography.domain.Country;
public class EnvServlet extends HttpServlet {
private static final long serialVersionUID = 7830536065252808839L;
private static final Logger log = Logger.getLogger(EnvServlet.class
.getName());
private static final ArrayList<String> properties = new ArrayList<String>();
static {
properties.add("photo_url_root");
properties.add("imageroot");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final VelocityEngine engine = new VelocityEngine();
engine.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.NullLogChute");
try {
engine.init();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not initialize velocity", e);
}
Template t = null;
try {
t = engine.getTemplate("Env.vm");
} catch (Exception e) {
log.log(Level.SEVERE, "Could not get the template `CurrentUser`", e);
return;
}
final VelocityContext context = new VelocityContext();
final Map<String, String> props = PropertyUtil
.getPropertiesMap(properties);
final BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class);
final JSONArray jsonArray = new JSONArray();
for (Country c : countryDAO.list(Constants.ALL_RESULTS)) {
if (c.getIncludeInExternal() != null
&& c.getIncludeInExternal()
&& (c.getCentroidLat().equals(0d) || c.getCentroidLon()
.equals(0d))) {
log.log(Level.SEVERE,
"Country "
+ c.getIsoAlpha2Code()
+ " was configured to show in the map, but doesn't have proper centroids");
continue;
}
- if (c.getIncludeInExternal()) {
+ if (c.getIncludeInExternal() != null && c.getIncludeInExternal()) {
jsonArray.put(new JSONObject(c));
}
}
props.put("countries", jsonArray.toString());
context.put("env", props);
final List<Map<String, String>> roles = new ArrayList<Map<String, String>>();
for (AppRole r : AppRole.values()) {
if (r.getLevel() < 10) {
continue; // don't expose NEW_USER, nor SUPER_USER
}
Map<String, String> role = new HashMap<String, String>();
role.put("value", String.valueOf(r.getLevel()));
role.put("label", "_" + r.toString());
roles.add(role);
}
context.put("roles", roles);
final StringWriter writer = new StringWriter();
t.merge(context, writer);
resp.setContentType("application/javascript;charset=UTF-8");
final PrintWriter pw = resp.getWriter();
pw.println(writer.toString());
pw.close();
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final VelocityEngine engine = new VelocityEngine();
engine.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.NullLogChute");
try {
engine.init();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not initialize velocity", e);
}
Template t = null;
try {
t = engine.getTemplate("Env.vm");
} catch (Exception e) {
log.log(Level.SEVERE, "Could not get the template `CurrentUser`", e);
return;
}
final VelocityContext context = new VelocityContext();
final Map<String, String> props = PropertyUtil
.getPropertiesMap(properties);
final BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class);
final JSONArray jsonArray = new JSONArray();
for (Country c : countryDAO.list(Constants.ALL_RESULTS)) {
if (c.getIncludeInExternal() != null
&& c.getIncludeInExternal()
&& (c.getCentroidLat().equals(0d) || c.getCentroidLon()
.equals(0d))) {
log.log(Level.SEVERE,
"Country "
+ c.getIsoAlpha2Code()
+ " was configured to show in the map, but doesn't have proper centroids");
continue;
}
if (c.getIncludeInExternal()) {
jsonArray.put(new JSONObject(c));
}
}
props.put("countries", jsonArray.toString());
context.put("env", props);
final List<Map<String, String>> roles = new ArrayList<Map<String, String>>();
for (AppRole r : AppRole.values()) {
if (r.getLevel() < 10) {
continue; // don't expose NEW_USER, nor SUPER_USER
}
Map<String, String> role = new HashMap<String, String>();
role.put("value", String.valueOf(r.getLevel()));
role.put("label", "_" + r.toString());
roles.add(role);
}
context.put("roles", roles);
final StringWriter writer = new StringWriter();
t.merge(context, writer);
resp.setContentType("application/javascript;charset=UTF-8");
final PrintWriter pw = resp.getWriter();
pw.println(writer.toString());
pw.close();
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final VelocityEngine engine = new VelocityEngine();
engine.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.NullLogChute");
try {
engine.init();
} catch (Exception e) {
log.log(Level.SEVERE, "Could not initialize velocity", e);
}
Template t = null;
try {
t = engine.getTemplate("Env.vm");
} catch (Exception e) {
log.log(Level.SEVERE, "Could not get the template `CurrentUser`", e);
return;
}
final VelocityContext context = new VelocityContext();
final Map<String, String> props = PropertyUtil
.getPropertiesMap(properties);
final BaseDAO<Country> countryDAO = new BaseDAO<Country>(Country.class);
final JSONArray jsonArray = new JSONArray();
for (Country c : countryDAO.list(Constants.ALL_RESULTS)) {
if (c.getIncludeInExternal() != null
&& c.getIncludeInExternal()
&& (c.getCentroidLat().equals(0d) || c.getCentroidLon()
.equals(0d))) {
log.log(Level.SEVERE,
"Country "
+ c.getIsoAlpha2Code()
+ " was configured to show in the map, but doesn't have proper centroids");
continue;
}
if (c.getIncludeInExternal() != null && c.getIncludeInExternal()) {
jsonArray.put(new JSONObject(c));
}
}
props.put("countries", jsonArray.toString());
context.put("env", props);
final List<Map<String, String>> roles = new ArrayList<Map<String, String>>();
for (AppRole r : AppRole.values()) {
if (r.getLevel() < 10) {
continue; // don't expose NEW_USER, nor SUPER_USER
}
Map<String, String> role = new HashMap<String, String>();
role.put("value", String.valueOf(r.getLevel()));
role.put("label", "_" + r.toString());
roles.add(role);
}
context.put("roles", roles);
final StringWriter writer = new StringWriter();
t.merge(context, writer);
resp.setContentType("application/javascript;charset=UTF-8");
final PrintWriter pw = resp.getWriter();
pw.println(writer.toString());
pw.close();
}
|
diff --git a/hw4/server/src/irc/Reactor.java b/hw4/server/src/irc/Reactor.java
index e54aa72..caab6d3 100644
--- a/hw4/server/src/irc/Reactor.java
+++ b/hw4/server/src/irc/Reactor.java
@@ -1,244 +1,244 @@
package irc;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
* An implementation of the Reactor pattern.
*/
public class Reactor<T> implements Runnable {
private static final Logger logger = Logger.getLogger("edu.spl.reactor");
private final int _port;
private final int _poolSize;
private final ServerProtocolFactory<T> _protocolFactory;
private final TokenizerFactory<T> _tokenizerFactory;
private volatile boolean _shouldRun = true;
private ReactorData<T> _data;
/**
* Creates a new Reactor
*
* @param poolSize
* the number of WorkerThreads to include in the ThreadPool
* @param port
* the port to bind the Reactor to
* @param protocol
* the protocol factory to work with
* @param tokenizer
* the tokenizer factory to work with
* @throws IOException
* if some I/O problems arise during connection
*/
public Reactor(int port, int poolSize, ServerProtocolFactory<T> protocol, TokenizerFactory<T> tokenizer) {
_port = port;
_poolSize = poolSize;
_protocolFactory = protocol;
_tokenizerFactory = tokenizer;
}
/**
* Create a non-blocking server socket channel and bind to to the Reactor
* port
*/
private ServerSocketChannel createServerSocket(int port)
throws IOException {
try {
ServerSocketChannel ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(false);
ssChannel.socket().bind(new InetSocketAddress(port));
return ssChannel;
} catch (IOException e) {
logger.info("Port " + port + " is busy");
throw e;
}
}
/**
* Main operation of the Reactor:
* <UL>
* <LI>Uses the <CODE>Selector.select()</CODE> method to find new
* requests from clients
* <LI>For each request in the selection set:
* <UL>
* If it is <B>acceptable</B>, use the ConnectionAcceptor to accept it,
* create a new ConnectionHandler for it register it to the Selector
* <LI>If it is <B>readable</B>, use the ConnectionHandler to read it,
* extract messages and insert them to the ThreadPool
* </UL>
*/
public void run() {
// Create & start the ThreadPool
ExecutorService executor = Executors.newFixedThreadPool(_poolSize);
Selector selector = null;
ServerSocketChannel ssChannel = null;
try {
selector = Selector.open();
ssChannel = createServerSocket(_port);
} catch (IOException e) {
logger.info("cannot create the selector -- server socket is busy?");
return;
}
_data = new ReactorData<T>(executor, selector, _protocolFactory, _tokenizerFactory);
- ConnectionAcceptor<T> connectionAcceptor = new ConnectionAcceptor<T>( ssChannel, _data);
+ ReactorConnectionAcceptor<T> ReactorconnectionAcceptor = new ReactorConnectionAcceptor<T>( ssChannel, _data);
// Bind the server socket channel to the selector, with the new
// acceptor as attachment
try {
- ssChannel.register(selector, SelectionKey.OP_ACCEPT, connectionAcceptor);
+ ssChannel.register(selector, SelectionKey.OP_ACCEPT, ReactorconnectionAcceptor);
} catch (ClosedChannelException e) {
logger.info("server channel seems to be closed!");
return;
}
while (_shouldRun && selector.isOpen()) {
// Wait for an event
try {
selector.select();
} catch (IOException e) {
logger.info("trouble with selector: " + e.getMessage());
continue;
}
// Get list of selection keys with pending events
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
// Process each key
while (it.hasNext()) {
// Get the selection key
SelectionKey selKey = (SelectionKey) it.next();
// Remove it from the list to indicate that it is being
// processed. it.remove removes the last item returned by next.
it.remove();
// Check if it's a connection request
if (selKey.isValid() && selKey.isAcceptable()) {
logger.info("Accepting a connection");
- ConnectionAcceptor<T> acceptor = (ConnectionAcceptor<T>) selKey.attachment();
+ ReactorConnectionAcceptor<T> acceptor = (ReactorConnectionAcceptor<T>) selKey.attachment();
try {
acceptor.accept();
} catch (IOException e) {
logger.info("problem accepting a new connection: "
+ e.getMessage());
}
continue;
}
// Check if a message has been sent
if (selKey.isValid() && selKey.isReadable()) {
- ConnectionHandler<T> handler = (ConnectionHandler<T>) selKey.attachment();
+ ReactorConnectionHandler<T> handler = (ReactorConnectionHandler<T>) selKey.attachment();
logger.info("Channel is ready for reading");
handler.read();
}
// Check if there are messages to send
if (selKey.isValid() && selKey.isWritable()) {
- ConnectionHandler<T> handler = (ConnectionHandler<T>) selKey.attachment();
+ ReactorConnectionHandler<T> handler = (ReactorConnectionHandler<T>) selKey.attachment();
logger.info("Channel is ready for writing");
handler.write();
}
}
}
stopReactor();
}
/**
* Returns the listening port of the Reactor
*
* @return the listening port of the Reactor
*/
public int getPort() {
return _port;
}
/**
* Stops the Reactor activity, including the Reactor thread and the Worker
* Threads in the Thread Pool.
*/
public synchronized void stopReactor() {
if (!_shouldRun)
return;
_shouldRun = false;
_data.getSelector().wakeup(); // Force select() to return
_data.getExecutor().shutdown();
try {
_data.getExecutor().awaitTermination(2000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// Someone didn't have patience to wait for the executor pool to
// close
e.printStackTrace();
}
}
/**
* Main program, used for demonstration purposes. Create and run a
* Reactor-based server for the Echo protocol. Listening port number and
* number of threads in the thread pool are read from the command line.
*/
public static void main(String args[]) {
// Test for errors.
if (args.length != 1) {
System.err.println(
"Not enough or too many arguments. " +
"use 'java Reactor <pool_size>");
System.exit(1);
}
try {
int port = 6667;
int poolSize = Integer.parseInt(args[0]);
Reactor<String> reactor = startIrcServer(port, poolSize);
Thread thread = new Thread(reactor);
thread.start();
logger.info(
"Reactor listening on 0.0.0.0:" + port + " ...");
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Reactor<String> startIrcServer(int port, int poolSize){
ServerProtocolFactory<String> protocolMaker = new ServerProtocolFactory<String>() {
public AsyncServerProtocol<String> create() {
return new IrcProtocol();
}
};
final Charset charset = Charset.forName("UTF-8");
TokenizerFactory<String> tokenizerMaker = new TokenizerFactory<String>() {
public MessageTokenizer<String> create() {
return new FixedSeparatorMessageTokenizer("\n", charset);
}
};
Reactor<String> reactor = new Reactor<String>(
port, poolSize, protocolMaker, tokenizerMaker);
return reactor;
}
}
| false | true | public void run() {
// Create & start the ThreadPool
ExecutorService executor = Executors.newFixedThreadPool(_poolSize);
Selector selector = null;
ServerSocketChannel ssChannel = null;
try {
selector = Selector.open();
ssChannel = createServerSocket(_port);
} catch (IOException e) {
logger.info("cannot create the selector -- server socket is busy?");
return;
}
_data = new ReactorData<T>(executor, selector, _protocolFactory, _tokenizerFactory);
ConnectionAcceptor<T> connectionAcceptor = new ConnectionAcceptor<T>( ssChannel, _data);
// Bind the server socket channel to the selector, with the new
// acceptor as attachment
try {
ssChannel.register(selector, SelectionKey.OP_ACCEPT, connectionAcceptor);
} catch (ClosedChannelException e) {
logger.info("server channel seems to be closed!");
return;
}
while (_shouldRun && selector.isOpen()) {
// Wait for an event
try {
selector.select();
} catch (IOException e) {
logger.info("trouble with selector: " + e.getMessage());
continue;
}
// Get list of selection keys with pending events
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
// Process each key
while (it.hasNext()) {
// Get the selection key
SelectionKey selKey = (SelectionKey) it.next();
// Remove it from the list to indicate that it is being
// processed. it.remove removes the last item returned by next.
it.remove();
// Check if it's a connection request
if (selKey.isValid() && selKey.isAcceptable()) {
logger.info("Accepting a connection");
ConnectionAcceptor<T> acceptor = (ConnectionAcceptor<T>) selKey.attachment();
try {
acceptor.accept();
} catch (IOException e) {
logger.info("problem accepting a new connection: "
+ e.getMessage());
}
continue;
}
// Check if a message has been sent
if (selKey.isValid() && selKey.isReadable()) {
ConnectionHandler<T> handler = (ConnectionHandler<T>) selKey.attachment();
logger.info("Channel is ready for reading");
handler.read();
}
// Check if there are messages to send
if (selKey.isValid() && selKey.isWritable()) {
ConnectionHandler<T> handler = (ConnectionHandler<T>) selKey.attachment();
logger.info("Channel is ready for writing");
handler.write();
}
}
}
stopReactor();
}
| public void run() {
// Create & start the ThreadPool
ExecutorService executor = Executors.newFixedThreadPool(_poolSize);
Selector selector = null;
ServerSocketChannel ssChannel = null;
try {
selector = Selector.open();
ssChannel = createServerSocket(_port);
} catch (IOException e) {
logger.info("cannot create the selector -- server socket is busy?");
return;
}
_data = new ReactorData<T>(executor, selector, _protocolFactory, _tokenizerFactory);
ReactorConnectionAcceptor<T> ReactorconnectionAcceptor = new ReactorConnectionAcceptor<T>( ssChannel, _data);
// Bind the server socket channel to the selector, with the new
// acceptor as attachment
try {
ssChannel.register(selector, SelectionKey.OP_ACCEPT, ReactorconnectionAcceptor);
} catch (ClosedChannelException e) {
logger.info("server channel seems to be closed!");
return;
}
while (_shouldRun && selector.isOpen()) {
// Wait for an event
try {
selector.select();
} catch (IOException e) {
logger.info("trouble with selector: " + e.getMessage());
continue;
}
// Get list of selection keys with pending events
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
// Process each key
while (it.hasNext()) {
// Get the selection key
SelectionKey selKey = (SelectionKey) it.next();
// Remove it from the list to indicate that it is being
// processed. it.remove removes the last item returned by next.
it.remove();
// Check if it's a connection request
if (selKey.isValid() && selKey.isAcceptable()) {
logger.info("Accepting a connection");
ReactorConnectionAcceptor<T> acceptor = (ReactorConnectionAcceptor<T>) selKey.attachment();
try {
acceptor.accept();
} catch (IOException e) {
logger.info("problem accepting a new connection: "
+ e.getMessage());
}
continue;
}
// Check if a message has been sent
if (selKey.isValid() && selKey.isReadable()) {
ReactorConnectionHandler<T> handler = (ReactorConnectionHandler<T>) selKey.attachment();
logger.info("Channel is ready for reading");
handler.read();
}
// Check if there are messages to send
if (selKey.isValid() && selKey.isWritable()) {
ReactorConnectionHandler<T> handler = (ReactorConnectionHandler<T>) selKey.attachment();
logger.info("Channel is ready for writing");
handler.write();
}
}
}
stopReactor();
}
|
diff --git a/src/com/github/peter200lx/toolbelt/tool/Paint.java b/src/com/github/peter200lx/toolbelt/tool/Paint.java
index 5e39dcb..3dce7dc 100644
--- a/src/com/github/peter200lx/toolbelt/tool/Paint.java
+++ b/src/com/github/peter200lx/toolbelt/tool/Paint.java
@@ -1,242 +1,246 @@
package com.github.peter200lx.toolbelt.tool;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.material.MaterialData;
import com.github.peter200lx.toolbelt.Tool;
public class Paint extends Tool {
public Paint(String modName, Server server, boolean debug,
boolean permissions, boolean useEvent) {
super(modName, server, debug, permissions, useEvent);
}
public static String name = "paint";
private Integer rangeDef = 0;
private Integer rangeCrouch = 25;
private HashMap<String, HashMap<Integer, MaterialData>> pPalette =
new HashMap<String, HashMap<Integer, MaterialData>>();
@Override
public String getToolName() {
return name;
}
@Override
public void handleInteract(PlayerInteractEvent event){
Player subject = event.getPlayer();
if(!delayElapsed(subject.getName()))
return;
if(!pPalette.containsKey(subject.getName())) {
pPalette.put(subject.getName(), new HashMap<Integer,MaterialData>());
}
switch(event.getAction()) {
case LEFT_CLICK_BLOCK:
case LEFT_CLICK_AIR:
//Acquire paint
MaterialData mdTarget = null;
if(event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
mdTarget = event.getClickedBlock().getState().getData();
if(subject.getGameMode().equals(GameMode.CREATIVE) &&(
mdTarget.getItemType().equals(Material.SIGN_POST) ||
mdTarget.getItemType().equals(Material.WALL_SIGN))){
subject.sendMessage("The sign is not erased on the server, "+
"it is just client side");
}
}else
mdTarget = subject.getTargetBlock(null, 200).getState().getData();
if(!stopCopy.contains(mdTarget.getItemType()) && ( onlyAllow.isEmpty() ||
onlyAllow.contains(mdTarget.getItemType()) ) ){
pPalette.get(subject.getName()).put(
subject.getInventory().getHeldItemSlot(), mdTarget );
paintPrint("Paint is now ",subject,mdTarget);
} else {
subject.sendMessage(ChatColor.RED + "Was not able to grab a block to paint.");
MaterialData old = pPalette.get(subject.getName()).get(
subject.getInventory().getHeldItemSlot());
paintPrint("Paint is still ",subject,old);
}
break;
case RIGHT_CLICK_BLOCK:
case RIGHT_CLICK_AIR:
//Draw paint
MaterialData set = pPalette.get(subject.getName()).get(
subject.getInventory().getHeldItemSlot());
if(set != null) {
Block bTarget = null;
if(hasRangePerm(subject) && event.getAction().equals(Action.RIGHT_CLICK_AIR) ){
if((rangeDef > 0) && !subject.isSneaking())
bTarget = subject.getTargetBlock(null, rangeDef);
else if((rangeCrouch > 0)&& subject.isSneaking())
bTarget = subject.getTargetBlock(null, rangeCrouch);
}else if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK))
bTarget = event.getClickedBlock();
if(bTarget != null && !stopOverwrite.contains(bTarget.getType()) &&
(onlyAllow.isEmpty() || onlyAllow.contains(bTarget.getType())) ){
if((bTarget.getType()==set.getItemType())&&(bTarget.getData()==set.getData())) {
//Don't replace blocks with the same type and data
return;
}
if(spawnBuild(bTarget,subject)) {
- if(isUseEvent())
- safeReplace(set,bTarget,subject,true);
- else
+ if(isUseEvent()) {
+ if(safeReplace(set,bTarget,subject,true)) {
+ subject.sendBlockChange(bTarget.getLocation(), set.getItemType(),set.getData());
+ }
+ }else {
bTarget.setTypeIdAndData(set.getItemTypeId(), set.getData(), false);
+ subject.sendBlockChange(bTarget.getLocation(), set.getItemType(), set.getData());
+ }
}
}else if(bTarget != null) {
if(bTarget.getType().equals(Material.AIR))
subject.sendMessage(ChatColor.RED + "Target is out of range");
else
subject.sendMessage(ChatColor.RED + "You can't overwrite "+
ChatColor.GOLD+bTarget.getType());
}
}
break;
default:
return;
}
}
private void paintPrint(String prefix, CommandSender subject, MaterialData m) {
if(m == null)
subject.sendMessage(ChatColor.RED + prefix + ChatColor.GOLD + "empty");
else if(printData.contains(m.getItemType())||(m.getData() != 0))
subject.sendMessage(ChatColor.GREEN + prefix + ChatColor.GOLD +
m.getItemType().toString() + ChatColor.WHITE + ":" +
ChatColor.BLUE + data2Str(m));
else
subject.sendMessage(ChatColor.GREEN + prefix + ChatColor.GOLD +
m.getItemType().toString());
}
private boolean hasRangePerm(CommandSender subject) {
if(isPermissions())
return subject.hasPermission(getPermStr()+".range");
else
return true;
}
@Override
public void handleItemChange(PlayerItemHeldEvent event) {
Player subject = event.getPlayer();
if(pPalette.containsKey(subject.getName()) &&
(pPalette.get(subject.getName()).size() > 1) ){
MaterialData c = pPalette.get(subject.getName()).get(event.getNewSlot());
paintPrint("Paint in this slot is ",subject,c);
}
}
@Override
public boolean printUse(CommandSender sender) {
if(hasPerm(sender)) {
sender.sendMessage("Left-click with the "+ChatColor.GOLD+getType()+
ChatColor.WHITE+" to load a block");
sender.sendMessage("Right-click with the "+ChatColor.GOLD+getType()+
ChatColor.WHITE+" to paint the loaded block");
if(hasRangePerm(sender)) {
if(rangeDef > 0)
sender.sendMessage("Be careful, you can paint at a range of up to "+
rangeDef+" blocks.");
if(rangeCrouch > 0)
sender.sendMessage("If you crouch, you can paint at a range of "+
rangeCrouch);
}
return true;
}
return false;
}
@Override
public boolean loadConf(String tSet, FileConfiguration conf) {
//Load the default restriction configuration
if(!loadGlobalRestrictions(tSet,conf))
return false;
//Load the repeat delay
if(!loadRepeatDelay(tSet,conf,0))
return false;
rangeDef = conf.getInt(tSet+"."+name+".rangeDefault", 0);
rangeCrouch = conf.getInt(tSet+"."+name+".rangeCrouch", 25);
if(isDebug()) {
log.info("["+modName+"][loadConf] Default painting range distance is set to "+
rangeDef);
log.info("["+modName+"][loadConf] Crouched painting range distance is set to "+
rangeCrouch);
}
List<Integer> intL = conf.getIntegerList(tSet+"."+name+".onlyAllow");
if(!intL.isEmpty())
{
if(isDebug())
log.info( "["+modName+"][loadConf] As "+name+".onlyAllow has items,"+
" it overwrites the global");
onlyAllow = loadMatList(intL,new HashSet<Material>(),tSet+"."+name+".onlyAllow");
if(onlyAllow == null)
return false;
if(isDebug()) {
logMatSet(onlyAllow,"loadGlobalRestrictions",name+".onlyAllow:");
log.info( "["+modName+"][loadConf] As "+name+".onlyAllow has items,"+
" only those materials are usable");
}
} else if(isDebug()&& !onlyAllow.isEmpty()) {
log.info( "["+modName+"][loadConf] As global.onlyAllow has items,"+
" only those materials are usable");
}
intL = conf.getIntegerList(tSet+"."+name+".stopCopy");
if(!intL.isEmpty())
{
if(isDebug())
log.info( "["+modName+"][loadConf] As "+name+".stopCopy has items,"+
" it overwrites the global");
stopCopy = loadMatList(intL,defStop(),tSet+"."+name+".stopCopy");
if(stopCopy == null)
return false;
if(isDebug()) logMatSet(stopCopy,"loadConf",name+".stopCopy:");
}
intL = conf.getIntegerList(tSet+"."+name+".stopOverwrite");
if(!intL.isEmpty())
{
if(isDebug())
log.info( "["+modName+"][loadConf] As "+name+".stopOverwrite has items,"+
" it overwrites the global");
stopOverwrite = loadMatList(intL,defStop(),tSet+"."+name+".stopOverwrite");
if(stopOverwrite == null)
return false;
if(isDebug()) logMatSet(stopOverwrite,"loadGlobalRestrictions",
name+".stopOverwrite:");
}
return true;
}
}
| false | true | public void handleInteract(PlayerInteractEvent event){
Player subject = event.getPlayer();
if(!delayElapsed(subject.getName()))
return;
if(!pPalette.containsKey(subject.getName())) {
pPalette.put(subject.getName(), new HashMap<Integer,MaterialData>());
}
switch(event.getAction()) {
case LEFT_CLICK_BLOCK:
case LEFT_CLICK_AIR:
//Acquire paint
MaterialData mdTarget = null;
if(event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
mdTarget = event.getClickedBlock().getState().getData();
if(subject.getGameMode().equals(GameMode.CREATIVE) &&(
mdTarget.getItemType().equals(Material.SIGN_POST) ||
mdTarget.getItemType().equals(Material.WALL_SIGN))){
subject.sendMessage("The sign is not erased on the server, "+
"it is just client side");
}
}else
mdTarget = subject.getTargetBlock(null, 200).getState().getData();
if(!stopCopy.contains(mdTarget.getItemType()) && ( onlyAllow.isEmpty() ||
onlyAllow.contains(mdTarget.getItemType()) ) ){
pPalette.get(subject.getName()).put(
subject.getInventory().getHeldItemSlot(), mdTarget );
paintPrint("Paint is now ",subject,mdTarget);
} else {
subject.sendMessage(ChatColor.RED + "Was not able to grab a block to paint.");
MaterialData old = pPalette.get(subject.getName()).get(
subject.getInventory().getHeldItemSlot());
paintPrint("Paint is still ",subject,old);
}
break;
case RIGHT_CLICK_BLOCK:
case RIGHT_CLICK_AIR:
//Draw paint
MaterialData set = pPalette.get(subject.getName()).get(
subject.getInventory().getHeldItemSlot());
if(set != null) {
Block bTarget = null;
if(hasRangePerm(subject) && event.getAction().equals(Action.RIGHT_CLICK_AIR) ){
if((rangeDef > 0) && !subject.isSneaking())
bTarget = subject.getTargetBlock(null, rangeDef);
else if((rangeCrouch > 0)&& subject.isSneaking())
bTarget = subject.getTargetBlock(null, rangeCrouch);
}else if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK))
bTarget = event.getClickedBlock();
if(bTarget != null && !stopOverwrite.contains(bTarget.getType()) &&
(onlyAllow.isEmpty() || onlyAllow.contains(bTarget.getType())) ){
if((bTarget.getType()==set.getItemType())&&(bTarget.getData()==set.getData())) {
//Don't replace blocks with the same type and data
return;
}
if(spawnBuild(bTarget,subject)) {
if(isUseEvent())
safeReplace(set,bTarget,subject,true);
else
bTarget.setTypeIdAndData(set.getItemTypeId(), set.getData(), false);
}
}else if(bTarget != null) {
if(bTarget.getType().equals(Material.AIR))
subject.sendMessage(ChatColor.RED + "Target is out of range");
else
subject.sendMessage(ChatColor.RED + "You can't overwrite "+
ChatColor.GOLD+bTarget.getType());
}
}
break;
default:
return;
}
}
| public void handleInteract(PlayerInteractEvent event){
Player subject = event.getPlayer();
if(!delayElapsed(subject.getName()))
return;
if(!pPalette.containsKey(subject.getName())) {
pPalette.put(subject.getName(), new HashMap<Integer,MaterialData>());
}
switch(event.getAction()) {
case LEFT_CLICK_BLOCK:
case LEFT_CLICK_AIR:
//Acquire paint
MaterialData mdTarget = null;
if(event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
mdTarget = event.getClickedBlock().getState().getData();
if(subject.getGameMode().equals(GameMode.CREATIVE) &&(
mdTarget.getItemType().equals(Material.SIGN_POST) ||
mdTarget.getItemType().equals(Material.WALL_SIGN))){
subject.sendMessage("The sign is not erased on the server, "+
"it is just client side");
}
}else
mdTarget = subject.getTargetBlock(null, 200).getState().getData();
if(!stopCopy.contains(mdTarget.getItemType()) && ( onlyAllow.isEmpty() ||
onlyAllow.contains(mdTarget.getItemType()) ) ){
pPalette.get(subject.getName()).put(
subject.getInventory().getHeldItemSlot(), mdTarget );
paintPrint("Paint is now ",subject,mdTarget);
} else {
subject.sendMessage(ChatColor.RED + "Was not able to grab a block to paint.");
MaterialData old = pPalette.get(subject.getName()).get(
subject.getInventory().getHeldItemSlot());
paintPrint("Paint is still ",subject,old);
}
break;
case RIGHT_CLICK_BLOCK:
case RIGHT_CLICK_AIR:
//Draw paint
MaterialData set = pPalette.get(subject.getName()).get(
subject.getInventory().getHeldItemSlot());
if(set != null) {
Block bTarget = null;
if(hasRangePerm(subject) && event.getAction().equals(Action.RIGHT_CLICK_AIR) ){
if((rangeDef > 0) && !subject.isSneaking())
bTarget = subject.getTargetBlock(null, rangeDef);
else if((rangeCrouch > 0)&& subject.isSneaking())
bTarget = subject.getTargetBlock(null, rangeCrouch);
}else if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK))
bTarget = event.getClickedBlock();
if(bTarget != null && !stopOverwrite.contains(bTarget.getType()) &&
(onlyAllow.isEmpty() || onlyAllow.contains(bTarget.getType())) ){
if((bTarget.getType()==set.getItemType())&&(bTarget.getData()==set.getData())) {
//Don't replace blocks with the same type and data
return;
}
if(spawnBuild(bTarget,subject)) {
if(isUseEvent()) {
if(safeReplace(set,bTarget,subject,true)) {
subject.sendBlockChange(bTarget.getLocation(), set.getItemType(),set.getData());
}
}else {
bTarget.setTypeIdAndData(set.getItemTypeId(), set.getData(), false);
subject.sendBlockChange(bTarget.getLocation(), set.getItemType(), set.getData());
}
}
}else if(bTarget != null) {
if(bTarget.getType().equals(Material.AIR))
subject.sendMessage(ChatColor.RED + "Target is out of range");
else
subject.sendMessage(ChatColor.RED + "You can't overwrite "+
ChatColor.GOLD+bTarget.getType());
}
}
break;
default:
return;
}
}
|
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/music/MusicActivity.java b/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/music/MusicActivity.java
index 11300b4c..2ac977fb 100644
--- a/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/music/MusicActivity.java
+++ b/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/music/MusicActivity.java
@@ -1,166 +1,171 @@
/**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* 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 us.nineworlds.serenity.ui.browser.music;
import java.util.ArrayList;
import com.google.analytics.tracking.android.EasyTracker;
import us.nineworlds.serenity.R;
import us.nineworlds.serenity.SerenityApplication;
import us.nineworlds.serenity.core.model.CategoryInfo;
import us.nineworlds.serenity.core.services.CategoryRetrievalIntentService;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
/**
* @author dcarver
*
*/
public class MusicActivity extends Activity {
private static String key;
private boolean restarted_state = false;
public static boolean MUSIC_GRIDVIEW = true;
private static Activity context;
private static Spinner categorySpinner;
private Handler categoryHandler = new CategoryHandler();
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
key = getIntent().getExtras().getString("key");
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
MUSIC_GRIDVIEW = prefs.getBoolean("music_layout_grid", false);
if (!MUSIC_GRIDVIEW) {
setContentView(R.layout.activity_music_artist_posters);
} else {
setContentView(R.layout.activity_music_artist_gridview);
}
if (prefs.getBoolean("overscan_compensation", false)) {
- RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.musicArtistBrowserLayout);
+ RelativeLayout mainLayout = null;
+ if (MUSIC_GRIDVIEW) {
+ mainLayout = (RelativeLayout) findViewById(R.id.musicBrowserBackgroundLayout);
+ } else {
+ mainLayout = (RelativeLayout) findViewById(R.id.musicArtistBrowserLayout);
+ }
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mainLayout.getLayoutParams();
params.setMargins(35, 20, 20, 20);
}
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
if (restarted_state == false) {
setupMusicAdapters();
}
restarted_state = false;
}
/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
restarted_state = true;
}
protected void setupMusicAdapters() {
categoryHandler = new CategoryHandler();
Messenger messenger = new Messenger(categoryHandler);
Intent categoriesIntent = new Intent(this,
CategoryRetrievalIntentService.class);
categoriesIntent.putExtra("key", key);
categoriesIntent.putExtra("filterAlbums", true);
categoriesIntent.putExtra("MESSENGER", messenger);
startService(categoriesIntent);
context = this;
}
private static class CategoryHandler extends Handler {
private ArrayList<CategoryInfo> categories;
/*
* (non-Javadoc)
*
* @see android.os.Handler#handleMessage(android.os.Message)
*/
@Override
public void handleMessage(Message msg) {
if (msg.obj != null) {
categories = (ArrayList<CategoryInfo>) msg.obj;
setupMovieBrowser();
}
}
/**
* Setup the Gallery and Category spinners
*/
protected void setupMovieBrowser() {
ArrayAdapter<CategoryInfo> spinnerArrayAdapter = new ArrayAdapter<CategoryInfo>(
context, R.layout.serenity_spinner_textview, categories);
spinnerArrayAdapter
.setDropDownViewResource(R.layout.serenity_spinner_textview_dropdown);
categorySpinner = (Spinner) context
.findViewById(R.id.musicCategoryFilter);
categorySpinner.setVisibility(View.VISIBLE);
categorySpinner.setAdapter(spinnerArrayAdapter);
categorySpinner
.setOnItemSelectedListener(new CategorySpinnerOnItemSelectedListener(
"all", key));
categorySpinner.requestFocus();
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
key = getIntent().getExtras().getString("key");
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
MUSIC_GRIDVIEW = prefs.getBoolean("music_layout_grid", false);
if (!MUSIC_GRIDVIEW) {
setContentView(R.layout.activity_music_artist_posters);
} else {
setContentView(R.layout.activity_music_artist_gridview);
}
if (prefs.getBoolean("overscan_compensation", false)) {
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.musicArtistBrowserLayout);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mainLayout.getLayoutParams();
params.setMargins(35, 20, 20, 20);
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
key = getIntent().getExtras().getString("key");
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
MUSIC_GRIDVIEW = prefs.getBoolean("music_layout_grid", false);
if (!MUSIC_GRIDVIEW) {
setContentView(R.layout.activity_music_artist_posters);
} else {
setContentView(R.layout.activity_music_artist_gridview);
}
if (prefs.getBoolean("overscan_compensation", false)) {
RelativeLayout mainLayout = null;
if (MUSIC_GRIDVIEW) {
mainLayout = (RelativeLayout) findViewById(R.id.musicBrowserBackgroundLayout);
} else {
mainLayout = (RelativeLayout) findViewById(R.id.musicArtistBrowserLayout);
}
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mainLayout.getLayoutParams();
params.setMargins(35, 20, 20, 20);
}
}
|
diff --git a/Atarashii/src/net/somethingdreadful/MAL/AboutActivity.java b/Atarashii/src/net/somethingdreadful/MAL/AboutActivity.java
index 014a0be6..c0aece01 100644
--- a/Atarashii/src/net/somethingdreadful/MAL/AboutActivity.java
+++ b/Atarashii/src/net/somethingdreadful/MAL/AboutActivity.java
@@ -1,43 +1,45 @@
package net.somethingdreadful.MAL;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
public class AboutActivity extends SherlockActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
setTitle(R.string.title_activity_about);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
TextView animaMalContent = (TextView) findViewById(R.id.contributor_anima_name);
TextView motokochanMalContent = (TextView) findViewById(R.id.contributor_motokochan_name);
TextView apkawaMalContent = (TextView) findViewById(R.id.contributor_apkawa_name);
TextView acknowledgementsContent = (TextView) findViewById(R.id.acknowledgements_card_content);
+ TextView communityContent = (TextView) findViewById(R.id.community_card_content);
animaMalContent.setMovementMethod(LinkMovementMethod.getInstance());
motokochanMalContent.setMovementMethod(LinkMovementMethod.getInstance());
apkawaMalContent.setMovementMethod(LinkMovementMethod.getInstance());
+ communityContent.setMovementMethod(LinkMovementMethod.getInstance());
acknowledgementsContent.setMovementMethod(LinkMovementMethod.getInstance());
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
}
return true;
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
setTitle(R.string.title_activity_about);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
TextView animaMalContent = (TextView) findViewById(R.id.contributor_anima_name);
TextView motokochanMalContent = (TextView) findViewById(R.id.contributor_motokochan_name);
TextView apkawaMalContent = (TextView) findViewById(R.id.contributor_apkawa_name);
TextView acknowledgementsContent = (TextView) findViewById(R.id.acknowledgements_card_content);
animaMalContent.setMovementMethod(LinkMovementMethod.getInstance());
motokochanMalContent.setMovementMethod(LinkMovementMethod.getInstance());
apkawaMalContent.setMovementMethod(LinkMovementMethod.getInstance());
acknowledgementsContent.setMovementMethod(LinkMovementMethod.getInstance());
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
setTitle(R.string.title_activity_about);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
TextView animaMalContent = (TextView) findViewById(R.id.contributor_anima_name);
TextView motokochanMalContent = (TextView) findViewById(R.id.contributor_motokochan_name);
TextView apkawaMalContent = (TextView) findViewById(R.id.contributor_apkawa_name);
TextView acknowledgementsContent = (TextView) findViewById(R.id.acknowledgements_card_content);
TextView communityContent = (TextView) findViewById(R.id.community_card_content);
animaMalContent.setMovementMethod(LinkMovementMethod.getInstance());
motokochanMalContent.setMovementMethod(LinkMovementMethod.getInstance());
apkawaMalContent.setMovementMethod(LinkMovementMethod.getInstance());
communityContent.setMovementMethod(LinkMovementMethod.getInstance());
acknowledgementsContent.setMovementMethod(LinkMovementMethod.getInstance());
}
|
diff --git a/tests/com/google/caja/parser/quasiliteral/CajitaRewriterTest.java b/tests/com/google/caja/parser/quasiliteral/CajitaRewriterTest.java
index feca5f40..0f32d33e 100644
--- a/tests/com/google/caja/parser/quasiliteral/CajitaRewriterTest.java
+++ b/tests/com/google/caja/parser/quasiliteral/CajitaRewriterTest.java
@@ -1,2224 +1,2224 @@
// Copyright (C) 2007 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.caja.parser.quasiliteral;
import com.google.caja.lexer.FilePosition;
import com.google.caja.lexer.ParseException;
import com.google.caja.parser.ParseTreeNode;
import com.google.caja.parser.ParseTreeNodes;
import com.google.caja.parser.js.Block;
import com.google.caja.parser.js.FormalParam;
import com.google.caja.parser.js.FunctionConstructor;
import com.google.caja.parser.js.FunctionDeclaration;
import com.google.caja.parser.js.Identifier;
import com.google.caja.parser.js.Operator;
import com.google.caja.parser.js.Statement;
import com.google.caja.parser.js.SyntheticNodes;
import com.google.caja.parser.js.UncajoledModule;
import com.google.caja.reporting.MessageLevel;
import com.google.caja.reporting.MessageType;
import com.google.caja.reporting.TestBuildInfo;
import com.google.caja.util.RhinoTestBed;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import junit.framework.AssertionFailedError;
/**
* @author [email protected]
*/
public class CajitaRewriterTest extends CommonJsRewriterTestCase {
protected Rewriter defaultCajaRewriter =
new CajitaRewriter(new TestBuildInfo(), false);
@Override
public void setUp() throws Exception {
super.setUp();
setRewriter(defaultCajaRewriter);
}
/**
* Welds together a string representing the repeated pattern of
* expected test output for assigning to an outer variable.
*
* @author [email protected]
*/
private static String weldSetPub(String obj,
String varName,
String value,
String tempObj,
String tempValue) {
return
tempObj + " = " + obj + "," +
tempValue + " = " + value + "," +
" " + tempObj + "." + varName + "_canSet___ ?" +
" " + tempObj + "." + varName + " = " + tempValue + ":" +
" ___.setPub(" + tempObj + ", '" + varName + "', " + tempValue + ")";
}
/**
* Welds together a string representing the repeated pattern of
* expected test output for reading an outer variable.
*
* @author [email protected]
*/
private static String weldReadPub(String obj, String varName, String tempObj) {
return weldReadPub(obj, varName, tempObj, false);
}
private static String weldReadPub(String obj, String varName, String tempObj, boolean flag) {
return
"(" +
"(" + tempObj + " = " + obj + ")," +
"(" + tempObj + "." + varName + "_canRead___ ?" +
" " + tempObj + "." + varName + ":" +
" ___.readPub(" + tempObj + ", '" + varName + "'" + (flag ? ", true" : "") + "))"+
")";
}
public static String weldPrelude(String name) {
return "var " + name + " = ___.readImport(IMPORTS___, '" + name + "');";
}
public static String weldPrelude(String name, String permitsUsed) {
return "var " + name + " = ___.readImport(IMPORTS___, '" + name +
"', " + permitsUsed + ");";
}
public void testToString() throws Exception {
assertConsistent(
"var z = { toString: function () { return 'blah'; } };" +
"try {" +
" '' + z;" +
"} catch (e) {" +
" throw new Error('PlusPlus error: ' + e);" +
"}");
assertConsistent(
" function foo() {"
+ " var x = 1;"
+ " return {"
+ " toString: function () {"
+ " return x;"
+ " }"
+ " };"
+ "}"
+ "'' + (new foo);");
rewriteAndExecute(
"testImports.exports = {};",
"exports.obj = {toString:function(){return '1';}};",
"if (testImports.exports.obj.toString_canSet___) {" +
" fail('toString fastpath gets set.');" +
"}"
);
rewriteAndExecute(
"testImports.exports = {};",
"exports.objMaker = function(f) { return { prop: f }; };",
"assertThrows(function() {testImports.exports.objMaker(function(){return '1';});});"
);
rewriteAndExecute(
"testImports.exports = {};",
"function objMaker(f) {return {toString:f};}" +
"exports.objMaker = objMaker;",
"assertThrows(function() {testImports.exports.objMaker(function(){return '1';});});"
);
}
public void testInitializeMap() throws Exception {
assertConsistent("var zerubabel = {bobble:2, apple:1}; zerubabel.apple;");
}
public void testValueOf() throws Exception {
checkFails("var a = {valueOf:1};", "The valueOf property must not be set");
checkFails("var a={}; a.valueOf=1;", "The valueOf property must not be set");
checkFails(
" function f(){}"
+ "f.prototype.valueOf=1;",
"The valueOf property must not be set");
checkFails(
"var a={}; delete a.valueOf;",
"The valueOf property must not be deleted");
rewriteAndExecute("var a={}; assertThrows(function(){a['valueOf']=1;});");
rewriteAndExecute(
"var a={}; assertThrows(function(){delete a['valueOf'];});");
}
public void testFunctionDoesNotMaskVariable() throws Exception {
// Regress http://code.google.com/p/google-caja/issues/detail?id=370
// TODO(ihab.awad): Enhance test framework to allow "before" and "after"
// un-cajoled code to be executed, then change this to a functional test.
checkSucceeds(
" function boo() { return x; }"
+ "var x;",
" function boo() {\n" +
" return x;\n" +
" }\n" +
" ___.func(boo, \'boo\');"
+ ";"
+ "var x;");
}
public void testAssertEqualsCajoled() throws Exception {
try {
rewriteAndExecute("assertEquals(1, 2);");
} catch (AssertionFailedError e) {
return;
}
fail("Assertions do not work in cajoled mode");
}
public void testAssertThrowsCajoledNoError() throws Exception {
rewriteAndExecute(
" assertThrows(function() { throw 'foo'; });");
rewriteAndExecute(
" assertThrows("
+ " function() { throw 'foo'; },"
+ " 'foo');");
}
public void testAssertThrowsCajoledErrorNoMsg() throws Exception {
try {
rewriteAndExecute("assertThrows(function() {});");
} catch (AssertionFailedError e) {
return;
}
fail("Assertions do not work in cajoled mode");
}
public void testAssertThrowsCajoledErrorWithMsg() throws Exception {
try {
rewriteAndExecute("assertThrows(function() {}, 'foo');");
} catch (AssertionFailedError e) {
return;
}
fail("Assertions do not work in cajoled mode");
}
public void testFreeVariables() throws Exception {
checkSucceeds(
"var y = x;",
weldPrelude("x") +
"var y = x;");
checkSucceeds(
"function() { var y = x; };",
weldPrelude("x") +
"___.frozenFunc(function() {" +
" var y = x;" +
"});");
}
public void testConstructionWithFunction() throws Exception {
assertConsistent(
" function Point() {}"
+ "var p = new Point();"
+ "(p !== undefined);");
assertConsistent(
" var Point = function() {};"
+ "var p = new Point();"
+ "(p !== undefined);");
}
public void testReflectiveMethodInvocation() throws Exception {
assertConsistent(
"(function (first, second) { return 'a' + first + 'b' + second; })"
+ ".call([], 8, 9);");
assertConsistent(
"var a = []; [].push.call(a, 5, 6); a;");
assertConsistent(
"(function (a, b) { return 'a' + a + 'b' + b; }).apply([], [8, 9]);");
assertConsistent(
"var a = []; [].push.apply(a, [5, 6]); a;");
assertConsistent(
"[].sort.apply([6, 5]);");
assertConsistent(
"(function (first, second) { return 'a' + first + 'b' + second; })"
+ ".bind([], 8)(9);");
}
/**
* Tests that <a href=
* "http://code.google.com/p/google-caja/issues/detail?id=242"
* >bug#242</a> is fixed.
* <p>
* The actual Function.bind() method used to be whitelisted and written to return a frozen
* simple-function, allowing it to be called from all code on all functions. As a result,
* if an <i>outer hull breach</i> occurs -- if Caja code
* obtains a reference to a JavaScript function value not marked as Caja-callable -- then
* that Caja code could call the whitelisted bind() on it, and then call the result,
* causing an <i>inner hull breach</i> which threatens kernel integrity.
*/
public void testToxicBind() throws Exception {
rewriteAndExecute(
"var confused = false;" +
"testImports.keystone = function keystone() { confused = true; };",
"assertThrows(function() {keystone.bind()();});",
"assertFalse(confused);");
}
/**
* Tests that <a href=
* "http://code.google.com/p/google-caja/issues/detail?id=590"
* >bug#590</a> is fixed.
* <p>
* As a client of an object, Caja code must only be able to directly delete
* <i>public</i> properties of non-frozen JSON containers. Due to this bug, Caja
* code was able to delete <i>protected</i> properties of non-frozen JSON
* containers.
*/
public void testBadDelete() throws Exception {
rewriteAndExecute(
"testImports.badContainer = {secret__: 3469};",
"assertThrows(function() {delete badContainer['secret__'];});",
"assertEquals(testImports.badContainer.secret__, 3469);");
rewriteAndExecute(
"assertThrows(function() {delete ({})['proto___'];});");
}
/**
* Tests that <a href=
* "http://code.google.com/p/google-caja/issues/detail?id=617"
* >bug#617</a> is fixed.
* <p>
* The ES3 spec specifies an insane scoping rule which Firefox 2.0.0.15 "correctly"
* implements according to the spec. The rule is that, within a named function
* expression, the function name <i>f</i> is brought into scope by creating a new object
* "as if by executing 'new Object()', adding an <tt>'<i>f</i>'</tt> property to this
* object, and adding this object to the scope chain. As a result, all properties
* inherited from <tt>Object.prototype</tt> shadow any outer lexically visible
* declarations of those names as variable names.
* <p>
* Unfortunately, we're currently doing our JUnit testing using Rhino, which doesn't
* engage in the questionable behavior of implementing specified but insane behavior.
* As a result, the following test currently succeeds whether this bug is fixed or
* not.
*/
public void testNameFuncExprScoping() throws Exception {
rewriteAndExecute(
"assertEquals(0, function() { \n" +
" var propertyIsEnumerable = 0;\n" +
" return (function f() {\n" +
" return propertyIsEnumerable;\n" +
" })();\n" +
"}());");
}
/**
* Tests that <a href=
* "http://code.google.com/p/google-caja/issues/detail?id=469"
* >bug#469</a> is fixed.
* <p>
* The members of the <tt>caja</tt> object available to Caja code
* (i.e., the <tt>safeCaja</tt> object) must be frozen. And if they
* are functions, they should be marked as simple-functions. Before
* this bug was fixed, <tt>cajita.js</tt> failed to do either.
*/
public void testCajaPropsFrozen() throws Exception {
rewriteAndExecute(";","0;",
"assertTrue(___.isFunc(___.sharedImports.cajita.manifest));");
rewriteAndExecute(";","0;",
"assertTrue(___.isFrozen(___.sharedImports.cajita.manifest));");
}
/**
* Tests that <a href=
* "http://code.google.com/p/google-caja/issues/detail?id=292"
* >bug#292</a> is fixed.
* <p>
* In anticipation of ES3.1, we should be able to index into strings
* using indexes which are numbers or stringified numbers, so long as
* they are in range.
*/
public void testStringIndexing() throws Exception {
rewriteAndExecute("assertEquals('b', 'abc'[1]);");
// TODO(erights): This test isn't green because we haven't yet fixed the bug.
if (false) {
rewriteAndExecute("assertEquals('b', 'abc'['1']);");
}
}
/**
* Tests that <a href=
* "http://code.google.com/p/google-caja/issues/detail?id=464"
* >bug#464</a> is fixed.
* <p>
* Reading the apply property of a function should result in the apply
* method as attached to that function.
*/
public void testAttachedReflection() throws Exception {
rewriteAndExecute(
"function f() {}\n" +
"f.apply;");
// TODO(erights): Need more tests.
}
/**
* Tests that <a href=
* "http://code.google.com/p/google-caja/issues/detail?id=347"
* >bug#347</a> is fixed.
* <p>
* The <tt>in</tt> operator should only test for properties visible to Caja.
*/
public void testInVeil() throws Exception {
rewriteAndExecute(
"assertFalse('FROZEN___' in Object);");
}
////////////////////////////////////////////////////////////////////////
// Handling of synthetic nodes
////////////////////////////////////////////////////////////////////////
public void testSyntheticIsUntouched() throws Exception {
ParseTreeNode input = js(fromString("function foo() { this; arguments; }"));
syntheticTree(input);
checkSucceeds(input, input);
}
public void testSyntheticMemberAccess() throws Exception {
ParseTreeNode input = js(fromString("({}).foo"));
syntheticTree(input);
checkSucceeds(input, js(fromString("___.initializeMap([]).foo;")));
}
public void testSyntheticNestedIsExpanded() throws Exception {
ParseTreeNode innerInput = js(fromString("function foo() {}"));
ParseTreeNode input = ParseTreeNodes.newNodeInstance(
Block.class,
FilePosition.UNKNOWN,
null,
Collections.singletonList(innerInput));
makeSynthetic(input);
ParseTreeNode expectedResult = js(fromString(
"var foo; { foo = (function () {\n" +
" function foo$_self() {\n" +
" }\n" +
" return ___.func(foo$_self, \'foo\');\n" +
" })(); ; }"));
checkSucceeds(input, expectedResult);
}
public void testSyntheticNestedFunctionIsExpanded() throws Exception {
// This test checks that a synthetic function, as is commonly generated
// by Caja to wrap JavaScript event handlers declared in HTML, is rewritten
// correctly.
Block innerBlock = js(fromString("foo().x = bar();"));
ParseTreeNode input = new Block(
FilePosition.UNKNOWN,
java.util.Arrays.asList(
new FunctionDeclaration(
SyntheticNodes.s(new FunctionConstructor(
FilePosition.UNKNOWN,
new Identifier(FilePosition.UNKNOWN, "f"),
Collections.<FormalParam>emptyList(),
innerBlock)))));
// We expect the stuff in 'innerBlock' to be expanded, *but* we expect the
// rewriter to be unaware of the enclosing function scope, so the temporary
// variables generated by expanding 'innerBlock' spill out and get declared
// outside the function rather than inside it.
ParseTreeNode expectedResult = js(fromString(
weldPrelude("bar")
+ weldPrelude("foo")
+ "var x0___;" // Temporaries are declared up here ...
+ "var x1___;"
+ "function f() {"
+ " " // ... not down here!
+ weldSetPub("foo.CALL___()", "x", "bar.CALL___()", "x0___", "x1___")
+ ";}"));
checkSucceeds(input, expectedResult);
}
////////////////////////////////////////////////////////////////////////
// Handling of nested blocks
////////////////////////////////////////////////////////////////////////
public void testNestedBlockWithFunction() throws Exception {
checkSucceeds(
"{ function foo() {} }",
"var foo;" +
"{ foo = (function () {\n" +
" function foo$_self() {\n" +
" }\n" +
" return ___.func(foo$_self, \'foo\');\n" +
" })(); ; }");
}
public void testNestedBlockWithVariable() throws Exception {
checkSucceeds(
"{ var x = g().y; }",
weldPrelude("g") +
"var x0___;" +
"{" +
" var x = " + weldReadPub("g.CALL___()", "y", "x0___") + ";"+
"}");
}
////////////////////////////////////////////////////////////////////////
// Specific rules
////////////////////////////////////////////////////////////////////////
public void testWith() throws Exception {
checkFails("with (dreams || ambiguousScoping) anything.isPossible();",
"\"with\" blocks are not allowed");
checkFails("with (dreams || ambiguousScoping) { anything.isPossible(); }",
"\"with\" blocks are not allowed");
}
public void testForInBad() throws Exception {
checkAddsMessage(js(fromString(
"for (var x in {}) {}")),
RewriterMessageType.FOR_IN_NOT_IN_CAJITA,
MessageLevel.FATAL_ERROR);
}
public void testTryCatch() throws Exception {
checkAddsMessage(js(fromString(
"try {" +
" throw 2;" +
"} catch (e) {" +
" var e;" +
"}")),
MessageType.MASKING_SYMBOL,
MessageLevel.ERROR);
checkAddsMessage(js(fromString(
"var e;" +
"try {" +
" throw 2;" +
"} catch (e) {" +
"}")),
MessageType.MASKING_SYMBOL,
MessageLevel.ERROR);
checkAddsMessage(js(fromString(
"try {} catch (x__) { }")),
RewriterMessageType.VARIABLES_CANNOT_END_IN_DOUBLE_UNDERSCORE);
// TODO(ihab.awad): The below should throw MessageType.MASKING_SYMBOL at
// MessageLevel.ERROR. See bug #313. For the moment, we merely check that
// it cajoles to something secure.
checkSucceeds(
"try {" +
" g[0];" +
" e;" +
" g[1];" +
"} catch (e) {" +
" g[2];" +
" e;" +
" g[3];" +
"}",
weldPrelude("e") +
weldPrelude("g") +
"try {" +
" ___.readPub(g, 0);" +
" e;" +
" ___.readPub(g, 1);" +
"} catch (ex___) {" +
" try {" +
" throw ___.tameException(ex___);" +
" } catch (e) {" +
" ___.readPub(g, 2);" +
" e;" +
" ___.readPub(g, 3);" +
" }" +
"}");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw null;" +
"} catch (ex) {" +
" assertEquals(null, ex);" + // Right value in ex.
" handled = true;" +
"}" +
"assertTrue(handled);"); // Control reached and left the catch block.
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw undefined;" +
"} catch (ex) {" +
" assertEquals(undefined, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw true;" +
"} catch (ex) {" +
" assertEquals(true, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw 37639105;" +
"} catch (ex) {" +
" assertEquals(37639105, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw 'panic';" +
"} catch (ex) {" +
" assertEquals('panic', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw new Error('hello');" +
"} catch (ex) {" +
" assertEquals('hello', ex.message);" +
" assertEquals('Error', ex.name);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw function () { throw 'should not be called'; };" +
"} catch (ex) {" +
- " assertEquals(undefined, ex);" +
+ " assertEquals(undefined, ex());" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw { toString: function () { return 'hiya'; }, y: 4 };" +
"} catch (ex) {" +
" assertEquals('string', typeof ex);" +
" assertEquals('hiya', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw { toString: function () { throw new Error(); } };" +
"} catch (ex) {" +
" assertEquals('Exception during exception handling.', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
}
public void testTryCatchFinally() throws Exception {
checkAddsMessage(js(fromString(
"try {" +
"} catch (e) {" +
" var e;" +
"} finally {" +
"}")),
MessageType.MASKING_SYMBOL,
MessageLevel.ERROR);
checkAddsMessage(js(fromString(
"var e;" +
"try {" +
"} catch (e) {" +
"} finally {" +
"}")),
MessageType.MASKING_SYMBOL,
MessageLevel.ERROR);
checkAddsMessage(js(fromString(
"try {} catch (x__) { } finally { }")),
RewriterMessageType.VARIABLES_CANNOT_END_IN_DOUBLE_UNDERSCORE);
checkSucceeds(
"try {" +
" g[0];" +
" e;" +
" g[1];" +
"} catch (e) {" +
" g[2];" +
" e;" +
" g[3];" +
"} finally {" +
" g[4];" +
" e;" +
" g[5];" +
"}",
weldPrelude("e") +
weldPrelude("g") +
"try {" +
" ___.readPub(g, 0);" +
" e;" +
" ___.readPub(g, 1);" +
"} catch (ex___) {" +
" try {" +
" throw ___.tameException(ex___);" +
" } catch (e) {" +
" ___.readPub(g, 2);" +
" e;" +
" ___.readPub(g, 3);" +
" }" +
"} finally {" +
" ___.readPub(g, 4);" +
" e;" +
" ___.readPub(g, 5);" +
"}");
}
public void testTryFinally() throws Exception {
assertConsistent(
"var out = 0;" +
"try {" +
" try {" +
" throw 2;" +
" } finally {" +
" out = 1;" +
" }" +
" out = 2;" +
"} catch (e) {" +
"}" +
"out;");
checkSucceeds(
"try {" +
" g[0];" +
" e;" +
" g[1];" +
"} finally {" +
" g[2];" +
" e;" +
" g[3];" +
"}",
weldPrelude("e") +
weldPrelude("g") +
"try {" +
" ___.readPub(g, 0);" +
" e;" +
" ___.readPub(g, 1);" +
"} finally {" +
" ___.readPub(g, 2);" +
" e;" +
" ___.readPub(g, 3);" +
"}");
}
public void testVarArgs() throws Exception {
checkSucceeds(
"var p;" +
"var foo = function() {" +
" p = arguments;" +
"};",
"var p;" +
"var foo = (function () {\n" +
" function foo$_var() {\n" +
" var a___ = ___.args(arguments);\n" +
" p = a___;\n" +
" }\n" +
" return ___.frozenFunc(foo$_var, 'foo$_var');\n" +
" })();");
}
public void testVarThisBad() throws Exception {
checkAddsMessage(
js(fromString("var x = this;")),
RewriterMessageType.THIS_NOT_IN_CAJITA,
MessageLevel.FATAL_ERROR);
checkAddsMessage(
js(fromString("this = 42;")),
RewriterMessageType.THIS_NOT_IN_CAJITA,
MessageLevel.FATAL_ERROR);
checkAddsMessage(
js(fromString("function foo() { var x = this; }")),
RewriterMessageType.THIS_NOT_IN_CAJITA,
MessageLevel.FATAL_ERROR);
checkAddsMessage(
js(fromString("function foo() { this = 42; }")),
RewriterMessageType.THIS_NOT_IN_CAJITA,
MessageLevel.FATAL_ERROR);
}
public void testVarBadSuffix() throws Exception {
checkFails(
"function() { foo__; };",
"Variables cannot end in \"__\"");
// Make sure *single* underscore is okay
checkSucceeds(
"function() { var foo_ = 3; };",
"___.frozenFunc(function() { var foo_ = 3; });");
}
public void testVarBadSuffixDeclaration() throws Exception {
checkFails(
"function foo__() { }",
"Variables cannot end in \"__\"");
checkFails(
"var foo__ = 3;",
"Variables cannot end in \"__\"");
checkFails(
"var foo__;",
"Variables cannot end in \"__\"");
checkFails(
"function() { function foo__() { } };",
"Variables cannot end in \"__\"");
checkFails(
"function() { var foo__ = 3; };",
"Variables cannot end in \"__\"");
checkFails(
"function() { var foo__; };",
"Variables cannot end in \"__\"");
}
public void testVarFuncFreeze() throws Exception {
// We can cajole and refer to a function
rewriteAndExecute(
"function foo() {};" +
"foo();");
// We can assign a dotted property of a variable
rewriteAndExecute(
"var foo = {};" +
"foo.x = 3;" +
"assertEquals(foo.x, 3);");
// We cannot assign to a function variable
assertAddsMessage(
"function foo() {}" +
"foo = 3;",
RewriterMessageType.CANNOT_ASSIGN_TO_FUNCTION_NAME,
MessageLevel.FATAL_ERROR);
// We cannot assign to a member of an aliased simple function
// since it is frozen.
rewriteAndExecute(
"assertThrows(function() {" +
" function foo() {};" +
" var bar = foo;" +
" bar.x = 3;" +
"});");
}
public void testVarGlobal() throws Exception {
checkSucceeds(
"foo;",
weldPrelude("foo") +
"foo;");
checkSucceeds(
"function() {" +
" foo;" +
"};",
weldPrelude("foo") +
"___.frozenFunc(function() {" +
" foo;" +
"});");
checkSucceeds(
"function() {" +
" var foo;" +
" foo;" +
"};",
"___.frozenFunc(function() {" +
" var foo;" +
" foo;" +
"});");
}
public void testVarDefault() throws Exception {
String unchanged =
"var x = 3;" +
"if (x) { }" +
"x + 3;" +
"var y = undefined;";
checkSucceeds(
"function() {" +
" " + unchanged +
"};",
"var undefined = ___.readImport(IMPORTS___, 'undefined', {});" +
"___.frozenFunc(function() {" +
" " + unchanged +
"});");
}
public void testReadBadSuffix() throws Exception {
checkFails(
"x.y__;",
"Properties cannot end in \"__\"");
}
public void testReadBadPrototype() throws Exception {
checkAddsMessage(
js(fromString("function foo() {} foo.prototype;")),
RewriterMessageType.PROTOTYPICAL_INHERITANCE_NOT_IN_CAJITA);
checkAddsMessage(
js(fromString("var q = function foo() { foo.prototype; };")),
RewriterMessageType.PROTOTYPICAL_INHERITANCE_NOT_IN_CAJITA);
}
public void testReadPublic() throws Exception {
checkSucceeds(
"var p;" +
"p = foo().p;",
weldPrelude("foo") +
"var x0___;" +
"var p;" +
"p = " + weldReadPub("foo.CALL___()", "p", "x0___") + ";");
}
public void testReadIndexPublic() throws Exception {
checkSucceeds(
"var p, q;" +
"p = q[3];",
"var p, q;" +
"p = ___.readPub(q, 3);");
}
public void testSetBadAssignToFunctionName() throws Exception {
checkAddsMessage(js(fromString(
" function foo() {};"
+ "foo = 3;")),
RewriterMessageType.CANNOT_ASSIGN_TO_FUNCTION_NAME);
checkAddsMessage(js(fromString(
" function foo() {};"
+ "foo += 3;")),
RewriterMessageType.CANNOT_ASSIGN_TO_FUNCTION_NAME);
checkAddsMessage(js(fromString(
" function foo() {};"
+ "foo++;")),
RewriterMessageType.CANNOT_ASSIGN_TO_FUNCTION_NAME);
checkAddsMessage(js(fromString(
" var x = function foo() {"
+ " foo = 3;"
+ "};")),
RewriterMessageType.CANNOT_ASSIGN_TO_FUNCTION_NAME);
checkAddsMessage(js(fromString(
" var x = function foo() {"
+ " foo += 3;"
+ "};")),
RewriterMessageType.CANNOT_ASSIGN_TO_FUNCTION_NAME);
checkAddsMessage(js(fromString(
" var x = function foo() {"
+ " foo++;"
+ "};")),
RewriterMessageType.CANNOT_ASSIGN_TO_FUNCTION_NAME);
}
public void testSetBadThis() throws Exception {
checkAddsMessage(
js(fromString("function f() { this = 3; }")),
RewriterMessageType.THIS_NOT_IN_CAJITA);
}
public void testSetBadFreeVariable() throws Exception {
checkAddsMessage(
js(fromString("Array = function () { return [] };")),
RewriterMessageType.CANNOT_MASK_IDENTIFIER);
checkAddsMessage(
js(fromString("x = 1;")),
RewriterMessageType.CANNOT_ASSIGN_TO_FREE_VARIABLE);
}
public void testSetBadSuffix() throws Exception {
checkFails(
"x.y__ = z;",
"Properties cannot end in \"__\"");
}
public void testSetBadPrototype() throws Exception {
checkAddsMessage(
js(fromString("function foo() {} foo.prototype = 3;")),
RewriterMessageType.PROTOTYPICAL_INHERITANCE_NOT_IN_CAJITA);
checkAddsMessage(
js(fromString("var q = function foo() { foo.prototype = 3; };")),
RewriterMessageType.PROTOTYPICAL_INHERITANCE_NOT_IN_CAJITA);
}
public void testSetPublic() throws Exception {
checkSucceeds(
"x().p = g[0];",
weldPrelude("g") +
weldPrelude("x") +
"var x0___;" +
"var x1___;" +
weldSetPub("x.CALL___()", "p", "___.readPub(g, 0)", "x0___", "x1___") +
";");
}
public void testSetIndexPublic() throws Exception {
checkSucceeds(
"g[0][g[1]] = g[2];",
weldPrelude("g") +
"___.setPub(___.readPub(g, 0), ___.readPub(g, 1), ___.readPub(g, 2));");
}
public void testSetBadInitialize() throws Exception {
checkFails(
"var x__ = 3;",
"Variables cannot end in \"__\"");
}
public void testSetInitialize() throws Exception {
checkSucceeds(
"var v = g[0];",
weldPrelude("g") +
"var v = ___.readPub(g, 0);");
}
public void testSetBadDeclare() throws Exception {
checkFails(
"var x__;",
"Variables cannot end in \"__\"");
}
public void testSetDeclare() throws Exception {
checkSucceeds(
"var v;",
"var v;");
checkSucceeds(
"try { } catch (e) { var v; }",
"try {" +
"} catch (ex___) {" +
" try {" +
" throw ___.tameException(ex___);" +
" } catch (e) {" +
" var v;" +
" }" +
"}");
}
public void testSetVar() throws Exception {
checkAddsMessage(
js(fromString("try {} catch (x__) { x__ = 3; }")),
RewriterMessageType.VARIABLES_CANNOT_END_IN_DOUBLE_UNDERSCORE);
checkSucceeds(
"var x;" +
"x = g[0];",
weldPrelude("g") +
"var x;" +
"x = ___.readPub(g, 0);");
}
public void testSetReadModifyWriteLocalVar() throws Exception {
checkFails("x__ *= 2;", "");
checkFails("x *= y__;", "");
checkSucceeds(
"var x; x += g[0];",
weldPrelude("g")
+ "var x; x = x + ___.readPub(g, 0);");
checkSucceeds(
"myArray().key += 1;",
weldPrelude("myArray")
+ "var x0___;"
+ "x0___ = myArray.CALL___(),"
+ "___.setPub(x0___, 'key',"
+ " ___.readPub(x0___, 'key') + 1);");
checkSucceeds(
"myArray()[myKey()] += 1;",
weldPrelude("myArray")
+ weldPrelude("myKey")
+ "var x0___;"
+ "var x1___;"
+ "x0___ = myArray.CALL___(),"
+ "x1___ = myKey.CALL___(),"
+ "___.setPub(x0___, x1___,"
+ " ___.readPub(x0___, x1___) + 1);");
checkSucceeds( // Local reference need not be assigned to a temp.
"(function (myKey) { myArray()[myKey] += 1; });",
weldPrelude("myArray")
+ "___.frozenFunc(function (myKey) {"
+ " var x0___;"
+ " x0___ = myArray.CALL___(),"
+ " ___.setPub(x0___, myKey,"
+ " ___.readPub(x0___, myKey) + 1);"
+ "});");
assertConsistent("var x = 3; x *= 2;");
assertConsistent("var x = 1; x += 7;");
assertConsistent("var x = 1; x /= '2';");
assertConsistent("var o = { x: 'a' }; o.x += 'b'; o;");
EnumSet<Operator> ops = EnumSet.of(
Operator.ASSIGN_MUL,
Operator.ASSIGN_DIV,
Operator.ASSIGN_MOD,
Operator.ASSIGN_SUM,
Operator.ASSIGN_SUB,
Operator.ASSIGN_LSH,
Operator.ASSIGN_RSH,
Operator.ASSIGN_USH,
Operator.ASSIGN_AND,
Operator.ASSIGN_XOR,
Operator.ASSIGN_OR
);
for (Operator op : ops) {
checkSucceeds(
"var x; x " + op.getSymbol() + " g[0];",
weldPrelude("g")
+ "var x;"
+ "x = x " + op.getAssignmentDelegate().getSymbol()
+ "___.readPub(g, 0);");
}
}
public void testSetIncrDecr() throws Exception {
checkFails("x__--;", "");
checkSucceeds(
"g[0]++;",
weldPrelude("g") +
"var x0___;" +
"var x1___;" +
"x0___ = g," +
"x1___ = +___.readPub(x0___, 0)," +
"___.setPub(x0___, 0, x1___ + 1)," +
"x1___;");
checkSucceeds(
"g[0]--;",
weldPrelude("g") +
"var x0___;" +
"var x1___;" +
"x0___ = g," +
"x1___ = +___.readPub(x0___, 0)," +
"___.setPub(x0___, 0, x1___ - 1)," +
"x1___;");
checkSucceeds(
"++g[0];",
weldPrelude("g") +
"var x0___;" +
"x0___ = g," +
"___.setPub(x0___, 0, ___.readPub(x0___, 0) - -1);");
assertConsistent(
"var x = 2;" +
"var arr = [--x, x, x--, x, ++x, x, x++, x];" +
"assertEquals('1,1,1,0,1,1,1,2', arr.join(','));" +
"arr;");
assertConsistent(
"var x = '2';" +
"var arr = [--x, x, x--, x, ++x, x, x++, x];" +
"assertEquals('1,1,1,0,1,1,1,2', arr.join(','));" +
"arr;");
}
public void testSetIncrDecrOnLocals() throws Exception {
checkFails("++x__;", "");
checkSucceeds(
"(function (x, y) { return [x--, --x, y++, ++y]; });",
"___.frozenFunc(" +
" function (x, y) { return [x--, --x, y++, ++y]; });");
assertConsistent(
"(function () {" +
" var x = 2;" +
" var arr = [--x, x, x--, x, ++x, x, x++, x];" +
" assertEquals('1,1,1,0,1,1,1,2', arr.join(','));" +
" return arr;" +
"})();");
}
public void testSetIncrDecrOfComplexLValues() throws Exception {
checkFails("arr[x__]--;", "Variables cannot end in \"__\"");
checkFails("arr__[x]--;", "Variables cannot end in \"__\"");
checkSucceeds(
"o.x++;",
weldPrelude("o") +
"var x0___;" +
"var x1___;" +
"x0___ = o," +
"x1___ = +___.readPub(x0___, 'x')," +
"___.setPub(x0___, 'x', x1___ + 1)," +
"x1___;");
assertConsistent(
"(function () {" +
" var o = { x: 2 };" +
" var arr = [--o.x, o.x, o.x--, o.x, ++o.x, o.x, o.x++, o.x];" +
" assertEquals('1,1,1,0,1,1,1,2', arr.join(','));" +
" return arr;" +
"})();");
}
public void testSetIncrDecrOrderOfAssignment() throws Exception {
assertConsistent(
"(function () {" +
" var arrs = [1, 2];" +
" var j = 0;" +
" arrs[++j] *= ++j;" +
" assertEquals(2, j);" +
" assertEquals(1, arrs[0]);" +
" assertEquals(4, arrs[1]);" +
" return arrs;" +
"})();");
assertConsistent(
"(function () {" +
" var foo = (function () {" +
" var k = 0;" +
" return function () {" +
" switch (k++) {" +
" case 0: return [10, 20, 30];" +
" case 1: return 1;" +
" case 2: return 2;" +
" default: throw new Error(k);" +
" }" +
" };" +
" })();" +
" return foo()[foo()] -= foo();" +
"})();"
);
}
public void testNewCallledCtor() throws Exception {
checkSucceeds(
"new Date();",
weldPrelude("Date", "{}")
+ "___.construct(Date, []);");
}
public void testNewCalllessCtor() throws Exception {
checkSucceeds(
"(new Date);",
weldPrelude("Date", "{}")
+ "___.construct(Date, []);");
}
public void testDeletePub() throws Exception {
checkFails("delete x.foo___;", "Properties cannot end in \"__\"");
checkSucceeds(
"delete foo()[bar()];",
weldPrelude("bar") +
weldPrelude("foo") +
"___.deletePub(foo.CALL___()," +
" bar.CALL___());");
checkSucceeds(
"delete foo().bar;",
weldPrelude("foo") +
"___.deletePub(foo.CALL___(), 'bar');");
assertConsistent(
"(function() {" +
" var o = { x: 3, y: 4 };" + // A JSON object.
" function ptStr(o) { return '(' + o.x + ',' + o.y + ')'; }" +
" var history = [ptStr(o)];" + // Record state before deletion.
" delete o.y;" + // Delete
" delete o.z;" + // Not present. Delete a no-op
" history.push(ptStr(o));" + // Record state after deletion.
" return history.toString();" +
"})();");
assertConsistent(
"var alert = 'a';" +
"var o = { a: 1 };" +
"delete o[alert];" +
"assertEquals(undefined, o.a);" +
"o;");
}
public void testDeleteFails() throws Exception {
assertConsistent(
"var status;" +
"try {" +
" if (delete [].length) {" +
" status = 'FAILED';" + // Passing is not ok.
" } else {" +
" status = 'PASSED';" + // Ok to return false
" }" +
"} catch (e) {" +
" status = 'PASSED';" + // Ok to fail with an exception
"}" +
"status;");
}
public void testDeleteNonLvalue() throws Exception {
checkFails("delete 4;", "Invalid operand to delete");
}
public void testCallPublic() throws Exception {
checkSucceeds(
"g[0].m(g[1], g[2]);",
weldPrelude("g") +
"var x0___;" +
"var x1___;" +
"var x2___;" +
"x0___ = ___.readPub(g, 0)," +
"x1___ = ___.readPub(g, 1), x2___ = ___.readPub(g, 2)," +
"x0___.m_canCall___ ?" +
" x0___.m(x1___, x2___) :" +
" ___.callPub(x0___, 'm', [x1___, x2___]);");
}
public void testCallIndexPublic() throws Exception {
checkSucceeds(
"g[0][g[1]](g[2], g[3]);",
weldPrelude("g") +
"___.callPub(" +
" ___.readPub(g, 0)," +
" ___.readPub(g, 1)," +
" [___.readPub(g, 2), ___.readPub(g, 3)]);");
}
public void testCallFunc() throws Exception {
checkSucceeds(
"g(g[1], g[2]);",
weldPrelude("g") +
"g.CALL___" +
" (___.readPub(g, 1), ___.readPub(g, 2));");
}
public void testPermittedCall() throws Exception {
// TODO(ihab.awad): Once permit templates can be loaded dynamically, create
// one here for testing rather than rely on the Valija permits.
String fixture =
" var x = 0;"
+ "var callPubCalled = false;"
+ "var origCallPub = ___.callPub;"
+ "___.callPub = function(obj, name, args) {"
+ " if (name === 'dis') { callPubCalled = true; }"
+ " origCallPub.call(___, obj, name, args);"
+ "};"
+ "testImports.$v = ___.primFreeze({"
+ " dis: ___.frozenFunc(function(n) { x = n; })"
+ "});";
rewriteAndExecute(
fixture,
" $v.dis(42);",
" assertFalse(callPubCalled);"
+ "assertEquals(42, x);");
rewriteAndExecute(
fixture,
" (function() {"
+ " var $v = { dis: function(x) {} };"
+ " $v.dis(42);"
+ "})();",
" assertTrue(callPubCalled);"
+ "assertEquals(0, x);");
}
public void testFuncAnonSimple() throws Exception {
// TODO(ihab.awad): The below test is not as complete as it should be
// since it does not test the "@stmts*" substitution in the rule
checkSucceeds(
"function(x, y) { x = arguments; y = g[0]; };",
weldPrelude("g") +
"___.frozenFunc(function(x, y) {" +
" var a___ = ___.args(arguments);" +
" x = a___;" +
" y = ___.readPub(g, 0);" +
"});");
rewriteAndExecute(
"(function () {" +
" var foo = function () {};" +
" foo();" +
" try {" +
" foo.x = 3;" +
" } catch (e) { return; }" +
" fail('mutate frozen function');" +
"})();");
assertConsistent(
"var foo = (function () {" +
" function foo() {};" +
" foo.x = 3;" +
" return foo;" +
" })();" +
"foo();" +
"foo.x;");
}
public void testFuncNamedSimpleDecl() throws Exception {
rewriteAndExecute(
" assertThrows(function() {"
+ " (function foo() { foo.x = 3; })();"
+ "});");
rewriteAndExecute(
" assertThrows(function() {"
+ " function foo() { foo.x = 3; }"
+ " foo();"
+ "});");
rewriteAndExecute(
" assertThrows(function() {"
+ " var foo = function() {};"
+ " foo.x = 3;"
+ "});");
rewriteAndExecute(
" function foo() {}"
+ "foo.x = 3;");
checkSucceeds(
"function() {" +
" function foo(x, y) {" +
" x = arguments;" +
" y = g[0];" +
" return foo(x - 1, y - 1);" +
" }" +
"};",
weldPrelude("g") +
"___.frozenFunc(function() {" +
" function foo(x, y) {\n" +
" var a___ = ___.args(arguments);\n" +
" x = a___;\n" +
" y = ___.readPub(g, 0);\n" +
" return foo.CALL___(x - 1, y - 1);\n" +
" }\n" +
" ___.func(foo, \'foo\');" +
" ;"+
"});");
checkSucceeds(
"function foo(x, y ) {" +
" return foo(x - 1, y - 1);" +
"}",
" function foo(x, y) {\n" +
" return foo.CALL___(x - 1, y - 1);\n" +
" }\n" +
" ___.func(foo, \'foo\');" +
";");
rewriteAndExecute(
"(function () {" +
" function foo() {}" +
" foo();" +
" try {" +
" foo.x = 3;" +
" } catch (e) { return; }" +
" fail('mutated frozen function');" +
"})();");
assertConsistent(
"function foo() {}" +
"foo.x = 3;" +
"foo();" +
"foo.x;");
rewriteAndExecute(
" function f_() { return 31415; }"
+ "var x = f_();"
+ "assertEquals(x, 31415);");
}
public void testFuncNamedSimpleValue() throws Exception {
checkSucceeds(
"var f = function foo(x, y) {" +
" x = arguments;" +
" y = z;" +
" return foo(x - 1, y - 1);" +
"};",
weldPrelude("z") +
" var f = function() {" +
" function foo(x, y) {" +
" var a___ = ___.args(arguments);" +
" x = a___;" +
" y = z;" +
" return foo.CALL___(x - 1, y - 1);" +
" }" +
" return ___.frozenFunc(foo, 'foo');" +
" }();");
checkSucceeds(
"var bar = function foo_(x, y ) {" +
" return foo_(x - 1, y - 1);" +
"};",
"var bar = function() {" +
" function foo_(x, y) {" +
" return foo_.CALL___(x - 1, y - 1);" +
" }" +
" return ___.frozenFunc(foo_, 'foo_');" +
"}();");
}
public void testMaskingFunction () throws Exception {
assertAddsMessage(
"function Goo() { function Goo() {} }",
MessageType.SYMBOL_REDEFINED,
MessageLevel.ERROR );
assertAddsMessage(
"function Goo() { var Goo = 1; }",
MessageType.MASKING_SYMBOL,
MessageLevel.LINT );
assertMessageNotPresent(
"function Goo() { this.x = 1; }",
MessageType.MASKING_SYMBOL );
}
public void testMapEmpty() throws Exception {
checkSucceeds(
"var f = {};",
"var f = ___.initializeMap([]);");
}
public void testMapBadKeySuffix() throws Exception {
checkAddsMessage(
js(fromString("var o = { x__: 3 };")),
RewriterMessageType.PROPERTIES_CANNOT_END_IN_DOUBLE_UNDERSCORE);
}
public void testMapNonEmpty() throws Exception {
checkSucceeds(
"var o = { k0: g().x, k1: g().y };",
weldPrelude("g") +
"var x0___;" +
"var x1___;" +
"var o = ___.initializeMap(" +
" [ 'k0', " + weldReadPub("g.CALL___()", "x", "x0___") + ", " +
" 'k1', " + weldReadPub("g.CALL___()", "y", "x1___") + " ]);");
// Ensure that calling an untamed function throws
rewriteAndExecute(
"testImports.f = function() {};",
"assertThrows(function() { f(); });",
";");
// Ensure that calling a tamed function in an object literal works
rewriteAndExecute(
" var f = function() {};"
+ "var m = { f : f };"
+ "m.f();");
// Ensure that putting an untamed function into an object literal
// causes an exception.
rewriteAndExecute(
"testImports.f = function() {};",
"assertThrows(function(){({ isPrototypeOf : f });});",
";");
}
public void testOtherInstanceof() throws Exception {
checkSucceeds(
"function foo() {}" +
"g[0] instanceof foo;",
weldPrelude("g") +
"function foo() {\n" +
" }\n" +
" ___.func(foo, \'foo\');" +
";" +
"___.readPub(g, 0) instanceof ___.primFreeze(foo);");
checkSucceeds(
"g[0] instanceof Object;",
weldPrelude("Object") +
weldPrelude("g") +
"___.readPub(g, 0) instanceof Object;");
assertConsistent("[ (({}) instanceof Object)," +
" ((new Date) instanceof Date)," +
" (({}) instanceof Date)" +
"];");
assertConsistent("function foo() {}; (new foo) instanceof foo;");
assertConsistent("function foo() {}; !(({}) instanceof foo);");
}
public void testOtherTypeof() throws Exception {
checkSucceeds(
"typeof g[0];",
weldPrelude("g") +
"___.typeOf(___.readPub(g, 0));");
checkFails("typeof ___;", "Variables cannot end in \"__\"");
}
public void testLabeledStatement() throws Exception {
checkFails("IMPORTS___: 1;", "Labels cannot end in \"__\"");
checkFails("IMPORTS___: while (1);", "Labels cannot end in \"__\"");
checkSucceeds("foo: 1;", "foo: 1;");
checkFails("while (1) { break x__; }", "Labels cannot end in \"__\"");
checkSucceeds("break foo;", "break foo;");
checkFails("while (1) { continue x__; }", "Labels cannot end in \"__\"");
checkSucceeds("continue foo;", "continue foo;");
assertConsistent(
"var k = 0;" +
"a: for (var i = 0; i < 10; ++i) {" +
" b: for (var j = 0; j < 10; ++j) {" +
" if (++k > 5) break a;" +
" }" +
"}" +
"k;");
assertConsistent(
"var k = 0;" +
"a: for (var i = 0; i < 10; ++i) {" +
" b: for (var j = 0; j < 10; ++j) {" +
" if (++k > 5) break b;" +
" }" +
"}" +
"k;");
}
public void testRegexLiteral() throws Exception {
checkAddsMessage(
js(fromString("/x/;")),
RewriterMessageType.REGEX_LITERALS_NOT_IN_CAJITA);
checkAddsMessage(
js(fromString("var y = /x/;")),
RewriterMessageType.REGEX_LITERALS_NOT_IN_CAJITA);
}
public void testOtherSpecialOp() throws Exception {
checkSucceeds("void 0;", "void 0;");
checkSucceeds("void g();",
weldPrelude("g") +
"void g.CALL___();");
checkSucceeds("g[0], g[1];",
weldPrelude("g") +
"___.readPub(g, 0), ___.readPub(g, 1);");
}
public void testMultiDeclaration2() throws Exception {
// 'var' in global scope, part of a block
checkSucceeds(
"var x, y;",
"var x, y;");
checkSucceeds(
"var x = g[0], y = g[1];",
weldPrelude("g") +
"var x = ___.readPub(g, 0), y = ___.readPub(g, 1);");
checkSucceeds(
"var x, y = g[0];",
weldPrelude("g") +
"var x, y = ___.readPub(g, 0);");
// 'var' in global scope, 'for' statement
checkSucceeds(
"for (var x, y; ; ) {}",
"for (var x, y; ; ) {}");
checkSucceeds(
"for (var x = g[0], y = g[1]; ; ) {}",
weldPrelude("g") +
"for (var x = ___.readPub(g, 0), y = ___.readPub(g, 1); ; ) {}");
checkSucceeds(
"for (var x, y = g[0]; ; ) {}",
weldPrelude("g") +
"for (var x, y = ___.readPub(g, 0); ; ) {}");
// 'var' in global scope, part of a block
checkSucceeds(
"function() {" +
" var x, y;" +
"};",
"___.frozenFunc(function() {" +
" var x, y;" +
"});");
checkSucceeds(
"function() {" +
" var x = g[0], y = g[1];" +
"};",
weldPrelude("g") +
"___.frozenFunc(function() {" +
" var x = ___.readPub(g, 0), y = ___.readPub(g, 1);" +
"});");
checkSucceeds(
"function() {" +
" var x, y = g[0];" +
"};",
weldPrelude("g") +
"___.frozenFunc(function() {" +
" var x, y = ___.readPub(g, 0);" +
"});");
// 'var' in global scope, 'for' statement
checkSucceeds(
"function() {" +
" for (var x, y; ; ) {}" +
"};",
"___.frozenFunc(function() {" +
" for (var x, y; ; ) {}" +
"});");
checkSucceeds(
"function() {" +
" for (var x = g[0], y = g[1]; ; ) {}" +
"};",
weldPrelude("g") +
"___.frozenFunc(function() {" +
" for (var x = ___.readPub(g, 0), " +
" y = ___.readPub(g, 1); ; ) {}" +
"});");
checkSucceeds(
"function() {" +
" for (var x, y = g[0]; ; ) {}" +
"};",
weldPrelude("g") +
"___.frozenFunc(function() {" +
" for (var x, y = ___.readPub(g, 0); ; ) {}" +
"});");
assertConsistent(
"var arr = [1, 2, 3], k = -1;" +
"(function () {" +
" var a = arr[++k], b = arr[++k], c = arr[++k];" +
" return [a, b, c];" +
"})();");
// Check exceptions on read of uninitialized variables.
assertConsistent(
"(function () {" +
" var a = [];" +
" for (var i = 0, j = 10; i < j; ++i) { a.push(i); }" +
" return a;" +
"})();");
assertConsistent(
"var a = [];" +
"for (var i = 0, j = 10; i < j; ++i) { a.push(i); }" +
"a;");
}
public void testRecurseParseTreeNodeContainer() throws Exception {
// Tested implicitly by other cases
}
public void testRecurseArrayConstructor() throws Exception {
checkSucceeds(
"var foo = [ g[0], g[1] ];",
weldPrelude("g") +
"var foo = [___.readPub(g, 0), ___.readPub(g, 1)];");
}
public void testRecurseBlock() throws Exception {
// Tested implicitly by other cases
}
public void testRecurseBreakStmt() throws Exception {
checkSucceeds(
"while (true) { break; }",
"while (true) { break; }");
}
public void testRecurseCaseStmt() throws Exception {
checkSucceeds(
"switch (g[0]) { case 1: break; }",
weldPrelude("g") +
"switch (___.readPub(g, 0)) { case 1: break; }");
}
public void testRecurseConditional() throws Exception {
checkSucceeds(
"if (g[0] === g[1]) {" +
" g[2];" +
"} else if (g[3] === g[4]) {" +
" g[5];" +
"} else {" +
" g[6];" +
"}",
weldPrelude("g") +
"if (___.readPub(g, 0) === ___.readPub(g, 1)) {" +
" ___.readPub(g, 2);" +
"} else if (___.readPub(g, 3) === ___.readPub(g, 4)) {" +
" ___.readPub(g, 5);" +
"} else {" +
" ___.readPub(g, 6);" +
"}");
}
public void testRecurseContinueStmt() throws Exception {
checkSucceeds(
"while (true) { continue; }",
"while (true) { continue; }");
}
public void testRecurseDebuggerStmt() throws Exception {
checkSucceeds("debugger;", "debugger;");
}
public void testRecurseDefaultCaseStmt() throws Exception {
checkSucceeds(
"switch (g[0]) { default: break; }",
weldPrelude("g") +
"switch(___.readPub(g, 0)) { default: break; }");
}
public void testRecurseExpressionStmt() throws Exception {
// Tested implicitly by other cases
}
public void testRecurseIdentifier() throws Exception {
// Tested implicitly by other cases
}
public void testRecurseLiteral() throws Exception {
checkSucceeds(
"3;",
"3;");
}
public void testRecurseLoop() throws Exception {
checkSucceeds(
"for (var k = 0; k < g[0]; k++) {" +
" g[1];" +
"}",
weldPrelude("g") +
"for (var k = 0; k < ___.readPub(g, 0); k++) {" +
" ___.readPub(g, 1);" +
"}");
checkSucceeds(
"while (g[0]) { g[1]; }",
weldPrelude("g") +
"while (___.readPub(g, 0)) { ___.readPub(g, 1); }");
}
public void testRecurseNoop() throws Exception {
checkSucceeds(
";",
";");
}
public void testRecurseOperation() throws Exception {
checkSucceeds(
"g[0] + g[1];",
weldPrelude("g") +
"___.readPub(g, 0) + ___.readPub(g, 1);");
checkSucceeds(
"1 + 2 * 3 / 4 - -5;",
"1 + 2 * 3 / 4 - -5;");
checkSucceeds(
"var x, y;" +
"x = y = g[0];",
weldPrelude("g") +
"var x, y;" +
"x = y = ___.readPub(g, 0);");
}
public void testRecurseReturnStmt() throws Exception {
checkSucceeds(
"return g[0];",
weldPrelude("g") +
"return ___.readPub(g, 0);");
}
public void testRecurseSwitchStmt() throws Exception {
checkSucceeds(
"switch (g[0]) { }",
weldPrelude("g") +
"switch (___.readPub(g, 0)) { }");
}
public void testRecurseThrowStmt() throws Exception {
checkSucceeds(
"throw g[0];",
weldPrelude("g") +
"throw ___.readPub(g, 0);");
checkSucceeds(
"function() {" +
" var x;" +
" throw x;" +
"};",
"___.frozenFunc(function() {" +
" var x;" +
" throw x;" +
"});");
}
public void testCantReadProto() throws Exception {
rewriteAndExecute(
"function foo(){}" +
"assertEquals(foo.prototype, undefined);");
}
public void testSpecimenClickme() throws Exception {
checkSucceeds(fromResource("clickme.js"));
}
public void testSpecimenListfriends() throws Exception {
checkSucceeds(fromResource("listfriends.js"));
}
public void testRecursionOnIE() throws Exception {
ParseTreeNode input = js(fromString(
""
+ "var x = 1;\n"
+ "var f = function x(b) { return b ? 1 : x(true); };\n"
+ "assertEquals(2, x + f());"));
ParseTreeNode cajoled = defaultCajaRewriter.expand(input, mq);
assertNoErrors();
ParseTreeNode emulated = emulateIE6FunctionConstructors(cajoled);
executePlain(
""
+ "___.getNewModuleHandler().getImports().assertEquals\n"
+ " = ___.frozenFunc(assertEquals);\n"
+ "___.loadModule({\n"
+ " instantiate: function (___, IMPORTS___) {\n"
+ " " + render(emulated) + "\n"
+ " }\n"
+ " });").toString();
}
public void testAssertConsistent() throws Exception {
// Since we test structurally, this works.
assertConsistent("({})");
try {
// But this won't.
assertConsistent("typeof (new RegExp('foo'))");
} catch (AssertionFailedError e) {
// Pass
return;
}
fail("assertConsistent not working");
}
public void testIE_Emulation() throws Exception {
ParseTreeNode input = js(fromString(
""
+ "void (function x() {});\n"
+ "assertEquals('function', typeof x);\n"));
assertNoErrors();
ParseTreeNode emulated = emulateIE6FunctionConstructors(input);
executePlain(
" ___.loadModule({"
+ " instantiate: function (___, IMPORTS___) {"
+ " " + render(emulated)
+ " }"
+ "});");
}
/**
* Tests that the container can get access to
* "virtual globals" defined in cajoled code.
*/
public void testWrapperAccess() throws Exception {
// TODO(ihab.awad): SECURITY: Re-enable by reading (say) x.foo, and
// defining the property IMPORTS___.foo.
if (false) {
rewriteAndExecute(
"",
"x='test';",
"if (___.getNewModuleHandler().getImports().x != 'test') {" +
"fail('Cannot see inside the wrapper');" +
"}");
}
}
/**
* Tests that Array.prototype cannot be modified.
*/
public void testFrozenArray() throws Exception {
rewriteAndExecute(
"var success = false;" +
"try {" +
"Array.prototype[4] = 'four';" +
"} catch (e){" +
"success = true;" +
"}" +
"if (!success) fail('Array not frozen.');");
}
/**
* Tests that Object.prototype cannot be modified.
*/
public void testFrozenObject() throws Exception {
rewriteAndExecute(
"var success = false;" +
"try {" +
"Object.prototype.x = 'X';" +
"} catch (e){" +
"success = true;" +
"}" +
"if (!success) fail('Object not frozen.');");
}
/**
* Tests that cajoled code can't construct new Function objects.
*/
public void testFunction() throws Exception {
rewriteAndExecute(
"var success=false;" +
"try{var f=new Function('1');}catch(e){success=true;}" +
"if (!success)fail('Function constructor is accessible.')");
}
/**
* Tests that constructors are inaccessible.
*/
public void testConstructor() throws Exception {
try {
rewriteAndExecute(
"function x(){}; var F = x.constructor;");
} catch (junit.framework.AssertionFailedError e) {
// pass
}
}
public void testStamp() throws Exception {
rewriteAndExecute(
"___.getNewModuleHandler().getImports().stamp =" +
" ___.frozenFunc(___.stamp);" +
"___.grantRead(___.getNewModuleHandler().getImports(), 'stamp');",
"function Foo(){}" +
"var foo = new Foo;" +
"var passed = false;" +
"cajita.log('### stamp = ' + stamp);" +
"try { stamp(cajita.Trademark('test'), foo); }" +
"catch (e) {" +
" if (!e.message.match('may not be stamped')) {" +
" fail(e.message);" +
" }" +
" passed = true;" +
"}" +
"if (!passed) { fail ('Able to stamp constructed objects.'); }",
"");
rewriteAndExecute(
"___.getNewModuleHandler().getImports().stamp =" +
" ___.frozenFunc(___.stamp);" +
"___.grantRead(___.getNewModuleHandler().getImports(), 'stamp');",
"function Foo(){}" +
"var foo = new Foo;" +
"try { stamp(cajita.Trademark('test'), foo, true); }" +
"catch (e) {" +
" fail(e.message);" +
"}",
"");
rewriteAndExecute(
"___.getNewModuleHandler().getImports().stamp =" +
" ___.frozenFunc(___.stamp);" +
"___.grantRead(___.getNewModuleHandler().getImports(), 'stamp');",
"var foo = {};" +
"var tm = cajita.Trademark('test');" +
"stamp(tm, foo);" +
"cajita.guard(tm, foo);",
"");
rewriteAndExecute(
"___.getNewModuleHandler().getImports().stamp =" +
" ___.frozenFunc(___.stamp);" +
"___.grantRead(___.getNewModuleHandler().getImports(), 'stamp');",
"var foo = {};" +
"var tm = cajita.Trademark('test');" +
"var passed = false;" +
"try { cajita.guard(tm, foo); }" +
"catch (e) {" +
" if (e.message != 'Object \"[object Object]\" does not have the \"test\" trademark') {" +
" fail(e.message);" +
" }" +
" passed = true;" +
"}" +
"if (!passed) { fail ('Able to forge trademarks.'); }",
"");
rewriteAndExecute(
"___.getNewModuleHandler().getImports().stamp =" +
" ___.frozenFunc(___.stamp);" +
"___.grantRead(___.getNewModuleHandler().getImports(), 'stamp');",
"var foo = {};" +
"var tm = cajita.Trademark('test');" +
"var tm2 = cajita.Trademark('test2');" +
"var passed = false;" +
"try { stamp(tm, foo); cajita.guard(tm2, foo); }" +
"catch (e) {" +
" if (e.message != 'Object \"[object Object]\" does not have the \"test2\" trademark') {" +
" fail(e.message);" +
" }" +
" passed = true;" +
"}" +
"if (!passed) { fail ('Able to forge trademarks.'); }",
"");
rewriteAndExecute(
"___.getNewModuleHandler().getImports().stamp =" +
" ___.frozenFunc(___.stamp);" +
"___.grantRead(___.getNewModuleHandler().getImports(), 'stamp');",
"function foo(){};" +
"var tm = cajita.Trademark('test');" +
"var passed = false;" +
"try { stamp(tm, foo); }" +
"catch (e) {" +
" if (!e.message.match('is frozen')) {" +
" fail(e.message);" +
" }" +
" passed = true;" +
"}" +
"if (!passed) { fail ('Able to stamp frozen objects.'); }",
"");
}
public void testForwardReference() throws Exception {
rewriteAndExecute(
"var g = Bar;" +
"if (true) { var f = Foo; }" +
"function Foo(){}" +
"do { var h = Bar; function Bar(){} } while (0);" +
"assertEquals(typeof f, 'function');" +
"assertEquals(typeof g, 'undefined');" +
"assertEquals(typeof h, 'function');");
rewriteAndExecute(
"(function(){" +
"var g = Bar;" +
"if (true) { var f = Foo; }" +
"function Foo(){}" +
"do { var h = Bar; function Bar(){} } while (0);" +
"assertEquals(typeof f, 'function');" +
"assertEquals(typeof g, 'undefined');" +
"assertEquals(typeof h, 'function');" +
"})();");
}
public void testReformedGenerics() throws Exception {
rewriteAndExecute(
"var x = [33];" +
"x.foo = [].push;" +
"assertThrows(function(){x.foo(44)});");
rewriteAndExecute(
"var x = {blue:'green'};" +
"x.foo = [].push;" +
"assertThrows(function(){x.foo(44)});");
}
public void testIndexOf() throws Exception {
assertConsistent("''.indexOf('1');");
}
public void testCallback() throws Exception {
// These two cases won't work in Valija since every Valija disfunction has its own
// non-generic call and apply methods.
assertConsistent("(function(){}).apply.call(function(a, b) {return a + b;}, {}, [3, 4]);");
assertConsistent("(function(){}).call.call(function(a, b) {return a + b;}, {}, 3, 4);");
}
/**
* Tests the cajita.newTable(opt_useKeyLifetime) abstraction.
* <p>
* From here, we are not in a position to test the weak-GC properties this abstraction is
* designed to provide, nor its O(1) complexity measure. However, we can test that it works
* as a simple lookup table.
*/
public void testTable() throws Exception {
rewriteAndExecute(
"var t = cajita.newTable();" +
"var k1 = {};" +
"var k2 = {};" +
"var k3 = {};" +
"t.set(k1, 'v1');" +
"t.set(k2, 'v2');" +
"assertEquals(t.get(k1), 'v1');" +
"assertEquals(t.get(k2), 'v2');" +
"assertTrue(t.get(k3) === void 0);");
rewriteAndExecute(
"var t = cajita.newTable(true);" +
"var k1 = {};" +
"var k2 = {};" +
"var k3 = {};" +
"t.set(k1, 'v1');" +
"t.set(k2, 'v2');" +
"assertEquals(t.get(k1), 'v1');" +
"assertEquals(t.get(k2), 'v2');" +
"assertTrue(t.get(k3) === void 0);");
rewriteAndExecute(
"var t = cajita.newTable();" +
"t.set('foo', 'v1');" +
"t.set(null, 'v2');" +
"assertEquals(t.get('foo'), 'v1');" +
"assertEquals(t.get(null), 'v2');" +
"assertTrue(t.get({toString: function(){return 'foo';}}) === void 0);");
rewriteAndExecute(
"var t = cajita.newTable(true);" +
"assertThrows(function(){t.set('foo', 'v1');});");
}
/**
* Although the golden output here tests many extraneous things, the point of
* this test is to see that various anonymous functions in the original are
* turned into named functions -- named after the variable or property
* they are initializing.
* <p>
* The test is structured as as a call stack resulting in a breakpoint.
* If executed, for example, in the testbed applet with Firebug enabled,
* one should see the stack of generated function names.
*/
public void testFuncNaming() throws Exception {
checkSucceeds(
"function foo(){debugger;}" +
"var x = {bar: function() {foo();}};" +
"x.baz = function(){x.bar();};" +
"var zip = function(){x.baz();};" +
"var zap;" +
"zap = function(){zip();};" +
"zap();",
"function foo() { debugger; }" +
"___.func(foo, 'foo');" +
"var x0___;;" +
"var x = ___.initializeMap(['bar', (function () {" +
" function bar$_lit() { foo.CALL___(); }" +
" return ___.frozenFunc(bar$_lit, 'bar$_lit');" +
"})()]);" +
"x0___ = (function () {" +
" function baz$_meth() {" +
" x.bar_canCall___? x.bar(): ___.callPub(x, 'bar', []);" +
" }" +
" return ___.frozenFunc(baz$_meth, 'baz$_meth');" +
"})(), x.baz_canSet___ ? (x.baz = x0___) : ___.setPub(x, 'baz', x0___);" +
"var zip = (function () {" +
" function zip$_var() {" +
" x.baz_canCall___ ? x.baz() : ___.callPub(x, 'baz', []);" +
" }" +
" return ___.frozenFunc(zip$_var, 'zip$_var');" +
"})();" +
"var zap;" +
"zap = (function () {" +
" function zap$_var() { zip.CALL___(); }" +
" return ___.frozenFunc(zap$_var, 'zap$_var');" +
"})();" +
"zap.CALL___();");
}
public void testRecordInheritance() throws Exception {
rewriteAndExecute(
"var x = {a: 8};" +
"var y = cajita.beget(x);" +
"testImports.y = y;",
// TODO(erights): Fix when bug 956 is fixed.
"var BAD_TEST = true;" +
"assertTrue(cajita.canReadPub(y, 'a') || BAD_TEST);",
"");
}
/**
* Tests that properties that the global object inherits from
* <tt>Object.prototype</tt> are not readable as global
* variables.
*/
public void testNoPrototypicalImports() throws Exception {
rewriteAndExecute(
"var x;" +
"try { x = toString; } catch (e) {}" +
"if (x) { cajita.fail('Inherited global properties are readable'); }");
}
@Override
protected Object executePlain(String caja) throws IOException {
mq.getMessages().clear();
return RhinoTestBed.runJs(
new RhinoTestBed.Input(getClass(), "/com/google/caja/cajita.js"),
new RhinoTestBed.Input(
getClass(), "../../../../../js/jsunit/2.2/jsUnitCore.js"),
new RhinoTestBed.Input(caja, getName() + "-uncajoled"));
}
@Override
protected Object rewriteAndExecute(String pre, String caja, String post)
throws IOException, ParseException {
mq.getMessages().clear();
List<Statement> children = new ArrayList<Statement>();
children.add(js(fromString(caja, is)));
String cajoledJs = render(rewriteTopLevelNode(
new UncajoledModule(new Block(FilePosition.UNKNOWN, children))));
assertNoErrors();
final String[] assertFunctions = new String[] {
"fail",
"assertEquals",
"assertTrue",
"assertFalse",
"assertLessThan",
"assertNull",
"assertThrows",
};
StringBuilder importsSetup = new StringBuilder();
importsSetup.append("var testImports = ___.copy(___.sharedImports);");
for (String f : assertFunctions) {
importsSetup
.append("testImports." + f + " = ___.func(" + f + ");")
.append("___.grantRead(testImports, '" + f + "');");
}
importsSetup.append("___.getNewModuleHandler().setImports(testImports);");
Object result = RhinoTestBed.runJs(
new RhinoTestBed.Input(
getClass(), "/com/google/caja/plugin/console-stubs.js"),
new RhinoTestBed.Input(getClass(), "/com/google/caja/cajita.js"),
new RhinoTestBed.Input(
getClass(), "../../../../../js/jsunit/2.2/jsUnitCore.js"),
new RhinoTestBed.Input(
getClass(), "/com/google/caja/log-to-console.js"),
new RhinoTestBed.Input(
importsSetup.toString(),
getName() + "-test-fixture"),
new RhinoTestBed.Input(pre, getName()),
// Load the cajoled code.
new RhinoTestBed.Input(cajoledJs, getName() + "-cajoled"),
new RhinoTestBed.Input(post, getName()),
// Return the output field as the value of the run.
new RhinoTestBed.Input(
"___.getNewModuleHandler().getLastValue();", getName()));
assertNoErrors();
return result;
}
}
| true | true | public void testTryCatch() throws Exception {
checkAddsMessage(js(fromString(
"try {" +
" throw 2;" +
"} catch (e) {" +
" var e;" +
"}")),
MessageType.MASKING_SYMBOL,
MessageLevel.ERROR);
checkAddsMessage(js(fromString(
"var e;" +
"try {" +
" throw 2;" +
"} catch (e) {" +
"}")),
MessageType.MASKING_SYMBOL,
MessageLevel.ERROR);
checkAddsMessage(js(fromString(
"try {} catch (x__) { }")),
RewriterMessageType.VARIABLES_CANNOT_END_IN_DOUBLE_UNDERSCORE);
// TODO(ihab.awad): The below should throw MessageType.MASKING_SYMBOL at
// MessageLevel.ERROR. See bug #313. For the moment, we merely check that
// it cajoles to something secure.
checkSucceeds(
"try {" +
" g[0];" +
" e;" +
" g[1];" +
"} catch (e) {" +
" g[2];" +
" e;" +
" g[3];" +
"}",
weldPrelude("e") +
weldPrelude("g") +
"try {" +
" ___.readPub(g, 0);" +
" e;" +
" ___.readPub(g, 1);" +
"} catch (ex___) {" +
" try {" +
" throw ___.tameException(ex___);" +
" } catch (e) {" +
" ___.readPub(g, 2);" +
" e;" +
" ___.readPub(g, 3);" +
" }" +
"}");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw null;" +
"} catch (ex) {" +
" assertEquals(null, ex);" + // Right value in ex.
" handled = true;" +
"}" +
"assertTrue(handled);"); // Control reached and left the catch block.
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw undefined;" +
"} catch (ex) {" +
" assertEquals(undefined, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw true;" +
"} catch (ex) {" +
" assertEquals(true, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw 37639105;" +
"} catch (ex) {" +
" assertEquals(37639105, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw 'panic';" +
"} catch (ex) {" +
" assertEquals('panic', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw new Error('hello');" +
"} catch (ex) {" +
" assertEquals('hello', ex.message);" +
" assertEquals('Error', ex.name);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw function () { throw 'should not be called'; };" +
"} catch (ex) {" +
" assertEquals(undefined, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw { toString: function () { return 'hiya'; }, y: 4 };" +
"} catch (ex) {" +
" assertEquals('string', typeof ex);" +
" assertEquals('hiya', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw { toString: function () { throw new Error(); } };" +
"} catch (ex) {" +
" assertEquals('Exception during exception handling.', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
}
| public void testTryCatch() throws Exception {
checkAddsMessage(js(fromString(
"try {" +
" throw 2;" +
"} catch (e) {" +
" var e;" +
"}")),
MessageType.MASKING_SYMBOL,
MessageLevel.ERROR);
checkAddsMessage(js(fromString(
"var e;" +
"try {" +
" throw 2;" +
"} catch (e) {" +
"}")),
MessageType.MASKING_SYMBOL,
MessageLevel.ERROR);
checkAddsMessage(js(fromString(
"try {} catch (x__) { }")),
RewriterMessageType.VARIABLES_CANNOT_END_IN_DOUBLE_UNDERSCORE);
// TODO(ihab.awad): The below should throw MessageType.MASKING_SYMBOL at
// MessageLevel.ERROR. See bug #313. For the moment, we merely check that
// it cajoles to something secure.
checkSucceeds(
"try {" +
" g[0];" +
" e;" +
" g[1];" +
"} catch (e) {" +
" g[2];" +
" e;" +
" g[3];" +
"}",
weldPrelude("e") +
weldPrelude("g") +
"try {" +
" ___.readPub(g, 0);" +
" e;" +
" ___.readPub(g, 1);" +
"} catch (ex___) {" +
" try {" +
" throw ___.tameException(ex___);" +
" } catch (e) {" +
" ___.readPub(g, 2);" +
" e;" +
" ___.readPub(g, 3);" +
" }" +
"}");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw null;" +
"} catch (ex) {" +
" assertEquals(null, ex);" + // Right value in ex.
" handled = true;" +
"}" +
"assertTrue(handled);"); // Control reached and left the catch block.
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw undefined;" +
"} catch (ex) {" +
" assertEquals(undefined, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw true;" +
"} catch (ex) {" +
" assertEquals(true, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw 37639105;" +
"} catch (ex) {" +
" assertEquals(37639105, ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw 'panic';" +
"} catch (ex) {" +
" assertEquals('panic', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw new Error('hello');" +
"} catch (ex) {" +
" assertEquals('hello', ex.message);" +
" assertEquals('Error', ex.name);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw function () { throw 'should not be called'; };" +
"} catch (ex) {" +
" assertEquals(undefined, ex());" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw { toString: function () { return 'hiya'; }, y: 4 };" +
"} catch (ex) {" +
" assertEquals('string', typeof ex);" +
" assertEquals('hiya', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
rewriteAndExecute(
"var handled = false;" +
"try {" +
" throw { toString: function () { throw new Error(); } };" +
"} catch (ex) {" +
" assertEquals('Exception during exception handling.', ex);" +
" handled = true;" +
"}" +
"assertTrue(handled);");
}
|
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/JsServlet.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/JsServlet.java
index 00564cba..7ac6621c 100644
--- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/JsServlet.java
+++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/JsServlet.java
@@ -1,151 +1,152 @@
/*
* 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.shindig.gadgets.http;
import org.apache.shindig.gadgets.GadgetException;
import org.apache.shindig.gadgets.GadgetFeatureFactory;
import org.apache.shindig.gadgets.GadgetFeatureRegistry;
import org.apache.shindig.gadgets.JsLibrary;
import org.apache.shindig.gadgets.JsLibraryFeatureFactory;
import org.apache.shindig.gadgets.RenderingContext;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Simple servlet serving up JavaScript files by their registered aliases.
* Used by type=URL gadgets in loading JavaScript resources.
*/
public class JsServlet extends HttpServlet {
private GadgetFeatureRegistry registry = null;
/**
* Create a JsServlet using a pre-configured feature registry.
* @param registry
*/
public JsServlet(GadgetFeatureRegistry registry) {
this.registry = registry;
}
/**
* Creates a JsServlet without a default registry; the registry will be
* created automatically when init is called.
*/
public JsServlet() {
registry = null;
}
@Override
public void init(ServletConfig config) {
ServletContext context = config.getServletContext();
if (registry == null) {
String features = context.getInitParameter("features");
try {
registry = new GadgetFeatureRegistry(features);
} catch (GadgetException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// Use the last component as filename; prefix is ignored
- String path = req.getPathTranslated();
- String[] pathComponents = path.split("/");
- String resourceName = pathComponents[pathComponents.length-1];
+ String uri = req.getRequestURI();
+ // We only want the file name part. There will always be at least 1 slash
+ // (the server root), so this is always safe.
+ String resourceName = uri.substring(uri.lastIndexOf("/") + 1);
if (resourceName.endsWith(".js")) {
// Lop off the suffix for lookup purposes
resourceName = resourceName.substring(
0, resourceName.length() - ".js".length());
}
Set<String> needed = new HashSet<String>();
if (resourceName.contains(":")) {
needed.addAll(Arrays.asList(resourceName.split(":")));
} else {
needed.add(resourceName);
}
Set<GadgetFeatureRegistry.Entry> found
= new HashSet<GadgetFeatureRegistry.Entry>();
Set<String> missing = new HashSet<String>();
if (registry.getIncludedFeatures(needed, found, missing)) {
String containerParam = req.getParameter("c");
RenderingContext context;
context = containerParam != null && containerParam.equals("1") ?
RenderingContext.CONTAINER :
RenderingContext.GADGET;
StringBuilder jsData = new StringBuilder();
Set<GadgetFeatureRegistry.Entry> done
= new HashSet<GadgetFeatureRegistry.Entry>();
do {
for (GadgetFeatureRegistry.Entry entry : found) {
if (!done.contains(entry) &&
done.containsAll(entry.getDependencies())) {
GadgetFeatureFactory feature = entry.getFeature();
if (feature instanceof JsLibraryFeatureFactory) {
JsLibraryFeatureFactory jsLib = (JsLibraryFeatureFactory)feature;
for (JsLibrary lib : jsLib.getLibraries(context)) {
// TODO: type url js files fail here.
if (lib.getType() != JsLibrary.Type.URL) {
jsData.append(lib.getContent());
}
}
}
done.add(entry);
}
}
} while (done.size() != found.size());
if (jsData.length() == 0) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
setCachingHeaders(resp);
resp.setContentType("text/javascript");
resp.setContentLength(jsData.length());
resp.getOutputStream().write(jsData.toString().getBytes());
} else {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
* Sets HTTP headers that instruct the browser to cache indefinitely.
* Implementations should take care to use cache-busting techniques on the
* url.
*
* @param response The HTTP response
*/
private void setCachingHeaders(HttpServletResponse response) {
response.setHeader("Cache-Control", "public,max-age=2592000");
response.setDateHeader("Expires", System.currentTimeMillis()
+ 2592000000L);
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// Use the last component as filename; prefix is ignored
String path = req.getPathTranslated();
String[] pathComponents = path.split("/");
String resourceName = pathComponents[pathComponents.length-1];
if (resourceName.endsWith(".js")) {
// Lop off the suffix for lookup purposes
resourceName = resourceName.substring(
0, resourceName.length() - ".js".length());
}
Set<String> needed = new HashSet<String>();
if (resourceName.contains(":")) {
needed.addAll(Arrays.asList(resourceName.split(":")));
} else {
needed.add(resourceName);
}
Set<GadgetFeatureRegistry.Entry> found
= new HashSet<GadgetFeatureRegistry.Entry>();
Set<String> missing = new HashSet<String>();
if (registry.getIncludedFeatures(needed, found, missing)) {
String containerParam = req.getParameter("c");
RenderingContext context;
context = containerParam != null && containerParam.equals("1") ?
RenderingContext.CONTAINER :
RenderingContext.GADGET;
StringBuilder jsData = new StringBuilder();
Set<GadgetFeatureRegistry.Entry> done
= new HashSet<GadgetFeatureRegistry.Entry>();
do {
for (GadgetFeatureRegistry.Entry entry : found) {
if (!done.contains(entry) &&
done.containsAll(entry.getDependencies())) {
GadgetFeatureFactory feature = entry.getFeature();
if (feature instanceof JsLibraryFeatureFactory) {
JsLibraryFeatureFactory jsLib = (JsLibraryFeatureFactory)feature;
for (JsLibrary lib : jsLib.getLibraries(context)) {
// TODO: type url js files fail here.
if (lib.getType() != JsLibrary.Type.URL) {
jsData.append(lib.getContent());
}
}
}
done.add(entry);
}
}
} while (done.size() != found.size());
if (jsData.length() == 0) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
setCachingHeaders(resp);
resp.setContentType("text/javascript");
resp.setContentLength(jsData.length());
resp.getOutputStream().write(jsData.toString().getBytes());
} else {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// Use the last component as filename; prefix is ignored
String uri = req.getRequestURI();
// We only want the file name part. There will always be at least 1 slash
// (the server root), so this is always safe.
String resourceName = uri.substring(uri.lastIndexOf("/") + 1);
if (resourceName.endsWith(".js")) {
// Lop off the suffix for lookup purposes
resourceName = resourceName.substring(
0, resourceName.length() - ".js".length());
}
Set<String> needed = new HashSet<String>();
if (resourceName.contains(":")) {
needed.addAll(Arrays.asList(resourceName.split(":")));
} else {
needed.add(resourceName);
}
Set<GadgetFeatureRegistry.Entry> found
= new HashSet<GadgetFeatureRegistry.Entry>();
Set<String> missing = new HashSet<String>();
if (registry.getIncludedFeatures(needed, found, missing)) {
String containerParam = req.getParameter("c");
RenderingContext context;
context = containerParam != null && containerParam.equals("1") ?
RenderingContext.CONTAINER :
RenderingContext.GADGET;
StringBuilder jsData = new StringBuilder();
Set<GadgetFeatureRegistry.Entry> done
= new HashSet<GadgetFeatureRegistry.Entry>();
do {
for (GadgetFeatureRegistry.Entry entry : found) {
if (!done.contains(entry) &&
done.containsAll(entry.getDependencies())) {
GadgetFeatureFactory feature = entry.getFeature();
if (feature instanceof JsLibraryFeatureFactory) {
JsLibraryFeatureFactory jsLib = (JsLibraryFeatureFactory)feature;
for (JsLibrary lib : jsLib.getLibraries(context)) {
// TODO: type url js files fail here.
if (lib.getType() != JsLibrary.Type.URL) {
jsData.append(lib.getContent());
}
}
}
done.add(entry);
}
}
} while (done.size() != found.size());
if (jsData.length() == 0) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
setCachingHeaders(resp);
resp.setContentType("text/javascript");
resp.setContentLength(jsData.length());
resp.getOutputStream().write(jsData.toString().getBytes());
} else {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.