diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/InterviewAnnihilator/src/com/huskysoft/interviewannihilator/model/Question.java b/InterviewAnnihilator/src/com/huskysoft/interviewannihilator/model/Question.java
index a40e7d0..53f8e21 100644
--- a/InterviewAnnihilator/src/com/huskysoft/interviewannihilator/model/Question.java
+++ b/InterviewAnnihilator/src/com/huskysoft/interviewannihilator/model/Question.java
@@ -1,239 +1,241 @@
/**
*
* Governs the fields and behavior of the questions that are created
* and displayed on our application
*
* @author Dan Sanders, 4/29/13
*
*/
package com.huskysoft.interviewannihilator.model;
+import java.io.Serializable;
import java.util.Date;
-public class Question implements Likeable {
+public class Question implements Likeable, Serializable {
+ private static final long serialVersionUID = 5304505688702584930L;
private int questionId;
private String text;
private String title;
private int authorId;
private Date dateCreated;
private Category category;
private Difficulty difficulty;
private int likes;
private int dislikes;
public Question() {
}
/**
* Called when our android application is trying to create a new question
* and load it into the database. The database will populate the rest of
* the fields and return the fleshed-out Question object back to the
* application
*
* @param text
* @param title
* @param categories
* @param difficulty
*/
public Question(String text, String title, Category category,
Difficulty difficulty) {
this.text = text;
this.title = title;
this.difficulty = difficulty;
this.category = category;
}
public int getQuestionId() {
return questionId;
}
public String getText() {
return text;
}
public String getTitle() {
return title;
}
public int getAuthorId() {
return authorId;
}
public Date getDateCreated() {
return dateCreated;
}
public Category getCategory() {
return category;
}
public Difficulty getDifficulty() {
return difficulty;
}
public int getLikes() {
return likes;
}
public int getDislikes() {
return dislikes;
}
public void setQuestionId(int id) {
this.questionId = id;
}
public void setText(String text) {
this.text = text;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthorId(int authorId) {
this.authorId = authorId;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public void setCategory(Category category) {
this.category = category;
}
public void setDifficulty(Difficulty difficulty) {
this.difficulty = difficulty;
}
public void setLikes(int likes) {
this.likes = likes;
}
public void setDislikes(int dislikes) {
this.dislikes = dislikes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + authorId;
int i;
if (category == null) {
i = 0;
}
else {
i = category.hashCode();
}
result = prime * result + i;
int diffResult;
if (dateCreated == null) {
diffResult = 0;
}
else {
diffResult = dateCreated.hashCode();
}
int nextPrime = diffResult;
int k = nextPrime;
result = prime * result + k;
int diffJ;
if (difficulty == null) {
diffJ = 0;
}
else {
diffJ = difficulty.hashCode();
}
result = prime * result + diffJ;
result = prime * result + dislikes;
result = prime * result + questionId;
result = prime * result + likes;
int y;
if (text == null) {
y = 0;
}
else {
y = text.hashCode();
}
result = prime * result + y;
int diffK;
if (title == null) {
diffK = 0;
}
else {
diffK = title.hashCode();
}
result = prime * result + diffK;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(getClass().equals(obj.getClass()))) {
return false;
}
Question other = (Question) obj;
if (authorId != other.authorId) {
return false;
}
if (category != other.category) {
return false;
}
if (dateCreated == null) {
if (other.dateCreated != null) {
return false;
}
}
else if (!dateCreated.equals(other.dateCreated)) {
return false;
}
if (difficulty != other.difficulty) {
return false;
}
if (dislikes != other.dislikes) {
return false;
}
if (questionId != other.questionId) {
return false;
}
if (likes != other.likes) {
return false;
}
if (text == null) {
if (other.text != null) {
return false;
}
}
else if (!text.equals(other.text)) {
return false;
}
if (title == null) {
if (other.title != null) {
return false;
}
}
else if (!title.equals(other.title)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Question [id=" + questionId + ", text=" + text + ", "
+ "title=" + title + ", authorId=" + authorId
+ ", dateCreated=" + dateCreated + ", category=" + category
+ ", difficulty=" + difficulty + ", likes=" + likes
+ ", dislikes=" + dislikes + "]";
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/app/controllers/MenuController.java b/app/controllers/MenuController.java
index ab1643b..c9062f5 100644
--- a/app/controllers/MenuController.java
+++ b/app/controllers/MenuController.java
@@ -1,143 +1,143 @@
package controllers;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import converter.MenuItemConverter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import job.WriteFileMenu;
import models.menu.Menu;
import models.menu.MenuItem;
import models.menu.items.MenuItem_ControllerChain;
import models.menu.items.MenuItem_LinkToPage;
import models.menu.items.MenuItem_OutgoingURL;
import models.menu.items.MenuItem_Title;
import play.Logger;
import play.Play;
import play.mvc.Controller;
import play.mvc.With;
import play.vfs.VirtualFile;
/**
*
* @author keruspe
*/
-//@With(Secure.class)
+@With(Secure.class)
public class MenuController extends Controller {
public static void list() {
List<Menu> menus = Menu.findAll();
List<VirtualFile> filemenus = Play.getVirtualFile("/data/menus").list();
render(menus, filemenus);
}
public static void edit(String id) {
Menu menu = Menu.getByMongodStringId(id);
if (menu == null) {
notFound();
}
render(menu);
}
public static void edit_end(String id) {
Menu menu = Menu.getByMongodStringId(id);
if (menu == null) {
notFound();
}
menu.name = params.get("menu.name");
menu.save();
list();
}
public static void delete(String id) {
Menu.getByMongodStringId(id).delete();
list();
}
public static void newMenu() {
render();
}
public static void newMenu_end() {
Menu.findOrCreateByName(params.get("menu.name").replaceAll("[ #\\.]", "-"));
list();
}
public static void addItem(String id) {
Menu menu = Menu.getByMongodStringId(id);
if (menu == null) {
notFound();
}
List<String> types = new ArrayList<String>();
types.add("ControllerChain");
types.add("LinkToPage");
types.add("OutgoingURL");
types.add("Title");
render(menu, types);
}
public static void doAddItem(String id) {
Menu menu = Menu.getByMongodStringId(id);
if (menu == null) {
notFound();
}
MenuItem item;
String type = params.get("item.type");
String value = params.get("item.value");
String displayStr = params.get("item.display");
if (displayStr == null || displayStr.isEmpty()) {
displayStr = value;
}
if (type.equals("ControllerChain")) {
item = new MenuItem_ControllerChain(value, displayStr);
} else if (type.equals("LinkToPage")) {
item = new MenuItem_LinkToPage(value, displayStr);
} else if (type.equals("OutgoingURL")) {
item = new MenuItem_OutgoingURL(value, displayStr);
} else if (type.equals("Title")) {
item = new MenuItem_Title(value, displayStr);
} else {
return;
}
item.setMenu(Menu.findByName(params.get("item.subMenu")), menu);
item.cssLinkClass = params.get("item.cssLink");
item.save();
menu.addItem(item);
edit(id);
}
public static void removeItem(String idMenu, String idMenuItem) {
Menu menu = Menu.getByMongodStringId(idMenu);
MenuItem item = MenuItem.getByMongodStringId(idMenuItem);
if (menu == null || item == null) {
notFound();
}
System.out.println("zedze " + item);
menu.removeItem(item);
edit(idMenu);
}
public static void writeMenuFile(String id) {
(new WriteFileMenu(Menu.getByMongodStringId(id))).now();
list();
}
public static void importMenuFromFile(String path) {
Gson gson = new GsonBuilder().registerTypeAdapter(MenuItem.class, new MenuItemConverter()).create();
try {
Menu menu = gson.fromJson(new FileReader(Play.getVirtualFile(path).getRealFile()), Menu.class);
menu.save();
} catch (FileNotFoundException e) {
Logger.error(e.getLocalizedMessage(), null);
}
list();
}
}
| true | false | null | null |
diff --git a/core/src/main/java/hudson/security/GlobalMatrixAuthorizationStrategy.java b/core/src/main/java/hudson/security/GlobalMatrixAuthorizationStrategy.java
index b0c167012..3103335e9 100644
--- a/core/src/main/java/hudson/security/GlobalMatrixAuthorizationStrategy.java
+++ b/core/src/main/java/hudson/security/GlobalMatrixAuthorizationStrategy.java
@@ -1,277 +1,278 @@
package hudson.security;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.util.FormFieldValidator;
import hudson.Functions;
import net.sf.json.JSONObject;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.acegisecurity.acls.sid.Sid;
+import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import org.springframework.dao.DataAccessException;
import javax.servlet.ServletException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.io.IOException;
/**
* Role-based authorization via a matrix.
*
* @author Kohsuke Kawaguchi
*/
// TODO: think about the concurrency commitment of this class
public class GlobalMatrixAuthorizationStrategy extends AuthorizationStrategy {
private transient SidACL acl = new AclImpl();
/**
* List up all permissions that are granted.
*
* Strings are either the granted authority or the principal,
* which is not distinguished.
*/
private final Map<Permission,Set<String>> grantedPermissions = new HashMap<Permission, Set<String>>();
private final Set<String> sids = new HashSet<String>();
/**
* Adds to {@link #grantedPermissions}.
* Use of this method should be limited during construction,
* as this object itself is considered immutable once populated.
*/
public void add(Permission p, String sid) {
Set<String> set = grantedPermissions.get(p);
if(set==null)
grantedPermissions.put(p,set = new HashSet<String>());
set.add(sid);
sids.add(sid);
}
/**
* Works like {@link #add(Permission, String)} but takes both parameters
* from a single string of the form <tt>PERMISSIONID:sid</tt>
*/
private void add(String shortForm) {
int idx = shortForm.indexOf(':');
add(Permission.fromId(shortForm.substring(0,idx)),shortForm.substring(idx+1));
}
@Override
public SidACL getRootACL() {
return acl;
}
public Set<String> getGroups() {
return sids;
}
private Object readResolve() {
acl = new AclImpl();
return this;
}
/**
* Checks if the given SID has the given permission.
*/
public boolean hasPermission(String sid, Permission p) {
for(; p!=null; p=p.impliedBy) {
Set<String> set = grantedPermissions.get(p);
if(set!=null && set.contains(sid))
return true;
}
return false;
}
/**
* Checks if the permission is explicitly given, instead of implied through {@link Permission#impliedBy}.
*/
public boolean hasExplicitPermission(String sid, Permission p) {
Set<String> set = grantedPermissions.get(p);
return set != null && set.contains(sid);
}
/**
* Returns all SIDs configured in this matrix, minus "anonymous"
*
* @return
* Always non-null.
*/
public List<String> getAllSIDs() {
Set<String> r = new HashSet<String>();
for (Set<String> set : grantedPermissions.values())
r.addAll(set);
r.remove("anonymous");
String[] data = r.toArray(new String[r.size()]);
Arrays.sort(data);
return Arrays.asList(data);
}
private final class AclImpl extends SidACL {
protected Boolean hasPermission(Sid p, Permission permission) {
if(GlobalMatrixAuthorizationStrategy.this.hasPermission(toString(p),permission))
return true;
return null;
}
}
public Descriptor<AuthorizationStrategy> getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
/**
* Persist {@link GlobalMatrixAuthorizationStrategy} as a list of IDs that
* represent {@link GlobalMatrixAuthorizationStrategy#grantedPermissions}.
*/
public static class ConverterImpl implements Converter {
public boolean canConvert(Class type) {
return type==GlobalMatrixAuthorizationStrategy.class;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
GlobalMatrixAuthorizationStrategy strategy = (GlobalMatrixAuthorizationStrategy)source;
for (Entry<Permission, Set<String>> e : strategy.grantedPermissions.entrySet()) {
String p = e.getKey().getId();
for (String sid : e.getValue()) {
writer.startNode("permission");
context.convertAnother(p+':'+sid);
writer.endNode();
}
}
}
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
GlobalMatrixAuthorizationStrategy as = create();
while (reader.hasMoreChildren()) {
reader.moveDown();
String id = (String)context.convertAnother(as,String.class);
as.add(id);
reader.moveUp();
}
return as;
}
protected GlobalMatrixAuthorizationStrategy create() {
return new GlobalMatrixAuthorizationStrategy();
}
}
static {
LIST.add(DESCRIPTOR);
}
public static class DescriptorImpl extends Descriptor<AuthorizationStrategy> {
protected DescriptorImpl(Class<? extends GlobalMatrixAuthorizationStrategy> clazz) {
super(clazz);
}
public DescriptorImpl() {
}
public String getDisplayName() {
return Messages.GlobalMatrixAuthorizationStrategy_DisplayName();
}
public AuthorizationStrategy newInstance(StaplerRequest req, JSONObject formData) throws FormException {
GlobalMatrixAuthorizationStrategy gmas = create();
for(Map.Entry<String,JSONObject> r : (Set<Map.Entry<String,JSONObject>>)formData.getJSONObject("data").entrySet()) {
String sid = r.getKey();
for(Map.Entry<String,Boolean> e : (Set<Map.Entry<String,Boolean>>)r.getValue().entrySet()) {
if(e.getValue()) {
Permission p = Permission.fromId(e.getKey());
gmas.add(p,sid);
}
}
}
return gmas;
}
protected GlobalMatrixAuthorizationStrategy create() {
return new GlobalMatrixAuthorizationStrategy();
}
public String getHelpFile() {
return "/help/security/global-matrix.html";
}
public List<PermissionGroup> getAllGroups() {
List<PermissionGroup> groups = new ArrayList<PermissionGroup>(PermissionGroup.getAll());
groups.remove(PermissionGroup.get(Permission.class));
return groups;
}
public boolean showPermission(Permission p) {
return true;
}
public void doCheckName(@QueryParameter String value ) throws IOException, ServletException {
final String v = value.substring(1,value.length()-1);
new FormFieldValidator(Hudson.ADMINISTER) {
protected void check() throws IOException, ServletException {
SecurityRealm sr = Hudson.getInstance().getSecurityRealm();
String ev = Functions.escape(v);
if(v.equals("authenticated")) {
// systerm reserved group
respond("<span>"+ makeImg("user.gif") +ev+"</span>");
return;
}
try {
sr.loadUserByUsername(v);
respond("<span>"+ makeImg("person.gif") +ev+"</span>");
return;
} catch (UserMayOrMayNotExistException e) {
// undecidable, meaning the user may exist
respond("<span>"+ev+"</span>");
return;
} catch (UsernameNotFoundException e) {
// fall through next
} catch (DataAccessException e) {
// fall through next
}
try {
sr.loadGroupByGroupname(v);
respond("<span>"+ makeImg("user.gif") +ev+"</span>");
return;
} catch (UserMayOrMayNotExistException e) {
// undecidable, meaning the group may exist
respond("<span>"+ev+"</span>");
return;
} catch (UsernameNotFoundException e) {
// fall through next
} catch (DataAccessException e) {
// fall through next
}
// couldn't find it. it doesn't exit
respond("<span>"+ makeImg("error.gif") +ev+"</span>");
}
}.process();
}
private String makeImg(String gif) {
- return String.format("<img src='%s%s/images/16x16/%s' style='margin-right:0.2em'>", Hudson.getInstance().getRootUrlFromRequest(), Hudson.RESOURCE_PATH, gif);
+ return String.format("<img src='%s%s/images/16x16/%s' style='margin-right:0.2em'>", Stapler.getCurrentRequest().getContextPath(), Hudson.RESOURCE_PATH, gif);
}
}
}
| false | false | null | null |
diff --git a/achartengine/src/org/achartengine/model/XYSeries.java b/achartengine/src/org/achartengine/model/XYSeries.java
index 56063b7..ac49a63 100644
--- a/achartengine/src/org/achartengine/model/XYSeries.java
+++ b/achartengine/src/org/achartengine/model/XYSeries.java
@@ -1,255 +1,256 @@
/**
* Copyright (C) 2009 - 2012 SC 4ViewSoft SRL
*
* 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.achartengine.model;
import java.io.Serializable;
import java.util.Iterator;
import java.util.SortedMap;
+import java.util.TreeMap;
import org.achartengine.util.IndexXYMap;
import org.achartengine.util.MathHelper;
import org.achartengine.util.XYEntry;
/**
* An XY series encapsulates values for XY charts like line, time, area,
* scatter... charts.
*/
public class XYSeries implements Serializable {
/** The series title. */
private String mTitle;
/** A map to contain values for X and Y axes and index for each bundle */
private final IndexXYMap<Double, Double> mXY = new IndexXYMap<Double, Double>();
/** The minimum value for the X axis. */
private double mMinX = MathHelper.NULL_VALUE;
/** The maximum value for the X axis. */
private double mMaxX = -MathHelper.NULL_VALUE;
/** The minimum value for the Y axis. */
private double mMinY = MathHelper.NULL_VALUE;
/** The maximum value for the Y axis. */
private double mMaxY = -MathHelper.NULL_VALUE;
/** The scale number for this series. */
private final int mScaleNumber;
/**
* Builds a new XY series.
*
* @param title the series title.
*/
public XYSeries(String title) {
this(title, 0);
}
/**
* Builds a new XY series.
*
* @param title the series title.
* @param scaleNumber the series scale number
*/
public XYSeries(String title, int scaleNumber) {
mTitle = title;
mScaleNumber = scaleNumber;
initRange();
}
public int getScaleNumber() {
return mScaleNumber;
}
/**
* Initializes the range for both axes.
*/
private void initRange() {
mMinX = MathHelper.NULL_VALUE;
mMaxX = -MathHelper.NULL_VALUE;
mMinY = MathHelper.NULL_VALUE;
mMaxY = -MathHelper.NULL_VALUE;
int length = getItemCount();
for (int k = 0; k < length; k++) {
double x = getX(k);
double y = getY(k);
updateRange(x, y);
}
}
/**
* Updates the range on both axes.
*
* @param x the new x value
* @param y the new y value
*/
private void updateRange(double x, double y) {
mMinX = Math.min(mMinX, x);
mMaxX = Math.max(mMaxX, x);
mMinY = Math.min(mMinY, y);
mMaxY = Math.max(mMaxY, y);
}
/**
* Returns the series title.
*
* @return the series title
*/
public String getTitle() {
return mTitle;
}
/**
* Sets the series title.
*
* @param title the series title
*/
public void setTitle(String title) {
mTitle = title;
}
/**
* Adds a new value to the series.
*
* @param x the value for the X axis
* @param y the value for the Y axis
*/
public synchronized void add(double x, double y) {
mXY.put(x, y);
updateRange(x, y);
}
/**
* Removes an existing value from the series.
*
* @param index the index in the series of the value to remove
*/
public synchronized void remove(int index) {
XYEntry<Double, Double> removedEntry = mXY.removeByIndex(index);
double removedX = removedEntry.getKey();
double removedY = removedEntry.getValue();
if (removedX == mMinX || removedX == mMaxX || removedY == mMinY || removedY == mMaxY) {
initRange();
}
}
/**
* Removes all the existing values from the series.
*/
public synchronized void clear() {
mXY.clear();
initRange();
}
/**
* Returns the X axis value at the specified index.
*
* @param index the index
* @return the X value
*/
public synchronized double getX(int index) {
return mXY.getXByIndex(index);
}
/**
* Returns the Y axis value at the specified index.
*
* @param index the index
* @return the Y value
*/
public synchronized double getY(int index) {
return mXY.getYByIndex(index);
}
/**
* Returns submap of x and y values according to the given start and end
*
* @param start start x value
* @param stop stop x value
* @return a submap of x and y values
*/
public synchronized SortedMap<Double, Double> getRange(double start, double stop,
int beforeAfterPoints) {
// we need to add one point before the start and one point after the end (if
// there are any)
// to ensure that line doesn't end before the end of the screen
// this would be simply: start = mXY.lowerKey(start) but NavigableMap is
// available since API 9
SortedMap<Double, Double> headMap = mXY.headMap(start);
if (!headMap.isEmpty()) {
start = headMap.lastKey();
}
// this would be simply: end = mXY.higherKey(end) but NavigableMap is
// available since API 9
// so we have to do this hack in order to support older versions
SortedMap<Double, Double> tailMap = mXY.tailMap(stop);
if (!tailMap.isEmpty()) {
Iterator<Double> tailIterator = tailMap.keySet().iterator();
Double next = tailIterator.next();
if (tailIterator.hasNext()) {
stop = tailIterator.next();
} else {
stop += next;
}
}
- return mXY.subMap(start, stop);
+ return new TreeMap<Double, Double>(mXY.subMap(start, stop));
}
public int getIndexForKey(double key) {
return mXY.getIndexForKey(key);
}
/**
* Returns the series item count.
*
* @return the series item count
*/
public synchronized int getItemCount() {
return mXY.size();
}
/**
* Returns the minimum value on the X axis.
*
* @return the X axis minimum value
*/
public double getMinX() {
return mMinX;
}
/**
* Returns the minimum value on the Y axis.
*
* @return the Y axis minimum value
*/
public double getMinY() {
return mMinY;
}
/**
* Returns the maximum value on the X axis.
*
* @return the X axis maximum value
*/
public double getMaxX() {
return mMaxX;
}
/**
* Returns the maximum value on the Y axis.
*
* @return the Y axis maximum value
*/
public double getMaxY() {
return mMaxY;
}
}
diff --git a/achartengine/src/org/achartengine/tools/Zoom.java b/achartengine/src/org/achartengine/tools/Zoom.java
index f9bcdea..f2e770d 100644
--- a/achartengine/src/org/achartengine/tools/Zoom.java
+++ b/achartengine/src/org/achartengine/tools/Zoom.java
@@ -1,185 +1,182 @@
/**
* Copyright (C) 2009 - 2012 SC 4ViewSoft SRL
*
* 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.achartengine.tools;
import java.util.ArrayList;
import java.util.List;
import org.achartengine.chart.AbstractChart;
import org.achartengine.chart.RoundChart;
import org.achartengine.chart.XYChart;
import org.achartengine.renderer.DefaultRenderer;
/**
* The zoom tool.
*/
public class Zoom extends AbstractTool {
/** A flag to be used to know if this is a zoom in or out. */
private boolean mZoomIn;
/** The zoom rate. */
private float mZoomRate;
/** The zoom listeners. */
private List<ZoomListener> mZoomListeners = new ArrayList<ZoomListener>();
/** Zoom limits reached on the X axis. */
private boolean limitsReachedX = false;
/** Zoom limits reached on the Y axis. */
private boolean limitsReachedY = false;
/** Zoom on X axis and Y axis */
public static final int ZOOM_AXIS_XY = 0;
/** Zoom on X axis independently */
public static final int ZOOM_AXIS_X = 1;
/** Zoom on Y axis independently */
public static final int ZOOM_AXIS_Y = 2;
/**
* Builds the zoom tool.
*
* @param chart the chart
* @param in zoom in or out
* @param rate the zoom rate
*/
public Zoom(AbstractChart chart, boolean in, float rate) {
super(chart);
mZoomIn = in;
setZoomRate(rate);
}
/**
* Sets the zoom rate.
*
* @param rate
*/
public void setZoomRate(float rate) {
mZoomRate = rate;
}
/**
* Apply the zoom.
*/
public void apply(int zoom_axis) {
-// long t = System.currentTimeMillis();
if (mChart instanceof XYChart) {
int scales = mRenderer.getScalesCount();
for (int i = 0; i < scales; i++) {
double[] range = getRange(i);
checkRange(range, i);
double[] limits = mRenderer.getZoomLimits();
double centerX = (range[0] + range[1]) / 2;
double centerY = (range[2] + range[3]) / 2;
double newWidth = range[1] - range[0];
double newHeight = range[3] - range[2];
double newXMin = centerX - newWidth / 2;
double newXMax = centerX + newWidth / 2;
double newYMin = centerY - newHeight / 2;
double newYMax = centerY + newHeight / 2;
// if already reached last zoom, then it will always set to reached
if (i == 0) {
limitsReachedX = limits != null && (newXMin <= limits[0] || newXMax >= limits[1]);
limitsReachedY = limits != null && (newYMin <= limits[2] || newYMax >= limits[3]);
}
if (mZoomIn) {
if (mRenderer.isZoomXEnabled() && (zoom_axis == ZOOM_AXIS_X || zoom_axis == ZOOM_AXIS_XY)) {
if (limitsReachedX && mZoomRate < 1) {
// ignore pinch zoom out once reached X limit
} else {
newWidth /= mZoomRate;
}
}
if (mRenderer.isZoomYEnabled() && (zoom_axis == ZOOM_AXIS_Y || zoom_axis == ZOOM_AXIS_XY)) {
if (limitsReachedY && mZoomRate < 1) {
} else {
newHeight /= mZoomRate;
}
}
} else {
if (mRenderer.isZoomXEnabled() && !limitsReachedX
&& (zoom_axis == ZOOM_AXIS_X || zoom_axis == ZOOM_AXIS_XY)) {
newWidth *= mZoomRate;
}
if (mRenderer.isZoomYEnabled() && !limitsReachedY
&& (zoom_axis == ZOOM_AXIS_Y || zoom_axis == ZOOM_AXIS_XY)) {
newHeight *= mZoomRate;
}
}
if (mRenderer.isZoomXEnabled() && (zoom_axis == ZOOM_AXIS_X || zoom_axis == ZOOM_AXIS_XY)) {
newXMin = centerX - newWidth / 2;
newXMax = centerX + newWidth / 2;
setXRange(newXMin, newXMax, i);
}
if (mRenderer.isZoomYEnabled() && (zoom_axis == ZOOM_AXIS_Y || zoom_axis == ZOOM_AXIS_XY)) {
newYMin = centerY - newHeight / 2;
newYMax = centerY + newHeight / 2;
setYRange(newYMin, newYMax, i);
}
}
} else {
DefaultRenderer renderer = ((RoundChart) mChart).getRenderer();
if (mZoomIn) {
renderer.setScale(renderer.getScale() * mZoomRate);
} else {
renderer.setScale(renderer.getScale() / mZoomRate);
}
}
-// System.out.println("t0=" + (System.currentTimeMillis() - t));
notifyZoomListeners(new ZoomEvent(mZoomIn, mZoomRate));
-// System.out.println("t =" + (System.currentTimeMillis() - t));
}
/**
* Notify the zoom listeners about a zoom change.
*
* @param e the zoom event
*/
private synchronized void notifyZoomListeners(ZoomEvent e) {
for (ZoomListener listener : mZoomListeners) {
listener.zoomApplied(e);
}
}
/**
* Notify the zoom listeners about a zoom reset.
*/
public synchronized void notifyZoomResetListeners() {
for (ZoomListener listener : mZoomListeners) {
listener.zoomReset();
}
}
/**
* Adds a new zoom listener.
*
* @param listener zoom listener
*/
public synchronized void addZoomListener(ZoomListener listener) {
mZoomListeners.add(listener);
}
/**
* Removes a zoom listener.
*
* @param listener zoom listener
*/
public synchronized void removeZoomListener(ZoomListener listener) {
mZoomListeners.add(listener);
}
}
| false | false | null | null |
diff --git a/src/gui/GUI_KitRobot.java b/src/gui/GUI_KitRobot.java
index 113a73d..c909c06 100644
--- a/src/gui/GUI_KitRobot.java
+++ b/src/gui/GUI_KitRobot.java
@@ -1,412 +1,425 @@
package gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.*;
import javax.swing.*;
import agents.Kit;
import agents.KitRobotAgent;
public class GUI_KitRobot implements GUI_Component {
boolean kitHeld;
GUI_Kit guikit;
GUI_KitStand stand;
KitRobotAgent kitRobot;
GUI_Conveyor conveyor;
ImageIcon robotBody;
ImageIcon robotHands;
boolean move;
boolean fullyExtended;
boolean goToOne = false,goToTwo = false,moveToOne = false,moveToTwo = false,moveToInspection = false,goToConveyor = false, finalMove = false;
int x,y,robotX,moveToY,moveToX,x2,y2,x1,y1;
public GUI_KitRobot(GUI_Conveyor con, GUI_KitStand kstand )//default constructor
{
guikit = null;
conveyor = con;
stand = kstand;
kitHeld = false;
robotBody = new ImageIcon("gfx/kitRobot.png");
robotHands = new ImageIcon("gfx/robotarm.png");
x = 30;
robotX = x+1;
y = 30;
moveToY = 0;
moveToX = 0;
move = false;
fullyExtended = false;
}
public GUI_KitRobot(String body, String hands, int x1, int y1)//constructor
{
guikit = null;
kitHeld = false;
robotBody = new ImageIcon(body);
robotHands = new ImageIcon(hands);
x = x1;
robotX = x+20;
y = y1;
moveToY = 0;
moveToX = 0;
move =false;
fullyExtended = false;
}
public void pickupKit(GUI_Kit k)//picks up kit passed through to it
{
if(!kitHeld)
{
kitHeld = true;
guikit = k;
guikit.setX(robotX);
guikit.setY(y);
}
}
public GUI_Kit placeKit()//places kit down
{
GUI_Kit new_kit = null;
if(kitHeld)
{
if(guikit != null)
{
new_kit = guikit;
guikit.x+= 39;
guikit = null;
kitHeld = false;
}
}
if(new_kit != null)
return new_kit;
else return null;
}
+
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public int getRobotX()
{
return robotX;
}
public void moveToStation(int x1,int y1)//moves to a given station
{
move = true;
if(x1 > 0)
x1 = x+40;
moveToY = y1;
moveToX = x1;
}
public boolean arrivedAtStation()//notifies that robot has arrived at station
{
return true;
}
public void DoPlaceOnKitStand(Kit kit, KitRobotAgent robotAgent)
{
Kit k = kit;
kitRobot = robotAgent;
if(conveyor.checkKit().getKitId() == k.getKitId())
{
int x1 = conveyor.checkKit().x;
int y1 = conveyor.checkKit().y;
moveToStation(x1,y1);
pickupKit(conveyor.robotRemoveKit());
if(stand.positionOpen(2))
{
goToTwo = true;
x2 = stand.getX(2);
y2 = stand.getY(2);
moveToStation(x2,y2);
if(y == y2)
{
- //stand.addkit(placeKit(), 2);
+ //stand.addkit(placeKit(), 2);
+ kitHeld = false;
+ guikit = null;
kitRobot.conveyor2StandLockRelease();
}
}
else if (stand.positionOpen(1))
{
goToTwo = true;
x2 = stand.getX(1);
y2 = stand.getY(1);
moveToStation(x2,y2);
if(y == y2)
{
- //stand.addkit(placeKit(), 1);
+ //stand.addkit(placeKit(), 1);
+ kitHeld = false;
+ guikit = null;
kitRobot.conveyor2StandLockRelease();
}
}
}
// Grab empty kit from conveyer
// Place on kit stand
//check of 2 is empty
//if empty place there
//else check if 1 is empty
//if so place kit
//if not do nothing
}
public void DoMoveFromKitStandToInspection(Kit kit, KitRobotAgent agent)
{
Kit k = kit;
kitRobot = agent;
if(stand.positionOpen(0))
{
if(stand.checkKit(2).kit== k)
{
moveToTwo = true;
x1 = stand.getX(2);
y1 = stand.getY(2);
moveToStation(x1,y1);
x2 = stand.getX(0);
y2 = stand.getY(0);
}
else if(kit.getKitId() == stand.checkKit(1).getKitId())
{
moveToOne = true;
x1 = stand.getX(1);
y1 = stand.getY(1);
moveToStation(x1,y1);
x2 = stand.getX(0);
y2 = stand.getY(0);
}
}
//check if inspection stand is empty
//check kit id from kit passed in
//check if stand 2 kit id matches passed kit id
//if so, grab and move to inspection
//if not check if stand 1 kit id matches passed kit id
//if so, grab and move to inspection
//if not error
}
public void DoMoveFromInspectionToConveyor(Kit kit)
{
Kit k = kit;
if(k.getKitId() == stand.checkKit(0).getKitId())
{
//goToConveyor = true;
x1 = stand.getX(0);
y1 = stand.getY(0);
moveToStation(x1,y1);
goToConveyor = true;
x2 = 30;
y2 = 70;
//conveyor.robotAddKit(placeKit());
+ kitHeld = false;
+ guikit = null;
}
//check if inspection kit id matches passed kit id
//if so move to conveyor
//place in conveyor
//else errorrrrrrrrr
}
public void paintComponent(JPanel j, Graphics2D g)
{
robotBody.paintIcon(j, g, x, y);
robotHands.paintIcon(j, g, robotX, y);
if(guikit!=null)
guikit.paintComponent(j,g);
}
public void updateGraphics()
{
if(guikit!=null)
guikit.updateGraphics();
if(move){
if(robotX == moveToX)
{
fullyExtended = true;
move = false;
}
if(y < moveToY)
{
y+=1;
}
else if(y > moveToY)
{
y-=1;
}
else if(x < moveToX)
{
robotX+=1;
}
/* else if(x > moveToX)
{
robotX-=1;
System.out.println("moved");
}*/
else
{
move = false;
}
}
if(fullyExtended)
{
if(robotX > (x+1))
{
robotX-=1;
}
else
{
fullyExtended = false;
}
}
if(kitHeld)
{
guikit.setX(robotX);
guikit.setY(y);
}
if(goToTwo)
{
if(y >= y2)
{
if(fullyExtended)
{
- //stand.addkit(placeKit(), 2);
+ //stand.addkit(placeKit(), 2);
+ kitHeld = false;
+ guikit = null;
kitRobot.conveyor2StandLockRelease();
goToTwo = false;
}
}
}
else if (goToOne)
{
if(y >= y2)
{
if(fullyExtended)
{
- //stand.addkit(placeKit(), 1);
+ //stand.addkit(placeKit(), 1);
+ kitHeld = false;
+ guikit = null;
kitRobot.conveyor2StandLockRelease();
goToOne = false;
}
}
}
if(moveToTwo)
{
if(y == y1)
{
if(fullyExtended)
{
pickupKit(stand.checkKit(2));
moveToTwo = false;
moveToInspection = true;
}
}
}
else if(moveToOne)
{
if(y == y1)
{
if(fullyExtended)
{
pickupKit(stand.checkKit(1));
moveToOne = false;
moveToInspection = true;
}
}
}
if(moveToInspection)
{
moveToStation(x2,y2);
if(y == y2)
{
if(fullyExtended)
{
kitRobot.inspectLockRelease();
//stand.addkit(placeKit(), 0);
+ kitHeld = false;
+ guikit = null;
moveToInspection = false;
}
}
}
if(goToConveyor)
{
if(y == y1)
{
if(fullyExtended)
{
pickupKit(stand.checkKit(0));
goToConveyor = false;
finalMove = true;
}
}
}
if(finalMove)
{
moveToStation(x2,y2);
if(y == y2)
{
if(fullyExtended)
{
conveyor.DoGetKitOut(placeKit().kit);
finalMove = false;
}
}
}
}
}
| false | false | null | null |
diff --git a/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3Resource.java b/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3Resource.java
index 2720bd5ca..215875b07 100755
--- a/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3Resource.java
+++ b/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3Resource.java
@@ -1,679 +1,680 @@
package railo.commons.io.res.type.s3;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import org.xml.sax.SAXException;
import railo.commons.io.res.Resource;
import railo.commons.io.res.ResourceProvider;
import railo.commons.io.res.util.ResourceSupport;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.StringUtil;
import railo.commons.net.http.HTTPEngine;
+import railo.commons.net.http.httpclient3.HTTPEngine3Impl;
import railo.loader.util.Util;
import railo.runtime.exp.PageRuntimeException;
import railo.runtime.op.Caster;
import railo.runtime.type.Array;
import railo.runtime.type.List;
public final class S3Resource extends ResourceSupport {
private static final long serialVersionUID = 2265457088552587701L;
private static final long FUTURE=50000000000000L;
private static final S3Info UNDEFINED=new Dummy("undefined",0,0,false,false,false);
private static final S3Info ROOT=new Dummy("root",0,0,true,false,true);
private static final S3Info LOCKED = new Dummy("locked",0,0,true,false,false);
private static final S3Info UNDEFINED_WITH_CHILDREN = new Dummy("undefined with children 1",0,0,true,false,true);
private static final S3Info UNDEFINED_WITH_CHILDREN2 = new Dummy("undefined with children 2",0,0,true,false,true);
private final S3ResourceProvider provider;
private final String bucketName;
private String objectName;
private final S3 s3;
long infoLastAccess=0;
private int storage=S3.STORAGE_UNKNOW;
private int acl=S3.ACL_PUBLIC_READ;
private boolean newPattern;
private S3Resource(S3 s3,int storage, S3ResourceProvider provider, String buckedName,String objectName, boolean newPattern) {
this.s3=s3;
this.provider=provider;
this.bucketName=buckedName;
this.objectName=objectName;
this.storage=storage;
this.newPattern=newPattern;
}
S3Resource(S3 s3,int storage, S3ResourceProvider provider, String path, boolean newPattern) {
this.s3=s3;
this.provider=provider;
this.newPattern=newPattern;
if(path.equals("/") || Util.isEmpty(path,true)) {
this.bucketName=null;
this.objectName="";
}
else {
path=ResourceUtil.translatePath(path, true, false);
String[] arr = toStringArray( List.listToArrayRemoveEmpty(path,"/"));
bucketName=arr[0];
for(int i=1;i<arr.length;i++) {
if(Util.isEmpty(objectName))objectName=arr[i];
else objectName+="/"+arr[i];
}
if(objectName==null)objectName="";
}
this.storage=storage;
}
public static String[] toStringArray(Array array) {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,""),"");
}
return arr;
}
public void createDirectory(boolean createParentWhenNotExists) throws IOException {
ResourceUtil.checkCreateDirectoryOK(this, createParentWhenNotExists);
try {
provider.lock(this);
if(isBucket()) {
s3.putBuckets(bucketName, acl,storage);
}
- else s3.put(bucketName, objectName+"/", acl, HTTPEngine.getEmptyEntity("application"));
+ else s3.put(bucketName, objectName+"/", acl, HTTPEngine3Impl.getEmptyEntity("application"));
}
catch (IOException ioe) {
throw ioe;
}
catch (Exception e) {
e.printStackTrace();
throw new IOException(e.getMessage());
}
finally {
provider.unlock(this);
}
s3.releaseCache(getInnerPath());
}
public void createFile(boolean createParentWhenNotExists) throws IOException {
ResourceUtil.checkCreateFileOK(this, createParentWhenNotExists);
if(isBucket()) throw new IOException("can't create file ["+getPath()+"], on this level (Bucket Level) you can only create directories");
try {
provider.lock(this);
- s3.put(bucketName, objectName, acl, HTTPEngine.getEmptyEntity("application"));
+ s3.put(bucketName, objectName, acl, HTTPEngine3Impl.getEmptyEntity("application"));
}
catch (Exception e) {
throw new IOException(e.getMessage());
}
finally {
provider.unlock(this);
}
s3.releaseCache(getInnerPath());
}
public boolean exists() {
return getInfo()
.exists();
}
public InputStream getInputStream() throws IOException {
ResourceUtil.checkGetInputStreamOK(this);
provider.read(this);
try {
return Util.toBufferedInputStream(s3.getInputStream(bucketName, objectName));
}
catch (Exception e) {
throw new IOException(e.getMessage());
}
}
public int getMode() {
return 777;
}
/**
* @see res.Resource#getFullName()
*/
public String getName() {
if(isRoot()) return "";
if(isBucket()) return bucketName;
return objectName.substring(objectName.lastIndexOf('/')+1);
}
/**
* @see res.Resource#isAbsolute()
*/
public boolean isAbsolute() {
return true;
}
/**
* @see railo.commons.io.res.Resource#getPath()
*/
public String getPath() {
return getPrefix().concat(getInnerPath());
}
private String getPrefix() {
String aki=s3.getAccessKeyId();
String sak=s3.getSecretAccessKey();
StringBuilder sb=new StringBuilder(provider.getScheme()).append("://");
if(!StringUtil.isEmpty(aki)){
sb.append(aki);
if(!StringUtil.isEmpty(sak)){
sb.append(":").append(sak);
if(storage!=S3.STORAGE_UNKNOW){
sb.append(":").append(S3.toStringStorage(storage,"us"));
}
}
sb.append("@");
}
if(!newPattern)
sb.append(s3.getHost());
return sb.toString();
}
/**
* @see res.Resource#getParent()
*/
public String getParent() {
if(isRoot()) return null;
return getPrefix().concat(getInnerParent());
}
private String getInnerPath() {
if(isRoot()) return "/";
return ResourceUtil.translatePath(bucketName+"/"+objectName, true, false);
}
private String getInnerParent() {
if(isRoot()) return null;
if(Util.isEmpty(objectName)) return "/";
if(objectName.indexOf('/')==-1) return "/"+bucketName;
String tmp=objectName.substring(0,objectName.lastIndexOf('/'));
return ResourceUtil.translatePath(bucketName+"/"+tmp, true, false);
}
/**
* @see railo.commons.io.res.Resource#getParentResource()
*/
public Resource getParentResource() {
if(isRoot()) return null;
return new S3Resource(s3,isBucket()?S3.STORAGE_UNKNOW:storage,provider,getInnerParent(),newPattern);// MUST direkter machen
}
private boolean isRoot() {
return bucketName==null;
}
private boolean isBucket() {
return bucketName!=null && Util.isEmpty(objectName);
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return getPath();
}
public OutputStream getOutputStream(boolean append) throws IOException {
ResourceUtil.checkGetOutputStreamOK(this);
//provider.lock(this);
try {
byte[] barr = null;
if(append){
InputStream is=null;
OutputStream os=null;
try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
os=baos;
Util.copy(is=getInputStream(), baos);
barr=baos.toByteArray();
}
catch (Exception e) {
throw new PageRuntimeException(Caster.toPageException(e));
}
finally{
Util.closeEL(is);
Util.closeEL(os);
}
}
S3ResourceOutputStream os = new S3ResourceOutputStream(s3,bucketName,objectName,acl);
if(append && !(barr==null || barr.length==0))
Util.copy(new ByteArrayInputStream(barr),os);
return os;
}
catch(IOException e) {
throw e;
}
catch (Exception e) {
throw new PageRuntimeException(Caster.toPageException(e));
}
finally {
s3.releaseCache(getInnerPath());
}
}
/**
* @see railo.commons.io.res.Resource#getRealResource(java.lang.String)
*/
public Resource getRealResource(String realpath) {
realpath=ResourceUtil.merge(getInnerPath(), realpath);
if(realpath.startsWith("../"))return null;
return new S3Resource(s3,S3.STORAGE_UNKNOW,provider,realpath,newPattern);
}
/**
* @see railo.commons.io.res.Resource#getResourceProvider()
*/
public ResourceProvider getResourceProvider() {
return provider;
}
/**
* @see railo.commons.io.res.Resource#isDirectory()
*/
public boolean isDirectory() {
return getInfo().isDirectory();
}
/**
* @see railo.commons.io.res.Resource#isFile()
*/
public boolean isFile() {
return getInfo().isFile();
}
public boolean isReadable() {
return exists();
}
public boolean isWriteable() {
return exists();
}
/**
* @see railo.commons.io.res.Resource#lastModified()
*/
public long lastModified() {
return getInfo().getLastModified();
}
private S3Info getInfo() {
S3Info info = s3.getInfo(getInnerPath());
if(info==null) {// || System.currentTimeMillis()>infoLastAccess
if(isRoot()) {
try {
s3.listBuckets();
info=ROOT;
}
catch (Exception e) {
info=UNDEFINED;
}
infoLastAccess=FUTURE;
}
else {
try {
provider.read(this);
} catch (IOException e) {
return LOCKED;
}
try {
if(isBucket()) {
Bucket[] buckets = s3.listBuckets();
String name=getName();
for(int i=0;i<buckets.length;i++) {
if(buckets[i].getName().equals(name)) {
info=buckets[i];
infoLastAccess=System.currentTimeMillis()+provider.getCache();
break;
}
}
}
else {
try {
// first check if the bucket exists
// TODO not happy about this step
Bucket[] buckets = s3.listBuckets();
boolean bucketExists=false;
for(int i=0;i<buckets.length;i++) {
if(buckets[i].getName().equals(bucketName)) {
bucketExists=true;
break;
}
}
if(bucketExists){
String path = objectName;
Content[] contents = s3.listContents(bucketName, path);
if(contents.length>0) {
boolean has=false;
for(int i=0;i<contents.length;i++) {
if(ResourceUtil.translatePath(contents[i].getKey(),false,false).equals(path)) {
has=true;
info=contents[i];
infoLastAccess=System.currentTimeMillis()+provider.getCache();
break;
}
}
if(!has){
for(int i=0;i<contents.length;i++) {
if(ResourceUtil.translatePath(contents[i].getKey(),false,false).startsWith(path)) {
info=UNDEFINED_WITH_CHILDREN;
infoLastAccess=System.currentTimeMillis()+provider.getCache();
break;
}
}
}
}
}
}
catch(SAXException e) {
}
}
if(info==null){
info=UNDEFINED;
infoLastAccess=System.currentTimeMillis()+provider.getCache();
}
}
catch(Exception t) {
return UNDEFINED;
}
}
s3.setInfo(getInnerPath(), info);
}
return info;
}
/**
* @see railo.commons.io.res.Resource#length()
*/
public long length() {
return getInfo().getSize();
}
public Resource[] listResources() {
S3Resource[] children=null;
try {
if(isRoot()) {
Bucket[] buckets = s3.listBuckets();
children=new S3Resource[buckets.length];
for(int i=0;i<children.length;i++) {
children[i]=new S3Resource(s3,storage,provider,buckets[i].getName(),"",newPattern);
s3.setInfo(children[i].getInnerPath(),buckets[i]);
}
}
else if(isDirectory()){
Content[] contents = s3.listContents(bucketName, isBucket()?null:objectName+"/");
ArrayList<S3Resource> tmp = new ArrayList<S3Resource>();
String key,name,path;
int index;
Set<String> names=new LinkedHashSet<String>();
Set<String> pathes=new LinkedHashSet<String>();
S3Resource r;
boolean isb=isBucket();
for(int i=0;i<contents.length;i++) {
key=ResourceUtil.translatePath(contents[i].getKey(), false, false);
if(!isb && !key.startsWith(objectName+"/")) continue;
if(Util.isEmpty(key)) continue;
index=key.indexOf('/',Util.length(objectName)+1);
if(index==-1) {
name=key;
path=null;
}
else {
name=key.substring(index+1);
path=key.substring(0,index);
}
//print.out("1:"+key);
//print.out("path:"+path);
//print.out("name:"+name);
if(path==null){
names.add(name);
tmp.add(r=new S3Resource(s3,storage,provider,contents[i].getBucketName(),key,newPattern));
s3.setInfo(r.getInnerPath(),contents[i]);
}
else {
pathes.add(path);
}
}
Iterator<String> it = pathes.iterator();
while(it.hasNext()) {
path=it.next();
if(names.contains(path)) continue;
tmp.add(r=new S3Resource(s3,storage,provider,bucketName,path,newPattern));
s3.setInfo(r.getInnerPath(),UNDEFINED_WITH_CHILDREN2);
}
//if(tmp.size()==0 && !isDirectory()) return null;
children=tmp.toArray(new S3Resource[tmp.size()]);
}
}
catch(Exception t) {
t.printStackTrace();
return null;
}
return children;
}
/**
* @see railo.commons.io.res.Resource#remove(boolean)
*/
public void remove(boolean force) throws IOException {
if(isRoot()) throw new IOException("can not remove root of S3 Service");
ResourceUtil.checkRemoveOK(this);
boolean isd=isDirectory();
if(isd) {
Resource[] children = listResources();
if(children.length>0) {
if(force) {
for(int i=0;i<children.length;i++) {
children[i].remove(force);
}
}
else {
throw new IOException("can not remove directory ["+this+"], directory is not empty");
}
}
}
// delete res itself
provider.lock(this);
try {
s3.delete(bucketName, isd?objectName+"/":objectName);
}
catch (Exception e) {
throw new IOException(e.getMessage());
}
finally {
s3.releaseCache(getInnerPath());
provider.unlock(this);
}
}
public boolean setLastModified(long time) {
s3.releaseCache(getInnerPath());
// TODO Auto-generated method stub
return false;
}
public void setMode(int mode) throws IOException {
s3.releaseCache(getInnerPath());
// TODO Auto-generated method stub
}
public boolean setReadable(boolean readable) {
s3.releaseCache(getInnerPath());
// TODO Auto-generated method stub
return false;
}
public boolean setWritable(boolean writable) {
s3.releaseCache(getInnerPath());
// TODO Auto-generated method stub
return false;
}
public AccessControlPolicy getAccessControlPolicy() {
String p = getInnerPath();
try {
AccessControlPolicy acp = s3.getACP(p);
if(acp==null){
acp=s3.getAccessControlPolicy(bucketName, getObjectName());
s3.setACP(p, acp);
}
return acp;
}
catch (Exception e) {
throw new PageRuntimeException(Caster.toPageException(e));
}
}
public void setAccessControlPolicy(AccessControlPolicy acp) {
try {
s3.setAccessControlPolicy(bucketName, getObjectName(),acp);
}
catch (Exception e) {
throw new PageRuntimeException(Caster.toPageException(e));
}
finally {
s3.releaseCache(getInnerPath());
}
}
private String getObjectName() {
if(!StringUtil.isEmpty(objectName) && isDirectory()) {
return objectName+"/";
}
return objectName;
}
public void setACL(int acl) {
this.acl=acl;
}
public void setStorage(int storage) {
this.storage=storage;
}
}
class Dummy implements S3Info {
private long lastModified;
private long size;
private boolean exists;
private boolean file;
private boolean directory;
private String label;
public Dummy(String label,long lastModified, long size, boolean exists,boolean file, boolean directory) {
this.label = label;
this.lastModified = lastModified;
this.size = size;
this.exists = exists;
this.file = file;
this.directory = directory;
}
/**
* @see railo.commons.io.res.type.s3.S3Info#getLastModified()
*/
public long getLastModified() {
return lastModified;
}
/**
* @see railo.commons.io.res.type.s3.S3Info#getSize()
*/
public long getSize() {
return size;
}
/**
*
* @see java.lang.Object#toString()
*/
public String toString() {
return "Dummy:"+getLabel();
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @see railo.commons.io.res.type.s3.S3Info#exists()
*/
public boolean exists() {
return exists;
}
/**
* @see railo.commons.io.res.type.s3.S3Info#isDirectory()
*/
public boolean isDirectory() {
return directory;
}
/**
* @see railo.commons.io.res.type.s3.S3Info#isFile()
*/
public boolean isFile() {
return file;
}
}
\ No newline at end of file
diff --git a/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3ResourceOutputStream.java b/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3ResourceOutputStream.java
index bd24fcc0f..59901917e 100755
--- a/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3ResourceOutputStream.java
+++ b/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3ResourceOutputStream.java
@@ -1,85 +1,87 @@
package railo.commons.io.res.type.s3;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import railo.commons.io.TemporaryStream;
import railo.commons.lang.ExceptionUtil;
import railo.commons.lang.StringUtil;
+import railo.commons.net.http.Entity;
import railo.commons.net.http.HTTPEngine;
+import railo.commons.net.http.httpclient3.HTTPEngine3Impl;
public final class S3ResourceOutputStream extends OutputStream {
private final S3 s3;
private final String contentType="application";
private final String bucketName;
private final String objectName;
private final int acl;
private TemporaryStream ts;
public S3ResourceOutputStream(S3 s3,String bucketName,String objectName,int acl) {
this.s3=s3;
this.bucketName=bucketName;
this.objectName=objectName;
this.acl=acl;
ts = new TemporaryStream();
}
/**
*
* @see java.io.OutputStream#close()
*/
public void close() throws IOException {
ts.close();
//InputStream is = ts.getInputStream();
try {
- s3.put(bucketName, objectName, acl, HTTPEngine.getTemporaryStreamEntity(ts,contentType));
+ s3.put(bucketName, objectName, acl, HTTPEngine3Impl.getTemporaryStreamEntity(ts,contentType));
}
catch (SocketException se) {
String msg = StringUtil.emptyIfNull(se.getMessage());
if(StringUtil.indexOfIgnoreCase(msg, "Socket closed")==-1)
throw se;
}
catch (Exception e) {
throw ExceptionUtil.toIOException(e);
}
}
/**
*
* @see java.io.OutputStream#flush()
*/
public void flush() throws IOException {
ts.flush();
}
/**
*
* @see java.io.OutputStream#write(byte[], int, int)
*/
public void write(byte[] b, int off, int len) throws IOException {
ts.write(b, off, len);
}
/**
*
* @see java.io.OutputStream#write(byte[])
*/
public void write(byte[] b) throws IOException {
ts.write(b);
}
/**
*
* @see java.io.OutputStream#write(int)
*/
public void write(int b) throws IOException {
ts.write(b);
}
}
| false | false | null | null |
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/rest/VerifyDeploymentIdEventsAPITest.java b/src/main/java/org/cloudifysource/quality/iTests/test/rest/VerifyDeploymentIdEventsAPITest.java
index 030eba19..afbfae5e 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/rest/VerifyDeploymentIdEventsAPITest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/rest/VerifyDeploymentIdEventsAPITest.java
@@ -1,73 +1,76 @@
/* Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*******************************************************************************/
package org.cloudifysource.quality.iTests.test.rest;
import java.io.IOException;
+import java.util.List;
import junit.framework.Assert;
import org.cloudifysource.dsl.internal.CloudifyMessageKeys;
import org.cloudifysource.dsl.internal.DSLException;
import org.cloudifysource.dsl.internal.packaging.PackagingException;
+import org.cloudifysource.dsl.rest.response.ServiceDescription;
import org.cloudifysource.quality.iTests.test.AbstractTestSupport;
import org.cloudifysource.quality.iTests.test.cli.cloudify.AbstractLocalCloudTest;
import org.cloudifysource.quality.iTests.test.cli.cloudify.NewRestTestUtils;
import org.cloudifysource.restclient.RestClient;
import org.cloudifysource.restclient.exceptions.RestClientException;
import org.testng.annotations.Test;
/**
* Tests the verification of deploymentId in events API.
*
* If a wrong (not exist) deployment id is passed to one of the events API methods,
* a ResourceNotFoundException should be thrown.
*
* @author yael
*
*/
public class VerifyDeploymentIdEventsAPITest extends AbstractLocalCloudTest {
private static final String NOT_EXIST_DEPLOYMENT_ID = "not-exist-deployment-id";
@Test(timeOut = AbstractTestSupport.DEFAULT_TEST_TIMEOUT * 2, enabled = true)
public void getLastEventsTest(){
RestClient restClient = NewRestTestUtils.createAndConnect(restUrl);
try {
restClient.getLastEvent(NOT_EXIST_DEPLOYMENT_ID);
Assert.fail("RestClientException was expected.");
} catch (RestClientException e) {
Assert.assertEquals(CloudifyMessageKeys.MISSING_RESOURCE.getName(), e.getMessageCode());
}
}
@Test(timeOut = AbstractTestSupport.DEFAULT_TEST_TIMEOUT * 2, enabled = true)
public void getDeploymentEventsTest(){
RestClient restClient = NewRestTestUtils.createAndConnect(restUrl);
try {
restClient.getDeploymentEvents(NOT_EXIST_DEPLOYMENT_ID, 0, -1);
Assert.fail("RestClientException was expected.");
} catch (RestClientException e) {
Assert.assertEquals(CloudifyMessageKeys.MISSING_RESOURCE.getName(), e.getMessageCode());
}
}
@Test(timeOut = AbstractTestSupport.DEFAULT_TEST_TIMEOUT * 2, enabled = true)
public void getServiceDescriptionsTest() throws IOException, DSLException, PackagingException{
RestClient restClient = NewRestTestUtils.createAndConnect(restUrl);
try {
- restClient.getServiceDescriptions(NOT_EXIST_DEPLOYMENT_ID);
- Assert.fail("RestClientException was expected.");
+ List<ServiceDescription> serviceDescriptions =
+ restClient.getServiceDescriptions(NOT_EXIST_DEPLOYMENT_ID);
+ Assert.fail("RestClientException was expected. but instead got " + serviceDescriptions);
} catch (RestClientException e) {
Assert.assertEquals(CloudifyMessageKeys.MISSING_RESOURCE.getName(), e.getMessageCode());
}
}
}
| false | false | null | null |
diff --git a/src/com/android/gallery3d/app/PhotoPage.java b/src/com/android/gallery3d/app/PhotoPage.java
index b43cf2a70..506d1ca6f 100644
--- a/src/com/android/gallery3d/app/PhotoPage.java
+++ b/src/com/android/gallery3d/app/PhotoPage.java
@@ -1,1496 +1,1498 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.app;
import android.annotation.TargetApi;
import android.app.ActionBar.OnMenuVisibilityListener;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateBeamUrisCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.android.camera.CameraActivity;
import com.android.camera.ProxyLauncher;
import com.android.gallery3d.R;
import com.android.gallery3d.common.ApiHelper;
import com.android.gallery3d.data.ComboAlbum;
import com.android.gallery3d.data.DataManager;
import com.android.gallery3d.data.FilterDeleteSet;
import com.android.gallery3d.data.FilterSource;
import com.android.gallery3d.data.LocalImage;
import com.android.gallery3d.data.MediaDetails;
import com.android.gallery3d.data.MediaItem;
import com.android.gallery3d.data.MediaObject;
import com.android.gallery3d.data.MediaObject.PanoramaSupportCallback;
import com.android.gallery3d.data.MediaSet;
import com.android.gallery3d.data.MtpSource;
import com.android.gallery3d.data.Path;
import com.android.gallery3d.data.SecureAlbum;
import com.android.gallery3d.data.SecureSource;
import com.android.gallery3d.data.SnailAlbum;
import com.android.gallery3d.data.SnailItem;
import com.android.gallery3d.data.SnailSource;
import com.android.gallery3d.filtershow.FilterShowActivity;
import com.android.gallery3d.picasasource.PicasaSource;
import com.android.gallery3d.ui.DetailsHelper;
import com.android.gallery3d.ui.DetailsHelper.CloseListener;
import com.android.gallery3d.ui.DetailsHelper.DetailsSource;
import com.android.gallery3d.ui.GLView;
import com.android.gallery3d.ui.ImportCompleteListener;
import com.android.gallery3d.ui.MenuExecutor;
import com.android.gallery3d.ui.PhotoView;
import com.android.gallery3d.ui.SelectionManager;
import com.android.gallery3d.ui.SynchronizedHandler;
import com.android.gallery3d.util.GalleryUtils;
public class PhotoPage extends ActivityState implements
PhotoView.Listener, AppBridge.Server,
PhotoPageBottomControls.Delegate, GalleryActionBar.OnAlbumModeSelectedListener {
private static final String TAG = "PhotoPage";
private static final int MSG_HIDE_BARS = 1;
private static final int MSG_ON_FULL_SCREEN_CHANGED = 4;
private static final int MSG_UPDATE_ACTION_BAR = 5;
private static final int MSG_UNFREEZE_GLROOT = 6;
private static final int MSG_WANT_BARS = 7;
private static final int MSG_REFRESH_BOTTOM_CONTROLS = 8;
private static final int MSG_ON_CAMERA_CENTER = 9;
private static final int MSG_ON_PICTURE_CENTER = 10;
private static final int MSG_REFRESH_IMAGE = 11;
private static final int MSG_UPDATE_PHOTO_UI = 12;
private static final int MSG_UPDATE_PROGRESS = 13;
private static final int MSG_UPDATE_DEFERRED = 14;
private static final int MSG_UPDATE_SHARE_URI = 15;
private static final int MSG_UPDATE_PANORAMA_UI = 16;
private static final int HIDE_BARS_TIMEOUT = 3500;
private static final int UNFREEZE_GLROOT_TIMEOUT = 250;
private static final int REQUEST_SLIDESHOW = 1;
private static final int REQUEST_CROP = 2;
private static final int REQUEST_CROP_PICASA = 3;
private static final int REQUEST_EDIT = 4;
private static final int REQUEST_PLAY_VIDEO = 5;
private static final int REQUEST_TRIM = 6;
public static final String KEY_MEDIA_SET_PATH = "media-set-path";
public static final String KEY_MEDIA_ITEM_PATH = "media-item-path";
public static final String KEY_INDEX_HINT = "index-hint";
public static final String KEY_OPEN_ANIMATION_RECT = "open-animation-rect";
public static final String KEY_APP_BRIDGE = "app-bridge";
public static final String KEY_TREAT_BACK_AS_UP = "treat-back-as-up";
public static final String KEY_START_IN_FILMSTRIP = "start-in-filmstrip";
public static final String KEY_RETURN_INDEX_HINT = "return-index-hint";
public static final String KEY_SHOW_WHEN_LOCKED = "show_when_locked";
public static final String KEY_IN_CAMERA_ROLL = "in_camera_roll";
public static final String KEY_ALBUMPAGE_TRANSITION = "albumpage-transition";
public static final int MSG_ALBUMPAGE_NONE = 0;
public static final int MSG_ALBUMPAGE_STARTED = 1;
public static final int MSG_ALBUMPAGE_RESUMED = 2;
public static final int MSG_ALBUMPAGE_PICKED = 4;
public static final String ACTION_NEXTGEN_EDIT = "action_nextgen_edit";
private GalleryApp mApplication;
private SelectionManager mSelectionManager;
private PhotoView mPhotoView;
private PhotoPage.Model mModel;
private DetailsHelper mDetailsHelper;
private boolean mShowDetails;
// mMediaSet could be null if there is no KEY_MEDIA_SET_PATH supplied.
// E.g., viewing a photo in gmail attachment
private FilterDeleteSet mMediaSet;
// The mediaset used by camera launched from secure lock screen.
private SecureAlbum mSecureAlbum;
private int mCurrentIndex = 0;
private Handler mHandler;
private boolean mShowBars = true;
private volatile boolean mActionBarAllowed = true;
private GalleryActionBar mActionBar;
private boolean mIsMenuVisible;
private boolean mHaveImageEditor;
private PhotoPageBottomControls mBottomControls;
private PhotoPageProgressBar mProgressBar;
private MediaItem mCurrentPhoto = null;
private MenuExecutor mMenuExecutor;
private boolean mIsActive;
private boolean mShowSpinner;
private String mSetPathString;
// This is the original mSetPathString before adding the camera preview item.
private String mOriginalSetPathString;
private AppBridge mAppBridge;
private SnailItem mScreenNailItem;
private SnailAlbum mScreenNailSet;
private OrientationManager mOrientationManager;
private boolean mTreatBackAsUp;
private boolean mStartInFilmstrip;
private boolean mHasCameraScreennailOrPlaceholder = false;
private boolean mRecenterCameraOnResume = true;
// These are only valid after the panorama callback
private boolean mIsPanorama;
private boolean mIsPanorama360;
private long mCameraSwitchCutoff = 0;
private boolean mSkipUpdateCurrentPhoto = false;
private static final long CAMERA_SWITCH_CUTOFF_THRESHOLD_MS = 300;
private static final long DEFERRED_UPDATE_MS = 250;
private boolean mDeferredUpdateWaiting = false;
private long mDeferUpdateUntil = Long.MAX_VALUE;
// The item that is deleted (but it can still be undeleted before commiting)
private Path mDeletePath;
private boolean mDeleteIsFocus; // whether the deleted item was in focus
private Uri[] mNfcPushUris = new Uri[1];
private final MyMenuVisibilityListener mMenuVisibilityListener =
new MyMenuVisibilityListener();
private UpdateProgressListener mProgressListener;
private final PanoramaSupportCallback mUpdatePanoramaMenuItemsCallback = new PanoramaSupportCallback() {
@Override
public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama,
boolean isPanorama360) {
if (mediaObject == mCurrentPhoto) {
mHandler.obtainMessage(MSG_UPDATE_PANORAMA_UI, isPanorama360 ? 1 : 0, 0,
mediaObject).sendToTarget();
}
}
};
private final PanoramaSupportCallback mRefreshBottomControlsCallback = new PanoramaSupportCallback() {
@Override
public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama,
boolean isPanorama360) {
if (mediaObject == mCurrentPhoto) {
mHandler.obtainMessage(MSG_REFRESH_BOTTOM_CONTROLS, isPanorama ? 1 : 0, isPanorama360 ? 1 : 0,
mediaObject).sendToTarget();
}
}
};
private final PanoramaSupportCallback mUpdateShareURICallback = new PanoramaSupportCallback() {
@Override
public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama,
boolean isPanorama360) {
if (mediaObject == mCurrentPhoto) {
mHandler.obtainMessage(MSG_UPDATE_SHARE_URI, isPanorama360 ? 1 : 0, 0, mediaObject)
.sendToTarget();
}
}
};
public static interface Model extends PhotoView.Model {
public void resume();
public void pause();
public boolean isEmpty();
public void setCurrentPhoto(Path path, int indexHint);
}
private class MyMenuVisibilityListener implements OnMenuVisibilityListener {
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
mIsMenuVisible = isVisible;
refreshHidingMessage();
}
}
private class UpdateProgressListener implements StitchingChangeListener {
@Override
public void onStitchingResult(Uri uri) {
sendUpdate(uri, MSG_REFRESH_IMAGE);
}
@Override
public void onStitchingQueued(Uri uri) {
sendUpdate(uri, MSG_UPDATE_PROGRESS);
}
@Override
public void onStitchingProgress(Uri uri, final int progress) {
sendUpdate(uri, MSG_UPDATE_PROGRESS);
}
private void sendUpdate(Uri uri, int message) {
MediaObject currentPhoto = mCurrentPhoto;
boolean isCurrentPhoto = currentPhoto instanceof LocalImage
&& currentPhoto.getContentUri().equals(uri);
if (isCurrentPhoto) {
mHandler.sendEmptyMessage(message);
}
}
};
@Override
protected int getBackgroundColorId() {
return R.color.photo_background;
}
private final GLView mRootPane = new GLView() {
@Override
protected void onLayout(
boolean changed, int left, int top, int right, int bottom) {
mPhotoView.layout(0, 0, right - left, bottom - top);
if (mShowDetails) {
mDetailsHelper.layout(left, mActionBar.getHeight(), right, bottom);
}
}
};
@Override
public void onCreate(Bundle data, Bundle restoreState) {
super.onCreate(data, restoreState);
mActionBar = mActivity.getGalleryActionBar();
mSelectionManager = new SelectionManager(mActivity, false);
mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager);
mPhotoView = new PhotoView(mActivity);
mPhotoView.setListener(this);
mRootPane.addComponent(mPhotoView);
mApplication = (GalleryApp) ((Activity) mActivity).getApplication();
mOrientationManager = mActivity.getOrientationManager();
mActivity.getGLRoot().setOrientationSource(mOrientationManager);
mHandler = new SynchronizedHandler(mActivity.getGLRoot()) {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_HIDE_BARS: {
hideBars();
break;
}
case MSG_REFRESH_BOTTOM_CONTROLS: {
if (mCurrentPhoto == message.obj && mBottomControls != null) {
mIsPanorama = message.arg1 == 1;
mIsPanorama360 = message.arg2 == 1;
mBottomControls.refresh();
}
break;
}
case MSG_ON_FULL_SCREEN_CHANGED: {
- mAppBridge.onFullScreenChanged(message.arg1 == 1);
+ if (mAppBridge != null) {
+ mAppBridge.onFullScreenChanged(message.arg1 == 1);
+ }
break;
}
case MSG_UPDATE_ACTION_BAR: {
updateBars();
break;
}
case MSG_WANT_BARS: {
wantBars();
break;
}
case MSG_UNFREEZE_GLROOT: {
mActivity.getGLRoot().unfreeze();
break;
}
case MSG_UPDATE_DEFERRED: {
long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis();
if (nextUpdate <= 0) {
mDeferredUpdateWaiting = false;
updateUIForCurrentPhoto();
} else {
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate);
}
break;
}
case MSG_ON_CAMERA_CENTER: {
mSkipUpdateCurrentPhoto = false;
boolean stayedOnCamera = false;
if (!mPhotoView.getFilmMode()) {
stayedOnCamera = true;
} else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff &&
mMediaSet.getMediaItemCount() > 1) {
mPhotoView.switchToImage(1);
} else {
if (mAppBridge != null) mPhotoView.setFilmMode(false);
stayedOnCamera = true;
}
if (stayedOnCamera) {
if (mAppBridge == null) {
launchCamera();
/* We got here by swiping from photo 1 to the
placeholder, so make it be the thing that
is in focus when the user presses back from
the camera app */
mPhotoView.switchToImage(1);
} else {
updateBars();
updateCurrentPhoto(mModel.getMediaItem(0));
}
}
break;
}
case MSG_ON_PICTURE_CENTER: {
if (!mPhotoView.getFilmMode() && mCurrentPhoto != null
&& (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) {
mPhotoView.setFilmMode(true);
}
break;
}
case MSG_REFRESH_IMAGE: {
final MediaItem photo = mCurrentPhoto;
mCurrentPhoto = null;
updateCurrentPhoto(photo);
break;
}
case MSG_UPDATE_PHOTO_UI: {
updateUIForCurrentPhoto();
break;
}
case MSG_UPDATE_PROGRESS: {
updateProgressBar();
break;
}
case MSG_UPDATE_SHARE_URI: {
if (mCurrentPhoto == message.obj) {
boolean isPanorama360 = message.arg1 != 0;
Uri contentUri = mCurrentPhoto.getContentUri();
Intent panoramaIntent = null;
if (isPanorama360) {
panoramaIntent = createSharePanoramaIntent(contentUri);
}
Intent shareIntent = createShareIntent(mCurrentPhoto);
mActionBar.setShareIntents(panoramaIntent, shareIntent);
setNfcBeamPushUri(contentUri);
}
break;
}
case MSG_UPDATE_PANORAMA_UI: {
if (mCurrentPhoto == message.obj) {
boolean isPanorama360 = message.arg1 != 0;
updatePanoramaUI(isPanorama360);
}
break;
}
default: throw new AssertionError(message.what);
}
}
};
mSetPathString = data.getString(KEY_MEDIA_SET_PATH);
mOriginalSetPathString = mSetPathString;
setupNfcBeamPush();
String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH);
Path itemPath = itemPathString != null ?
Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) :
null;
mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false);
mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false);
boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false);
mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0);
if (mSetPathString != null) {
mShowSpinner = true;
mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE);
if (mAppBridge != null) {
mShowBars = false;
mHasCameraScreennailOrPlaceholder = true;
mAppBridge.setServer(this);
// Get the ScreenNail from AppBridge and register it.
int id = SnailSource.newId();
Path screenNailSetPath = SnailSource.getSetPath(id);
Path screenNailItemPath = SnailSource.getItemPath(id);
mScreenNailSet = (SnailAlbum) mActivity.getDataManager()
.getMediaObject(screenNailSetPath);
mScreenNailItem = (SnailItem) mActivity.getDataManager()
.getMediaObject(screenNailItemPath);
mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail());
if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) {
// Set the flag to be on top of the lock screen.
mFlags |= FLAG_SHOW_WHEN_LOCKED;
}
// Don't display "empty album" action item for capture intents.
if (!mSetPathString.equals("/local/all/0")) {
// Check if the path is a secure album.
if (SecureSource.isSecurePath(mSetPathString)) {
mSecureAlbum = (SecureAlbum) mActivity.getDataManager()
.getMediaSet(mSetPathString);
mShowSpinner = false;
}
mSetPathString = "/filter/empty/{"+mSetPathString+"}";
}
// Combine the original MediaSet with the one for ScreenNail
// from AppBridge.
mSetPathString = "/combo/item/{" + screenNailSetPath +
"," + mSetPathString + "}";
// Start from the screen nail.
itemPath = screenNailItemPath;
} else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) {
mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT +
"," + mSetPathString + "}";
mCurrentIndex++;
mHasCameraScreennailOrPlaceholder = true;
}
MediaSet originalSet = mActivity.getDataManager()
.getMediaSet(mSetPathString);
if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) {
// Use the name of the camera album rather than the default
// ComboAlbum behavior
((ComboAlbum) originalSet).useNameOfChild(1);
}
mSelectionManager.setSourceMediaSet(originalSet);
mSetPathString = "/filter/delete/{" + mSetPathString + "}";
mMediaSet = (FilterDeleteSet) mActivity.getDataManager()
.getMediaSet(mSetPathString);
if (mMediaSet == null) {
Log.w(TAG, "failed to restore " + mSetPathString);
}
if (itemPath == null) {
int mediaItemCount = mMediaSet.getMediaItemCount();
if (mediaItemCount > 0) {
if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0;
itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1)
.get(0).getPath();
} else {
// Bail out, PhotoPage can't load on an empty album
return;
}
}
PhotoDataAdapter pda = new PhotoDataAdapter(
mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex,
mAppBridge == null ? -1 : 0,
mAppBridge == null ? false : mAppBridge.isPanorama(),
mAppBridge == null ? false : mAppBridge.isStaticCamera());
mModel = pda;
mPhotoView.setModel(mModel);
pda.setDataListener(new PhotoDataAdapter.DataListener() {
@Override
public void onPhotoChanged(int index, Path item) {
int oldIndex = mCurrentIndex;
mCurrentIndex = index;
if (mHasCameraScreennailOrPlaceholder) {
if (mCurrentIndex > 0) {
mSkipUpdateCurrentPhoto = false;
}
if (oldIndex == 0 && mCurrentIndex > 0
&& !mPhotoView.getFilmMode()) {
mPhotoView.setFilmMode(true);
} else if (oldIndex == 2 && mCurrentIndex == 1) {
mCameraSwitchCutoff = SystemClock.uptimeMillis() +
CAMERA_SWITCH_CUTOFF_THRESHOLD_MS;
mPhotoView.stopScrolling();
} else if (oldIndex >= 1 && mCurrentIndex == 0) {
mPhotoView.setWantPictureCenterCallbacks(true);
mSkipUpdateCurrentPhoto = true;
}
}
if (!mSkipUpdateCurrentPhoto) {
if (item != null) {
MediaItem photo = mModel.getMediaItem(0);
if (photo != null) updateCurrentPhoto(photo);
}
updateBars();
}
// Reset the timeout for the bars after a swipe
refreshHidingMessage();
}
@Override
public void onLoadingFinished(boolean loadingFailed) {
if (!mModel.isEmpty()) {
MediaItem photo = mModel.getMediaItem(0);
if (photo != null) updateCurrentPhoto(photo);
} else if (mIsActive) {
// We only want to finish the PhotoPage if there is no
// deletion that the user can undo.
if (mMediaSet.getNumberOfDeletions() == 0) {
mActivity.getStateManager().finishState(
PhotoPage.this);
}
}
}
@Override
public void onLoadingStarted() {
}
});
} else {
// Get default media set by the URI
MediaItem mediaItem = (MediaItem)
mActivity.getDataManager().getMediaObject(itemPath);
mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem);
mPhotoView.setModel(mModel);
updateCurrentPhoto(mediaItem);
mShowSpinner = false;
}
mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1);
RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity)
.findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root);
if (galleryRoot != null) {
if (mSecureAlbum == null) {
mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot);
}
StitchingProgressManager progressManager = mApplication.getStitchingProgressManager();
if (progressManager != null) {
mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot);
mProgressListener = new UpdateProgressListener();
progressManager.addChangeListener(mProgressListener);
if (mSecureAlbum != null) {
progressManager.addChangeListener(mSecureAlbum);
}
}
}
}
@Override
public void onPictureCenter(boolean isCamera) {
isCamera = isCamera || (mHasCameraScreennailOrPlaceholder && mAppBridge == null);
mPhotoView.setWantPictureCenterCallbacks(false);
mHandler.removeMessages(MSG_ON_CAMERA_CENTER);
mHandler.removeMessages(MSG_ON_PICTURE_CENTER);
mHandler.sendEmptyMessage(isCamera ? MSG_ON_CAMERA_CENTER : MSG_ON_PICTURE_CENTER);
}
@Override
public boolean canDisplayBottomControls() {
return mIsActive && !mPhotoView.canUndo();
}
@Override
public boolean canDisplayBottomControl(int control) {
if (mCurrentPhoto == null) {
return false;
}
switch(control) {
case R.id.photopage_bottom_control_edit:
return mHaveImageEditor && mShowBars
&& !mPhotoView.getFilmMode()
&& (mCurrentPhoto.getSupportedOperations() & MediaItem.SUPPORT_EDIT) != 0
&& mCurrentPhoto.getMediaType() == MediaObject.MEDIA_TYPE_IMAGE;
case R.id.photopage_bottom_control_panorama:
return mIsPanorama;
case R.id.photopage_bottom_control_tiny_planet:
return mHaveImageEditor && mShowBars
&& mIsPanorama360 && !mPhotoView.getFilmMode();
default:
return false;
}
}
@Override
public void onBottomControlClicked(int control) {
switch(control) {
case R.id.photopage_bottom_control_edit:
launchPhotoEditor();
return;
case R.id.photopage_bottom_control_panorama:
mActivity.getPanoramaViewHelper()
.showPanorama(mCurrentPhoto.getContentUri());
return;
case R.id.photopage_bottom_control_tiny_planet:
launchTinyPlanet();
return;
default:
return;
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setupNfcBeamPush() {
if (!ApiHelper.HAS_SET_BEAM_PUSH_URIS) return;
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mActivity);
if (adapter != null) {
adapter.setBeamPushUris(null, mActivity);
adapter.setBeamPushUrisCallback(new CreateBeamUrisCallback() {
@Override
public Uri[] createBeamUris(NfcEvent event) {
return mNfcPushUris;
}
}, mActivity);
}
}
private void setNfcBeamPushUri(Uri uri) {
mNfcPushUris[0] = uri;
}
private static Intent createShareIntent(MediaObject mediaObject) {
int type = mediaObject.getMediaType();
return new Intent(Intent.ACTION_SEND)
.setType(MenuExecutor.getMimeType(type))
.putExtra(Intent.EXTRA_STREAM, mediaObject.getContentUri())
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
private static Intent createSharePanoramaIntent(Uri contentUri) {
return new Intent(Intent.ACTION_SEND)
.setType(GalleryUtils.MIME_TYPE_PANORAMA360)
.putExtra(Intent.EXTRA_STREAM, contentUri)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
private void overrideTransitionToEditor() {
((Activity) mActivity).overridePendingTransition(android.R.anim.slide_in_left,
android.R.anim.fade_out);
}
private void launchTinyPlanet() {
// Deep link into tiny planet
MediaItem current = mModel.getMediaItem(0);
Intent intent = new Intent(FilterShowActivity.TINY_PLANET_ACTION);
intent.setClass(mActivity, FilterShowActivity.class);
intent.setDataAndType(current.getContentUri(), current.getMimeType())
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN,
mActivity.isFullscreen());
mActivity.startActivityForResult(intent, REQUEST_EDIT);
overrideTransitionToEditor();
}
private void launchCamera() {
Intent intent = new Intent(mActivity, CameraActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mRecenterCameraOnResume = false;
mActivity.startActivity(intent);
}
private void launchPhotoEditor() {
MediaItem current = mModel.getMediaItem(0);
if (current == null || (current.getSupportedOperations()
& MediaObject.SUPPORT_EDIT) == 0) {
return;
}
Intent intent = new Intent(ACTION_NEXTGEN_EDIT);
intent.setDataAndType(current.getContentUri(), current.getMimeType())
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (mActivity.getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() == 0) {
intent.setAction(Intent.ACTION_EDIT);
}
intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN,
mActivity.isFullscreen());
((Activity) mActivity).startActivityForResult(Intent.createChooser(intent, null),
REQUEST_EDIT);
overrideTransitionToEditor();
}
private void requestDeferredUpdate() {
mDeferUpdateUntil = SystemClock.uptimeMillis() + DEFERRED_UPDATE_MS;
if (!mDeferredUpdateWaiting) {
mDeferredUpdateWaiting = true;
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, DEFERRED_UPDATE_MS);
}
}
private void updateUIForCurrentPhoto() {
if (mCurrentPhoto == null) return;
// If by swiping or deletion the user ends up on an action item
// and zoomed in, zoom out so that the context of the action is
// more clear
if ((mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0
&& !mPhotoView.getFilmMode()) {
mPhotoView.setWantPictureCenterCallbacks(true);
}
updateMenuOperations();
refreshBottomControlsWhenReady();
if (mShowDetails) {
mDetailsHelper.reloadDetails();
}
if ((mSecureAlbum == null)
&& (mCurrentPhoto.getSupportedOperations() & MediaItem.SUPPORT_SHARE) != 0) {
mCurrentPhoto.getPanoramaSupport(mUpdateShareURICallback);
}
updateProgressBar();
}
private void updateCurrentPhoto(MediaItem photo) {
if (mCurrentPhoto == photo) return;
mCurrentPhoto = photo;
if (mPhotoView.getFilmMode()) {
requestDeferredUpdate();
} else {
updateUIForCurrentPhoto();
}
}
private void updateProgressBar() {
if (mProgressBar != null) {
mProgressBar.hideProgress();
StitchingProgressManager progressManager = mApplication.getStitchingProgressManager();
if (progressManager != null && mCurrentPhoto instanceof LocalImage) {
Integer progress = progressManager.getProgress(mCurrentPhoto.getContentUri());
if (progress != null) {
mProgressBar.setProgress(progress);
}
}
}
}
private void updateMenuOperations() {
Menu menu = mActionBar.getMenu();
// it could be null if onCreateActionBar has not been called yet
if (menu == null) return;
MenuItem item = menu.findItem(R.id.action_slideshow);
if (item != null) {
item.setVisible((mSecureAlbum == null) && canDoSlideShow());
}
if (mCurrentPhoto == null) return;
int supportedOperations = mCurrentPhoto.getSupportedOperations();
if (mSecureAlbum != null) {
supportedOperations &= MediaObject.SUPPORT_DELETE;
} else if (!mHaveImageEditor) {
supportedOperations &= ~MediaObject.SUPPORT_EDIT;
}
MenuExecutor.updateMenuOperation(menu, supportedOperations);
mCurrentPhoto.getPanoramaSupport(mUpdatePanoramaMenuItemsCallback);
}
private boolean canDoSlideShow() {
if (mMediaSet == null || mCurrentPhoto == null) {
return false;
}
if (mCurrentPhoto.getMediaType() != MediaObject.MEDIA_TYPE_IMAGE) {
return false;
}
if (MtpSource.isMtpPath(mOriginalSetPathString)) {
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// Action Bar show/hide management
//////////////////////////////////////////////////////////////////////////
private void showBars() {
if (mShowBars) return;
mShowBars = true;
mOrientationManager.unlockOrientation();
mActionBar.show();
mActivity.getGLRoot().setLightsOutMode(false);
refreshHidingMessage();
refreshBottomControlsWhenReady();
}
private void hideBars() {
if (!mShowBars) return;
mShowBars = false;
mActionBar.hide();
mActivity.getGLRoot().setLightsOutMode(true);
mHandler.removeMessages(MSG_HIDE_BARS);
refreshBottomControlsWhenReady();
}
private void refreshHidingMessage() {
mHandler.removeMessages(MSG_HIDE_BARS);
if (!mIsMenuVisible && !mPhotoView.getFilmMode()) {
mHandler.sendEmptyMessageDelayed(MSG_HIDE_BARS, HIDE_BARS_TIMEOUT);
}
}
private boolean canShowBars() {
// No bars if we are showing camera preview.
if (mAppBridge != null && mCurrentIndex == 0
&& !mPhotoView.getFilmMode()) return false;
// No bars if it's not allowed.
if (!mActionBarAllowed) return false;
return true;
}
private void wantBars() {
if (canShowBars()) showBars();
}
private void toggleBars() {
if (mShowBars) {
hideBars();
} else {
if (canShowBars()) showBars();
}
}
private void updateBars() {
if (!canShowBars()) {
hideBars();
}
}
@Override
protected void onBackPressed() {
if (mShowDetails) {
hideDetails();
} else if (mAppBridge == null || !switchWithCaptureAnimation(-1)) {
// We are leaving this page. Set the result now.
setResult();
if (mStartInFilmstrip && !mPhotoView.getFilmMode()) {
mPhotoView.setFilmMode(true);
} else if (mTreatBackAsUp) {
onUpPressed();
} else {
super.onBackPressed();
}
}
}
private void onUpPressed() {
if ((mStartInFilmstrip || mAppBridge != null)
&& !mPhotoView.getFilmMode()) {
mPhotoView.setFilmMode(true);
return;
}
if (mActivity.getStateManager().getStateCount() > 1) {
setResult();
super.onBackPressed();
return;
}
if (mOriginalSetPathString == null) return;
if (mAppBridge == null) {
// We're in view mode so set up the stacks on our own.
Bundle data = new Bundle(getData());
data.putString(AlbumPage.KEY_MEDIA_PATH, mOriginalSetPathString);
data.putString(AlbumPage.KEY_PARENT_MEDIA_PATH,
mActivity.getDataManager().getTopSetPath(
DataManager.INCLUDE_ALL));
mActivity.getStateManager().switchState(this, AlbumPage.class, data);
} else {
GalleryUtils.startGalleryActivity(mActivity);
}
}
private void setResult() {
Intent result = null;
result = new Intent();
result.putExtra(KEY_RETURN_INDEX_HINT, mCurrentIndex);
setStateResult(Activity.RESULT_OK, result);
}
//////////////////////////////////////////////////////////////////////////
// AppBridge.Server interface
//////////////////////////////////////////////////////////////////////////
@Override
public void setCameraRelativeFrame(Rect frame) {
mPhotoView.setCameraRelativeFrame(frame);
}
@Override
public boolean switchWithCaptureAnimation(int offset) {
return mPhotoView.switchWithCaptureAnimation(offset);
}
@Override
public void setSwipingEnabled(boolean enabled) {
mPhotoView.setSwipingEnabled(enabled);
}
@Override
public void notifyScreenNailChanged() {
mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail());
mScreenNailSet.notifyChange();
}
@Override
public void addSecureAlbumItem(boolean isVideo, int id) {
mSecureAlbum.addMediaItem(isVideo, id);
}
@Override
protected boolean onCreateActionBar(Menu menu) {
mActionBar.createActionBarMenu(R.menu.photo, menu);
mHaveImageEditor = GalleryUtils.isEditorAvailable(mActivity, "image/*");
updateMenuOperations();
mActionBar.setTitle(mMediaSet != null ? mMediaSet.getName() : "");
return true;
}
private MenuExecutor.ProgressListener mConfirmDialogListener =
new MenuExecutor.ProgressListener() {
@Override
public void onProgressUpdate(int index) {}
@Override
public void onProgressComplete(int result) {}
@Override
public void onConfirmDialogShown() {
mHandler.removeMessages(MSG_HIDE_BARS);
}
@Override
public void onConfirmDialogDismissed(boolean confirmed) {
refreshHidingMessage();
}
@Override
public void onProgressStart() {}
};
private void switchToGrid() {
if (mActivity.getStateManager().hasStateClass(AlbumPage.class)) {
onUpPressed();
} else {
if (mOriginalSetPathString == null) return;
if (mProgressBar != null) {
updateCurrentPhoto(null);
mProgressBar.hideProgress();
}
Bundle data = new Bundle(getData());
data.putString(AlbumPage.KEY_MEDIA_PATH, mOriginalSetPathString);
data.putString(AlbumPage.KEY_PARENT_MEDIA_PATH,
mActivity.getDataManager().getTopSetPath(
DataManager.INCLUDE_ALL));
// We only show cluster menu in the first AlbumPage in stack
// TODO: Enable this when running from the camera app
boolean inAlbum = mActivity.getStateManager().hasStateClass(AlbumPage.class);
data.putBoolean(AlbumPage.KEY_SHOW_CLUSTER_MENU, !inAlbum
&& mAppBridge == null);
data.putBoolean(PhotoPage.KEY_APP_BRIDGE, mAppBridge != null);
// Account for live preview being first item
mActivity.getTransitionStore().put(KEY_RETURN_INDEX_HINT,
mAppBridge != null ? mCurrentIndex - 1 : mCurrentIndex);
if (mHasCameraScreennailOrPlaceholder && mAppBridge != null) {
mActivity.getStateManager().startState(AlbumPage.class, data);
} else {
mActivity.getStateManager().switchState(this, AlbumPage.class, data);
}
}
}
@Override
protected boolean onItemSelected(MenuItem item) {
if (mModel == null) return true;
refreshHidingMessage();
MediaItem current = mModel.getMediaItem(0);
if (current == null) {
// item is not ready, ignore
return true;
}
int currentIndex = mModel.getCurrentIndex();
Path path = current.getPath();
DataManager manager = mActivity.getDataManager();
int action = item.getItemId();
String confirmMsg = null;
switch (action) {
case android.R.id.home: {
onUpPressed();
return true;
}
case R.id.action_slideshow: {
Bundle data = new Bundle();
data.putString(SlideshowPage.KEY_SET_PATH, mMediaSet.getPath().toString());
data.putString(SlideshowPage.KEY_ITEM_PATH, path.toString());
data.putInt(SlideshowPage.KEY_PHOTO_INDEX, currentIndex);
data.putBoolean(SlideshowPage.KEY_REPEAT, true);
mActivity.getStateManager().startStateForResult(
SlideshowPage.class, REQUEST_SLIDESHOW, data);
return true;
}
case R.id.action_crop: {
Activity activity = mActivity;
Intent intent = new Intent(FilterShowActivity.CROP_ACTION);
intent.setClass(activity, FilterShowActivity.class);
intent.setDataAndType(manager.getContentUri(path), current.getMimeType())
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivityForResult(intent, PicasaSource.isPicasaImage(current)
? REQUEST_CROP_PICASA
: REQUEST_CROP);
return true;
}
case R.id.action_trim: {
Intent intent = new Intent(mActivity, TrimVideo.class);
intent.setData(manager.getContentUri(path));
// We need the file path to wrap this into a RandomAccessFile.
intent.putExtra(KEY_MEDIA_ITEM_PATH, current.getFilePath());
mActivity.startActivityForResult(intent, REQUEST_TRIM);
return true;
}
case R.id.action_edit: {
launchPhotoEditor();
return true;
}
case R.id.action_details: {
if (mShowDetails) {
hideDetails();
} else {
showDetails();
}
return true;
}
case R.id.action_delete:
confirmMsg = mActivity.getResources().getQuantityString(
R.plurals.delete_selection, 1);
case R.id.action_setas:
case R.id.action_rotate_ccw:
case R.id.action_rotate_cw:
case R.id.action_show_on_map:
mSelectionManager.deSelectAll();
mSelectionManager.toggle(path);
mMenuExecutor.onMenuClicked(item, confirmMsg, mConfirmDialogListener);
return true;
case R.id.action_import:
mSelectionManager.deSelectAll();
mSelectionManager.toggle(path);
mMenuExecutor.onMenuClicked(item, confirmMsg,
new ImportCompleteListener(mActivity));
return true;
default :
return false;
}
}
private void hideDetails() {
mShowDetails = false;
mDetailsHelper.hide();
}
private void showDetails() {
mShowDetails = true;
if (mDetailsHelper == null) {
mDetailsHelper = new DetailsHelper(mActivity, mRootPane, new MyDetailsSource());
mDetailsHelper.setCloseListener(new CloseListener() {
@Override
public void onClose() {
hideDetails();
}
});
}
mDetailsHelper.show();
}
////////////////////////////////////////////////////////////////////////////
// Callbacks from PhotoView
////////////////////////////////////////////////////////////////////////////
@Override
public void onSingleTapUp(int x, int y) {
if (mAppBridge != null) {
if (mAppBridge.onSingleTapUp(x, y)) return;
}
MediaItem item = mModel.getMediaItem(0);
if (item == null || item == mScreenNailItem) {
// item is not ready or it is camera preview, ignore
return;
}
int supported = item.getSupportedOperations();
boolean playVideo = ((supported & MediaItem.SUPPORT_PLAY) != 0);
boolean unlock = ((supported & MediaItem.SUPPORT_UNLOCK) != 0);
boolean goBack = ((supported & MediaItem.SUPPORT_BACK) != 0);
boolean launchCamera = ((supported & MediaItem.SUPPORT_CAMERA_SHORTCUT) != 0);
if (playVideo) {
// determine if the point is at center (1/6) of the photo view.
// (The position of the "play" icon is at center (1/6) of the photo)
int w = mPhotoView.getWidth();
int h = mPhotoView.getHeight();
playVideo = (Math.abs(x - w / 2) * 12 <= w)
&& (Math.abs(y - h / 2) * 12 <= h);
}
if (playVideo) {
if (mSecureAlbum == null) {
playVideo(mActivity, item.getPlayUri(), item.getName());
} else {
mActivity.getStateManager().finishState(this);
}
} else if (goBack) {
onBackPressed();
} else if (unlock) {
Intent intent = new Intent(mActivity, Gallery.class);
intent.putExtra(Gallery.KEY_DISMISS_KEYGUARD, true);
mActivity.startActivity(intent);
} else if (launchCamera) {
launchCamera();
} else {
toggleBars();
}
}
@Override
public void onActionBarAllowed(boolean allowed) {
mActionBarAllowed = allowed;
mHandler.sendEmptyMessage(MSG_UPDATE_ACTION_BAR);
}
@Override
public void onActionBarWanted() {
mHandler.sendEmptyMessage(MSG_WANT_BARS);
}
@Override
public void onFullScreenChanged(boolean full) {
Message m = mHandler.obtainMessage(
MSG_ON_FULL_SCREEN_CHANGED, full ? 1 : 0, 0);
m.sendToTarget();
}
// How we do delete/undo:
//
// When the user choose to delete a media item, we just tell the
// FilterDeleteSet to hide that item. If the user choose to undo it, we
// again tell FilterDeleteSet not to hide it. If the user choose to commit
// the deletion, we then actually delete the media item.
@Override
public void onDeleteImage(Path path, int offset) {
onCommitDeleteImage(); // commit the previous deletion
mDeletePath = path;
mDeleteIsFocus = (offset == 0);
mMediaSet.addDeletion(path, mCurrentIndex + offset);
}
@Override
public void onUndoDeleteImage() {
if (mDeletePath == null) return;
// If the deletion was done on the focused item, we want the model to
// focus on it when it is undeleted.
if (mDeleteIsFocus) mModel.setFocusHintPath(mDeletePath);
mMediaSet.removeDeletion(mDeletePath);
mDeletePath = null;
}
@Override
public void onCommitDeleteImage() {
if (mDeletePath == null) return;
mSelectionManager.deSelectAll();
mSelectionManager.toggle(mDeletePath);
mMenuExecutor.onMenuClicked(R.id.action_delete, null, true, false);
mDeletePath = null;
}
public void playVideo(Activity activity, Uri uri, String title) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW)
.setDataAndType(uri, "video/*")
.putExtra(Intent.EXTRA_TITLE, title)
.putExtra(MovieActivity.KEY_TREAT_UP_AS_BACK, true);
activity.startActivityForResult(intent, REQUEST_PLAY_VIDEO);
} catch (ActivityNotFoundException e) {
Toast.makeText(activity, activity.getString(R.string.video_err),
Toast.LENGTH_SHORT).show();
}
}
private void setCurrentPhotoByIntent(Intent intent) {
if (intent == null) return;
Path path = mApplication.getDataManager()
.findPathByUri(intent.getData(), intent.getType());
if (path != null) {
Path albumPath = mApplication.getDataManager().getDefaultSetOf(path);
if (!albumPath.equalsIgnoreCase(mOriginalSetPathString)) {
// If the edited image is stored in a different album, we need
// to start a new activity state to show the new image
Bundle data = new Bundle(getData());
data.putString(KEY_MEDIA_SET_PATH, albumPath.toString());
data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, path.toString());
mActivity.getStateManager().startState(PhotoPage.class, data);
return;
}
mModel.setCurrentPhoto(path, mCurrentIndex);
}
}
@Override
protected void onStateResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
// This is a reset, not a canceled
return;
}
if (resultCode == ProxyLauncher.RESULT_USER_CANCELED) {
// Unmap reset vs. canceled
resultCode = Activity.RESULT_CANCELED;
}
mRecenterCameraOnResume = false;
switch (requestCode) {
case REQUEST_EDIT:
setCurrentPhotoByIntent(data);
break;
case REQUEST_CROP:
if (resultCode == Activity.RESULT_OK) {
setCurrentPhotoByIntent(data);
}
break;
case REQUEST_CROP_PICASA: {
if (resultCode == Activity.RESULT_OK) {
Context context = mActivity.getAndroidContext();
String message = context.getString(R.string.crop_saved,
context.getString(R.string.folder_edited_online_photos));
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
break;
}
case REQUEST_SLIDESHOW: {
if (data == null) break;
String path = data.getStringExtra(SlideshowPage.KEY_ITEM_PATH);
int index = data.getIntExtra(SlideshowPage.KEY_PHOTO_INDEX, 0);
if (path != null) {
mModel.setCurrentPhoto(Path.fromString(path), index);
}
}
}
}
@Override
public void onPause() {
super.onPause();
mIsActive = false;
mActivity.getGLRoot().unfreeze();
mHandler.removeMessages(MSG_UNFREEZE_GLROOT);
DetailsHelper.pause();
// Hide the detail dialog on exit
if (mShowDetails) hideDetails();
if (mModel != null) {
mModel.pause();
}
mPhotoView.pause();
mHandler.removeMessages(MSG_HIDE_BARS);
mHandler.removeMessages(MSG_REFRESH_BOTTOM_CONTROLS);
refreshBottomControlsWhenReady();
mActionBar.removeOnMenuVisibilityListener(mMenuVisibilityListener);
if (mShowSpinner) {
mActionBar.disableAlbumModeMenu(true);
}
onCommitDeleteImage();
mMenuExecutor.pause();
if (mMediaSet != null) mMediaSet.clearDeletion();
}
@Override
public void onCurrentImageUpdated() {
mActivity.getGLRoot().unfreeze();
}
@Override
public void onFilmModeChanged(boolean enabled) {
refreshBottomControlsWhenReady();
if (mShowSpinner) {
if (enabled) {
mActionBar.enableAlbumModeMenu(
GalleryActionBar.ALBUM_FILMSTRIP_MODE_SELECTED, this);
} else {
mActionBar.disableAlbumModeMenu(true);
}
}
if (enabled) {
mHandler.removeMessages(MSG_HIDE_BARS);
} else {
refreshHidingMessage();
}
}
private void transitionFromAlbumPageIfNeeded() {
TransitionStore transitions = mActivity.getTransitionStore();
int albumPageTransition = transitions.get(
KEY_ALBUMPAGE_TRANSITION, MSG_ALBUMPAGE_NONE);
if (albumPageTransition == MSG_ALBUMPAGE_NONE && mAppBridge != null
&& mRecenterCameraOnResume) {
// Generally, resuming the PhotoPage when in Camera should
// reset to the capture mode to allow quick photo taking
mCurrentIndex = 0;
mPhotoView.resetToFirstPicture();
} else {
int resumeIndex = transitions.get(KEY_INDEX_HINT, -1);
if (resumeIndex >= 0) {
if (mHasCameraScreennailOrPlaceholder) {
// Account for preview/placeholder being the first item
resumeIndex++;
}
if (resumeIndex < mMediaSet.getMediaItemCount()) {
mCurrentIndex = resumeIndex;
mModel.moveTo(mCurrentIndex);
}
}
}
if (albumPageTransition == MSG_ALBUMPAGE_RESUMED) {
mPhotoView.setFilmMode(mStartInFilmstrip || mAppBridge != null);
} else if (albumPageTransition == MSG_ALBUMPAGE_PICKED) {
mPhotoView.setFilmMode(false);
}
}
@Override
protected void onResume() {
super.onResume();
if (mModel == null) {
mActivity.getStateManager().finishState(this);
return;
}
transitionFromAlbumPageIfNeeded();
mActivity.getGLRoot().freeze();
mIsActive = true;
setContentPane(mRootPane);
mModel.resume();
mPhotoView.resume();
mActionBar.setDisplayOptions(
((mSecureAlbum == null) && (mSetPathString != null)), false);
mActionBar.addOnMenuVisibilityListener(mMenuVisibilityListener);
refreshBottomControlsWhenReady();
if (mShowSpinner && mPhotoView.getFilmMode()) {
mActionBar.enableAlbumModeMenu(
GalleryActionBar.ALBUM_FILMSTRIP_MODE_SELECTED, this);
}
if (!mShowBars) {
mActionBar.hide();
mActivity.getGLRoot().setLightsOutMode(true);
}
boolean haveImageEditor = GalleryUtils.isEditorAvailable(mActivity, "image/*");
if (haveImageEditor != mHaveImageEditor) {
mHaveImageEditor = haveImageEditor;
updateMenuOperations();
}
mRecenterCameraOnResume = true;
mHandler.sendEmptyMessageDelayed(MSG_UNFREEZE_GLROOT, UNFREEZE_GLROOT_TIMEOUT);
}
@Override
protected void onDestroy() {
if (mAppBridge != null) {
mAppBridge.setServer(null);
mScreenNailItem.setScreenNail(null);
mAppBridge.detachScreenNail();
mAppBridge = null;
mScreenNailSet = null;
mScreenNailItem = null;
}
mActivity.getGLRoot().setOrientationSource(null);
if (mBottomControls != null) mBottomControls.cleanup();
// Remove all pending messages.
mHandler.removeCallbacksAndMessages(null);
super.onDestroy();
}
private class MyDetailsSource implements DetailsSource {
@Override
public MediaDetails getDetails() {
return mModel.getMediaItem(0).getDetails();
}
@Override
public int size() {
return mMediaSet != null ? mMediaSet.getMediaItemCount() : 1;
}
@Override
public int setIndex() {
return mModel.getCurrentIndex();
}
}
@Override
public void onAlbumModeSelected(int mode) {
if (mode == GalleryActionBar.ALBUM_GRID_MODE_SELECTED) {
switchToGrid();
}
}
@Override
public void refreshBottomControlsWhenReady() {
if (mBottomControls == null) {
return;
}
MediaObject currentPhoto = mCurrentPhoto;
if (currentPhoto == null) {
mHandler.obtainMessage(MSG_REFRESH_BOTTOM_CONTROLS, 0, 0, currentPhoto).sendToTarget();
} else {
currentPhoto.getPanoramaSupport(mRefreshBottomControlsCallback);
}
}
private void updatePanoramaUI(boolean isPanorama360) {
Menu menu = mActionBar.getMenu();
// it could be null if onCreateActionBar has not been called yet
if (menu == null) {
return;
}
MenuExecutor.updateMenuForPanorama(menu, isPanorama360, isPanorama360);
if (isPanorama360) {
MenuItem item = menu.findItem(R.id.action_share);
if (item != null) {
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
item.setTitle(mActivity.getResources().getString(R.string.share_as_photo));
}
} else if ((mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_SHARE) != 0) {
MenuItem item = menu.findItem(R.id.action_share);
if (item != null) {
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
item.setTitle(mActivity.getResources().getString(R.string.share));
}
}
}
@Override
public void onUndoBarVisibilityChanged(boolean visible) {
refreshBottomControlsWhenReady();
}
}
| true | true | public void onCreate(Bundle data, Bundle restoreState) {
super.onCreate(data, restoreState);
mActionBar = mActivity.getGalleryActionBar();
mSelectionManager = new SelectionManager(mActivity, false);
mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager);
mPhotoView = new PhotoView(mActivity);
mPhotoView.setListener(this);
mRootPane.addComponent(mPhotoView);
mApplication = (GalleryApp) ((Activity) mActivity).getApplication();
mOrientationManager = mActivity.getOrientationManager();
mActivity.getGLRoot().setOrientationSource(mOrientationManager);
mHandler = new SynchronizedHandler(mActivity.getGLRoot()) {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_HIDE_BARS: {
hideBars();
break;
}
case MSG_REFRESH_BOTTOM_CONTROLS: {
if (mCurrentPhoto == message.obj && mBottomControls != null) {
mIsPanorama = message.arg1 == 1;
mIsPanorama360 = message.arg2 == 1;
mBottomControls.refresh();
}
break;
}
case MSG_ON_FULL_SCREEN_CHANGED: {
mAppBridge.onFullScreenChanged(message.arg1 == 1);
break;
}
case MSG_UPDATE_ACTION_BAR: {
updateBars();
break;
}
case MSG_WANT_BARS: {
wantBars();
break;
}
case MSG_UNFREEZE_GLROOT: {
mActivity.getGLRoot().unfreeze();
break;
}
case MSG_UPDATE_DEFERRED: {
long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis();
if (nextUpdate <= 0) {
mDeferredUpdateWaiting = false;
updateUIForCurrentPhoto();
} else {
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate);
}
break;
}
case MSG_ON_CAMERA_CENTER: {
mSkipUpdateCurrentPhoto = false;
boolean stayedOnCamera = false;
if (!mPhotoView.getFilmMode()) {
stayedOnCamera = true;
} else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff &&
mMediaSet.getMediaItemCount() > 1) {
mPhotoView.switchToImage(1);
} else {
if (mAppBridge != null) mPhotoView.setFilmMode(false);
stayedOnCamera = true;
}
if (stayedOnCamera) {
if (mAppBridge == null) {
launchCamera();
/* We got here by swiping from photo 1 to the
placeholder, so make it be the thing that
is in focus when the user presses back from
the camera app */
mPhotoView.switchToImage(1);
} else {
updateBars();
updateCurrentPhoto(mModel.getMediaItem(0));
}
}
break;
}
case MSG_ON_PICTURE_CENTER: {
if (!mPhotoView.getFilmMode() && mCurrentPhoto != null
&& (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) {
mPhotoView.setFilmMode(true);
}
break;
}
case MSG_REFRESH_IMAGE: {
final MediaItem photo = mCurrentPhoto;
mCurrentPhoto = null;
updateCurrentPhoto(photo);
break;
}
case MSG_UPDATE_PHOTO_UI: {
updateUIForCurrentPhoto();
break;
}
case MSG_UPDATE_PROGRESS: {
updateProgressBar();
break;
}
case MSG_UPDATE_SHARE_URI: {
if (mCurrentPhoto == message.obj) {
boolean isPanorama360 = message.arg1 != 0;
Uri contentUri = mCurrentPhoto.getContentUri();
Intent panoramaIntent = null;
if (isPanorama360) {
panoramaIntent = createSharePanoramaIntent(contentUri);
}
Intent shareIntent = createShareIntent(mCurrentPhoto);
mActionBar.setShareIntents(panoramaIntent, shareIntent);
setNfcBeamPushUri(contentUri);
}
break;
}
case MSG_UPDATE_PANORAMA_UI: {
if (mCurrentPhoto == message.obj) {
boolean isPanorama360 = message.arg1 != 0;
updatePanoramaUI(isPanorama360);
}
break;
}
default: throw new AssertionError(message.what);
}
}
};
mSetPathString = data.getString(KEY_MEDIA_SET_PATH);
mOriginalSetPathString = mSetPathString;
setupNfcBeamPush();
String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH);
Path itemPath = itemPathString != null ?
Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) :
null;
mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false);
mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false);
boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false);
mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0);
if (mSetPathString != null) {
mShowSpinner = true;
mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE);
if (mAppBridge != null) {
mShowBars = false;
mHasCameraScreennailOrPlaceholder = true;
mAppBridge.setServer(this);
// Get the ScreenNail from AppBridge and register it.
int id = SnailSource.newId();
Path screenNailSetPath = SnailSource.getSetPath(id);
Path screenNailItemPath = SnailSource.getItemPath(id);
mScreenNailSet = (SnailAlbum) mActivity.getDataManager()
.getMediaObject(screenNailSetPath);
mScreenNailItem = (SnailItem) mActivity.getDataManager()
.getMediaObject(screenNailItemPath);
mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail());
if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) {
// Set the flag to be on top of the lock screen.
mFlags |= FLAG_SHOW_WHEN_LOCKED;
}
// Don't display "empty album" action item for capture intents.
if (!mSetPathString.equals("/local/all/0")) {
// Check if the path is a secure album.
if (SecureSource.isSecurePath(mSetPathString)) {
mSecureAlbum = (SecureAlbum) mActivity.getDataManager()
.getMediaSet(mSetPathString);
mShowSpinner = false;
}
mSetPathString = "/filter/empty/{"+mSetPathString+"}";
}
// Combine the original MediaSet with the one for ScreenNail
// from AppBridge.
mSetPathString = "/combo/item/{" + screenNailSetPath +
"," + mSetPathString + "}";
// Start from the screen nail.
itemPath = screenNailItemPath;
} else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) {
mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT +
"," + mSetPathString + "}";
mCurrentIndex++;
mHasCameraScreennailOrPlaceholder = true;
}
MediaSet originalSet = mActivity.getDataManager()
.getMediaSet(mSetPathString);
if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) {
// Use the name of the camera album rather than the default
// ComboAlbum behavior
((ComboAlbum) originalSet).useNameOfChild(1);
}
mSelectionManager.setSourceMediaSet(originalSet);
mSetPathString = "/filter/delete/{" + mSetPathString + "}";
mMediaSet = (FilterDeleteSet) mActivity.getDataManager()
.getMediaSet(mSetPathString);
if (mMediaSet == null) {
Log.w(TAG, "failed to restore " + mSetPathString);
}
if (itemPath == null) {
int mediaItemCount = mMediaSet.getMediaItemCount();
if (mediaItemCount > 0) {
if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0;
itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1)
.get(0).getPath();
} else {
// Bail out, PhotoPage can't load on an empty album
return;
}
}
PhotoDataAdapter pda = new PhotoDataAdapter(
mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex,
mAppBridge == null ? -1 : 0,
mAppBridge == null ? false : mAppBridge.isPanorama(),
mAppBridge == null ? false : mAppBridge.isStaticCamera());
mModel = pda;
mPhotoView.setModel(mModel);
pda.setDataListener(new PhotoDataAdapter.DataListener() {
@Override
public void onPhotoChanged(int index, Path item) {
int oldIndex = mCurrentIndex;
mCurrentIndex = index;
if (mHasCameraScreennailOrPlaceholder) {
if (mCurrentIndex > 0) {
mSkipUpdateCurrentPhoto = false;
}
if (oldIndex == 0 && mCurrentIndex > 0
&& !mPhotoView.getFilmMode()) {
mPhotoView.setFilmMode(true);
} else if (oldIndex == 2 && mCurrentIndex == 1) {
mCameraSwitchCutoff = SystemClock.uptimeMillis() +
CAMERA_SWITCH_CUTOFF_THRESHOLD_MS;
mPhotoView.stopScrolling();
} else if (oldIndex >= 1 && mCurrentIndex == 0) {
mPhotoView.setWantPictureCenterCallbacks(true);
mSkipUpdateCurrentPhoto = true;
}
}
if (!mSkipUpdateCurrentPhoto) {
if (item != null) {
MediaItem photo = mModel.getMediaItem(0);
if (photo != null) updateCurrentPhoto(photo);
}
updateBars();
}
// Reset the timeout for the bars after a swipe
refreshHidingMessage();
}
@Override
public void onLoadingFinished(boolean loadingFailed) {
if (!mModel.isEmpty()) {
MediaItem photo = mModel.getMediaItem(0);
if (photo != null) updateCurrentPhoto(photo);
} else if (mIsActive) {
// We only want to finish the PhotoPage if there is no
// deletion that the user can undo.
if (mMediaSet.getNumberOfDeletions() == 0) {
mActivity.getStateManager().finishState(
PhotoPage.this);
}
}
}
@Override
public void onLoadingStarted() {
}
});
} else {
// Get default media set by the URI
MediaItem mediaItem = (MediaItem)
mActivity.getDataManager().getMediaObject(itemPath);
mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem);
mPhotoView.setModel(mModel);
updateCurrentPhoto(mediaItem);
mShowSpinner = false;
}
mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1);
RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity)
.findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root);
if (galleryRoot != null) {
if (mSecureAlbum == null) {
mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot);
}
StitchingProgressManager progressManager = mApplication.getStitchingProgressManager();
if (progressManager != null) {
mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot);
mProgressListener = new UpdateProgressListener();
progressManager.addChangeListener(mProgressListener);
if (mSecureAlbum != null) {
progressManager.addChangeListener(mSecureAlbum);
}
}
}
}
| public void onCreate(Bundle data, Bundle restoreState) {
super.onCreate(data, restoreState);
mActionBar = mActivity.getGalleryActionBar();
mSelectionManager = new SelectionManager(mActivity, false);
mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager);
mPhotoView = new PhotoView(mActivity);
mPhotoView.setListener(this);
mRootPane.addComponent(mPhotoView);
mApplication = (GalleryApp) ((Activity) mActivity).getApplication();
mOrientationManager = mActivity.getOrientationManager();
mActivity.getGLRoot().setOrientationSource(mOrientationManager);
mHandler = new SynchronizedHandler(mActivity.getGLRoot()) {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_HIDE_BARS: {
hideBars();
break;
}
case MSG_REFRESH_BOTTOM_CONTROLS: {
if (mCurrentPhoto == message.obj && mBottomControls != null) {
mIsPanorama = message.arg1 == 1;
mIsPanorama360 = message.arg2 == 1;
mBottomControls.refresh();
}
break;
}
case MSG_ON_FULL_SCREEN_CHANGED: {
if (mAppBridge != null) {
mAppBridge.onFullScreenChanged(message.arg1 == 1);
}
break;
}
case MSG_UPDATE_ACTION_BAR: {
updateBars();
break;
}
case MSG_WANT_BARS: {
wantBars();
break;
}
case MSG_UNFREEZE_GLROOT: {
mActivity.getGLRoot().unfreeze();
break;
}
case MSG_UPDATE_DEFERRED: {
long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis();
if (nextUpdate <= 0) {
mDeferredUpdateWaiting = false;
updateUIForCurrentPhoto();
} else {
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate);
}
break;
}
case MSG_ON_CAMERA_CENTER: {
mSkipUpdateCurrentPhoto = false;
boolean stayedOnCamera = false;
if (!mPhotoView.getFilmMode()) {
stayedOnCamera = true;
} else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff &&
mMediaSet.getMediaItemCount() > 1) {
mPhotoView.switchToImage(1);
} else {
if (mAppBridge != null) mPhotoView.setFilmMode(false);
stayedOnCamera = true;
}
if (stayedOnCamera) {
if (mAppBridge == null) {
launchCamera();
/* We got here by swiping from photo 1 to the
placeholder, so make it be the thing that
is in focus when the user presses back from
the camera app */
mPhotoView.switchToImage(1);
} else {
updateBars();
updateCurrentPhoto(mModel.getMediaItem(0));
}
}
break;
}
case MSG_ON_PICTURE_CENTER: {
if (!mPhotoView.getFilmMode() && mCurrentPhoto != null
&& (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) {
mPhotoView.setFilmMode(true);
}
break;
}
case MSG_REFRESH_IMAGE: {
final MediaItem photo = mCurrentPhoto;
mCurrentPhoto = null;
updateCurrentPhoto(photo);
break;
}
case MSG_UPDATE_PHOTO_UI: {
updateUIForCurrentPhoto();
break;
}
case MSG_UPDATE_PROGRESS: {
updateProgressBar();
break;
}
case MSG_UPDATE_SHARE_URI: {
if (mCurrentPhoto == message.obj) {
boolean isPanorama360 = message.arg1 != 0;
Uri contentUri = mCurrentPhoto.getContentUri();
Intent panoramaIntent = null;
if (isPanorama360) {
panoramaIntent = createSharePanoramaIntent(contentUri);
}
Intent shareIntent = createShareIntent(mCurrentPhoto);
mActionBar.setShareIntents(panoramaIntent, shareIntent);
setNfcBeamPushUri(contentUri);
}
break;
}
case MSG_UPDATE_PANORAMA_UI: {
if (mCurrentPhoto == message.obj) {
boolean isPanorama360 = message.arg1 != 0;
updatePanoramaUI(isPanorama360);
}
break;
}
default: throw new AssertionError(message.what);
}
}
};
mSetPathString = data.getString(KEY_MEDIA_SET_PATH);
mOriginalSetPathString = mSetPathString;
setupNfcBeamPush();
String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH);
Path itemPath = itemPathString != null ?
Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) :
null;
mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false);
mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false);
boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false);
mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0);
if (mSetPathString != null) {
mShowSpinner = true;
mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE);
if (mAppBridge != null) {
mShowBars = false;
mHasCameraScreennailOrPlaceholder = true;
mAppBridge.setServer(this);
// Get the ScreenNail from AppBridge and register it.
int id = SnailSource.newId();
Path screenNailSetPath = SnailSource.getSetPath(id);
Path screenNailItemPath = SnailSource.getItemPath(id);
mScreenNailSet = (SnailAlbum) mActivity.getDataManager()
.getMediaObject(screenNailSetPath);
mScreenNailItem = (SnailItem) mActivity.getDataManager()
.getMediaObject(screenNailItemPath);
mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail());
if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) {
// Set the flag to be on top of the lock screen.
mFlags |= FLAG_SHOW_WHEN_LOCKED;
}
// Don't display "empty album" action item for capture intents.
if (!mSetPathString.equals("/local/all/0")) {
// Check if the path is a secure album.
if (SecureSource.isSecurePath(mSetPathString)) {
mSecureAlbum = (SecureAlbum) mActivity.getDataManager()
.getMediaSet(mSetPathString);
mShowSpinner = false;
}
mSetPathString = "/filter/empty/{"+mSetPathString+"}";
}
// Combine the original MediaSet with the one for ScreenNail
// from AppBridge.
mSetPathString = "/combo/item/{" + screenNailSetPath +
"," + mSetPathString + "}";
// Start from the screen nail.
itemPath = screenNailItemPath;
} else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) {
mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT +
"," + mSetPathString + "}";
mCurrentIndex++;
mHasCameraScreennailOrPlaceholder = true;
}
MediaSet originalSet = mActivity.getDataManager()
.getMediaSet(mSetPathString);
if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) {
// Use the name of the camera album rather than the default
// ComboAlbum behavior
((ComboAlbum) originalSet).useNameOfChild(1);
}
mSelectionManager.setSourceMediaSet(originalSet);
mSetPathString = "/filter/delete/{" + mSetPathString + "}";
mMediaSet = (FilterDeleteSet) mActivity.getDataManager()
.getMediaSet(mSetPathString);
if (mMediaSet == null) {
Log.w(TAG, "failed to restore " + mSetPathString);
}
if (itemPath == null) {
int mediaItemCount = mMediaSet.getMediaItemCount();
if (mediaItemCount > 0) {
if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0;
itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1)
.get(0).getPath();
} else {
// Bail out, PhotoPage can't load on an empty album
return;
}
}
PhotoDataAdapter pda = new PhotoDataAdapter(
mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex,
mAppBridge == null ? -1 : 0,
mAppBridge == null ? false : mAppBridge.isPanorama(),
mAppBridge == null ? false : mAppBridge.isStaticCamera());
mModel = pda;
mPhotoView.setModel(mModel);
pda.setDataListener(new PhotoDataAdapter.DataListener() {
@Override
public void onPhotoChanged(int index, Path item) {
int oldIndex = mCurrentIndex;
mCurrentIndex = index;
if (mHasCameraScreennailOrPlaceholder) {
if (mCurrentIndex > 0) {
mSkipUpdateCurrentPhoto = false;
}
if (oldIndex == 0 && mCurrentIndex > 0
&& !mPhotoView.getFilmMode()) {
mPhotoView.setFilmMode(true);
} else if (oldIndex == 2 && mCurrentIndex == 1) {
mCameraSwitchCutoff = SystemClock.uptimeMillis() +
CAMERA_SWITCH_CUTOFF_THRESHOLD_MS;
mPhotoView.stopScrolling();
} else if (oldIndex >= 1 && mCurrentIndex == 0) {
mPhotoView.setWantPictureCenterCallbacks(true);
mSkipUpdateCurrentPhoto = true;
}
}
if (!mSkipUpdateCurrentPhoto) {
if (item != null) {
MediaItem photo = mModel.getMediaItem(0);
if (photo != null) updateCurrentPhoto(photo);
}
updateBars();
}
// Reset the timeout for the bars after a swipe
refreshHidingMessage();
}
@Override
public void onLoadingFinished(boolean loadingFailed) {
if (!mModel.isEmpty()) {
MediaItem photo = mModel.getMediaItem(0);
if (photo != null) updateCurrentPhoto(photo);
} else if (mIsActive) {
// We only want to finish the PhotoPage if there is no
// deletion that the user can undo.
if (mMediaSet.getNumberOfDeletions() == 0) {
mActivity.getStateManager().finishState(
PhotoPage.this);
}
}
}
@Override
public void onLoadingStarted() {
}
});
} else {
// Get default media set by the URI
MediaItem mediaItem = (MediaItem)
mActivity.getDataManager().getMediaObject(itemPath);
mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem);
mPhotoView.setModel(mModel);
updateCurrentPhoto(mediaItem);
mShowSpinner = false;
}
mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1);
RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity)
.findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root);
if (galleryRoot != null) {
if (mSecureAlbum == null) {
mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot);
}
StitchingProgressManager progressManager = mApplication.getStitchingProgressManager();
if (progressManager != null) {
mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot);
mProgressListener = new UpdateProgressListener();
progressManager.addChangeListener(mProgressListener);
if (mSecureAlbum != null) {
progressManager.addChangeListener(mSecureAlbum);
}
}
}
}
|
diff --git a/src/com/example/tabletapp/MainActivity.java b/src/com/example/tabletapp/MainActivity.java
index e82f1d4..713d505 100644
--- a/src/com/example/tabletapp/MainActivity.java
+++ b/src/com/example/tabletapp/MainActivity.java
@@ -1,89 +1,89 @@
package com.example.tabletapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainview);
backbuttonenable();
mHandler = new Handler();
mHandler.post(mUpdate);
}
private Runnable mUpdate = new Runnable() {
public void run() {
showCurrentTime();
showBestTime();
showLane();
showCurrentDistance();
showCurrentRoundNumber();
mHandler.postDelayed(this, 1000);
}
};
private void showCurrentTime() {
Match match = Match.getInstance();
TextView currentTime = (TextView) findViewById(R.id.textView1);
- currentTime.setText(Integer.toString(match.getCurrentTime()));
+ currentTime.setText(match.createMatchTime(match.getCurrentTime()));
}
private void showBestTime() {
Match match = Match.getInstance();
TextView bestTime = (TextView) findViewById(R.id.TextView03);
- bestTime.setText(Integer.toString(match.getBestLapTime()));
+ bestTime.setText(match.createMatchTime(match.getBestLapTime()));
}
private void showCurrentDistance() {
Match match = Match.getInstance();
TextView currentDistance = (TextView) findViewById(R.id.TextView08);
currentDistance.setText(Integer.toString(match.getCurrentDistance()));
}
private void showCurrentRoundNumber() {
Match match = Match.getInstance();
TextView currentRound = (TextView) findViewById(R.id.roundNumber);
currentRound.setText(Integer.toString(match.getRoundNumber()) + "/" + Integer.toString(match.getTotalRounds()));
}
private void showLane() {
Match match = Match.getInstance();
TextView lane = (TextView) findViewById(R.id.TextView05);
String currentLane;
if(match.getInfo().getLane())
currentLane = "Inner";
else
currentLane = "Outer";
lane.setText(currentLane);
}
public void backbuttonenable(){
if(findViewById(R.id.back)!=null){
ImageButton buttonback = (ImageButton) findViewById(R.id.back);
buttonback.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MenuActivity.class);
startActivity(i);
}
});
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/gdx/src/com/badlogic/gdx/maps/tiled/renderers/OrthogonalTiledMapRenderer2.java b/gdx/src/com/badlogic/gdx/maps/tiled/renderers/OrthogonalTiledMapRenderer2.java
index 311117c35..d0a4672c9 100755
--- a/gdx/src/com/badlogic/gdx/maps/tiled/renderers/OrthogonalTiledMapRenderer2.java
+++ b/gdx/src/com/badlogic/gdx/maps/tiled/renderers/OrthogonalTiledMapRenderer2.java
@@ -1,280 +1,283 @@
package com.badlogic.gdx.maps.tiled.renderers;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.C1;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.C2;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.C3;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.C4;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.U1;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.U2;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.U3;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.U4;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.V1;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.V2;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.V3;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.V4;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.X1;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.X2;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.X3;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.X4;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.Y1;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.Y2;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.Y3;
import static com.badlogic.gdx.graphics.g2d.SpriteBatch.Y4;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL11;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteCache;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
public class OrthogonalTiledMapRenderer2 implements TiledMapRenderer {
protected TiledMap map;
protected float unitScale;
protected SpriteCache spriteCache;
protected Rectangle viewBounds;
private float[] vertices = new float[20];
public boolean recache;
public OrthogonalTiledMapRenderer2(TiledMap map) {
this.map = map;
this.unitScale = 1;
this.spriteCache = new SpriteCache(4000, true);
this.viewBounds = new Rectangle();
}
public OrthogonalTiledMapRenderer2(TiledMap map, float unitScale) {
this.map = map;
this.unitScale = unitScale;
this.viewBounds = new Rectangle();
this.spriteCache = new SpriteCache(4000, true);
}
@Override
public void setView(OrthographicCamera camera) {
spriteCache.setProjectionMatrix(camera.combined);
float width = camera.viewportWidth * camera.zoom;
float height = camera.viewportHeight * camera.zoom;
viewBounds.set(camera.position.x - width / 2, camera.position.y - height / 2, width, height);
recache = true;
}
@Override
public void setView (Matrix4 projection, float x, float y, float width, float height) {
spriteCache.setProjectionMatrix(projection);
viewBounds.set(x, y, width, height);
recache = true;
}
public void begin () {
if (recache) {
cached = false;
recache = false;
spriteCache.clear();
}
if (!cached) {
spriteCache.beginCache();
} else {
Gdx.gl.glEnable(GL10.GL_BLEND);
Gdx.gl.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
spriteCache.begin();
}
}
public void end () {
if (!cached) {
spriteCache.endCache();
cached = true;
- begin();
- render();
- end();
+ Gdx.gl.glEnable(GL10.GL_BLEND);
+ Gdx.gl.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
+ spriteCache.begin();
+ spriteCache.draw(0);
+ spriteCache.end();
+ Gdx.gl.glDisable(GL10.GL_BLEND);
} else {
spriteCache.end();
Gdx.gl.glDisable(GL10.GL_BLEND);
}
}
@Override
public void render () {
begin();
if (cached) {
spriteCache.draw(0);
} else {
for (MapLayer layer : map.getLayers()) {
if (layer.getVisible()) {
if (layer instanceof TiledMapTileLayer) {
renderTileLayer((TiledMapTileLayer) layer);
} else {
for (MapObject object : layer.getObjects()) {
renderObject(object);
}
}
}
}
}
end();
}
@Override
public void render (int[] layers) {
// FIXME not implemented
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void renderObject (MapObject object) {
// TODO Auto-generated method stub
}
boolean cached = false;
int count = 0;
@Override
public void renderTileLayer (TiledMapTileLayer layer) {
final float color = Color.toFloatBits(1, 1, 1, layer.getOpacity());
final int layerWidth = layer.getWidth();
final int layerHeight = layer.getHeight();
final float layerTileWidth = layer.getTileWidth() * unitScale;
final float layerTileHeight = layer.getTileHeight() * unitScale;
final int col1 = Math.max(0, (int) (viewBounds.x / layerTileWidth));
final int col2 = Math.min(layerWidth, (int) ((viewBounds.x + viewBounds.width + layerTileWidth) / layerTileWidth));
final int row1 = Math.max(0, (int) (viewBounds.y / layerTileHeight));
final int row2 = Math.min(layerHeight, (int) ((viewBounds.y + viewBounds.height + layerTileHeight) / layerTileHeight));
for (int row = row1; row < row2; row++) {
for (int col = col1; col < col2; col++) {
final TiledMapTileLayer.Cell cell = layer.getCell(col, row);
final TiledMapTile tile = cell.getTile();
if (tile != null) {
count++;
final boolean flipX = cell.getFlipHorizontally();
final boolean flipY = cell.getFlipVertically();
final int rotations = cell.getRotation();
TextureRegion region = tile.getTextureRegion();
float x1 = col * layerTileWidth;
float y1 = row * layerTileHeight;
float x2 = x1 + region.getRegionWidth() * unitScale;
float y2 = y1 + region.getRegionHeight() * unitScale;
float u1 = region.getU();
float v1 = region.getV2();
float u2 = region.getU2();
float v2 = region.getV();
vertices[X1] = x1;
vertices[Y1] = y1;
vertices[C1] = color;
vertices[U1] = u1;
vertices[V1] = v1;
vertices[X2] = x1;
vertices[Y2] = y2;
vertices[C2] = color;
vertices[U2] = u1;
vertices[V2] = v2;
vertices[X3] = x2;
vertices[Y3] = y2;
vertices[C3] = color;
vertices[U3] = u2;
vertices[V3] = v2;
vertices[X4] = x2;
vertices[Y4] = y1;
vertices[C4] = color;
vertices[U4] = u2;
vertices[V4] = v1;
if (flipX) {
float temp = vertices[U1];
vertices[U1] = vertices[U3];
vertices[U3] = temp;
temp = vertices[U2];
vertices[U2] = vertices[U4];
vertices[U4] = temp;
}
if (flipY) {
float temp = vertices[V1];
vertices[V1] = vertices[V3];
vertices[V3] = temp;
temp = vertices[V2];
vertices[V2] = vertices[V4];
vertices[V4] = temp;
}
if (rotations != 0) {
switch (rotations) {
case Cell.ROTATE_90: {
float tempV = vertices[V1];
vertices[V1] = vertices[V2];
vertices[V2] = vertices[V3];
vertices[V3] = vertices[V4];
vertices[V4] = tempV;
float tempU = vertices[U1];
vertices[U1] = vertices[U2];
vertices[U2] = vertices[U3];
vertices[U3] = vertices[U4];
vertices[U4] = tempU;
break;
}
case Cell.ROTATE_180: {
float tempU = vertices[U1];
vertices[U1] = vertices[U3];
vertices[U3] = tempU;
tempU = vertices[U2];
vertices[U2] = vertices[U4];
vertices[U4] = tempU;
float tempV = vertices[V1];
vertices[V1] = vertices[V3];
vertices[V3] = tempV;
tempV = vertices[V2];
vertices[V2] = vertices[V4];
vertices[V4] = tempV;
break;
}
case Cell.ROTATE_270: {
float tempV = vertices[V1];
vertices[V1] = vertices[V4];
vertices[V4] = vertices[V3];
vertices[V3] = vertices[V2];
vertices[V2] = tempV;
float tempU = vertices[U1];
vertices[U1] = vertices[U4];
vertices[U4] = vertices[U3];
vertices[U3] = vertices[U2];
vertices[U2] = tempU;
break;
}
}
}
spriteCache.add(region.getTexture(), vertices, 0, 20);
}
}
}
}
}
\ No newline at end of file
diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java
index d0a835c03..74fda8933 100644
--- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java
+++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java
@@ -1,47 +1,47 @@
/*******************************************************************************
* 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.tests.lwjgl;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.tests.AssetManagerTest;
import com.badlogic.gdx.tests.GleedTest;
import com.badlogic.gdx.tests.GamepadTest;
import com.badlogic.gdx.tests.InverseKinematicsTest;
import com.badlogic.gdx.tests.TiledMapDirectLoaderTest;
import com.badlogic.gdx.tests.TiledMapAssetManagerTest;
import com.badlogic.gdx.tests.YDownTest;
import com.badlogic.gdx.tests.bench.TiledMapBench;
import com.badlogic.gdx.tests.extensions.FreeTypeTest;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.SharedLibraryLoader;
public class LwjglDebugStarter {
public static void main (String[] argv) {
// this is only here for me to debug native code faster
new SharedLibraryLoader("../../extensions/gdx-audio/libs/gdx-audio-natives.jar").load("gdx-audio");
new SharedLibraryLoader("../../extensions/gdx-image/libs/gdx-image-natives.jar").load("gdx-image");
new SharedLibraryLoader("../../extensions/gdx-freetype/libs/gdx-freetype-natives.jar").load("gdx-freetype");
new SharedLibraryLoader("../../extensions/gdx-controllers/gdx-controllers-desktop/libs/gdx-controllers-desktop-natives.jar").load("gdx-controllers-desktop");
new SharedLibraryLoader("../../gdx/libs/gdx-natives.jar").load("gdx");
- GdxTest test = new GleedTest();
+ GdxTest test = new TiledMapBench();
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.useGL20 = test.needsGL20();
new LwjglApplication(test, config);
}
}
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapAssetManagerTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapAssetManagerTest.java
index e17dba477..5ecab6a9a 100644
--- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapAssetManagerTest.java
+++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapAssetManagerTest.java
@@ -1,66 +1,67 @@
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.IsometricTiledMapRenderer;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.OrthoCamController;
public class TiledMapAssetManagerTest extends GdxTest {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private OrthoCamController cameraController;
private AssetManager assetManager;
private BitmapFont font;
private SpriteBatch batch;
@Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, (w / h) * 10, 10);
+ camera.zoom = 2;
camera.update();
cameraController = new OrthoCamController(camera);
Gdx.input.setInputProcessor(cameraController);
font = new BitmapFont();
batch = new SpriteBatch();
assetManager = new AssetManager();
assetManager.setLoader(TiledMap.class, new TmxMapLoader(new InternalFileHandleResolver()));
assetManager.load("data/maps/isometric_grass_and_water.tmx", TiledMap.class);
assetManager.finishLoading();
map = assetManager.get("data/maps/isometric_grass_and_water.tmx");
renderer = new IsometricTiledMapRenderer(map, 1f / 64f);
}
@Override
public void render() {
Gdx.gl.glClearColor(100f / 255f, 100f / 255f, 250f / 255f, 1f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
renderer.setView(camera);
renderer.render();
batch.begin();
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
@Override
public boolean needsGL20 () {
return true;
}
}
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/bench/TiledMapBench.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/bench/TiledMapBench.java
index f1cefb34e..c593d461b 100644
--- a/tests/gdx-tests/src/com/badlogic/gdx/tests/bench/TiledMapBench.java
+++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/bench/TiledMapBench.java
@@ -1,82 +1,83 @@
package com.badlogic.gdx.tests.bench;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayers;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
+import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer2;
import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.OrthoCamController;
public class TiledMapBench extends GdxTest {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private OrthoCamController cameraController;
private AssetManager assetManager;
private Texture tiles;
private Texture texture;
private BitmapFont font;
private SpriteBatch batch;
@Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, (w / h) * 320, 320);
camera.update();
cameraController = new OrthoCamController(camera);
Gdx.input.setInputProcessor(cameraController);
font = new BitmapFont();
batch = new SpriteBatch();
{
tiles = new Texture(Gdx.files.internal("data/maps/tiles.png"));
TextureRegion[][] splitTiles = TextureRegion.split(tiles, 32, 32);
map = new TiledMap();
MapLayers layers = map.getLayers();
for (int l = 0; l < 20; l++) {
TiledMapTileLayer layer = new TiledMapTileLayer(150, 100, 32, 32);
for (int x = 0; x < 150; x++) {
for (int y = 0; y < 100; y++) {
int ty = (int)(Math.random() * splitTiles.length);
int tx = (int)(Math.random() * splitTiles[ty].length);
layer.setCell(x, y, new StaticTiledMapTile(splitTiles[ty][tx]));
}
}
layers.addLayer(layer);
}
}
- renderer = new OrthogonalTiledMapRenderer(map);
+ renderer = new OrthogonalTiledMapRenderer2(map);
}
@Override
public void render() {
Gdx.gl.glClearColor(100f / 255f, 100f / 255f, 250f / 255f, 1f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.update();
renderer.setView(camera);
renderer.render();
batch.begin();
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
}
| false | false | null | null |
diff --git a/src/com/shade/lighting/LightMask.java b/src/com/shade/lighting/LightMask.java
index 0828cb0..db17042 100644
--- a/src/com/shade/lighting/LightMask.java
+++ b/src/com/shade/lighting/LightMask.java
@@ -1,164 +1,168 @@
package com.shade.lighting;
import java.util.Arrays;
import java.util.LinkedList;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.state.StateBasedGame;
import com.shade.controls.DayPhaseTimer;
/**
* A view which renders a set of entities, lights, and background images in such
* a way as to generate dynamic lighting.
*
* It's safe to draw things to the screen after calling LightMask.render if you
* want them to appear above the gameplay, for instance user controls.
*
* <em>Note that calling render will update your entities' luminosity. Please
* direct any hate mail to JJ Jou.</em>
*
* @author JJ Jou <[email protected]>
* @author Alexander Schearer <[email protected]>
*/
public class LightMask {
protected final static Color SHADE = new Color(0, 0, 0, .3f);
public static final float MAX_DARKNESS = 0.4f;
private DayPhaseTimer timer;
/**======================END CONSTANTS=======================*/
private int threshold;
private LinkedList<LightSource> lights;
public LightMask(int threshold, DayPhaseTimer time) {
this.threshold = threshold;
lights = new LinkedList<LightSource>();
timer = time;
}
public void add(LightSource light) {
lights.add(light);
}
public void render(StateBasedGame game, Graphics g,
LuminousEntity[] entities, Image... backgrounds) {
renderLights(game, g, entities);
renderBackgrounds(game, g, backgrounds);
renderEntities(game, g, entities);
//RENDER NIGHT! WHEEE
renderTimeOfDay(game, g);
}
public void renderTimeOfDay(StateBasedGame game, Graphics g){
Color c = g.getColor();
if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.DUSK){
g.setColor(new Color(1-timer.timeLeft(),1-timer.timeLeft(),0f,MAX_DARKNESS*timer.timeLeft()));
g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight());
}
else if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.NIGHT){
g.setColor(new Color(0,0,0,MAX_DARKNESS));
g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight());
}
else if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.DAWN){
g.setColor(new Color(timer.timeLeft(),timer.timeLeft(),0,MAX_DARKNESS*(1-timer.timeLeft())));
g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight());
}
g.setColor(c);
}
private void renderLights(StateBasedGame game, Graphics g,
LuminousEntity... entities) {
enableStencil();
for (LightSource light : lights) {
light.render(game, g, entities);
}
disableStencil();
GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
g.setColor(SHADE);
GameContainer c = game.getContainer();
g.fillRect(0, 0, c.getWidth(), c.getHeight());
g.setColor(Color.white);
}
private void renderBackgrounds(StateBasedGame game, Graphics g,
Image... backgrounds) {
GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ONE);
for (Image background : backgrounds) {
background.draw();
}
}
private void renderEntities(StateBasedGame game, Graphics g,
LuminousEntity... entities) {
Arrays.sort(entities);
int i = 0;
- GL11.glEnable(GL11.GL_ALPHA_TEST);
+ // GL11.glEnable(GL11.GL_ALPHA_TEST);
+ GL11.glEnable(GL11.GL_STENCIL_TEST);
+ GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 1);
+ GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_REPLACE);
GL11.glAlphaFunc(GL11.GL_GREATER, 0);
- GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ZERO);
+ GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
while (i < entities.length && entities[i].getZIndex() < threshold) {
entities[i].render(game, g);
entities[i].setLuminosity(getLuminosityFor(entities[i], g));
i++;
}
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
while (i < entities.length) {
entities[i].render(game, g);
entities[i].setLuminosity(getLuminosityFor(entities[i], g));
i++;
}
+ GL11.glDisable(GL11.GL_STENCIL_TEST);
GL11.glDisable(GL11.GL_ALPHA_TEST);
}
private float getLuminosityFor(LuminousEntity entity, Graphics g) {
return g.getPixel((int) entity.getXCenter(), (int) entity.getYCenter()).a;
}
/**
* Called before drawing the shadows cast by a light.
*/
protected static void enableStencil() {
// write only to the stencil buffer
GL11.glEnable(GL11.GL_STENCIL_TEST);
GL11.glColorMask(false, false, false, false);
GL11.glDepthMask(false);
}
protected static void resetStencil(){
GL11.glClearStencil(0);
// write a one to the stencil buffer everywhere we are about to draw
GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 1);
// this is to always pass a one to the stencil buffer where we draw
GL11.glStencilOp(GL11.GL_REPLACE, GL11.GL_REPLACE, GL11.GL_REPLACE);
}
/**
* Called after drawing the shadows cast by a light.
*/
protected static void keepStencil() {
// resume drawing to everything
GL11.glDepthMask(true);
GL11.glColorMask(true, true, true, true);
GL11.glStencilFunc(GL11.GL_NOTEQUAL, 1, 1);
// don't modify the contents of the stencil buffer
GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP);
GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
}
protected static void disableStencil(){
GL11.glDisable(GL11.GL_STENCIL_TEST);
GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT);
}
}
| false | true | private void renderEntities(StateBasedGame game, Graphics g,
LuminousEntity... entities) {
Arrays.sort(entities);
int i = 0;
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glAlphaFunc(GL11.GL_GREATER, 0);
GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ZERO);
while (i < entities.length && entities[i].getZIndex() < threshold) {
entities[i].render(game, g);
entities[i].setLuminosity(getLuminosityFor(entities[i], g));
i++;
}
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
while (i < entities.length) {
entities[i].render(game, g);
entities[i].setLuminosity(getLuminosityFor(entities[i], g));
i++;
}
GL11.glDisable(GL11.GL_ALPHA_TEST);
}
| private void renderEntities(StateBasedGame game, Graphics g,
LuminousEntity... entities) {
Arrays.sort(entities);
int i = 0;
// GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_STENCIL_TEST);
GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 1);
GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_REPLACE);
GL11.glAlphaFunc(GL11.GL_GREATER, 0);
GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
while (i < entities.length && entities[i].getZIndex() < threshold) {
entities[i].render(game, g);
entities[i].setLuminosity(getLuminosityFor(entities[i], g));
i++;
}
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
while (i < entities.length) {
entities[i].render(game, g);
entities[i].setLuminosity(getLuminosityFor(entities[i], g));
i++;
}
GL11.glDisable(GL11.GL_STENCIL_TEST);
GL11.glDisable(GL11.GL_ALPHA_TEST);
}
|
diff --git a/spring-faces/src/main/java/org/springframework/faces/mvc/JsfView.java b/spring-faces/src/main/java/org/springframework/faces/mvc/JsfView.java
index 70906ce7..debe4fe7 100644
--- a/spring-faces/src/main/java/org/springframework/faces/mvc/JsfView.java
+++ b/spring-faces/src/main/java/org/springframework/faces/mvc/JsfView.java
@@ -1,100 +1,104 @@
/*
* Copyright 2004-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.faces.mvc;
import static org.springframework.faces.webflow.JsfRuntimeInformation.isAtLeastJsf12;
import static org.springframework.faces.webflow.JsfRuntimeInformation.isPortletRequest;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.faces.webflow.FacesContextHelper;
import org.springframework.faces.webflow.JsfUtils;
import org.springframework.util.Assert;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
/**
* JSF View that renders a transient (stateless) JSF view template. The UIViewRoot will not be saved and thus the JSF
* lifecycle will not be able to be invoked on postback.
*
* @author Jeremy Grelle
*/
public class JsfView extends AbstractUrlBasedView {
private Lifecycle facesLifecycle;
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
facesLifecycle = createFacesLifecycle();
}
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
FacesContextHelper facesContextHelper = new FacesContextHelper();
FacesContext facesContext = facesContextHelper.getFacesContext(getServletContext(), request, response);
populateRequestMap(facesContext, model);
JsfUtils.notifyBeforeListeners(PhaseId.RESTORE_VIEW, facesLifecycle, facesContext);
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
if (isAtLeastJsf12() && (!isPortletRequest(facesContext))) {
viewHandler.initView(facesContext);
}
UIViewRoot viewRoot = viewHandler.createView(facesContext, getUrl());
Assert.notNull(viewRoot, "A JSF view could not be created for " + getUrl());
viewRoot.setLocale(RequestContextUtils.getLocale(request));
viewRoot.setTransient(true);
facesContext.setViewRoot(viewRoot);
JsfUtils.notifyAfterListeners(PhaseId.RESTORE_VIEW, facesLifecycle, facesContext);
facesContext.setViewRoot(viewRoot);
facesContext.renderResponse();
try {
logger.debug("Asking faces lifecycle to render");
facesLifecycle.render(facesContext);
} finally {
logger.debug("View rendering complete");
facesContextHelper.releaseIfNecessary();
}
}
private void populateRequestMap(FacesContext facesContext, Map<String, Object> model) {
- facesContext.getExternalContext().getRequestMap().putAll(model);
+ Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
+ for (Map.Entry<String, Object> entry : model.entrySet()) {
+ // JSF does not insist that putAll is implemented, hence we use individual put calls
+ requestMap.put(entry.getKey(), entry.getValue());
+ }
}
private Lifecycle createFacesLifecycle() {
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
return lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
}
}
| true | false | null | null |
diff --git a/src/be/ibridge/kettle/core/database/Database.java b/src/be/ibridge/kettle/core/database/Database.java
index cc511844..5357a1db 100644
--- a/src/be/ibridge/kettle/core/database/Database.java
+++ b/src/be/ibridge/kettle/core/database/Database.java
@@ -1,3824 +1,3824 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import org.eclipse.core.runtime.IProgressMonitor;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Counter;
import be.ibridge.kettle.core.DBCache;
import be.ibridge.kettle.core.DBCacheEntry;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Result;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleDatabaseBatchException;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.dimensionlookup.DimensionLookupMeta;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database
{
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_pun;
private PreparedStatement pstmt_dup;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private Row rowinfo;
private int written;
private LogWriter log;
/**
* Counts the number of rows written to a batch.
*/
private int batchCounter;
/**
* Construnct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
pstmt = null;
rsmd = null;
rowinfo = null;
dbmd = null;
rowlimit=0;
written=0;
log.logDetailed(toString(), "New database connection defined");
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect()
throws KettleDatabaseException
{
try
{
if (databaseMeta!=null)
{
connect(databaseMeta.getDriverClass());
log.logDetailed(toString(), "Connected to database.");
}
else
{
throw new KettleDatabaseException("No valid database connection defined!");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connect(String classname)
throws KettleDatabaseException
{
// Install and load the jdbc Driver
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
connection = DriverManager.getConnection(databaseMeta.getURL(), databaseMeta.getUsername(), databaseMeta.getPassword());
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public void disconnect()
{
try
{
if (connection==null) return ; // Nothing to do...
if (connection.isClosed()) return ; // Nothing to do...
if (!isAutoCommit()) commit();
if (pstmt !=null) { pstmt.close(); pstmt=null; }
if (prepStatementLookup!=null) { prepStatementLookup.close(); prepStatementLookup=null; }
if (prepStatementInsert!=null) { prepStatementInsert.close(); prepStatementInsert=null; }
if (prepStatementUpdate!=null) { prepStatementUpdate.close(); prepStatementUpdate=null; }
if (pstmt_seq!=null) { pstmt_seq.close(); pstmt_seq=null; }
if (connection !=null) { connection.close(); connection=null; }
log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
}
}
public void cancelQuery() throws KettleDatabaseException
{
try
{
if (pstmt !=null)
{
pstmt.cancel();
}
if (sel_stmt !=null)
{
sel_stmt.cancel();
}
log.logDetailed(toString(), "Open query canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling query", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit()
throws KettleDatabaseException
{
try
{
if (getDatabaseMetaData().supportsTransactions())
{
connection.commit();
}
else
{
log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback()
throws KettleDatabaseException
{
try
{
if (getDatabaseMetaData().supportsTransactions())
{
connection.rollback();
}
else
{
log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param r The row to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(Row r, String table)
throws KettleDatabaseException
{
if (r.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(table, r);
log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
try
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(Row r)
throws KettleDatabaseException
{
setValues(r, pstmt);
}
public void setValuesInsert(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementInsert);
}
public void setValuesUpdate(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementUpdate);
}
public void setValuesLookup(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementLookup);
}
public void setProcValues(Row r, int argnrs[], String argdir[], boolean result)
throws KettleDatabaseException
{
int i;
int pos;
if (result) pos=2; else pos=1;
for (i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN"))
{
Value v=r.getValue(argnrs[i]);
setValue(cstmt, v, pos);
pos++;
}
}
}
public void setValue(PreparedStatement ps, Value v, int pos)
throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case Value.VALUE_TYPE_BIGNUMBER:
debug="BigNumber";
if (!v.isNull())
{
ps.setBigDecimal(pos, v.getBigNumber());
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case Value.VALUE_TYPE_NUMBER :
debug="Number";
if (!v.isNull())
{
double num = v.getNumber();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
num = Const.round(num, v.getPrecision());
}
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case Value.VALUE_TYPE_INTEGER:
debug="Integer";
if (!v.isNull())
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, Math.round( v.getNumber() ) );
}
else
{
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, v.getNumber() );
}
else
{
ps.setDouble(pos, Const.round( v.getNumber(), v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.BIGINT);
}
break;
case Value.VALUE_TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (!v.isNull() && v.getString()!=null)
{
ps.setString(pos, v.getString());
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (!v.isNull())
{
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = v.getStringLength();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = v.getString().substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case Value.VALUE_TYPE_DATE :
debug="Date";
// VALUE_TYPE_DATE: Date with Time component.
if (!v.isNull() && v.getDate()!=null)
{
long dat = v.getDate().getTime();
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
- java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
- ps.setTimestamp(pos, sdate);
+ java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
+ ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
- ps.setNull(pos, java.sql.Types.TIME);
+ ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case Value.VALUE_TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (!v.isNull())
{
ps.setBoolean(pos, v.getBoolean());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (!v.isNull())
{
ps.setString(pos, v.getBoolean()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
default:
debug="default";
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
// Sets the values of the preparedStatement pstmt.
public void setValues(Row r, PreparedStatement ps)
throws KettleDatabaseException
{
int i;
Value v;
// now set the values in the row!
for (i=0;i<r.size();i++)
{
v=r.getValue(i);
try
{
//System.out.println("Setting value ["+v+"] on preparedStatement, position="+i);
setValue(ps, v, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+r, e);
}
}
}
public void setDimValues(Row r, Value dateval)
throws KettleDatabaseException
{
setDimValues(r, dateval, prepStatementLookup);
}
// Sets the values of the preparedStatement pstmt.
public void setDimValues(Row r, Value dateval, PreparedStatement ps)
throws KettleDatabaseException
{
int i;
Value v;
long dat;
// now set the values in the row!
for (i=0;i<r.size();i++)
{
v=r.getValue(i);
try
{
setValue(ps, v, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("Unable to set value #"+i+" on dimension using row :"+r, e);
}
}
if (dateval!=null && dateval.getDate()!=null && !dateval.isNull())
{
dat = dateval.getDate().getTime();
}
else
{
Calendar cal=Calendar.getInstance(); // use system date!
dat = cal.getTime().getTime();
}
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
try
{
ps.setTimestamp(r.size()+1, sdate); // ? > date_from
ps.setTimestamp(r.size()+2, sdate); // ? <= date_to
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to set timestamp on fromdate or todate", ex);
}
}
public void dimUpdate(Row row,
String table,
String fieldlookup[],
int fieldnrs[],
String returnkey,
Value dimkey
)
throws KettleDatabaseException
{
int i;
if (pstmt_dup==null) // first time: construct prepared statement
{
// Construct the SQL statement...
/*
* UPDATE d_customer
* SET fieldlookup[] = row.getValue(fieldnrs)
* WHERE returnkey = dimkey
* ;
*/
String sql="UPDATE "+table+Const.CR+"SET ";
for (i=0;i<fieldlookup.length;i++)
{
if (i>0) sql+=", "; else sql+=" ";
sql+=fieldlookup[i]+" = ?"+Const.CR;
}
sql+="WHERE "+returnkey+" = ?";
try
{
log.logDebug(toString(), "Preparing statement: ["+sql+"]");
pstmt_dup=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Coudln't prepare statement :"+Const.CR+sql, ex);
}
}
// Assemble information
// New
Row rupd=new Row();
for (i=0;i<fieldnrs.length;i++)
{
rupd.addValue( row.getValue(fieldnrs[i]));
}
rupd.addValue( dimkey );
setValues(rupd, pstmt_dup);
insertRow(pstmt_dup);
}
// This inserts new record into dimension
// Optionally, if the entry already exists, update date range from previous version
// of the entry.
//
public void dimInsert(Row row,
String table,
boolean newentry,
String keyfield,
boolean autoinc,
Value technicalKey,
String versionfield,
Value val_version,
String datefrom,
Value val_datfrom,
String dateto,
Value val_datto,
String fieldlookup[],
int fieldnrs[],
String key[],
String keylookup[],
int keynrs[]
)
throws KettleDatabaseException
{
int i;
if (prepStatementInsert==null && prepStatementUpdate==null) // first time: construct prepared statement
{
/* Construct the SQL statement...
*
* INSERT INTO
* d_customer(keyfield, versionfield, datefrom, dateto, key[], fieldlookup[])
* VALUES (val_key ,val_version , val_datfrom, val_datto, keynrs[], fieldnrs[])
* ;
*/
String sql="INSERT INTO "+table+"( ";
if (!autoinc) sql+=keyfield+", "; // NO AUTOINCREMENT
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_INFORMIX) sql+="0, "; // placeholder on informix!
sql+=versionfield+", "+datefrom+", "+dateto;
for (i=0;i<keylookup.length;i++)
{
sql+=", "+keylookup[i];
}
for (i=0;i<fieldlookup.length;i++)
{
sql+=", "+fieldlookup[i];
}
sql+=") VALUES(";
if (!autoinc) sql+="?, ";
sql+="?, ?, ?";
for (i=0;i<keynrs.length;i++)
{
sql+=", ?";
}
for (i=0;i<fieldnrs.length;i++)
{
sql+=", ?";
}
sql+=" )";
try
{
if (keyfield==null)
{
log.logDetailed(toString(), "SQL w/ return keys=["+sql+"]");
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
log.logDetailed(toString(), "SQL=["+sql+"]");
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql));
}
//pstmt=con.prepareStatement(sql, new String[] { "klant_tk" } );
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension insert :"+Const.CR+sql, ex);
}
/*
* UPDATE d_customer
* SET dateto = val_datnow
* WHERE keylookup[] = keynrs[]
* AND versionfield = val_version - 1
* ;
*/
String sql_upd="UPDATE "+table+Const.CR+"SET "+dateto+" = ?"+Const.CR;
sql_upd+="WHERE ";
for (i=0;i<keylookup.length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=keylookup[i]+" = ?"+Const.CR;
}
sql_upd+="AND "+versionfield+" = ? ";
try
{
log.logDetailed(toString(), "Preparing update: "+Const.CR+sql+Const.CR);
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension update :"+Const.CR+sql, ex);
}
}
Row rins=new Row();
if (!autoinc) rins.addValue(technicalKey);
if (!newentry)
{
Value val_new_version = new Value(val_version);
val_new_version.setValue( val_new_version.getNumber()+1 ); // determine next version
rins.addValue(val_new_version);
}
else
{
rins.addValue(val_version);
}
rins.addValue(val_datfrom);
rins.addValue(val_datto);
for (i=0;i<keynrs.length;i++)
{
rins.addValue( row.getValue(keynrs[i]));
}
for (i=0;i<fieldnrs.length;i++)
{
Value val = row.getValue(fieldnrs[i]);
rins.addValue( val );
}
log.logDebug(toString(), "rins, size="+rins.size()+", values="+rins.toString());
// INSERT NEW VALUE!
setValues(rins, prepStatementInsert);
insertRow(prepStatementInsert);
log.logDebug(toString(), "Row inserted!");
if (keyfield==null)
{
try
{
ResultSet keys=prepStatementInsert.getGeneratedKeys(); // 1 key
if (keys.next()) technicalKey.setValue(keys.getLong(1));
else
{
throw new KettleDatabaseException("Unable to retrieve technical key value from auto-increment field : "+keyfield+", no fields in resultset.");
}
keys.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to retrieve technical key value from auto-increment field : "+keyfield, ex);
}
}
if (!newentry) // we have to update the previous version in the dimension!
{
/*
* UPDATE d_customer
* SET dateto = val_datfrom
* WHERE keylookup[] = keynrs[]
* AND versionfield = val_version - 1
* ;
*/
Row rupd = new Row();
rupd.addValue(val_datfrom);
for (i=0;i<keynrs.length;i++)
{
rupd.addValue( row.getValue(keynrs[i]));
}
rupd.addValue(val_version);
log.logRowlevel(toString(), "UPDATE using rupd="+rupd.toString());
// UPDATE VALUES
setValues(rupd, prepStatementUpdate); // set values for update
log.logDebug(toString(), "Values set for update ("+rupd.size()+")");
insertRow(prepStatementUpdate); // do the actual update
log.logDebug(toString(), "Row updated!");
}
}
// This updates all versions of a dimension entry.
//
public void dimPunchThrough(Row row,
String table,
int fieldupdate[],
String fieldlookup[],
int fieldnrs[],
String key[],
String keylookup[],
int keynrs[]
)
throws KettleDatabaseException
{
int i;
boolean first;
if (pstmt_pun==null) // first time: construct prepared statement
{
/*
* UPDATE table
* SET punchv1 = fieldx, ...
* WHERE keylookup[] = keynrs[]
* ;
*/
String sql_upd="UPDATE "+table+Const.CR;
sql_upd+="SET ";
first=true;
for (i=0;i<fieldlookup.length;i++)
{
if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
if (!first) sql_upd+=", "; else sql_upd+=" ";
first=false;
sql_upd+=fieldlookup[i]+" = ?"+Const.CR;
}
}
sql_upd+="WHERE ";
for (i=0;i<keylookup.length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=keylookup[i]+" = ?"+Const.CR;
}
try
{
pstmt_pun=connection.prepareStatement(databaseMeta.stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension punchThrough update statement : "+Const.CR+sql_upd, ex);
}
}
Row rupd=new Row();
for (i=0;i<fieldlookup.length;i++)
{
if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
rupd.addValue( row.getValue(fieldnrs[i]));
}
}
for (i=0;i<keynrs.length;i++)
{
rupd.addValue( row.getValue(keynrs[i]));
}
// UPDATE VALUES
setValues(rupd, pstmt_pun); // set values for update
insertRow(pstmt_pun); // do the actual update
}
// This inserts new record into dimension
// Optionally, if the entry already exists, update date range from previous version
// of the entry.
//
public void combiInsert(Row row,
String table,
String keyfield,
boolean autoinc,
Value val_key,
String keylookup[],
int keynrs[],
boolean crc,
String crcfield,
Value val_crc
)
throws KettleDatabaseException
{
int i;
boolean comma;
if (prepStatementInsert==null) // first time: construct prepared statement
{
/* Construct the SQL statement...
*
* INSERT INTO
* d_test(keyfield, [crcfield,] keylookup[])
* VALUES(val_key, [val_crc], row values with keynrs[])
* ;
*/
String sql="INSERT INTO "+table+"( ";
comma=false;
if (!autoinc) // NO AUTOINCREMENT
{
sql+=keyfield;
comma=true;
}
else
if (databaseMeta.needsPlaceHolder())
{
sql+="0"; // placeholder on informix! Will be replaced in table by real autoinc value.
comma=true;
}
if (crc)
{
if (comma) sql+=", ";
sql+=crcfield;
comma=true;
}
for (i=0;i<keylookup.length;i++)
{
if (comma) sql+=", ";
sql+=keylookup[i];
comma=true;
}
sql+=") VALUES (";
comma=false;
if (keyfield!=null)
{
sql+="?";
comma=true;
}
if (crc)
{
if (comma) sql+=",";
sql+="?";
comma=true;
}
for (i=0;i<keylookup.length;i++)
{
if (comma) sql+=","; else comma=true;
sql+="?";
}
sql+=" )";
try
{
if (keyfield==null)
{
log.logDetailed(toString(), "SQL with return keys: "+sql);
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
log.logDetailed(toString(), "SQL without return keys: "+sql);
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sql, ex);
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sql, ex);
}
}
Row rins=new Row();
if (!autoinc) rins.addValue(val_key);
if (crc)
{
rins.addValue(val_crc);
}
for (i=0;i<keynrs.length;i++)
{
rins.addValue( row.getValue(keynrs[i]));
}
//log.logRowlevel("rins="+rins.toString());
// INSERT NEW VALUE!
setValues(rins, prepStatementInsert);
insertRow(prepStatementInsert);
if (keyfield==null)
{
try
{
ResultSet keys=pstmt.getGeneratedKeys(); // 1 key
if (keys.next()) val_key.setValue(keys.getDouble(1));
else
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield+", no fields in resultset");
}
keys.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex);
}
}
}
public Value getNextSequenceValue(String seq, String keyfield)
throws KettleDatabaseException
{
Value retval=null;
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(seq)));
}
ResultSet rs=pstmt_seq.executeQuery();
if (rs.next())
{
long next = rs.getLong(1);
retval=new Value(keyfield, next);
retval.setLength(9,0);
}
rs.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+seq, ex);
}
return retval;
}
public void insertRow(String tableName, Row fields)
throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, Row fields)
{
String ins="";
ins+="INSERT INTO "+tableName+"(";
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins+=", ";
String name = fields.getValue(i).getName();
ins+=databaseMeta.quoteField(name);
}
ins+=") VALUES (";
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins+=", ";
ins+=" ?";
}
ins+=")";
return ins;
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* @param batchCounter The batchCounter to set.
*/
public void setBatchCounter(int batchCounter)
{
this.batchCounter = batchCounter;
}
/**
* @return Returns the batchCounter.
*/
public int getBatchCounter()
{
return batchCounter;
}
private long testCounter = 0;
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commitsize)
* @throws KettleDatabaseException
*/
public void insertRow(PreparedStatement ps, boolean batch)
throws KettleDatabaseException
{
String debug="insertRow start";
try
{
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates();
//
// Add support for batch inserts...
//
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
batchCounter++;
ps.addBatch(); // Add the batch, but don't forget to run the batch
testCounter++;
// System.out.println("testCounter is at "+testCounter);
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
// System.out.println("EXECUTE BATCH, testcounter is at "+testCounter);
batchCounter=0;
}
else
{
debug="insertRow normal commit";
commit();
}
}
}
catch(BatchUpdateException ex)
{
//System.out.println("Batch update exception "+ex.getMessage());
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
throw kdbe;
}
catch(SQLException ex)
{
// System.out.println("SQLException: "+ex.getMessage());
throw new KettleDatabaseException("Error inserting row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
public void insertFinished(PreparedStatement ps, boolean batch)
throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0)
{
//System.out.println("Executing batch with "+batchCounter+" elements...");
ps.executeBatch();
commit();
}
else
{
commit();
}
}
ps.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql)
throws KettleDatabaseException
{
return execStatement(sql, null);
}
public Result execStatement(String sql, Row params)
throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
Statement stmt = connection.createStatement();
resultSet = stmt.execute(databaseMeta.stripCR(sql));
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// System.out.println("What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput((long) count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated((long) count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted((long) count);
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script)
throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat = all.substring(from, to);
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Row r = getRow(rs);
while (r!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
log.logDetailed(toString(), r.toString());
r=getRow(rs);
}
}
else
{
log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
}
else // any kind of statement
{
log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql)
throws KettleDatabaseException
{
return openQuery(sql, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, Row params)
throws KettleDatabaseException
{
return openQuery(sql, params, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, Row params, int fetch_mode)
throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params); // set the dates etc!
if (databaseMeta.isFetchSizeSupported() && ( pstmt.getMaxRows()>0 || databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES ) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
pstmt.setFetchSize(fs);
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>0)
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
sel_stmt.setFetchSize(fs);
debug = "Set fetch direction";
sel_stmt.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "Set max rows";
if (rowlimit>0) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get metadata";
rsmd = res.getMetaData();
debug = "openQuery : get rowinfo";
rowinfo = getRowInfo();
}
catch(SQLException ex)
{
log.logError(toString(), "ERROR executing ["+sql+"]");
log.logError(toString(), "ERROR in part: ["+debug+"]");
printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
public ResultSet openQuery(PreparedStatement ps, Row params)
throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, ps); // set the parameters!
if (databaseMeta.isFetchSizeSupported() && ps.getMaxRows()>0)
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
ps.setFetchSize(fs);
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ get metadata";
rsmd = res.getMetaData();
debug = "OQ getRowInfo()";
rowinfo = getRowInfo();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public Row getTableFields(String tablename)
throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public Row getQueryFields(String sql, boolean param)
throws KettleDatabaseException
{
return getQueryFields(sql, param, null);
}
/**
* See if the table specified exists by looking at the data dictionary!
* @param tablename The name of the table to check.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename)
throws KettleDatabaseException
{
try
{
log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName)
throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
try
{
//
// Get the info from the data dictionary...
//
String sql = databaseMeta.getSQLSequenceExists(sequenceName);
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+sequenceName+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tablename, String idx_fields[])
throws KettleDatabaseException
{
if (!checkTableExists(tablename)) return false;
log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
//
// Get the info from the data dictionary...
//
String sql = "select i.name table_name, c.name column_name ";
sql += "from sysindexes i, sysindexkeys k, syscolumns c ";
sql += "where i.name = '"+tablename+"' ";
sql += "AND i.id = k.id ";
sql += "AND i.id = c.id ";
sql += "AND k.colid = c.colid ";
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
while (row!=null)
{
String column = row.getString("column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
closeQuery(res);
}
else
{
return false;
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
//
// Get the info from the data dictionary...
//
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tablename.toUpperCase()+"'";
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
while (row!=null)
{
String column = row.getString("COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
closeQuery(res);
}
else
{
return false;
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
indexList.close(); }
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
indexList.close();
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
e.printStackTrace();
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+indexname+Const.CR+" ";
cr_index += "ON "+tablename+Const.CR;
cr_index += "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += idx_fields[i]+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.getIndexTablespace();
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
String cr_seq="";
if (sequence==null || sequence.length()==0) return cr_seq;
if (databaseMeta.supportsSequences())
{
cr_seq += "CREATE SEQUENCE "+sequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value>0) cr_seq += "MAXVALUE "+max_value+Const.CR;
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public Row getQueryFields(String sql, boolean param, Row inform)
throws KettleDatabaseException
{
Row fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
String debug="";
try
{
if (inform==null)
{
debug="inform==null";
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug="isFetchSizeSupported()";
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
debug = "Set fetchsize";
sel_stmt.setFetchSize(1); // Only one row needed!
}
debug = "Set max rows to 1";
sel_stmt.setMaxRows(1);
debug = "exec query";
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
debug = "getQueryFields get metadata";
rsmd = r.getMetaData();
debug = "getQueryFields get row info";
fields = getRowInfo();
debug="close resultset";
r.close();
debug="close statement";
sel_stmt.close();
sel_stmt=null;
}
else
{
debug="prepareStatement";
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
Row par = inform;
debug="getParameterMetaData()";
if (par==null) par = getParameterMetaData(ps);
debug="getParameterMetaData()";
if (par==null) par = getParameterMetaData(sql, inform);
setValues(par, ps);
}
debug="executeQuery()";
ResultSet r = ps.executeQuery();
debug="getMetaData";
rsmd = ps.getMetaData();
debug="getRowInfo";
fields=getRowInfo(rsmd);
debug="close resultset";
r.close();
debug="close preparedStatement";
ps.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR+"Location: "+debug, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Couldn't get field info in part ["+debug+"]", e);
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
public void closeQuery(ResultSet res)
throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
//
// Build the row using ResultSetMetaData rsmd
//
private Row getRowInfo(ResultSetMetaData rm)
throws KettleDatabaseException
{
int nrcols;
int i;
Value v;
String name;
int type, valtype;
int precision;
int length;
if (rm==null) return null;
rowinfo = new Row();
try
{
nrcols=rm.getColumnCount();
for (i=1;i<=nrcols;i++)
{
name=new String(rm.getColumnName(i));
type=rm.getColumnType(i);
valtype=Value.VALUE_TYPE_NONE;
length=-1;
precision=-1;
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=Value.VALUE_TYPE_STRING;
length=rm.getColumnDisplaySize(i);
// System.out.println("Display of "+name+" = "+precision);
// System.out.println("Precision of "+name+" = "+rm.getPrecision(i));
// System.out.println("Scale of "+name+" = "+rm.getScale(i));
break;
case java.sql.Types.CLOB:
valtype=Value.VALUE_TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
break;
case java.sql.Types.BIGINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
break;
case java.sql.Types.INTEGER:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=Value.VALUE_TYPE_NUMBER;
length=rm.getPrecision(i);
precision=rm.getScale(i);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (precision==0 && length<18 && length>0) valtype=Value.VALUE_TYPE_INTEGER;
if (length>18 || precision>18) valtype=Value.VALUE_TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision<=0 && length<=0) // undefined size: BIGNUMBER
{
valtype=Value.VALUE_TYPE_BIGNUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=Value.VALUE_TYPE_DATE;
break;
case java.sql.Types.BOOLEAN:
valtype=Value.VALUE_TYPE_BOOLEAN;
break;
default:
valtype=Value.VALUE_TYPE_STRING;
length=rm.getPrecision(i);
precision=rm.getScale(i);
break;
}
// comment=rm.getColumnLabel(i);
// TODO: change this hack!
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ACCESS)
{
if (valtype==Value.VALUE_TYPE_INTEGER)
{
valtype=Value.VALUE_TYPE_NUMBER;
length = -1;
precision = -1;
}
}
v=new Value(name, valtype);
v.setLength(length, precision);
rowinfo.addValue(v);
}
return rowinfo;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
//
// Build the row using ResultSetMetaData rsmd
//
private Row getRowInfo()
throws KettleDatabaseException
{
return getRowInfo(rsmd);
}
public boolean absolute(ResultSet rs, int position)
throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows)
throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Row getRow(ResultSet rs)
throws KettleDatabaseException
{
Row row;
int nrcols, i;
Value val;
try
{
nrcols=rsmd.getColumnCount();
if (rs.next())
{
row=new Row();
for (i=0;i<nrcols;i++)
{
val=new Value(rowinfo.getValue(i)); // copy info from meta-data.
switch(val.getType())
{
case Value.VALUE_TYPE_BOOLEAN : val.setValue( rs.getBoolean(i+1) ); break;
case Value.VALUE_TYPE_NUMBER : val.setValue( rs.getDouble(i+1) ); break;
case Value.VALUE_TYPE_BIGNUMBER : val.setValue( rs.getBigDecimal(i+1) ); break;
case Value.VALUE_TYPE_INTEGER : val.setValue( rs.getLong(i+1) ); break;
case Value.VALUE_TYPE_STRING : val.setValue( rs.getString(i+1) ); break;
case Value.VALUE_TYPE_DATE :
if (databaseMeta.supportsTimeStampToDateConversion())
{
val.setValue( rs.getTimestamp(i+1) ); break;
}
else
{
val.setValue( rs.getDate(i+1) ); break;
}
default: break;
}
if (rs.wasNull()) val.setNull(); // null value!
row.addValue(val);
}
}
else
{
row=null;
}
return row;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
// Lookup certain fields in a table
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby)
throws KettleDatabaseException
{
String sql;
int i;
sql = "SELECT ";
for (i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += gets[i];
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+rename[i];
}
}
sql += " FROM "+table+" WHERE ";
for (i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
// Lookup certain fields in a table
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
String sql;
int i;
sql = "UPDATE "+table+Const.CR+"SET ";
for (i=0;i<sets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(sets[i]);
sql+=" = ?"+Const.CR;
}
sql += "WHERE ";
for (i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
int i;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (returnvalue!=null)
{
switch(returntype)
{
case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
/*
* table: dimension table
* keys[]: which dim-fields do we use to look up key?
* retval: name of the key to return
* datefield: do we have a datefield?
* datefrom, dateto: date-range, if any.
*/
public boolean setDimLookup(String table,
String keys[],
String tk,
String version,
String extra[],
String extraRename[],
String datefrom,
String dateto
)
throws KettleDatabaseException
{
String sql;
int i;
/*
* SELECT <tk>, <version>, ...
* FROM <table>
* WHERE key1=keys[1]
* AND key2=keys[2] ...
* AND <datefield> BETWEEN <datefrom> AND <dateto>
* ;
*
*/
sql = "SELECT "+tk+", "+version;
if (extra!=null)
{
for (i=0;i<extra.length;i++)
{
if (extra[i]!=null && extra[i].length()!=0)
{
sql+=", "+extra[i];
if (extraRename[i]!=null &&
extraRename[i].length()>0 &&
!extra[i].equals(extraRename[i]))
{
sql+=" AS "+extraRename[i];
}
}
}
}
sql+= " FROM "+table+" WHERE ";
for (i=0;i<keys.length;i++)
{
if (i!=0) sql += " AND ";
sql += keys[i]+" = ? ";
}
sql += " AND ? >= "+datefrom+" AND ? < "+dateto;
try
{
log.logDetailed(toString(), "Dimension Lookup setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
log.logDetailed(toString(), "Finished preparing dimension lookup statement.");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension lookup", ex);
}
return true;
}
/* CombinationLookup
* table: dimension table
* keys[]: which dim-fields do we use to look up key?
* retval: name of the key to return
*/
public void setCombiLookup(String table,
String keys[],
String retval,
boolean crc,
String crcfield
)
throws KettleDatabaseException
{
String sql;
int i;
boolean comma;
/*
* SELECT <retval>
* FROM <table>
* WHERE ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* ...
* ;
*
* OR
*
* SELECT <retval>
* FROM <table>
* WHERE <crcfield> = ?
* AND ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* ...
* ;
*
*/
sql = "SELECT "+retval+Const.CR+"FROM "+table+Const.CR+"WHERE ";
comma=false;
if (crc)
{
sql+=crcfield+" = ? "+Const.CR;
comma=true;
}
else
{
sql+="( ( ";
}
for (i=0;i<keys.length;i++)
{
if (comma)
{
sql += " AND ( ( ";
}
else
{
comma=true;
}
sql += keys[i]+" = ? ) OR ( "+keys[i]+" IS NULL AND ? IS NULL ) )"+Const.CR;
}
try
{
log.logDebug(toString(), "preparing combi-lookup statement:"+Const.CR+sql);
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare combi-lookup statement", ex);
}
}
public Row callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype)
throws KettleDatabaseException
{
Row ret;
try
{
cstmt.execute();
ret=new Row();
int pos=1;
if (resultname!=null && resultname.length()!=0)
{
Value v=new Value(resultname, Value.VALUE_TYPE_NONE);
switch(resulttype)
{
case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos) ); break;
case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos) ); break;
case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos)); break;
case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos) ); break;
case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos) ); break;
case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos) ); break;
}
ret.addValue(v);
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
Value v=new Value(arg[i], Value.VALUE_TYPE_NONE);
switch(argtype[i])
{
case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos+i) ); break;
case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos+i) ); break;
case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos+i)); break;
case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos+i) ); break;
case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos+i) ); break;
case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos+i) ); break;
}
ret.addValue(v);
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
public Row getLookup()
throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Row getLookup(PreparedStatement ps)
throws KettleDatabaseException
{
String debug = "start";
Row ret;
try
{
debug = "pstmt.executeQuery()";
ResultSet res = ps.executeQuery();
debug = "res.getMetaData";
rsmd = res.getMetaData();
debug = "getRowInfo()";
rowinfo = getRowInfo();
debug = "getRow(res)";
ret=getRow(res);
debug = "res.close()";
res.close(); // close resultset!
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex);
}
}
public DatabaseMetaData getDatabaseMetaData()
throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, Row fields)
throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk)
throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.replaceReservedWords(fields);
if (checkTableExists(tablename))
{
retval=getAlterTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon);
}
return retval;
}
public String getCreateTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tablename+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
Value v=fields.getValue(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
Row tabFields = getTableFields(tablename);
// Find the missing fields
Row missing = new Row();
for (int i=0;i<fields.size();i++)
{
Value v = fields.getValue(i);
// Not found?
if (tabFields.searchValue( v.getName() )==null )
{
missing.addValue(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
Value v=missing.getValue(i);
retval+=databaseMeta.getAddColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
Row surplus = new Row();
for (int i=0;i<tabFields.size();i++)
{
Value v = tabFields.getValue(i);
// Found in table, not in input ?
if (fields.searchValue( v.getName() )==null )
{
surplus.addValue(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
Value v=surplus.getValue(i);
retval+=databaseMeta.getDropColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
//
// OK, see if there are fields for wich we need to modify the type... (length, precision)
//
Row modify = new Row();
for (int i=0;i<fields.size();i++)
{
Value desiredField = fields.getValue(i);
Value currentField = tabFields.searchValue( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValue(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
Value v=modify.getValue(i);
retval+=databaseMeta.getModifyColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void checkDimZero(String tablename, String tk, String version, boolean use_autoinc)
throws KettleDatabaseException
{
int start_tk = databaseMeta.getNotFoundTK(use_autoinc);
String sql = "SELECT count(*) FROM "+tablename+" WHERE "+tk+" = "+start_tk;
ResultSet rs = openQuery(sql, null);
Row r = getRow(rs); // One value: a number;
Value count = r.getValue(0);
if (count.getNumber() == 0)
{
try
{
Statement st = connection.createStatement();
String isql;
if (!databaseMeta.supportsAutoinc() || !use_autoinc)
{
isql = isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)";
}
else
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_CACHE :
case DatabaseMeta.TYPE_DATABASE_GUPTA :
case DatabaseMeta.TYPE_DATABASE_ORACLE : isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)"; break;
case DatabaseMeta.TYPE_DATABASE_INFORMIX :
case DatabaseMeta.TYPE_DATABASE_MYSQL : isql = "insert into "+tablename+"("+tk+", "+version+") values (1, 1)"; break;
case DatabaseMeta.TYPE_DATABASE_MSSQL :
case DatabaseMeta.TYPE_DATABASE_DB2 :
case DatabaseMeta.TYPE_DATABASE_DBASE :
case DatabaseMeta.TYPE_DATABASE_GENERIC :
case DatabaseMeta.TYPE_DATABASE_SYBASE :
case DatabaseMeta.TYPE_DATABASE_ACCESS : isql = "insert into "+tablename+"("+version+") values (1)"; break;
default: isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)"; break;
}
}
st.executeUpdate(databaseMeta.stripCR(isql));
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error inserting 'unknown' row in dimension ["+tablename+"] : "+sql, e);
}
}
}
public Value checkSequence(String seqname)
throws KettleDatabaseException
{
String sql=null;
if (databaseMeta.supportsSequences())
{
sql = databaseMeta.getSQLCurrentSequenceValue(seqname);
ResultSet rs = openQuery(sql, null);
Row r = getRow(rs); // One value: a number;
if (r!=null)
{
Value last = r.getValue(0);
// errorstr="Sequence is at number: "+last.toString();
return last;
}
else
{
return null;
}
}
else
{
throw new KettleDatabaseException("Sequences are only available for Oracle databases.");
}
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
execStatement(databaseMeta.getTruncateTableStatement(tablename));
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public Row getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, null);
if (rs!=null)
{
Row r = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return r;
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public Row getOneRow(String sql, Row param)
throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param);
if (rs!=null)
{
Row r = getRow(rs); // One value: a number;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return r;
}
else
{
return null;
}
}
public Row getParameterMetaData(PreparedStatement ps)
{
Row par = new Row();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
Value val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new Value(name, Value.VALUE_TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new Value(name, Value.VALUE_TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new Value(name, Value.VALUE_TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new Value(name, Value.VALUE_TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
val=new Value(name, Value.VALUE_TYPE_BOOLEAN);
break;
default:
val=new Value(name, Value.VALUE_TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new Value(name, Value.VALUE_TYPE_BIGNUMBER);
}
val.setNull();
par.addValue(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public Row getParameterMetaData(String sql, Row inform)
{
// The database coudln't handle it: try manually!
int q=countParameters(sql);
Row par=new Row();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
Value inf=inform.getValue(i);
Value v = new Value(inf);
par.addValue(v);
}
}
else
{
for (int i=0;i<q;i++)
{
Value v = new Value("name"+i, Value.VALUE_TYPE_NUMBER);
v.setValue( 0.0 );
par.addValue(v);
}
}
return par;
}
public static final Row getTransLogrecordFields(boolean use_batchid, boolean use_logfield)
{
Row r = new Row();
Value v;
if (use_batchid)
{
v=new Value("ID_BATCH", Value.VALUE_TYPE_INTEGER); v.setLength(8,0); r.addValue(v);
}
v=new Value("TRANSNAME", Value.VALUE_TYPE_STRING ); v.setLength(50); r.addValue(v);
v=new Value("STATUS", Value.VALUE_TYPE_STRING ); v.setLength(15); r.addValue(v);
v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("REPLAYDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
if (use_logfield)
{
v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING);
v.setLength(DatabaseMeta.CLOB_LENGTH,0);
r.addValue(v);
}
return r;
}
public static final Row getJobLogrecordFields(boolean use_jobid, boolean use_logfield)
{
Row r = new Row();
Value v;
if (use_jobid)
{
v=new Value("ID_JOB", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v);
}
v=new Value("JOBNAME", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v);
v=new Value("STATUS", Value.VALUE_TYPE_STRING); v.setLength(15); r.addValue(v);
v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
if (use_logfield)
{
v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING);
v.setLength(DatabaseMeta.CLOB_LENGTH,0);
r.addValue(v);
}
return r;
}
public void writeLogRecord( String logtable,
boolean use_id,
long id,
boolean job,
String name,
String status,
long read, long written, long updated,
long input, long output, long errors,
java.util.Date startdate, java.util.Date enddate,
java.util.Date logdate, java.util.Date depdate,
java.util.Date replayDate,
String log_string
)
throws KettleDatabaseException
{
if (!job && use_id && log_string!=null && !status.equalsIgnoreCase("start"))
{
String sql = "UPDATE "+logtable+" SET STATUS=?, LINES_READ=?, LINES_WRITTEN=?, LINES_INPUT=?," +
" LINES_OUTPUT=?, LINES_UPDATED=?, ERRORS=?, STARTDATE=?, ENDDATE=?, LOGDATE=?, DEPDATE=?, REPLAYDATE=?, LOG_FIELD=? " +
"WHERE ID_BATCH=?";
Row r = new Row();
r.addValue( new Value("STATUS", status ));
r.addValue( new Value("LINES_READ", (long)read ));
r.addValue( new Value("LINES_WRITTEN", (long)written));
r.addValue( new Value("LINES_INPUT", (long)input ));
r.addValue( new Value("LINES_OUTPUT", (long)output ));
r.addValue( new Value("LINES_UPDATED", (long)updated));
r.addValue( new Value("ERRORS", (long)errors ));
r.addValue( new Value("STARTDATE", startdate ));
r.addValue( new Value("ENDDATE", enddate ));
r.addValue( new Value("LOGDATE", logdate ));
r.addValue( new Value("DEPDATE", depdate ));
r.addValue( new Value("REPLAYDATE", replayDate ));
Value logfield = new Value("LOG_FIELD", log_string);
logfield.setLength(DatabaseMeta.CLOB_LENGTH);
r.addValue( logfield );
r.addValue( new Value("ID_BATCH", id ));
execStatement(sql, r);
}
else
{
int parms;
String sql = "INSERT INTO "+logtable+" ( ";
if (job)
{
if (use_id)
{
sql+="ID_JOB, JOBNAME";
parms=14;
}
else
{
sql+="JOBNAME";
parms=13;
}
}
else
{
if (use_id)
{
sql+="ID_BATCH, TRANSNAME";
parms=14;
}
else
{
sql+="TRANSNAME";
parms=13;
}
}
sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE, REPLAYDATE";
if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB!
sql+=") VALUES(";
for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?";
if (log_string!=null && log_string.length()>0) sql+=", ?";
sql+=")";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
Row r = new Row();
if (job)
{
if (use_id)
{
r.addValue( new Value("ID_BATCH", id ));
}
r.addValue( new Value("TRANSNAME", name ));
}
else
{
if (use_id)
{
r.addValue( new Value("ID_JOB", id ));
}
r.addValue( new Value("JOBNAME", name ));
}
r.addValue( new Value("STATUS", status ));
r.addValue( new Value("LINES_READ", (long)read ));
r.addValue( new Value("LINES_WRITTEN", (long)written));
r.addValue( new Value("LINES_UPDATED", (long)updated));
r.addValue( new Value("LINES_INPUT", (long)input ));
r.addValue( new Value("LINES_OUTPUT", (long)output ));
r.addValue( new Value("ERRORS", (long)errors ));
r.addValue( new Value("STARTDATE", startdate ));
r.addValue( new Value("ENDDATE", enddate ));
r.addValue( new Value("LOGDATE", logdate ));
r.addValue( new Value("DEPDATE", depdate ));
r.addValue( new Value("REPLAYDATE", replayDate ));
if (log_string!=null && log_string.length()>0)
{
Value large = new Value("LOG_FIELD", log_string );
large.setLength(DatabaseMeta.CLOB_LENGTH);
r.addValue( large );
}
setValues(r);
pstmt.executeUpdate();
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex);
}
}
}
public Row getLastLogDate( String logtable,
String name,
boolean job,
String status
)
throws KettleDatabaseException
{
Row row=null;
String jobtrans = job?"JOBNAME":"TRANSNAME";
String sql = "";
sql+=" SELECT ENDDATE, DEPDATE, STARTDATE";
sql+=" FROM "+logtable;
sql+=" WHERE ERRORS = 0";
sql+=" AND STATUS = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
Row r = new Row();
r.addValue( new Value("TRANSNAME", name ));
setValues(r);
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rsmd = res.getMetaData();
rowinfo = getRowInfo();
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized void getNextValue(TransMeta transMeta, String table, Value val_key)
throws KettleDatabaseException
{
String lookup = table+"."+val_key.getName();
// Try to find the previous sequence value...
Counter counter = (Counter)transMeta.getCounters().get(lookup);
if (counter==null)
{
Row r = getOneRow("SELECT MAX("+val_key.getName()+") FROM "+table);
if (r!=null)
{
counter = new Counter(r.getValue(0).getInteger()+1, 1);
val_key.setValue(counter.next());
transMeta.getCounters().put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+table);
}
}
else
{
val_key.setValue(counter.next());
}
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
int i=0;
boolean stop=false;
ArrayList result = new ArrayList();
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Row row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
public ArrayList getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
public ArrayList getFirstRows(String table_name, int limit, IProgressMonitor monitor)
throws KettleDatabaseException
{
String sql = "SELECT * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public Row getReturnRow()
{
return rowinfo;
}
public String[] getTableTypes()
throws KettleDatabaseException
{
try
{
ArrayList types = new ArrayList();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return (String[])types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames()
throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got table from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getViews()
throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got view from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getSynonyms()
throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got view from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
ArrayList procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Row)procs.get(i)).getValue(0).getString();
}
return str;
}
return null;
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
String sql = databaseMeta.getSQLLockTables(tableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
String sql = databaseMeta.getSQLUnlockTables(tableNames);
if (sql!=null)
{
execStatement(sql);
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/engine/hu/mentlerd/hybrid/lib/StringLib.java b/engine/hu/mentlerd/hybrid/lib/StringLib.java
index e9c26bd..731664f 100644
--- a/engine/hu/mentlerd/hybrid/lib/StringLib.java
+++ b/engine/hu/mentlerd/hybrid/lib/StringLib.java
@@ -1,334 +1,340 @@
package hu.mentlerd.hybrid.lib;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hu.mentlerd.hybrid.CallFrame;
import hu.mentlerd.hybrid.Callable;
import hu.mentlerd.hybrid.LuaClosure;
import hu.mentlerd.hybrid.LuaException;
import hu.mentlerd.hybrid.LuaTable;
import hu.mentlerd.hybrid.LuaThread;
import hu.mentlerd.hybrid.LuaUtil;
public enum StringLib implements Callable{
SUB {
public int call(CallFrame frame, int argCount) {
String string = frame.getArg(0, String.class);
int start = frame.getIntArg(1);
int limit = frame.getIntArg(2, string.length());
//Magic negative start/limit
int len = string.length();
if ( start < 0 )
start = Math.max(len + start +1, 1);
else if ( start == 0 )
start = 1;
if ( limit < 0 )
limit = Math.max(limit + len +1, 0);
else if ( limit > len )
limit = len;
//substring
if ( start > limit )
frame.push("");
else
frame.push( string.substring(start -1, limit) );
return 1;
}
},
CHAR {
public int call(CallFrame frame, int argCount) {
StringBuilder sb = new StringBuilder();
for ( int index = 0; index < argCount; index++ )
sb.append((char) frame.getIntArg(index));
frame.push( sb.toString() );
return 1;
}
},
BYTE {
public int call(CallFrame frame, int argCount) {
String string = frame.getArg(0, String.class);
int start = frame.getIntArg(1, 1);
int limit = frame.getIntArg(2, 1);
//Magic negative start/limit
int len = string.length();
if ( start < 0 )
start = start + len +1;
if ( start <= 0 )
start = 1;
if ( limit < 0 )
limit = limit + len +1;
else if ( limit > len )
limit = len;
//chars
int chars = limit - start +1;
if ( chars <= 0 )
return 0;
frame.setTop(chars);
for ( int index = 0; index < chars; index++ )
frame.set(index, Double.valueOf( string.charAt(index + start -1) ));
return chars;
}
},
LOWER {
public int call(CallFrame frame, int argCount) {
String string = frame.getArg(0, String.class);
frame.push( string.toLowerCase() );
return 1;
}
},
UPPER {
public int call(CallFrame frame, int argCount) {
String string = frame.getArg(0, String.class);
frame.push( string.toUpperCase() );
return 1;
}
},
REVERSE {
public int call(CallFrame frame, int argCount) {
String string = frame.getArg(0, String.class);
string = new StringBuilder(string).reverse().toString();
frame.push(string);
return 1;
}
},
LEN {
public int call(CallFrame frame, int argCount) {
String string = frame.getArg(0, String.class);
frame.push( string.length() );
return 1;
}
},
REP {
public int call(CallFrame frame, int argCount) {
String rep = frame.getArg(0, String.class);
int count = frame.getIntArg(1);
StringBuilder sb = new StringBuilder(rep);
for ( int index = 1; index < count; index++ )
sb.append(rep);
frame.push( sb.toString() );
return 1;
}
},
FORMAT {
public int call(CallFrame frame, int argCount) {
throw new LuaException("unimplemented string.format");
}
},
FIND {
public int call(CallFrame frame, int argCount) {
return find(frame, argCount, true);
}
},
MATCH {
public int call(CallFrame frame, int argCount) {
return find(frame, argCount, false);
}
},
GMATCH {
public int call(CallFrame frame, int argCount) {
String string = frame.getArg(0, String.class);
String pattern = frame.getArg(1, String.class);
frame.push( new MatchIterator(string, pattern) );
return 1;
}
},
GSUB {
public int call(CallFrame frame, int argCount) {
String string = frame.getArg(0, String.class);
String pattern = frame.getArg(1, String.class);
Object object = frame.getArg(2);
int limit = frame.getIntArg(3, Integer.MAX_VALUE);
if ( !( object instanceof String || object instanceof LuaClosure ||
object instanceof Callable || object instanceof LuaTable ) ){
throw LuaUtil.argError(2, "string/function/table expected");
}
LuaThread thread = frame.getThread();
- Pattern finder = Pattern.compile(pattern);
+ Pattern finder = compile(pattern);
Matcher matcher = finder.matcher(string);
StringBuilder sb = new StringBuilder();
int index = 0;
int last = 0;
while( index < limit ){ //Iterate over
if ( !matcher.find() )
break;
//Append inner parts
int start = matcher.start();
if ( last < start )
sb.append( string.substring(last, start) );
last = matcher.end();
//Replace
String replace = LuaUtil.rawToString(object);
if ( replace == null ){
String match = matcher.group();
Object value = null;
if ( object instanceof LuaTable )
value = ((LuaTable) object).rawget(match);
else
value = thread.call(object, match);
if ( value == null )
replace = match;
else
replace = LuaUtil.rawToString(value);
}
sb.append(replace);
}
//Append the ending
sb.append( string.substring(last) );
frame.push( sb.toString() );
return 1;
}
};
+ protected static Pattern compile( String pattern ){
+ pattern = pattern.replace("\\", "\\\\").replace('%', '\\');
+
+ return Pattern.compile(pattern);
+ }
+
protected static final String SPECIALS = "^$*+?.([%-";
protected static boolean hasSpecials( String pattern ){
for ( int index = 0; index < pattern.length(); index++ ){
if ( SPECIALS.indexOf( pattern.charAt(index) ) != -1 )
return true;
}
return false;
}
protected static int find(CallFrame frame, int argCount, boolean isFind){
String string = frame.getArg(0, String.class);
String pattern = frame.getArg(1, String.class);
int init = frame.getIntArg(2, 1) -1;
int len = string.length();
boolean plain = LuaUtil.toBoolean( frame.getArg(3, Boolean.FALSE) );
//Magic negative limit
if ( init < 0 )
init = Math.max( init + len, 0 );
else if ( init > len )
init = len;
//Do plain search on request, or no specials
if ( isFind && ( plain || !hasSpecials(pattern) ) ){
int pos = string.indexOf(pattern, init);
if ( pos > -1 ){
frame.push(pos);
frame.push(pos + string.length());
return 2;
}
} else {
if ( init != 0 )
string = string.substring(init);
- Pattern finder = Pattern.compile(pattern.replace('%', '\\'));
+ Pattern finder = compile(pattern);
Matcher matcher = finder.matcher(string);
if ( matcher.find() ){
int rets = matcher.groupCount();
if ( isFind ){ //Push region in before matches
frame.push( matcher.start() );
frame.push( matcher.end() );
rets += 2;
} else {
frame.push( matcher.group() );
rets += 1;
}
for ( int index = 0; index < matcher.groupCount(); index++ ) //Push groups
frame.push( matcher.group(index +1) );
return rets;
}
}
frame.push( null );
return 1;
}
protected static class MatchIterator implements Callable{
protected Matcher matcher;
public MatchIterator( String string, String pattern ){
- Pattern finder = Pattern.compile(pattern.replace('%', '\\'));
+ Pattern finder = compile(pattern);
this.matcher = finder.matcher(string);
}
public int call(CallFrame frame, int argCount) {
if ( matcher.find() ){
int groups = matcher.groupCount();
if ( groups == 0 ){
frame.push( matcher.group() ); //Push the matched region
return 1;
} else {
for ( int index = 0; index < groups; index++ ) //Push groups
frame.push( matcher.group(index +1) );
return groups;
}
} else {
frame.push(null);
return 1;
}
}
}
public static LuaTable bind(){
return bind( new LuaTable() );
}
public static LuaTable bind( LuaTable into ){
for ( StringLib entry : values() )
into.rawset(entry.name().toLowerCase(), entry);
return into;
}
}
| false | false | null | null |
diff --git a/src/main/de/roderick/weberknecht/WebSocketHandshake.java b/src/main/de/roderick/weberknecht/WebSocketHandshake.java
index 59cab6a..030469c 100644
--- a/src/main/de/roderick/weberknecht/WebSocketHandshake.java
+++ b/src/main/de/roderick/weberknecht/WebSocketHandshake.java
@@ -1,118 +1,118 @@
/*
* Copyright (C) 2012 Roderick Baier
*
* 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 de.roderick.weberknecht;
import java.net.URI;
import java.util.HashMap;
import org.apache.commons.codec.binary.Base64;
public class WebSocketHandshake
{
private URI url = null;
private String origin = null;
private String protocol = null;
private String nonce = null;
public WebSocketHandshake(URI url, String protocol, String origin)
{
this.url = url;
this.protocol = protocol;
this.origin = origin;
- this.nonce = this.createNone();
+ this.nonce = this.createNonce();
}
public byte[] getHandshake()
{
String path = url.getPath();
String host = url.getHost();
if (url.getPort() != -1) {
host += ":" + url.getPort();
}
String handshake = "GET " + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
"Sec-WebSocket-Version: " + WebSocket.getVersion() + "\r\n" +
"Sec-WebSocket-Key: " + this.nonce + "\r\n";
if (this.protocol != null) {
handshake += "Sec-WebSocket-Protocol: " + this.protocol + "\r\n";
}
if (this.origin != null) {
handshake += "Origin: " + this.origin + "\r\n";
}
handshake += "\r\n";
byte[] handshakeBytes = new byte[handshake.getBytes().length];
System.arraycopy(handshake.getBytes(), 0, handshakeBytes, 0, handshake.getBytes().length);
return handshakeBytes;
}
- private String createNone() {
+ private String createNonce() {
byte[] nonce = new byte[16];
for (int i = 0; i < 16; i++) {
nonce[i] = (byte) rand(0, 255);
}
return Base64.encodeBase64String(nonce);
}
public void verifyServerStatusLine(String statusLine)
throws WebSocketException
{
int statusCode = Integer.valueOf(statusLine.substring(9, 12));
if (statusCode == 407) {
throw new WebSocketException("connection failed: proxy authentication not supported");
}
else if (statusCode == 404) {
throw new WebSocketException("connection failed: 404 not found");
}
else if (statusCode != 101) {
throw new WebSocketException("connection failed: unknown status code " + statusCode);
}
}
public void verifyServerHandshakeHeaders(HashMap<String, String> headers)
throws WebSocketException
{
if (!headers.get("Upgrade").toLowerCase().equals("websocket")) {
throw new WebSocketException("connection failed: missing header field in server handshake: Upgrade");
}
else if (!headers.get("Connection").equals("Upgrade")) {
throw new WebSocketException("connection failed: missing header field in server handshake: Connection");
}
}
private int rand(int min, int max)
{
int rand = (int) (Math.random() * max + min);
return rand;
}
}
| false | false | null | null |
diff --git a/org.eclipse.riena.core/src/org/eclipse/riena/core/injector/extension/CreateLazy.java b/org.eclipse.riena.core/src/org/eclipse/riena/core/injector/extension/CreateLazy.java
index f38ecd1d0..31a88a0b8 100644
--- a/org.eclipse.riena.core/src/org/eclipse/riena/core/injector/extension/CreateLazy.java
+++ b/org.eclipse.riena.core/src/org/eclipse/riena/core/injector/extension/CreateLazy.java
@@ -1,33 +1,37 @@
/*******************************************************************************
* Copyright (c) 2007, 2011 compeople AG 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:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.core.injector.extension;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a <i>creator</i> method so that the returned instance is a proxy
- * instead of the real object. The real object will be created lazily on demand.<br>
+ * instead of the real object. The real object will be created lazily on demand,
+ * i.e. its first usage.<br>
+ * The first usage can also be generated while debugging because the debugger
+ * calls toString() on it!! This might result in undesired side effects.
+ * <p>
* <b>Note:</b> This requires that the executable extension object implements an
- * interface that is compatible to the return type of the <i>create</i> method.
+ * interface that is compatible to the return type of the <i>create</i> method.<br>
*
* <pre>
* @CreateLazy()
* ISomething createSomething();
* </pre>
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CreateLazy {
}
| false | false | null | null |
diff --git a/src/net/avs234/iconifiedlist/IconifiedTextListAdapter.java b/src/net/avs234/iconifiedlist/IconifiedTextListAdapter.java
index ff6a9b2..5ec9eae 100644
--- a/src/net/avs234/iconifiedlist/IconifiedTextListAdapter.java
+++ b/src/net/avs234/iconifiedlist/IconifiedTextListAdapter.java
@@ -1,63 +1,70 @@
package net.avs234.iconifiedlist;
import java.util.ArrayList;
import java.util.List;
import net.avs234.R;
import android.content.Context;
+import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/** @author Steven Osborn - http://steven.bitsetters.com */
public class IconifiedTextListAdapter extends BaseAdapter {
LayoutInflater factory;
-
+ View newView;
+
+ TextView txtView;
+ ImageView imgView;
+
/** Remember our context so we can use it when constructing views. */
private Context mContext;
private List<IconifiedText> mItems = new ArrayList<IconifiedText>();
public IconifiedTextListAdapter(Context context) {
mContext = context;
factory = LayoutInflater.from(context);
+
}
public void addItem(IconifiedText it) { mItems.add(it); }
public void setListItems(List<IconifiedText> lit) { mItems = lit; }
/** @return The number of items in the */
public int getCount() { return mItems.size(); }
public Object getItem(int position) { return mItems.get(position); }
public boolean areAllItemsSelectable() { return false; }
public boolean isSelectable(int position) {
return mItems.get(position).isSelectable();
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
/** @param convertView The old view to overwrite, if one is passed
* @returns a IconifiedTextView that holds wraps around an IconifiedText */
public View getView(int position, View convertView, ViewGroup parent) {
-
- View newView = factory.inflate(R.layout.row, null);
-
- TextView txtView = (TextView)newView.findViewById(R.id.title);
+ if(convertView == null) {
+ newView = factory.inflate(R.layout.row, null);
+ } else {
+ newView = convertView;
+ }
+ txtView = (TextView)newView.findViewById(R.id.title);
txtView.setText(mItems.get(position).getText());
-
- ImageView imgView = (ImageView)newView.findViewById(R.id.icon);
+ imgView = (ImageView)newView.findViewById(R.id.icon);
imgView.setImageDrawable(mItems.get(position).getIcon());
-
+
return newView;
}
}
| false | false | null | null |
diff --git a/EscapeIR-Android/src/fr/umlv/escape/gesture/GestureDetector.java b/EscapeIR-Android/src/fr/umlv/escape/gesture/GestureDetector.java
index b063b78..6f23699 100644
--- a/EscapeIR-Android/src/fr/umlv/escape/gesture/GestureDetector.java
+++ b/EscapeIR-Android/src/fr/umlv/escape/gesture/GestureDetector.java
@@ -1,339 +1,339 @@
package fr.umlv.escape.gesture;
import android.graphics.Point;
+import android.widget.Toast;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jbox2d.common.Vec2;
import fr.umlv.escape.Objects;
import fr.umlv.escape.game.Game;
import fr.umlv.escape.ship.Ship;
import fr.umlv.escape.world.EscapeWorld;
/** Static class that allow to detect gestures and calculate forces that they represent
*/
public class GestureDetector {
private final ArrayList<Point> pointList;
private final ArrayList<Gesture> gestureList;
private Ship playerShip;
Vec2 lastForce;
private final float SHOOT_SENSIBILITY;
private boolean mustShoot;
/**
* Enum that represent a gesture.
*/
public enum GestureType{
/**No gesture detected.
*/
NOT_DETECTED,
/**Bad gesture detected.
*/
NOT_GESTURE,
HORIZONTAL_LEFT,
/**Horizontal right detected.
*/
HORIZONTAL_RIGHT,
/**Cheat code detected.
*/
CHEAT_CODE,
/**Stats detected.
*/
STATS
}
/**
* Constructor.
*/
public GestureDetector(){
this.pointList=new ArrayList<Point>();
this.gestureList=new ArrayList<Gesture>();
this.playerShip = null;
this.SHOOT_SENSIBILITY = 3;
}
//
// /** Detect if a point list represent a horizontal line left or right.
// *
// * @param pointList the list of point used to detect the gesture.
// * @return True if the gesture is recognized else false.
// */
// private boolean isHorizontalLine(){
// Iterator<Point> iterPoint=pointList.iterator();
// Point firstPoint;
// Point previous;
//
// if(!iterPoint.hasNext()){
// return false;
// }
// previous=iterPoint.next();
// firstPoint=previous;
// int numOfPoint=1;
// Point tmp;
// while(iterPoint.hasNext()){
// tmp=iterPoint.next();
// if(tmp.y<(firstPoint.y-marginErrorBack) ||
// tmp.y>(firstPoint.y+marginErrorBack)){
// return false;
// }
// previous=tmp;
// numOfPoint++;
// }
// if(numOfPoint>minNumOfPoint){
// float forceX=(float)previous.x-firstPoint.x;
// if(forceX>0){
// this.lastDetected=GestureType.HORIZONTAL_RIGHT;
// }
// else{
// this.lastDetected=GestureType.HORIZONTAL_LEFT;
// }
// setLastForce(forceX,0f);
// return true;
// }
// return false;
// }
//
// /** Detect if a point list represent a cheat code.
// *
// * @param pointList the list of point used to detect the gesture.
// * @return True if the gesture is recognized else false.
// */
// private boolean isCheatCode(){
// Iterator<Point> iterPoint=pointList.iterator();
//
// Point previous;
// int stateOfDetection=0;
//
// previous=iterPoint.next();
// Point firstPoint=previous;
//
// if((firstPoint.x<width-150) || (firstPoint.y<height-150)){
// return false;
// }
// int numOfPoint=1;
// int badPoint=0;
// Point tmp;
// while(iterPoint.hasNext()){
// tmp=iterPoint.next();
// switch (stateOfDetection){
// case 0: // detect straight line to the left
// if(numOfPoint<5){
// if(tmp.y>firstPoint.y + marginErrorBack){
// return false;
// }
// }
// if((tmp.x>previous.x)||(tmp.y<firstPoint.y - marginErrorBack)){
// badPoint++;
// if(badPoint>10){
// return false;
// }
// }
// if(tmp.y>firstPoint.y + marginErrorBack){
// stateOfDetection++;
// firstPoint=previous;
// numOfPoint=0;
// }
// break;
// case 1: // detect back off
// if(numOfPoint<5){
// if(tmp.x>(firstPoint.x+marginErrorBack)){
// return false;
// }
// }
// if(tmp.y<previous.y || tmp.x<(firstPoint.x-marginErrorBack)){
// badPoint++;
// if(badPoint>10){
// return false;
// }
// }
// if(tmp.x>(firstPoint.x+marginErrorBack)){
// stateOfDetection++;
// numOfPoint=0;
// firstPoint=previous;
// }
// break;
// case 2: // detect straight line to the right
// if((tmp.x<previous.x)||(tmp.y<firstPoint.y - marginErrorBack)||(tmp.y>firstPoint.y + marginErrorBack)){
// badPoint++;
// if(badPoint>10){
// return false;
// }
// }
// break;
// default:
// return false;
// }
// previous=tmp;
// numOfPoint++;
// }
// if(stateOfDetection==2 && numOfPoint>5){
// lastDetected=GestureType.CHEAT_CODE;
// setLastForce(0f,0f);
// return true;
// }
// return false;
// }
//
// /** Detect if a point list represent a stat gesture.
// *
// * @param pointList the list of point used to detect the gesture.
// * @return True if the gesture is recognized else false.
// */
// private boolean isStats(){
// Iterator<Point> iterPoint=pointList.iterator();
// Point previous;
// int stateOfDetection=0;
//
// previous=iterPoint.next();
// Point firsPoint=previous;
// int numOfPoint=1;
// int badPoint=0;
// Point tmp;
//
// while(iterPoint.hasNext()){
// tmp=iterPoint.next();
// switch (stateOfDetection){
// case 0: // detect straight line to the right
// if(numOfPoint<5){
// if(tmp.y>firsPoint.y + marginErrorBack){
// return false;
// }
// }
// if((tmp.x<previous.x)||(tmp.y<firsPoint.y - marginErrorBack)){
// badPoint++;
// if(badPoint>10){
// return false;
// }
// }
// if(tmp.y>firsPoint.y + marginErrorBack){
// stateOfDetection++;
// firsPoint=previous;
// numOfPoint=0;
// }
// break;
// case 1: // detect back off
// if(numOfPoint<5){
// if(tmp.x<(firsPoint.x-marginErrorBack)){
// return false;
// }
// }
// if(tmp.y<previous.y || tmp.x>(firsPoint.x+marginErrorBack)){
// badPoint++;
// if(badPoint>10){
// return false;
// }
// }
// if(tmp.x<(firsPoint.x-marginErrorBack)){
// stateOfDetection++;
// numOfPoint=0;
// firsPoint=previous;
// }
// break;
// case 2: // detect straight line to the left
// if((tmp.x>previous.x)||(tmp.y<firsPoint.y - marginErrorBack)||(tmp.y>firsPoint.y + marginErrorBack)){
// badPoint++;
// if(badPoint>10){
// return false;
// }
// }
// break;
// default:
// return false;
// }
// previous=tmp;
// numOfPoint++;
// }
// if(stateOfDetection==2 && numOfPoint>5){
// lastDetected=GestureType.STATS;
// setLastForce(0f,0f);
// return true;
// }
// return false;
// }
/**
* Try to detect a gesture. You can get the gesture detected by calling {@link #getLastGestureDetected()}.
* @return true a gesture has been detected else false.
*/
public boolean detect(){
int size = gestureList.size();
if(this.playerShip==null) {
this.playerShip = Game.getTheGame().getPlayer1().getShip();
}
System.out.println(gestureList.size());
System.out.println(pointList.size());
System.out.println(this.playerShip);
if(mustShoot){
- //TODO tirer
-
+ System.out.println("SHHHHOOOOOTTTTTT");
mustShoot = false;
return false;
}
for(int i = 0; i < size; i++){
Gesture g = gestureList.get(i);
System.out.println(g.getClass().toString());
if(g.isRecognized(pointList)){
System.out.println("RECOGNIZED");
System.out.println(g.getClass().toString());
g.apply(this.playerShip);
return true;
}
}
return false;
}
/**
* Add a point to the gesture detector. When the method {@link #detectGesture()} will be called
* it will uses all the point added to detect a gesture.
* @param point
* @return true if the point could have been added else false.
*/
public boolean addPoint(Point point){
Objects.requireNonNull(point);
//If it is not the first point, the ship must follow the points
if(this.pointList.size()!=0){
Point last = pointList.get(pointList.size()-1);
Vec2 force = new Vec2(point.x-last.x,point.y-last.y);
//If the distance between two point is too high it is a shoot
if(force.x < SHOOT_SENSIBILITY && force.y < SHOOT_SENSIBILITY){
this.playerShip.body.setLinearVelocity(force);
} else {
this.mustShoot = true;
}
}
return this.pointList.add(point);
}
public boolean addGesture(Gesture gesture){
Objects.requireNonNull(gesture);
return this.gestureList.add(gesture);
}
/**
* Get the list of point added to the gesture detector.
* @return The list of point added to the gesture detector.
*/
public List<Point> getListPoint(){
return this.pointList;
}
/**
* Clear the gesture detector to an empty state with no point added and nothing detected.
*/
public void clear(){
this.pointList.clear();
if(this.lastForce != null){
this.lastForce.x = 0;
this.lastForce.y = 0;
}
}
public Vec2 getLastForce() {
return lastForce;
}
}
| false | false | null | null |
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.java
index 00a5ab7e..a7224f52 100755
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.java
@@ -1,172 +1,174 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2007 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.modifier;
import antlr.collections.AST;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
/**
* <p>
* Checks that the order of modifiers conforms to the suggestions in the
* <a
* href="http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html">
* Java Language specification, sections 8.1.1, 8.3.1 and 8.4.3</a>.
* The correct order is:</p>
<ol>
<li><span class="code">public</span></li>
<li><span class="code">protected</span></li>
<li><span class="code">private</span></li>
<li><span class="code">abstract</span></li>
<li><span class="code">static</span></li>
<li><span class="code">final</span></li>
<li><span class="code">transient</span></li>
<li><span class="code">volatile</span></li>
<li><span class="code">synchronized</span></li>
<li><span class="code">native</span></li>
<li><span class="code">strictfp</span></li>
</ol>
* In additional, modifiers are checked to ensure all annotations
* are declared before all other modifiers.
* <p>
* Rationale: Code is easier to read if everybody follows
* a standard.
* </p>
* <p>
* An example of how to configure the check is:
* </p>
* <pre>
* <module name="ModifierOrder"/>
* </pre>
* @author Lars K�hne
*/
public class ModifierOrderCheck
extends Check
{
/**
* The order of modifiers as suggested in sections 8.1.1,
* 8.3.1 and 8.4.3 of the JLS.
*/
private static final String[] JLS_ORDER =
{
"public", "protected", "private", "abstract", "static", "final",
"transient", "volatile", "synchronized", "native", "strictfp",
};
/** {@inheritDoc} */
+ @Override
public int[] getDefaultTokens()
{
return new int[] {TokenTypes.MODIFIERS};
}
/** {@inheritDoc} */
+ @Override
public void visitToken(DetailAST aAST)
{
- final List mods = new ArrayList();
+ final List<AST> mods = new ArrayList();
AST modifier = aAST.getFirstChild();
while (modifier != null) {
mods.add(modifier);
modifier = modifier.getNextSibling();
}
if (!mods.isEmpty()) {
final DetailAST error = checkOrderSuggestedByJLS(mods);
if (error != null) {
if (error.getType() == TokenTypes.ANNOTATION) {
log(error.getLineNo(), error.getColumnNo(),
"annotation.order",
error.getFirstChild().getText()
+ error.getFirstChild().getNextSibling()
.getText());
}
else {
log(error.getLineNo(), error.getColumnNo(),
"mod.order", error.getText());
}
}
}
}
/**
* Checks if the modifiers were added in the order suggested
* in the Java language specification.
*
* @param aModifiers list of modifier AST tokens
* @return null if the order is correct, otherwise returns the offending
* * modifier AST.
*/
DetailAST checkOrderSuggestedByJLS(List aModifiers)
{
int i = 0;
DetailAST modifier;
final Iterator it = aModifiers.iterator();
//No modifiers, no problems
if (!it.hasNext()) {
return null;
}
//Speed past all initial annotations
do {
modifier = (DetailAST) it.next();
}
while (it.hasNext() && (modifier.getType() == TokenTypes.ANNOTATION));
//All modifiers are annotations, no problem
if (modifier.getType() == TokenTypes.ANNOTATION) {
return null;
}
while (i < JLS_ORDER.length) {
if (modifier.getType() == TokenTypes.ANNOTATION) {
//Annotation not at start of modifiers, bad
return modifier;
}
while ((i < JLS_ORDER.length)
&& !JLS_ORDER[i].equals(modifier.getText()))
{
i++;
}
if (i == JLS_ORDER.length) {
//Current modifier is out of JLS order
return modifier;
}
else if (!it.hasNext()) {
//Reached end of modifiers without problem
return null;
}
else {
modifier = (DetailAST) it.next();
}
}
return modifier;
}
}
| false | false | null | null |
diff --git a/src/com/android/launcher2/FolderIcon.java b/src/com/android/launcher2/FolderIcon.java
index a09b6e04..78a9516f 100644
--- a/src/com/android/launcher2/FolderIcon.java
+++ b/src/com/android/launcher2/FolderIcon.java
@@ -1,111 +1,113 @@
/*
* 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.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.android.launcher.R;
/**
* An icon that can appear on in the workspace representing an {@link UserFolder}.
*/
public class FolderIcon extends BubbleTextView implements DropTarget {
private UserFolderInfo mInfo;
private Launcher mLauncher;
private Drawable mCloseIcon;
private Drawable mOpenIcon;
public FolderIcon(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FolderIcon(Context context) {
super(context);
}
static FolderIcon fromXml(int resId, Launcher launcher, ViewGroup group,
UserFolderInfo folderInfo) {
FolderIcon icon = (FolderIcon) LayoutInflater.from(launcher).inflate(resId, group, false);
final Resources resources = launcher.getResources();
Drawable d = resources.getDrawable(R.drawable.ic_launcher_folder);
icon.mCloseIcon = d;
icon.mOpenIcon = resources.getDrawable(R.drawable.ic_launcher_folder_open);
icon.setCompoundDrawablesWithIntrinsicBounds(null, d, null, null);
icon.setText(folderInfo.title);
icon.setTag(folderInfo);
icon.setOnClickListener(launcher);
icon.mInfo = folderInfo;
icon.mLauncher = launcher;
return icon;
}
public boolean acceptDrop(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
final ItemInfo item = (ItemInfo) dragInfo;
final int itemType = item.itemType;
return (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT)
&& item.container != mInfo.id;
}
public Rect estimateDropLocation(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo, Rect recycle) {
return null;
}
public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
ShortcutInfo item;
if (dragInfo instanceof ApplicationInfo) {
// Came from all apps -- make a copy
item = ((ApplicationInfo)dragInfo).makeShortcut();
} else {
item = (ShortcutInfo)dragInfo;
}
mInfo.add(item);
LauncherModel.addOrMoveItemInDatabase(mLauncher, item, mInfo.id, 0, 0, 0);
}
public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
- setCompoundDrawablesWithIntrinsicBounds(null, mOpenIcon, null, null);
+ if (acceptDrop(source, x, y, xOffset, yOffset, dragView, dragInfo)) {
+ setCompoundDrawablesWithIntrinsicBounds(null, mOpenIcon, null, null);
+ }
}
public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
}
public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
setCompoundDrawablesWithIntrinsicBounds(null, mCloseIcon, null, null);
}
@Override
public DropTarget getDropTargetDelegate(DragSource source, int x, int y, int xOffset, int yOffset,
DragView dragView, Object dragInfo) {
return null;
}
}
| true | false | null | null |
diff --git a/mmstudio/src/org/micromanager/acquisition/AcquisitionVirtualStack.java b/mmstudio/src/org/micromanager/acquisition/AcquisitionVirtualStack.java
index b062aa04f..33211b67b 100644
--- a/mmstudio/src/org/micromanager/acquisition/AcquisitionVirtualStack.java
+++ b/mmstudio/src/org/micromanager/acquisition/AcquisitionVirtualStack.java
@@ -1,184 +1,184 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.micromanager.acquisition;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import java.awt.image.ColorModel;
import mmcorej.TaggedImage;
import org.json.JSONObject;
import org.micromanager.api.TaggedImageStorage;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.ReportingUtils;
/**
* This stack class provides the ImagePlus with images from the MMImageCache.
*
*/
public class AcquisitionVirtualStack extends ij.VirtualStack {
final private TaggedImageStorage imageCache_;
final private VirtualAcquisitionDisplay acq_;
final protected int width_, height_, type_;
private int nSlices_;
private int positionIndex_ = 0;
public AcquisitionVirtualStack(int width, int height, int type,
ColorModel cm, TaggedImageStorage imageCache, int nSlices,
VirtualAcquisitionDisplay acq) {
super(width, height, cm, "");
imageCache_ = imageCache;
width_ = width;
height_ = height;
nSlices_ = nSlices;
acq_ = acq;
type_ = type;
}
public void setPositionIndex(int pos) {
positionIndex_ = pos;
}
public int getPositionIndex() {
return positionIndex_;
}
public VirtualAcquisitionDisplay getVirtualAcquisitionDisplay() {
return acq_;
}
public void setSize(int size) {
nSlices_ = size;
}
public TaggedImageStorage getCache() {
return imageCache_;
}
public TaggedImage getTaggedImage(int flatIndex) {
int[] pos;
// If we don't have the ImagePlus yet, then we need to assume
// we are on the very first image.
ImagePlus imagePlus = acq_.getImagePlus();
if (imagePlus == null) {
- return getTaggedImage(1,1,1);
+ return getTaggedImage(0,0,0);
} else {
pos = imagePlus.convertIndexToPosition(flatIndex);
}
int chanIndex = acq_.grayToRGBChannel(pos[0] - 1);
int frame = pos[2] - 1;
int slice = pos[1] - 1;
return getTaggedImage(chanIndex, slice, frame);
}
public TaggedImage getTaggedImage(int chanIndex, int slice, int frame) {
int nSlices;
ImagePlus imagePlus = acq_.getImagePlus();
if (imagePlus == null) {
nSlices = 1;
} else {
nSlices = imagePlus.getNSlices();
}
try {
TaggedImage img;
img = imageCache_.getImage(chanIndex, slice, frame, positionIndex_);
int backIndex = slice - 1, forwardIndex = slice + 1;
int frameSearchIndex = frame;
//If some but not all channels have z stacks, find the closest slice for the given
//channel that has an image. Also if time point missing, go back until image is found
while (img == null) {
img = imageCache_.getImage(chanIndex, slice, frameSearchIndex, positionIndex_);
if (img != null) {
break;
}
if (backIndex >= 0) {
img = imageCache_.getImage(chanIndex, backIndex, frameSearchIndex, positionIndex_);
if (img != null) {
break;
}
backIndex--;
}
if (forwardIndex < nSlices) {
img = imageCache_.getImage(chanIndex, forwardIndex, frameSearchIndex, positionIndex_);
if (img != null) {
break;
}
forwardIndex++;
}
if (backIndex < 0 && forwardIndex >= nSlices) {
frameSearchIndex--;
backIndex = slice - 1;
forwardIndex = slice + 1;
if (frameSearchIndex < 0) {
break;
}
}
}
return img;
} catch (Exception e) {
ReportingUtils.logError(e);
return null;
}
}
@Override
public Object getPixels(int flatIndex) {
Object pixels = null;
try {
TaggedImage image = getTaggedImage(flatIndex);
if (image == null) {
pixels = ImageUtils.makeProcessor(type_, width_, height_).getPixels();
} else if (MDUtils.isGRAY(image)) {
pixels = image.pix;
} else if (MDUtils.isRGB32(image)) {
pixels = ImageUtils.singleChannelFromRGB32((byte[]) image.pix, (flatIndex - 1) % 3);
} else if (MDUtils.isRGB64(image)) {
pixels = ImageUtils.singleChannelFromRGB64((short[]) image.pix, (flatIndex - 1) % 3);
}
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
return pixels;
}
@Override
public ImageProcessor getProcessor(int flatIndex) {
return ImageUtils.makeProcessor(type_, width_, height_, getPixels(flatIndex));
}
@Override
public int getSize() {
// returns the stack size of VirtualAcquisitionDisplay unless this size is -1
// which occurs in constructor while hyperImage_ is still null. In this case
// returns the number of slices speciefiec in AcquisitionVirtualStack constructor
int size = acq_.getStackSize();
if (size == -1) {
return nSlices_;
}
return size;
}
@Override
public String getSliceLabel(int n) {
TaggedImage img = getTaggedImage(n);
if (img == null) {
return "";
}
JSONObject md = img.tags;
try {
return md.get("Acquisition-PixelSizeUm") + " um/px";
//return MDUtils.getChannelName(md) + ", " + md.get("Acquisition-ZPositionUm") + " um(z), " + md.get("Acquisition-TimeMs") + " s";
} catch (Exception ex) {
return "";
}
}
}
| true | false | null | null |
diff --git a/com/imjake9/simplejail/SimpleJailCommandHandler.java b/com/imjake9/simplejail/SimpleJailCommandHandler.java
index c837ccb..6c79cd2 100644
--- a/com/imjake9/simplejail/SimpleJailCommandHandler.java
+++ b/com/imjake9/simplejail/SimpleJailCommandHandler.java
@@ -1,310 +1,311 @@
package com.imjake9.simplejail;
import com.imjake9.simplejail.SimpleJail.JailMessage;
import com.imjake9.simplejail.api.SimpleJailCommandListener;
import com.imjake9.simplejail.api.SimpleJailCommandListener.Priority;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class SimpleJailCommandHandler implements CommandExecutor {
private final SimpleJail plugin;
private Map<Priority, List<SimpleJailCommandListener>> commandListeners = new EnumMap<Priority, List<SimpleJailCommandListener>>(Priority.class);
public SimpleJailCommandHandler(SimpleJail plugin) {
this.plugin = plugin;
this.registerCommands();
}
private void registerCommands() {
plugin.getCommand("jail").setExecutor(this);
plugin.getCommand("unjail").setExecutor(this);
plugin.getCommand("setjail").setExecutor(this);
plugin.getCommand("setunjail").setExecutor(this);
plugin.getCommand("jailtime").setExecutor(this);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(commandLabel.equalsIgnoreCase("jail")) {
if(!hasPermission(sender, "simplejail.jail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.jail");
return true;
}
if (this.dispatchCommandToListeners(sender, commandLabel, args))
return true;
if (args.length != 1 && args.length != 2) return false;
// Catch JailExceptions
try {
// Jail/tempjail player:
if (args.length == 1)
plugin.jailPlayer(args[0]);
else {
int time = plugin.parseTimeString(args[1]);
plugin.jailPlayer(args[0], time);
}
} catch (JailException ex) {
// Send error message
sender.sendMessage(ex.getFormattedMessage());
return true;
}
// Send success message:
if (args.length == 1)
JailMessage.JAIL.send(sender, args[0]);
else
JailMessage.TEMPJAIL.send(sender, args[0], args[1]);
return true;
} else if(commandLabel.equalsIgnoreCase("unjail")) {
if(!hasPermission(sender, "simplejail.unjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.unjail");
return true;
}
if (this.dispatchCommandToListeners(sender, commandLabel, args))
return true;
if (args.length != 1) return false;
// Catch JailExceptions
try {
// Unjail player
plugin.unjailPlayer(args[0]);
} catch (JailException ex) {
// Send error message
sender.sendMessage(ex.getFormattedMessage());
return true;
}
// Send success message
JailMessage.UNJAIL.send(sender, args[0]);
return true;
} else if(commandLabel.equalsIgnoreCase("setjail")) {
if(!hasPermission(sender, "simplejail.setjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.setjail");
return true;
}
if (args.length != 0 && args.length != 4) return false;
// If not a player, only use explicit notation:
if (!(sender instanceof Player) && args.length != 4) {
JailMessage.ONLY_PLAYERS.send(sender);
return true;
}
Location loc;
// Use explicit vs current location:
if (args.length == 0) {
Player player = (Player)sender;
loc = player.getLocation();
} else {
// Check if passed coordinates are correct:
if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) {
JailMessage.INVALID_COORDINATE.send(sender);
return true;
}
// Set up Location value
loc = new Location(
plugin.getServer().getWorld(args[3]),
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
}
// Set the jail point
plugin.setJail(loc);
// Send success message
JailMessage.JAIL_POINT_SET.send(sender);
return true;
} else if(commandLabel.equalsIgnoreCase("setunjail")) {
if(!hasPermission(sender, "simplejail.setjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.setjail");
return true;
}
if (args.length != 0 && args.length != 4) return false;
// If not a player, only use explicit notation:
if (!(sender instanceof Player) && args.length != 4) {
JailMessage.ONLY_PLAYERS.send(sender);
return true;
}
Location loc;
// Use explicit vs current location:
if (args.length == 0) {
Player player = (Player)sender;
loc = player.getLocation();
} else {
// Check if passed coordinates are correct:
if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) {
JailMessage.INVALID_COORDINATE.send(sender);
return true;
}
// Set up Location value
loc = new Location(
plugin.getServer().getWorld(args[3]),
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
}
// Set the jail point
plugin.setUnjail(loc);
// Send success message
JailMessage.UNJAIL_POINT_SET.send(sender);
return true;
} else if(commandLabel.equalsIgnoreCase("jailtime")) {
if(!hasPermission(sender, "simplejail.jailtime")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.jailtime");
return true;
}
if (args.length > 1) return false;
// If not a player, a target must be explicit:
if (!(sender instanceof Player) && args.length == 0) {
JailMessage.MUST_SPECIFY_TARGET.send(sender);
return true;
}
// Get the target
Player player = (args.length == 0) ? (Player) sender : plugin.getServer().getPlayer(args[0]);
// Validate target:
if (player == null) {
JailMessage.PLAYER_NOT_FOUND.send(sender, args[0]);
return true;
}
if (!plugin.playerIsTempJailed(player)) {
JailMessage.NOT_TEMPJAILED.send(sender, (args.length == 0) ? sender.getName() : args[0]);
return true;
}
// Send success message:
int minutes = (int) ((plugin.getTempJailTime(player) - System.currentTimeMillis()) / 60000);
JailMessage.JAIL_TIME.send(sender, plugin.prettifyMinutes(minutes));
return true;
} else {
return false;
}
}
/**
* Checks any CommandSender for a permission node.
*
* @param sender
* @param permission
* @return
*/
private boolean hasPermission(CommandSender sender, String permission) {
if (sender instanceof Player)
return sender.hasPermission(permission);
else return true;
}
/**
* Dispatches a particular command to all listeners, ordered by priority.
*
* @param sender
* @param command
* @param args
* @return
*/
private boolean dispatchCommandToListeners(CommandSender sender, String command, String args[]) {
boolean handled = false;
execute:
for (Priority priority : commandListeners.keySet()) {
if (priority.equals(Priority.MONITOR)) break;
for (SimpleJailCommandListener listener : commandListeners.get(priority)) {
if (listener.handleJailCommand(sender, command, args)) {
handled = true;
break execute;
}
}
}
- for (SimpleJailCommandListener listener : commandListeners.get(Priority.MONITOR)) {
- listener.handleJailCommand(sender, command, args);
- }
+ if (commandListeners.containsKey(Priority.MONITOR))
+ for (SimpleJailCommandListener listener : commandListeners.get(Priority.MONITOR)) {
+ listener.handleJailCommand(sender, command, args);
+ }
return handled;
}
/**
* Registers a command listener.
*
* @param listener
* @param priority
*/
public void addListener(SimpleJailCommandListener listener, Priority priority) {
if (!commandListeners.containsKey(priority))
commandListeners.put(priority, new ArrayList<SimpleJailCommandListener>());
commandListeners.get(priority).add(listener);
}
/**
* Unregisters a command listener.
*
* @param listener
* @param priority
*/
public void removeListener(SimpleJailCommandListener listener, Priority priority) {
if (!commandListeners.containsKey(priority)) return;
if (!commandListeners.get(priority).contains(listener)) return;
commandListeners.get(priority).remove(listener);
}
}
| true | false | null | null |
diff --git a/src/com/android/providers/downloads/DownloadNotifier.java b/src/com/android/providers/downloads/DownloadNotifier.java
index df0bf84..0405478 100644
--- a/src/com/android/providers/downloads/DownloadNotifier.java
+++ b/src/com/android/providers/downloads/DownloadNotifier.java
@@ -1,366 +1,368 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.downloads;
import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE;
import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED;
import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION;
import static android.provider.Downloads.Impl.STATUS_RUNNING;
import static com.android.providers.downloads.Constants.TAG;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.SystemClock;
import android.provider.Downloads;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.util.LongSparseLongArray;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import javax.annotation.concurrent.GuardedBy;
/**
* Update {@link NotificationManager} to reflect current {@link DownloadInfo}
* states. Collapses similar downloads into a single notification, and builds
* {@link PendingIntent} that launch towards {@link DownloadReceiver}.
*/
public class DownloadNotifier {
private static final int TYPE_ACTIVE = 1;
private static final int TYPE_WAITING = 2;
private static final int TYPE_COMPLETE = 3;
private final Context mContext;
private final NotificationManager mNotifManager;
/**
* Currently active notifications, mapped from clustering tag to timestamp
* when first shown.
*
* @see #buildNotificationTag(DownloadInfo)
*/
@GuardedBy("mActiveNotifs")
private final HashMap<String, Long> mActiveNotifs = Maps.newHashMap();
/**
* Current speed of active downloads, mapped from {@link DownloadInfo#mId}
* to speed in bytes per second.
*/
@GuardedBy("mDownloadSpeed")
private final LongSparseLongArray mDownloadSpeed = new LongSparseLongArray();
/**
* Last time speed was reproted, mapped from {@link DownloadInfo#mId} to
* {@link SystemClock#elapsedRealtime()}.
*/
@GuardedBy("mDownloadSpeed")
private final LongSparseLongArray mDownloadTouch = new LongSparseLongArray();
public DownloadNotifier(Context context) {
mContext = context;
mNotifManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
}
public void cancelAll() {
mNotifManager.cancelAll();
}
/**
* Notify the current speed of an active download, used for calculating
* estimated remaining time.
*/
public void notifyDownloadSpeed(long id, long bytesPerSecond) {
synchronized (mDownloadSpeed) {
if (bytesPerSecond != 0) {
mDownloadSpeed.put(id, bytesPerSecond);
mDownloadTouch.put(id, SystemClock.elapsedRealtime());
} else {
mDownloadSpeed.delete(id);
mDownloadTouch.delete(id);
}
}
}
/**
* Update {@link NotificationManager} to reflect the given set of
* {@link DownloadInfo}, adding, collapsing, and removing as needed.
*/
public void updateWith(Collection<DownloadInfo> downloads) {
synchronized (mActiveNotifs) {
updateWithLocked(downloads);
}
}
private void updateWithLocked(Collection<DownloadInfo> downloads) {
final Resources res = mContext.getResources();
// Cluster downloads together
final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
for (DownloadInfo info : downloads) {
final String tag = buildNotificationTag(info);
if (tag != null) {
clustered.put(tag, info);
}
}
// Build notification for each cluster
for (String tag : clustered.keySet()) {
final int type = getNotificationTagType(tag);
final Collection<DownloadInfo> cluster = clustered.get(tag);
final Notification.Builder builder = new Notification.Builder(mContext);
// Use time when cluster was first shown to avoid shuffling
final long firstShown;
if (mActiveNotifs.containsKey(tag)) {
firstShown = mActiveNotifs.get(tag);
} else {
firstShown = System.currentTimeMillis();
mActiveNotifs.put(tag, firstShown);
}
builder.setWhen(firstShown);
// Show relevant icon
if (type == TYPE_ACTIVE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download);
} else if (type == TYPE_WAITING) {
builder.setSmallIcon(android.R.drawable.stat_sys_warning);
} else if (type == TYPE_COMPLETE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
}
// Build action intents
if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
+ // build a synthetic uri for intent identification purposes
+ final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
final Intent intent = new Intent(Constants.ACTION_LIST,
- null, mContext, DownloadReceiver.class);
+ uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
- builder.setContentIntent(PendingIntent.getBroadcast(
- mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
+ builder.setContentIntent(PendingIntent.getBroadcast(mContext,
+ 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
builder.setOngoing(true);
} else if (type == TYPE_COMPLETE) {
final DownloadInfo info = cluster.iterator().next();
final Uri uri = ContentUris.withAppendedId(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
final String action;
if (Downloads.Impl.isStatusError(info.mStatus)) {
action = Constants.ACTION_LIST;
} else {
if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
action = Constants.ACTION_OPEN;
} else {
action = Constants.ACTION_LIST;
}
}
final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
- builder.setContentIntent(PendingIntent.getBroadcast(
- mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
+ builder.setContentIntent(PendingIntent.getBroadcast(mContext,
+ 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
final Intent hideIntent = new Intent(Constants.ACTION_HIDE,
uri, mContext, DownloadReceiver.class);
builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
}
// Calculate and show progress
String remainingText = null;
String percentText = null;
if (type == TYPE_ACTIVE) {
long current = 0;
long total = 0;
long speed = 0;
synchronized (mDownloadSpeed) {
for (DownloadInfo info : cluster) {
if (info.mTotalBytes != -1) {
current += info.mCurrentBytes;
total += info.mTotalBytes;
speed += mDownloadSpeed.get(info.mId);
}
}
}
if (total > 0) {
final int percent = (int) ((current * 100) / total);
percentText = res.getString(R.string.download_percent, percent);
if (speed > 0) {
final long remainingMillis = ((total - current) * 1000) / speed;
remainingText = res.getString(R.string.download_remaining,
DateUtils.formatDuration(remainingMillis));
}
builder.setProgress(100, percent, false);
} else {
builder.setProgress(100, 0, true);
}
}
// Build titles and description
final Notification notif;
if (cluster.size() == 1) {
final DownloadInfo info = cluster.iterator().next();
builder.setContentTitle(getDownloadTitle(res, info));
if (type == TYPE_ACTIVE) {
if (!TextUtils.isEmpty(info.mDescription)) {
builder.setContentText(info.mDescription);
} else {
builder.setContentText(remainingText);
}
builder.setContentInfo(percentText);
} else if (type == TYPE_WAITING) {
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
} else if (type == TYPE_COMPLETE) {
if (Downloads.Impl.isStatusError(info.mStatus)) {
builder.setContentText(res.getText(R.string.notification_download_failed));
} else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
builder.setContentText(
res.getText(R.string.notification_download_complete));
}
}
notif = builder.build();
} else {
final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder);
for (DownloadInfo info : cluster) {
inboxStyle.addLine(getDownloadTitle(res, info));
}
if (type == TYPE_ACTIVE) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_active, cluster.size(), cluster.size()));
builder.setContentText(remainingText);
builder.setContentInfo(percentText);
inboxStyle.setSummaryText(remainingText);
} else if (type == TYPE_WAITING) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
inboxStyle.setSummaryText(
res.getString(R.string.notification_need_wifi_for_size));
}
notif = inboxStyle.build();
}
mNotifManager.notify(tag, 0, notif);
}
// Remove stale tags that weren't renewed
final Iterator<String> it = mActiveNotifs.keySet().iterator();
while (it.hasNext()) {
final String tag = it.next();
if (!clustered.containsKey(tag)) {
mNotifManager.cancel(tag, 0);
it.remove();
}
}
}
private static CharSequence getDownloadTitle(Resources res, DownloadInfo info) {
if (!TextUtils.isEmpty(info.mTitle)) {
return info.mTitle;
} else {
return res.getString(R.string.download_unknown_title);
}
}
private long[] getDownloadIds(Collection<DownloadInfo> infos) {
final long[] ids = new long[infos.size()];
int i = 0;
for (DownloadInfo info : infos) {
ids[i++] = info.mId;
}
return ids;
}
public void dumpSpeeds() {
synchronized (mDownloadSpeed) {
for (int i = 0; i < mDownloadSpeed.size(); i++) {
final long id = mDownloadSpeed.keyAt(i);
final long delta = SystemClock.elapsedRealtime() - mDownloadTouch.get(id);
Log.d(TAG, "Download " + id + " speed " + mDownloadSpeed.valueAt(i) + "bps, "
+ delta + "ms ago");
}
}
}
/**
* Build tag used for collapsing several {@link DownloadInfo} into a single
* {@link Notification}.
*/
private static String buildNotificationTag(DownloadInfo info) {
if (info.mStatus == Downloads.Impl.STATUS_QUEUED_FOR_WIFI) {
return TYPE_WAITING + ":" + info.mPackage;
} else if (isActiveAndVisible(info)) {
return TYPE_ACTIVE + ":" + info.mPackage;
} else if (isCompleteAndVisible(info)) {
// Complete downloads always have unique notifs
return TYPE_COMPLETE + ":" + info.mId;
} else {
return null;
}
}
/**
* Return the cluster type of the given tag, as created by
* {@link #buildNotificationTag(DownloadInfo)}.
*/
private static int getNotificationTagType(String tag) {
return Integer.parseInt(tag.substring(0, tag.indexOf(':')));
}
private static boolean isActiveAndVisible(DownloadInfo download) {
return download.mStatus == STATUS_RUNNING &&
(download.mVisibility == VISIBILITY_VISIBLE
|| download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
private static boolean isCompleteAndVisible(DownloadInfo download) {
return Downloads.Impl.isStatusCompleted(download.mStatus) &&
(download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED
|| download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
}
}
| false | true | private void updateWithLocked(Collection<DownloadInfo> downloads) {
final Resources res = mContext.getResources();
// Cluster downloads together
final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
for (DownloadInfo info : downloads) {
final String tag = buildNotificationTag(info);
if (tag != null) {
clustered.put(tag, info);
}
}
// Build notification for each cluster
for (String tag : clustered.keySet()) {
final int type = getNotificationTagType(tag);
final Collection<DownloadInfo> cluster = clustered.get(tag);
final Notification.Builder builder = new Notification.Builder(mContext);
// Use time when cluster was first shown to avoid shuffling
final long firstShown;
if (mActiveNotifs.containsKey(tag)) {
firstShown = mActiveNotifs.get(tag);
} else {
firstShown = System.currentTimeMillis();
mActiveNotifs.put(tag, firstShown);
}
builder.setWhen(firstShown);
// Show relevant icon
if (type == TYPE_ACTIVE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download);
} else if (type == TYPE_WAITING) {
builder.setSmallIcon(android.R.drawable.stat_sys_warning);
} else if (type == TYPE_COMPLETE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
}
// Build action intents
if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
final Intent intent = new Intent(Constants.ACTION_LIST,
null, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(
mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
builder.setOngoing(true);
} else if (type == TYPE_COMPLETE) {
final DownloadInfo info = cluster.iterator().next();
final Uri uri = ContentUris.withAppendedId(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
final String action;
if (Downloads.Impl.isStatusError(info.mStatus)) {
action = Constants.ACTION_LIST;
} else {
if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
action = Constants.ACTION_OPEN;
} else {
action = Constants.ACTION_LIST;
}
}
final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(
mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
final Intent hideIntent = new Intent(Constants.ACTION_HIDE,
uri, mContext, DownloadReceiver.class);
builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
}
// Calculate and show progress
String remainingText = null;
String percentText = null;
if (type == TYPE_ACTIVE) {
long current = 0;
long total = 0;
long speed = 0;
synchronized (mDownloadSpeed) {
for (DownloadInfo info : cluster) {
if (info.mTotalBytes != -1) {
current += info.mCurrentBytes;
total += info.mTotalBytes;
speed += mDownloadSpeed.get(info.mId);
}
}
}
if (total > 0) {
final int percent = (int) ((current * 100) / total);
percentText = res.getString(R.string.download_percent, percent);
if (speed > 0) {
final long remainingMillis = ((total - current) * 1000) / speed;
remainingText = res.getString(R.string.download_remaining,
DateUtils.formatDuration(remainingMillis));
}
builder.setProgress(100, percent, false);
} else {
builder.setProgress(100, 0, true);
}
}
// Build titles and description
final Notification notif;
if (cluster.size() == 1) {
final DownloadInfo info = cluster.iterator().next();
builder.setContentTitle(getDownloadTitle(res, info));
if (type == TYPE_ACTIVE) {
if (!TextUtils.isEmpty(info.mDescription)) {
builder.setContentText(info.mDescription);
} else {
builder.setContentText(remainingText);
}
builder.setContentInfo(percentText);
} else if (type == TYPE_WAITING) {
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
} else if (type == TYPE_COMPLETE) {
if (Downloads.Impl.isStatusError(info.mStatus)) {
builder.setContentText(res.getText(R.string.notification_download_failed));
} else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
builder.setContentText(
res.getText(R.string.notification_download_complete));
}
}
notif = builder.build();
} else {
final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder);
for (DownloadInfo info : cluster) {
inboxStyle.addLine(getDownloadTitle(res, info));
}
if (type == TYPE_ACTIVE) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_active, cluster.size(), cluster.size()));
builder.setContentText(remainingText);
builder.setContentInfo(percentText);
inboxStyle.setSummaryText(remainingText);
} else if (type == TYPE_WAITING) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
inboxStyle.setSummaryText(
res.getString(R.string.notification_need_wifi_for_size));
}
notif = inboxStyle.build();
}
mNotifManager.notify(tag, 0, notif);
}
// Remove stale tags that weren't renewed
final Iterator<String> it = mActiveNotifs.keySet().iterator();
while (it.hasNext()) {
final String tag = it.next();
if (!clustered.containsKey(tag)) {
mNotifManager.cancel(tag, 0);
it.remove();
}
}
}
| private void updateWithLocked(Collection<DownloadInfo> downloads) {
final Resources res = mContext.getResources();
// Cluster downloads together
final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
for (DownloadInfo info : downloads) {
final String tag = buildNotificationTag(info);
if (tag != null) {
clustered.put(tag, info);
}
}
// Build notification for each cluster
for (String tag : clustered.keySet()) {
final int type = getNotificationTagType(tag);
final Collection<DownloadInfo> cluster = clustered.get(tag);
final Notification.Builder builder = new Notification.Builder(mContext);
// Use time when cluster was first shown to avoid shuffling
final long firstShown;
if (mActiveNotifs.containsKey(tag)) {
firstShown = mActiveNotifs.get(tag);
} else {
firstShown = System.currentTimeMillis();
mActiveNotifs.put(tag, firstShown);
}
builder.setWhen(firstShown);
// Show relevant icon
if (type == TYPE_ACTIVE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download);
} else if (type == TYPE_WAITING) {
builder.setSmallIcon(android.R.drawable.stat_sys_warning);
} else if (type == TYPE_COMPLETE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
}
// Build action intents
if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
// build a synthetic uri for intent identification purposes
final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
final Intent intent = new Intent(Constants.ACTION_LIST,
uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(mContext,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
builder.setOngoing(true);
} else if (type == TYPE_COMPLETE) {
final DownloadInfo info = cluster.iterator().next();
final Uri uri = ContentUris.withAppendedId(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
final String action;
if (Downloads.Impl.isStatusError(info.mStatus)) {
action = Constants.ACTION_LIST;
} else {
if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
action = Constants.ACTION_OPEN;
} else {
action = Constants.ACTION_LIST;
}
}
final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(mContext,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
final Intent hideIntent = new Intent(Constants.ACTION_HIDE,
uri, mContext, DownloadReceiver.class);
builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
}
// Calculate and show progress
String remainingText = null;
String percentText = null;
if (type == TYPE_ACTIVE) {
long current = 0;
long total = 0;
long speed = 0;
synchronized (mDownloadSpeed) {
for (DownloadInfo info : cluster) {
if (info.mTotalBytes != -1) {
current += info.mCurrentBytes;
total += info.mTotalBytes;
speed += mDownloadSpeed.get(info.mId);
}
}
}
if (total > 0) {
final int percent = (int) ((current * 100) / total);
percentText = res.getString(R.string.download_percent, percent);
if (speed > 0) {
final long remainingMillis = ((total - current) * 1000) / speed;
remainingText = res.getString(R.string.download_remaining,
DateUtils.formatDuration(remainingMillis));
}
builder.setProgress(100, percent, false);
} else {
builder.setProgress(100, 0, true);
}
}
// Build titles and description
final Notification notif;
if (cluster.size() == 1) {
final DownloadInfo info = cluster.iterator().next();
builder.setContentTitle(getDownloadTitle(res, info));
if (type == TYPE_ACTIVE) {
if (!TextUtils.isEmpty(info.mDescription)) {
builder.setContentText(info.mDescription);
} else {
builder.setContentText(remainingText);
}
builder.setContentInfo(percentText);
} else if (type == TYPE_WAITING) {
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
} else if (type == TYPE_COMPLETE) {
if (Downloads.Impl.isStatusError(info.mStatus)) {
builder.setContentText(res.getText(R.string.notification_download_failed));
} else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
builder.setContentText(
res.getText(R.string.notification_download_complete));
}
}
notif = builder.build();
} else {
final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder);
for (DownloadInfo info : cluster) {
inboxStyle.addLine(getDownloadTitle(res, info));
}
if (type == TYPE_ACTIVE) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_active, cluster.size(), cluster.size()));
builder.setContentText(remainingText);
builder.setContentInfo(percentText);
inboxStyle.setSummaryText(remainingText);
} else if (type == TYPE_WAITING) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
inboxStyle.setSummaryText(
res.getString(R.string.notification_need_wifi_for_size));
}
notif = inboxStyle.build();
}
mNotifManager.notify(tag, 0, notif);
}
// Remove stale tags that weren't renewed
final Iterator<String> it = mActiveNotifs.keySet().iterator();
while (it.hasNext()) {
final String tag = it.next();
if (!clustered.containsKey(tag)) {
mNotifManager.cancel(tag, 0);
it.remove();
}
}
}
|
diff --git a/core/src/visad/trunk/util/ArrowSlider.java b/core/src/visad/trunk/util/ArrowSlider.java
index b0a51823d..6188f8839 100644
--- a/core/src/visad/trunk/util/ArrowSlider.java
+++ b/core/src/visad/trunk/util/ArrowSlider.java
@@ -1,336 +1,344 @@
/*
-@(#) $Id: ArrowSlider.java,v 1.13 2000-04-19 18:37:19 billh Exp $
+@(#) $Id: ArrowSlider.java,v 1.14 2000-04-20 14:33:02 billh Exp $
VisAD Utility Library: Widgets for use in building applications with
the VisAD interactive analysis and visualization library
Copyright (C) 1998 Nick Rasmussen
VisAD is Copyright (C) 1996 - 1998 Bill Hibbard, Curtis Rueden, Tom
Rink and Dave Glowacki.
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 1, 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 in file NOTICE for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package visad.util;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* A pointer slider for visad .
*
* @author Nick Rasmussen [email protected]
- * @version $Revision: 1.13 $, $Date: 2000-04-19 18:37:19 $
+ * @version $Revision: 1.14 $, $Date: 2000-04-20 14:33:02 $
* @since Visad Utility Library v0.7.1
*/
public class ArrowSlider extends Slider implements MouseListener, MouseMotionListener {
/** The upper bound */
private float upper;
/** The lower bound */
private float lower;
/** The current value */
private float val;
/** widget sizes */
Dimension minSize = null;
Dimension prefSize = null;
Dimension maxSize = null;
private Object lock = new Object();
/** Construct a new arrow slider with the default values */
public ArrowSlider() {
this(-1, 1, 0);
}
/**
* Construct a new arrow slider with the givden lower, upper and initial values
* @throws IllegalArgumenentException if lower is not less than initial or initial
* is not less than upper
*/
public ArrowSlider(float lower, float upper, float initial) {
this(lower, upper, initial, "value");
}
/**
* Construct a new arrow slider with the given lower, upper and initial values
* @throws IllegalArgumenentException if lower is not less than initial or initial
* is not less than upper
*/
public ArrowSlider(float lower, float upper, float initial, String name) {
if (lower > initial) {
throw new IllegalArgumentException("ArrowSlider: lower bound is greater than initial value");
}
if (initial > upper) {
throw new IllegalArgumentException("ArrowSlider: initial value is greater than the upper bound");
}
this.upper = upper;
this.lower = lower;
this.val = initial;
this.name = name;
this.addMouseListener(this);
this.addMouseMotionListener(this);
+// javax.swing.RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);
+// setDebugGraphicsOptions(javax.swing.DebugGraphics.LOG_OPTION);
+
}
/** For testing purposes */
public static void main(String[] argv) {
javax.swing.JFrame frame;
frame = new javax.swing.JFrame("Visad Arrow Slider");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
ArrowSlider a = new ArrowSlider();
frame.add(a);
frame.setSize(a.getPreferredSize());
frame.setVisible(true);
}
/* CTR: 29 Jul 1998: added setBounds method */
/** Sets new minimum, maximum, and initial values for this slider */
// public synchronized void setBounds(float min, float max, float init) {
public void setBounds(float min, float max, float init) {
synchronized (lock) {
if (min > max) {
throw new IllegalArgumentException("ArrowSlider: min cannot be "
+"greater than max");
}
if (init < min || init > max) {
throw new IllegalArgumentException("ArrowSlider: initial value "
+"must be between min and max");
}
lower = min;
upper = max;
val = init;
}
notifyListeners(new SliderChangeEvent(SliderChangeEvent.LOWER_CHANGE, min));
notifyListeners(new SliderChangeEvent(SliderChangeEvent.UPPER_CHANGE, max));
notifyListeners(new SliderChangeEvent(SliderChangeEvent.VALUE_CHANGE, init));
// redraw
validate();
repaint();
}
/** Return the minimum value of this slider */
public float getMinimum() {
return lower;
}
/** Sets the minimum value for this slider */
// public synchronized void setMinimum(float value) {
public void setMinimum(float value) {
synchronized (lock) {
if (value > val || (value == val && value == upper)) {
throw new IllegalArgumentException("ArrowSlider: Attemped to set new minimum value greater than the current value");
}
lower = value;
}
notifyListeners(new SliderChangeEvent(SliderChangeEvent.LOWER_CHANGE, value));
// redraw
validate();
repaint();
}
/** Return the maximum value of this slider */
public float getMaximum() {
return upper;
}
/** Sets the maximum value of this scrolbar */
// public synchronized void setMaximum(float value){
public void setMaximum(float value){
synchronized (lock) {
if (value < val || (value == val && value == lower)) {
throw new IllegalArgumentException("ArrowSlider: Attemped to set new maximum value less than the current value");
}
upper = value;
}
notifyListeners(new SliderChangeEvent(SliderChangeEvent.UPPER_CHANGE, value));
// redraw
validate();
repaint();
}
/** Returns the current value of the slider */
public float getValue() {
return val;
}
/**
* Sets the current value of the slider
* @throws IllegalArgumentException if the new value is out of bounds for the slider
*/
// public synchronized void setValue(float value) {
public void setValue(float value) {
synchronized (lock) {
if (value > upper || value < lower) {
throw new IllegalArgumentException("ArrowSlider: Attemped to set new value out of slider range");
}
val = value;
}
notifyListeners(new SliderChangeEvent(SliderChangeEvent.VALUE_CHANGE, value));
// redraw
validate();
repaint();
}
/** Return the preferred sise of the arrow slider */
public Dimension getPreferredSize() {
if (prefSize == null) {
prefSize = new Dimension(256, 16);
}
return prefSize;
}
/** Set the preferred size of the arrow slider */
public void setPreferredSize(Dimension dim) { prefSize = dim; }
/** Return the maximum size of the arrow slider */
public Dimension getMaximumSize() {
if (maxSize == null) {
maxSize = new Dimension(Integer.MAX_VALUE, 16);
}
return maxSize;
}
/** Set the preferred size of the arrow slider */
public void setMaximumSize(Dimension dim) { maxSize = dim; }
/** Return the minimum size of the arrow slider */
public Dimension getMinimumSize() {
if (minSize == null) {
minSize = new Dimension(40, 16);
}
return minSize;
}
/** Set the preferred size of the arrow slider */
public void setMinimumSize(Dimension dim) { minSize = dim; }
/** Present to implement MouseListener, currently ignored */
public void mouseClicked(MouseEvent e) {
//System.out.println(e.paramString());
}
/** Present to implement MouseListener, currently ignored */
public void mouseEntered(MouseEvent e) {
//System.out.println(e.paramString());
}
/** Present to implement MouseListener, currently ignored */
public void mouseExited(MouseEvent e) {
//System.out.println(e.paramString());
}
/** Moves the slider to the clicked position */
public void mousePressed(MouseEvent e) {
//System.out.println(e.paramString());
updatePosition(e);
}
/** Present to implement MouseListener, currently ignored */
public void mouseReleased(MouseEvent e) {
//System.out.println(e.paramString());
}
/** Updates the slider position */
public void mouseDragged(MouseEvent e) {
//System.out.println(e.paramString());
updatePosition(e);
}
/** Present to implement MouseMovementListener, currently ignored */
public void mouseMoved(MouseEvent e) {
//System.out.println(e.paramString());
}
/** Recalculate the position and value of the slider given the new mouse position */
private void updatePosition(MouseEvent e) {
int x = e.getX();
if (x < 0) x = 0;
if (x >= getBounds().width) x = getBounds().width - 1;
float dist = (float) x / (float) (getBounds().width - 1);
setValue(lower + dist*(upper - lower));
}
/** the last position where the arrow was drawn */
private int oldxval;
/** update the slider */
public void update(Graphics g) {
g.setColor(Color.black);
g.drawLine(oldxval, 0, oldxval, getBounds().height - 1);
g.drawLine(oldxval, 0, oldxval - 4, 4);
g.drawLine(oldxval, 0, oldxval + 4, 4);
g.setColor(Color.white);
int xval = (int) Math.floor((val - lower) * (getBounds().width - 1) / (upper - lower));
g.drawLine(xval, 0, xval, getBounds().height - 1);
g.drawLine(xval, 0, xval - 4, 4);
g.drawLine(xval, 0, xval + 4, 4);
oldxval = xval;
}
/** Redraw the slider */
public void paint(Graphics g) {
+// System.out.println("ArrowSlider.paint in");
+// Test66 hangs between ArrowSlider.paint in and out
+// but not with DebugGraphics in constructor
+
g.setColor(Color.black);
g.fillRect(0, 0, getBounds().width, getBounds().height);
g.setColor(Color.white);
int xval = (int) Math.floor((val - lower) * (getBounds().width - 1) / (upper - lower));
g.drawLine(xval, 0, xval, getBounds().height - 1);
g.drawLine(xval, 0, xval - 4, 4);
g.drawLine(xval, 0, xval + 4, 4);
oldxval = xval;
+// System.out.println("ArrowSlider.paint out");
}
}
| false | false | null | null |
diff --git a/onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/beans/itineraries/ItinerariesBeanServiceImpl.java b/onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/beans/itineraries/ItinerariesBeanServiceImpl.java
index 3819470e..3d23ffcc 100644
--- a/onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/beans/itineraries/ItinerariesBeanServiceImpl.java
+++ b/onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/beans/itineraries/ItinerariesBeanServiceImpl.java
@@ -1,904 +1,904 @@
package org.onebusaway.transit_data_federation.impl.beans.itineraries;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.ObjectUtils;
import org.onebusaway.exceptions.ServiceException;
import org.onebusaway.geospatial.model.CoordinatePoint;
import org.onebusaway.geospatial.model.EncodedPolylineBean;
import org.onebusaway.geospatial.services.PolylineEncoder;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.transit_data.model.ListBean;
import org.onebusaway.transit_data.model.StopBean;
import org.onebusaway.transit_data.model.schedule.FrequencyBean;
import org.onebusaway.transit_data.model.tripplanning.ConstraintsBean;
import org.onebusaway.transit_data.model.tripplanning.EdgeNarrativeBean;
import org.onebusaway.transit_data.model.tripplanning.ItinerariesBean;
import org.onebusaway.transit_data.model.tripplanning.ItineraryBean;
import org.onebusaway.transit_data.model.tripplanning.LegBean;
import org.onebusaway.transit_data.model.tripplanning.LocationBean;
import org.onebusaway.transit_data.model.tripplanning.StreetLegBean;
import org.onebusaway.transit_data.model.tripplanning.TransitLegBean;
import org.onebusaway.transit_data.model.tripplanning.VertexBean;
import org.onebusaway.transit_data.model.trips.TripBean;
import org.onebusaway.transit_data_federation.impl.beans.FrequencyBeanLibrary;
import org.onebusaway.transit_data_federation.impl.otp.AbstractStopVertex;
import org.onebusaway.transit_data_federation.impl.otp.ArrivalVertex;
import org.onebusaway.transit_data_federation.impl.otp.BlockArrivalVertex;
import org.onebusaway.transit_data_federation.impl.otp.BlockDepartureVertex;
import org.onebusaway.transit_data_federation.impl.otp.DepartureVertex;
import org.onebusaway.transit_data_federation.impl.otp.OTPConfiguration;
import org.onebusaway.transit_data_federation.impl.otp.RemainingWeightHeuristicImpl;
import org.onebusaway.transit_data_federation.impl.otp.WalkFromStopVertex;
import org.onebusaway.transit_data_federation.impl.otp.WalkToStopVertex;
import org.onebusaway.transit_data_federation.model.ShapePoints;
import org.onebusaway.transit_data_federation.model.narrative.StopTimeNarrative;
import org.onebusaway.transit_data_federation.services.ShapePointService;
import org.onebusaway.transit_data_federation.services.beans.ItinerariesBeanService;
import org.onebusaway.transit_data_federation.services.beans.StopBeanService;
import org.onebusaway.transit_data_federation.services.beans.TripBeanService;
import org.onebusaway.transit_data_federation.services.blocks.BlockInstance;
import org.onebusaway.transit_data_federation.services.narrative.NarrativeService;
import org.onebusaway.transit_data_federation.services.realtime.ArrivalAndDepartureInstance;
import org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.BlockStopTimeEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.BlockTripEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.StopEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.StopTimeEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.TripEntry;
import org.opentripplanner.routing.core.Edge;
import org.opentripplanner.routing.core.EdgeNarrative;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.GraphVertex;
import org.opentripplanner.routing.core.HasEdges;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.TraverseModeSet;
import org.opentripplanner.routing.core.TraverseOptions;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.StreetEdge;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
import org.opentripplanner.routing.edgetype.StreetVertex;
import org.opentripplanner.routing.services.PathService;
import org.opentripplanner.routing.services.StreetVertexIndexService;
import org.opentripplanner.routing.spt.GraphPath;
import org.opentripplanner.routing.spt.SPTEdge;
import org.opentripplanner.routing.spt.SPTVertex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LineString;
@Component
public class ItinerariesBeanServiceImpl implements ItinerariesBeanService {
private PathService _pathService;
private StreetVertexIndexService _streetVertexIndexService;
private Graph _graph;
private TripBeanService _tripBeanService;
private NarrativeService _narrativeService;
private StopBeanService _stopBeanService;
private ShapePointService _shapePointService;
@Autowired
public void setPathService(PathService pathService) {
_pathService = pathService;
}
@Autowired
public void setStreetVertexIndexService(
StreetVertexIndexService streetVertexIndexService) {
_streetVertexIndexService = streetVertexIndexService;
}
@Autowired
public void setGraph(Graph graph) {
_graph = graph;
}
@Autowired
public void setTripBeanService(TripBeanService tripBeanService) {
_tripBeanService = tripBeanService;
}
@Autowired
public void setStopBeanService(StopBeanService stopBeanService) {
_stopBeanService = stopBeanService;
}
@Autowired
public void setNarrativeService(NarrativeService narrativeService) {
_narrativeService = narrativeService;
}
@Autowired
public void setShapePointService(ShapePointService shapePointService) {
_shapePointService = shapePointService;
}
@Override
public ItinerariesBean getItinerariesBetween(double latFrom, double lonFrom,
double latTo, double lonTo, ConstraintsBean constraints)
throws ServiceException {
String fromPlace = latFrom + "," + lonFrom;
String toPlace = latTo + "," + lonTo;
Date time = new Date(constraints.getTime());
TraverseOptions options = createTraverseOptions();
applyConstraintsToOptions(constraints, options);
List<GraphPath> paths = _pathService.plan(fromPlace, toPlace, time,
options, 1);
LocationBean from = getPointAsLocation(latFrom, lonFrom);
LocationBean to = getPointAsLocation(latTo, lonTo);
return getPathsAsItineraries(paths, from, to);
}
@Override
public ListBean<VertexBean> getStreetGraphForRegion(double latFrom,
double lonFrom, double latTo, double lonTo) {
double x1 = Math.min(lonFrom, lonTo);
double x2 = Math.max(lonFrom, lonTo);
double y1 = Math.min(latFrom, latTo);
double y2 = Math.max(latFrom, latTo);
Envelope env = new Envelope(x1, x2, y1, y2);
Collection<Vertex> vertices = _streetVertexIndexService.getVerticesForEnvelope(env);
Map<Vertex, VertexBean> beansByVertex = new HashMap<Vertex, VertexBean>();
for (Vertex vertex : vertices)
getVertexAsBean(beansByVertex, vertex);
for (Vertex vertex : vertices) {
Collection<Edge> edges = null;
if (vertex instanceof HasEdges) {
HasEdges hasEdges = (HasEdges) vertex;
edges = hasEdges.getOutgoing();
} else {
GraphVertex gv = _graph.getGraphVertex(vertex.getLabel());
if (gv != null)
edges = gv.getOutgoing();
}
if (edges != null) {
VertexBean from = getVertexAsBean(beansByVertex, vertex);
List<EdgeNarrativeBean> edgeNarratives = new ArrayList<EdgeNarrativeBean>();
for (Edge edge : edges) {
if (edge instanceof EdgeNarrative) {
EdgeNarrative narrative = (EdgeNarrative) edge;
EdgeNarrativeBean narrativeBean = new EdgeNarrativeBean();
narrativeBean.setName(narrative.getName());
Geometry geom = narrative.getGeometry();
if (geom != null) {
List<CoordinatePoint> path = new ArrayList<CoordinatePoint>();
appendGeometryToPath(geom, path, true);
EncodedPolylineBean polyline = PolylineEncoder.createEncodings(path);
narrativeBean.setPath(polyline.getPoints());
}
narrativeBean.setFrom(from);
narrativeBean.setTo(getVertexAsBean(beansByVertex,
narrative.getToVertex()));
Map<String, Object> tags = new HashMap<String, Object>();
if (edge instanceof StreetEdge) {
StreetEdge streetEdge = (StreetEdge) edge;
StreetTraversalPermission permission = streetEdge.getPermission();
if (permission != null)
tags.put("access", permission.toString().toLowerCase());
}
if (!tags.isEmpty())
narrativeBean.setTags(tags);
edgeNarratives.add(narrativeBean);
}
}
if (!edgeNarratives.isEmpty())
from.setOutgoing(edgeNarratives);
}
}
List<VertexBean> beans = new ArrayList<VertexBean>(beansByVertex.values());
return new ListBean<VertexBean>(beans, false);
}
/****
* Private Methods
****/
/**
* From 'Transit Capacity and Quality of Service Manual' - Part 3 - Exhibit
* 3.9
*
* http://onlinepubs.trb.org/Onlinepubs/tcrp/tcrp100/part%203.pdf
*
* Table of passenger perceptions of time. Given that actual in-vehicle time
* seems to occur in real-time (penalty ratio of 1.0), how do passengers
* perceived walking, waiting for the first vehicle, and waiting for a
* transfer. In addition, is there an additive penalty for making a transfer
* of any kind.
*/
private TraverseOptions createTraverseOptions() {
TraverseOptions options = new TraverseOptions();
options.walkReluctance = 2.2;
options.waitAtBeginningFactor = 0.1;
options.waitReluctance = 2.5;
options.boardCost = 14 * 60;
options.maxTransfers = 2;
options.minTransferTime = 60;
options.remainingWeightHeuristic = new RemainingWeightHeuristicImpl();
return options;
}
private void applyConstraintsToOptions(ConstraintsBean constraints,
TraverseOptions options) {
options.setArriveBy(constraints.isArriveBy());
/**
* Modes
*/
Set<String> modes = constraints.getModes();
if (modes != null) {
TraverseModeSet ms = new TraverseModeSet();
if (modes.contains("walk"))
ms.setWalk(true);
if (modes.contains("transit"))
ms.setTransit(true);
options.setModes(ms);
}
/**
* Walking
*/
if (constraints.getWalkSpeed() != -1)
options.speed = constraints.getWalkSpeed();
if (constraints.getMaxWalkingDistance() != -1)
options.maxWalkDistance = constraints.getMaxWalkingDistance();
if (constraints.getWalkReluctance() != -1)
- options.walkReluctance = constraints.getWaitReluctance();
+ options.walkReluctance = constraints.getWalkReluctance();
/**
* Waiting
*/
if (constraints.getInitialWaitReluctance() != -1)
options.waitAtBeginningFactor = constraints.getInitialWaitReluctance();
if (constraints.getInitialWaitReluctance() != -1)
options.waitReluctance = constraints.getWaitReluctance();
/**
* Transferring
*/
if (constraints.getTransferCost() != -1)
options.boardCost = constraints.getTransferCost();
if (constraints.getMinTransferTime() != -1)
options.minTransferTime = constraints.getMinTransferTime();
if (constraints.getMaxTransfers() != -1)
options.maxTransfers = constraints.getMaxTransfers();
/**
* Our custom traverse options extension
*/
OTPConfiguration config = new OTPConfiguration();
options.putExtension(OTPConfiguration.class, config);
config.useRealtime = constraints.isUseRealTime();
}
private LocationBean getPointAsLocation(double lat, double lon) {
LocationBean bean = new LocationBean();
bean.setLocation(new CoordinatePoint(lat, lon));
return bean;
}
private ItinerariesBean getPathsAsItineraries(List<GraphPath> paths,
LocationBean from, LocationBean to) {
ItinerariesBean bean = new ItinerariesBean();
bean.setFrom(from);
bean.setTo(to);
List<ItineraryBean> beans = new ArrayList<ItineraryBean>();
bean.setItineraries(beans);
for (GraphPath path : paths) {
ItineraryBean itinerary = getPathAsItinerary(path);
beans.add(itinerary);
}
return bean;
}
private ItineraryBean getPathAsItinerary(GraphPath path) {
ItineraryBean itinerary = new ItineraryBean();
SPTVertex startVertex = path.vertices.firstElement();
State startState = startVertex.state;
SPTVertex endVertex = path.vertices.lastElement();
State endState = endVertex.state;
itinerary.setStartTime(startState.getTime());
itinerary.setEndTime(endState.getTime());
List<LegBean> legs = new ArrayList<LegBean>();
itinerary.setLegs(legs);
List<SPTEdge> edges = path.edges;
int currentIndex = 0;
while (currentIndex < edges.size()) {
SPTEdge sptEdge = edges.get(currentIndex);
EdgeNarrative edgeNarrative = sptEdge.narrative;
TraverseMode mode = edgeNarrative.getMode();
if (mode.isTransit()) {
currentIndex = extendTransitLeg(edges, currentIndex, legs);
} else {
currentIndex = extendStreetLeg(edges, currentIndex, mode, legs);
}
}
return itinerary;
}
private int extendTransitLeg(List<SPTEdge> edges, int currentIndex,
List<LegBean> legs) {
TransitLegBuilder builder = new TransitLegBuilder();
while (currentIndex < edges.size()) {
SPTEdge sptEdge = edges.get(currentIndex);
EdgeNarrative narrative = sptEdge.narrative;
TraverseMode mode = narrative.getMode();
if (!mode.isTransit())
break;
Vertex vFrom = narrative.getFromVertex();
Vertex vTo = narrative.getToVertex();
if (vFrom instanceof BlockDepartureVertex) {
builder = extendTransitLegWithDepartureAndArrival(legs, builder,
(BlockDepartureVertex) vFrom, (BlockArrivalVertex) vTo);
} else if (vFrom instanceof BlockArrivalVertex) {
BlockArrivalVertex arrival = (BlockArrivalVertex) vFrom;
/**
* Did we finish up a transit leg?
*/
if (vTo instanceof ArrivalVertex) {
/**
* We've finished up our transit leg, so publish the leg
*/
builder = getTransitLegBuilderAsLeg(builder, legs);
}
/**
* Did we have a transfer to another stop?
*/
else if (vTo instanceof DepartureVertex) {
/**
* We've finished up our transit leg either way, so publish the leg
*/
builder = getTransitLegBuilderAsLeg(builder, legs);
/**
* We've possibly transfered to another stop, so we need to insert the
* walk leg
*/
ArrivalAndDepartureInstance fromStopTimeInstance = arrival.getInstance();
StopEntry fromStop = fromStopTimeInstance.getStop();
DepartureVertex toStopVertex = (DepartureVertex) vTo;
StopEntry toStop = toStopVertex.getStop();
addTransferLegIfNeeded(sptEdge, fromStop, toStop, legs);
}
} else if (vFrom instanceof ArrivalVertex) {
if (vTo instanceof BlockDepartureVertex) {
/**
* This vertex combination occurs when we are doing an "arrive by"
* trip and we need to do a transfer between two stops.
*/
ArrivalVertex fromStopVertex = (ArrivalVertex) vFrom;
StopEntry fromStop = fromStopVertex.getStop();
BlockDepartureVertex toStopVertex = (BlockDepartureVertex) vTo;
ArrivalAndDepartureInstance departureInstance = toStopVertex.getInstance();
StopEntry toStop = departureInstance.getStop();
addTransferLegIfNeeded(sptEdge, fromStop, toStop, legs);
}
}
currentIndex++;
}
return currentIndex;
}
private void addTransferLegIfNeeded(SPTEdge sptEdge, StopEntry fromStop,
StopEntry toStop, List<LegBean> legs) {
if (!fromStop.equals(toStop)) {
long timeFrom = sptEdge.fromv.state.getTime();
long timeTo = sptEdge.tov.state.getTime();
ItineraryBean walk = getWalkingItineraryBetweenStops(fromStop, toStop,
timeFrom);
if (walk != null) {
scaleItinerary(walk, timeFrom, timeTo);
legs.addAll(walk.getLegs());
}
}
}
private TransitLegBuilder extendTransitLegWithDepartureAndArrival(
List<LegBean> legs, TransitLegBuilder builder,
BlockDepartureVertex vFrom, BlockArrivalVertex vTo) {
ArrivalAndDepartureInstance from = vFrom.getInstance();
ArrivalAndDepartureInstance to = vTo.getInstance();
BlockTripEntry tripFrom = from.getBlockTrip();
BlockTripEntry tripTo = to.getBlockTrip();
if (builder.getBlockInstance() == null) {
builder.setScheduledDepartureTime(from.getScheduledDepartureTime());
builder.setPredictedDepartureTime(from.getPredictedDepartureTime());
builder.setBlockInstance(from.getBlockInstance());
builder.setBlockTrip(tripFrom);
builder.setFromStop(from);
}
if (!tripFrom.equals(tripTo)) {
/**
* We switch trips during the course of the block, so we clean up the
* current leg and introduce a new one
*/
/**
* We just split the difference for now
*/
long scheduledTransitionTime = (from.getScheduledDepartureTime() + to.getScheduledArrivalTime()) / 2;
long predictedTransitionTime = 0;
if (from.isPredictedDepartureTimeSet() && to.isPredictedArrivalTimeSet())
predictedTransitionTime = (from.getPredictedDepartureTime() + to.getPredictedArrivalTime()) / 2;
builder.setScheduledArrivalTime(scheduledTransitionTime);
builder.setPredictedArrivalTime(predictedTransitionTime);
builder.setToStop(null);
getTransitLegBuilderAsLeg(builder, legs);
builder = new TransitLegBuilder();
builder.setScheduledDepartureTime(scheduledTransitionTime);
builder.setPredictedDepartureTime(predictedTransitionTime);
builder.setBlockInstance(to.getBlockInstance());
builder.setBlockTrip(tripTo);
}
builder.setToStop(to);
builder.setScheduledArrivalTime(to.getScheduledArrivalTime());
builder.setPredictedArrivalTime(to.getPredictedArrivalTime());
return builder;
}
private TransitLegBuilder getTransitLegBuilderAsLeg(
TransitLegBuilder builder, List<LegBean> legs) {
BlockInstance blockInstance = builder.getBlockInstance();
BlockTripEntry blockTrip = builder.getBlockTrip();
if (blockInstance == null || blockTrip == null)
return new TransitLegBuilder();
LegBean leg = new LegBean();
legs.add(leg);
leg.setStartTime(builder.getBestDepartureTime());
leg.setEndTime(builder.getBestArrivalTime());
double distance = getTransitLegBuilderAsDistance(builder);
leg.setDistance(distance);
leg.setMode("transit");
TripEntry trip = blockTrip.getTrip();
TransitLegBean transitLeg = new TransitLegBean();
leg.setTransitLeg(transitLeg);
transitLeg.setServiceDate(blockInstance.getServiceDate());
if (blockInstance.getFrequency() != null) {
FrequencyBean frequency = FrequencyBeanLibrary.getBeanForFrequency(
blockInstance.getServiceDate(), blockInstance.getFrequency());
transitLeg.setFrequency(frequency);
}
TripBean tripBean = _tripBeanService.getTripForId(trip.getId());
transitLeg.setTrip(tripBean);
transitLeg.setScheduledDepartureTime(builder.getScheduledDepartureTime());
transitLeg.setScheduledArrivalTime(builder.getScheduledArrivalTime());
transitLeg.setPredictedDepartureTime(builder.getPredictedDepartureTime());
transitLeg.setPredictedArrivalTime(builder.getPredictedArrivalTime());
String path = getTransitLegBuilderAsPath(builder);
transitLeg.setPath(path);
applyFromStopDetailsForTransitLeg(builder, transitLeg);
applyToStopDetailsForTransitLeg(builder, transitLeg);
return new TransitLegBuilder();
}
private double getTransitLegBuilderAsDistance(TransitLegBuilder builder) {
BlockInstance blockInstance = builder.getBlockInstance();
BlockConfigurationEntry blockConfig = blockInstance.getBlock();
BlockStopTimeEntry fromStop = null;
BlockStopTimeEntry toStop = null;
if (builder.getFromStop() != null)
fromStop = builder.getFromStop().getBlockStopTime();
if (builder.getToStop() != null)
toStop = builder.getToStop().getBlockStopTime();
if (fromStop == null && toStop == null)
return blockConfig.getTotalBlockDistance();
if (fromStop == null && toStop != null)
return toStop.getDistanceAlongBlock();
if (fromStop != null && toStop == null)
return blockConfig.getTotalBlockDistance()
- fromStop.getDistanceAlongBlock();
return toStop.getDistanceAlongBlock() - fromStop.getDistanceAlongBlock();
}
private String getTransitLegBuilderAsPath(TransitLegBuilder builder) {
BlockTripEntry blockTrip = builder.getBlockTrip();
TripEntry trip = blockTrip.getTrip();
AgencyAndId shapeId = trip.getShapeId();
if (shapeId == null)
return null;
ShapePoints shapePoints = _shapePointService.getShapePointsForShapeId(shapeId);
BlockStopTimeEntry fromStop = null;
BlockStopTimeEntry toStop = null;
if (builder.getFromStop() != null)
fromStop = builder.getFromStop().getBlockStopTime();
if (builder.getToStop() != null)
toStop = builder.getToStop().getBlockStopTime();
if (fromStop == null && toStop == null) {
return ShapeSupport.getFullPath(shapePoints);
}
if (fromStop == null && toStop != null) {
return ShapeSupport.getPartialPathToStop(shapePoints,
toStop.getStopTime());
}
if (fromStop != null && toStop == null) {
return ShapeSupport.getPartialPathFromStop(shapePoints,
fromStop.getStopTime());
}
return ShapeSupport.getPartialPathBetweenStops(shapePoints,
fromStop.getStopTime(), toStop.getStopTime());
}
private void applyFromStopDetailsForTransitLeg(TransitLegBuilder builder,
TransitLegBean transitLeg) {
ArrivalAndDepartureInstance fromStopTimeInstance = builder.getFromStop();
if (fromStopTimeInstance == null)
return;
BlockStopTimeEntry bstFrom = fromStopTimeInstance.getBlockStopTime();
StopTimeEntry fromStopTime = bstFrom.getStopTime();
StopTimeNarrative stopTimeNarrative = _narrativeService.getStopTimeForEntry(fromStopTime);
transitLeg.setRouteShortName(stopTimeNarrative.getRouteShortName());
transitLeg.setTripHeadsign(stopTimeNarrative.getStopHeadsign());
StopEntry fromStop = fromStopTimeInstance.getStop();
StopBean fromStopBean = _stopBeanService.getStopForId(fromStop.getId());
transitLeg.setFromStop(fromStopBean);
transitLeg.setFromStopSequence(fromStopTime.getSequence());
}
private void applyToStopDetailsForTransitLeg(TransitLegBuilder builder,
TransitLegBean transitLeg) {
ArrivalAndDepartureInstance toStopTimeInstance = builder.getToStop();
if (toStopTimeInstance == null)
return;
StopEntry toStop = toStopTimeInstance.getStop();
StopBean toStopBean = _stopBeanService.getStopForId(toStop.getId());
transitLeg.setToStop(toStopBean);
BlockStopTimeEntry blockStopTime = toStopTimeInstance.getBlockStopTime();
StopTimeEntry stopTime = blockStopTime.getStopTime();
transitLeg.setToStopSequence(stopTime.getSequence());
}
private int extendStreetLeg(List<SPTEdge> edges, int currentIndex,
TraverseMode mode, List<LegBean> legs) {
List<SPTEdge> streetEdges = new ArrayList<SPTEdge>();
while (currentIndex < edges.size()) {
SPTEdge sptEdge = edges.get(currentIndex);
EdgeNarrative narrative = sptEdge.narrative;
TraverseMode edgeMode = narrative.getMode();
if (mode != edgeMode)
break;
streetEdges.add(sptEdge);
currentIndex++;
}
if (!streetEdges.isEmpty()) {
getStreetLegBuilderAsLeg(streetEdges, mode, legs);
}
return currentIndex;
}
private void getStreetLegBuilderAsLeg(List<SPTEdge> streetEdges,
TraverseMode mode, List<LegBean> legs) {
List<StreetLegBean> streetLegs = new ArrayList<StreetLegBean>();
StreetLegBean streetLeg = null;
List<CoordinatePoint> path = new ArrayList<CoordinatePoint>();
double distance = 0.0;
double totalDistance = 0.0;
long startTime = 0;
long endTime = 0;
for (SPTEdge sptEdge : streetEdges) {
EdgeNarrative edgeResult = sptEdge.narrative;
Geometry geom = edgeResult.getGeometry();
if (geom == null) {
continue;
}
String streetName = edgeResult.getName();
if (streetLeg == null
|| !ObjectUtils.equals(streetLeg.getStreetName(), streetName)) {
addPathToStreetLegIfApplicable(streetLeg, path, distance);
streetLeg = createStreetLeg(sptEdge);
streetLegs.add(streetLeg);
path = new ArrayList<CoordinatePoint>();
appendGeometryToPath(geom, path, true);
distance = edgeResult.getDistance();
} else {
appendGeometryToPath(geom, path, false);
distance += edgeResult.getDistance();
}
totalDistance += edgeResult.getDistance();
if (startTime == 0)
startTime = sptEdge.fromv.state.getTime();
endTime = sptEdge.tov.state.getTime();
}
addPathToStreetLegIfApplicable(streetLeg, path, distance);
LegBean leg = new LegBean();
legs.add(leg);
leg.setStartTime(startTime);
leg.setEndTime(endTime);
leg.setMode(getStreetModeAsString(mode));
leg.setDistance(totalDistance);
leg.setStreetLegs(streetLegs);
}
private void addPathToStreetLegIfApplicable(StreetLegBean streetLeg,
List<CoordinatePoint> path, double distance) {
if (streetLeg != null) {
EncodedPolylineBean polyline = PolylineEncoder.createEncodings(path);
streetLeg.setPath(polyline.getPoints());
streetLeg.setDistance(distance);
}
}
private void appendGeometryToPath(Geometry geom, List<CoordinatePoint> path,
boolean includeFirstPoint) {
if (geom instanceof LineString) {
LineString ls = (LineString) geom;
for (int i = 0; i < ls.getNumPoints(); i++) {
if (i == 0 && !includeFirstPoint)
continue;
Coordinate c = ls.getCoordinateN(i);
CoordinatePoint p = new CoordinatePoint(c.y, c.x);
path.add(p);
}
} else {
throw new IllegalStateException("unknown geometry: " + geom);
}
}
private StreetLegBean createStreetLeg(SPTEdge edge) {
StreetLegBean bean = new StreetLegBean();
bean.setStreetName(edge.getName());
return bean;
}
private String getStreetModeAsString(TraverseMode mode) {
switch (mode) {
case BICYCLE:
return "bicycle";
case WALK:
return "walk";
}
throw new IllegalStateException("unknown street mode: " + mode);
}
private ItineraryBean getWalkingItineraryBetweenStops(StopEntry from,
StopEntry to, long time) {
String fromPlace = WalkFromStopVertex.getVertexLabelForStop(from);
String toPlace = WalkToStopVertex.getVertexLabelForStop(to);
TraverseOptions options = createTraverseOptions();
TraverseModeSet modes = new TraverseModeSet(TraverseMode.WALK);
options.setModes(modes);
List<GraphPath> paths = _pathService.plan(fromPlace, toPlace,
new Date(time), options, 1);
if (paths.isEmpty())
return null;
return getPathAsItinerary(paths.get(0));
}
private void scaleItinerary(ItineraryBean bean, long timeFrom, long timeTo) {
long tStart = bean.getStartTime();
long tEnd = bean.getEndTime();
double ratio = (timeTo - timeFrom) / (tEnd - tStart);
bean.setStartTime(scaleTime(tStart, timeFrom, ratio, tStart));
bean.setEndTime(scaleTime(tStart, timeFrom, ratio, tEnd));
for (LegBean leg : bean.getLegs()) {
leg.setStartTime(scaleTime(tStart, timeFrom, ratio, leg.getStartTime()));
leg.setEndTime(scaleTime(tStart, timeFrom, ratio, leg.getEndTime()));
}
}
private long scaleTime(long tStartOrig, long tStartNew, double ratio, long t) {
return (long) ((t - tStartOrig) * ratio + tStartNew);
}
private VertexBean getVertexAsBean(Map<Vertex, VertexBean> beansByVertex,
Vertex vertex) {
VertexBean bean = beansByVertex.get(vertex);
if (bean == null) {
bean = new VertexBean();
bean.setId(vertex.getLabel());
bean.setLocation(new CoordinatePoint(vertex.getY(), vertex.getX()));
Map<String, Object> tags = new HashMap<String, Object>();
tags.put("class", vertex.getClass().getName());
if (vertex instanceof StreetVertex) {
StreetVertex sv = (StreetVertex) vertex;
StreetTraversalPermission perms = sv.getPermission();
if (perms != null)
tags.put("access", perms.toString().toLowerCase());
} else if (vertex instanceof AbstractStopVertex) {
AbstractStopVertex stopVertex = (AbstractStopVertex) vertex;
StopEntry stop = stopVertex.getStop();
StopBean stopBean = _stopBeanService.getStopForId(stop.getId());
tags.put("stop", stopBean);
}
bean.setTags(tags);
beansByVertex.put(vertex, bean);
}
return bean;
}
}
| true | false | null | null |
diff --git a/dspace-api/src/main/java/org/dspace/core/ConfigurationManager.java b/dspace-api/src/main/java/org/dspace/core/ConfigurationManager.java
index bb0de692e..493b92695 100644
--- a/dspace-api/src/main/java/org/dspace/core/ConfigurationManager.java
+++ b/dspace-api/src/main/java/org/dspace/core/ConfigurationManager.java
@@ -1,826 +1,831 @@
/*
* ConfigurationManager.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS 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.dspace.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Category;
import org.apache.log4j.Logger;
import org.apache.log4j.helpers.OptionConverter;
/**
* Class for reading the DSpace system configuration. The main configuration is
* read in as properties from a standard properties file. Email templates and
* configuration files for other tools are also be accessed via this class.
* <P>
* The main configuration is by default read from the <em>resource</em>
* <code>/dspace.cfg</code>.
* To specify a different configuration, the system property
* <code>dspace.configuration</code> should be set to the <em>filename</em>
* of the configuration file.
* <P>
* Other configuration files are read from the <code>config</code> directory
* of the DSpace installation directory (specified as the property
* <code>dspace.dir</code> in the main configuration file.)
*
*
* @author Robert Tansley
* @author Larry Stone - Interpolated values.
* @version $Revision$
*/
public class ConfigurationManager
{
/** log4j category */
private static Logger log = Logger.getLogger(ConfigurationManager.class);
/** The configuration properties */
private static Properties properties = null;
/** The default license */
private static String license;
// limit of recursive depth of property variable interpolation in
// configuration; anything greater than this is very likely to be a loop.
private final static int RECURSION_LIMIT = 9;
/**
*
*/
public static Properties getProperties()
{
+ if (properties == null)
+ {
+ loadConfig(null);
+ }
+
return (Properties)properties.clone();
}
/**
* Get a configuration property
*
* @param property
* the name of the property
*
* @return the value of the property, or <code>null</code> if the property
* does not exist.
*/
public static String getProperty(String property)
{
if (properties == null)
{
loadConfig(null);
}
return properties.getProperty(property);
}
/**
* Get a configuration property as an integer
*
* @param property
* the name of the property
*
* @return the value of the property. <code>0</code> is returned if the
* property does not exist. To differentiate between this case and
* when the property actually is zero, use <code>getProperty</code>.
*/
public static int getIntProperty(String property)
{
if (properties == null)
{
loadConfig(null);
}
String stringValue = properties.getProperty(property);
int intValue = 0;
if (stringValue != null)
{
try
{
intValue = Integer.parseInt(stringValue.trim());
}
catch (NumberFormatException e)
{
warn("Warning: Number format error in property: " + property);
}
}
return intValue;
}
/**
* Get the License
*
* @param
* license file name
*
* @return
* license text
*
*/
public static String getLicenseText(String licenseFile)
{
// Load in default license
try
{
BufferedReader br = new BufferedReader(new FileReader(licenseFile));
String lineIn;
license = "";
while ((lineIn = br.readLine()) != null)
{
license = license + lineIn + '\n';
}
}
catch (IOException e)
{
fatal("Can't load configuration", e);
// FIXME: Maybe something more graceful here, but with the
// configuration we can't do anything
System.exit(1);
}
return license;
}
/**
* Get a configuration property as a boolean. True is indicated if the value
* of the property is <code>TRUE</code> or <code>YES</code> (case
* insensitive.)
*
* @param property
* the name of the property
*
* @return the value of the property. <code>false</code> is returned if
* the property does not exist. To differentiate between this case
* and when the property actually is false, use
* <code>getProperty</code>.
*/
public static boolean getBooleanProperty(String property)
{
return getBooleanProperty(property, false);
}
/**
* Get a configuration property as a boolean, with default.
* True is indicated if the value
* of the property is <code>TRUE</code> or <code>YES</code> (case
* insensitive.)
*
* @param property
* the name of the property
*
* @param defaultValue
* value to return if property is not found.
*
* @return the value of the property. <code>default</code> is returned if
* the property does not exist. To differentiate between this case
* and when the property actually is false, use
* <code>getProperty</code>.
*/
public static boolean getBooleanProperty(String property, boolean defaultValue)
{
if (properties == null)
{
loadConfig(null);
}
String stringValue = properties.getProperty(property);
if (stringValue != null)
{
stringValue = stringValue.trim();
return stringValue.equalsIgnoreCase("true") ||
stringValue.equalsIgnoreCase("yes");
}
else
{
return defaultValue;
}
}
/**
* Returns an enumeration of all the keys in the DSpace configuration
*
* @return an enumeration of all the keys in the DSpace configuration
*/
public static Enumeration propertyNames()
{
if (properties == null)
loadConfig(null);
return properties.propertyNames();
}
/**
* Get the template for an email message. The message is suitable for
* inserting values using <code>java.text.MessageFormat</code>.
*
* @param emailFile
* full name for the email template, for example "/dspace/config/emails/register".
*
* @return the email object, with the content and subject filled out from
* the template
*
* @throws IOException
* if the template couldn't be found, or there was some other
* error reading the template
*/
public static Email getEmail(String emailFile) throws IOException
{
String charset = null;
String subject = "";
StringBuffer contentBuffer = new StringBuffer();
// Read in template
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(emailFile));
boolean more = true;
while (more)
{
String line = reader.readLine();
if (line == null)
{
more = false;
}
else if (line.toLowerCase().startsWith("subject:"))
{
// Extract the first subject line - everything to the right
// of the colon, trimmed of whitespace
subject = line.substring(8).trim();
}
else if (line.toLowerCase().startsWith("charset:"))
{
// Extract the character set from the email
charset = line.substring(8).trim();
}
else if (!line.startsWith("#"))
{
// Add non-comment lines to the content
contentBuffer.append(line);
contentBuffer.append("\n");
}
}
}
finally
{
if (reader != null)
{
reader.close();
}
}
// Create an email
Email email = new Email();
email.setSubject(subject);
email.setContent(contentBuffer.toString());
if (charset != null)
email.setCharset(charset);
return email;
}
/**
* Get the site-wide default license that submitters need to grant
*
* @return the default license
*/
public static String getDefaultSubmissionLicense()
{
if (properties == null)
{
loadConfig(null);
}
return license;
}
/**
* Get the path for the news files.
*
*/
public static String getNewsFilePath()
{
String filePath = ConfigurationManager.getProperty("dspace.dir")
+ File.separator + "config" + File.separator;
return filePath;
}
/**
* Reads news from a text file.
*
* @param position
* a constant indicating which file (top or side) should be read
* in.
*/
public static String readNewsFile(String newsFile)
{
String fileName = getNewsFilePath();
fileName += newsFile;
String text = "";
try
{
// retrieve existing news from file
FileInputStream fir = new FileInputStream(fileName);
InputStreamReader ir = new InputStreamReader(fir, "UTF-8");
BufferedReader br = new BufferedReader(ir);
String lineIn;
while ((lineIn = br.readLine()) != null)
{
text += lineIn;
}
br.close();
}
catch (IOException e)
{
warn("news_read: " + e.getLocalizedMessage());
}
return text;
}
/**
* Writes news to a text file.
*
* @param position
* a constant indicating which file (top or side) should be
* written to.
*
* @param news
* the text to be written to the file.
*/
public static String writeNewsFile(String newsFile, String news)
{
String fileName = getNewsFilePath();
fileName += newsFile;
try
{
// write the news out to the appropriate file
FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
PrintWriter out = new PrintWriter(osr);
out.print(news);
out.close();
}
catch (IOException e)
{
warn("news_write: " + e.getLocalizedMessage());
}
return news;
}
/**
* Writes license to a text file.
*
* @param news
* the text to be written to the file.
*/
public static void writeLicenseFile(String newLicense)
{
String licenseFile = getProperty("dspace.dir") + File.separator
+ "config" + File.separator + "default.license";
try
{
// write the news out to the appropriate file
FileOutputStream fos = new FileOutputStream(licenseFile);
OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
PrintWriter out = new PrintWriter(osr);
out.print(newLicense);
out.close();
}
catch (IOException e)
{
warn("license_write: " + e.getLocalizedMessage());
}
license = newLicense;
}
private static File loadedFile = null;
/**
* Return the file that configuration was actually loaded from. Only returns
* a valid File after configuration has been loaded.
*
* @deprecated Please remove all direct usage of the configuration file.
* @return File naming configuration data file, or null if not loaded yet.
*/
protected static File getConfigurationFile()
{
// in case it hasn't been done yet.
loadConfig(null);
return loadedFile;
}
/**
* Load the DSpace configuration properties. Only does anything if
* properties are not already loaded. Properties are loaded in from the
* specified file, or default locations.
*
* @param configFile
* The <code>dspace.cfg</code> configuration file to use, or
* <code>null</code> to try default locations
*/
public static void loadConfig(String configFile)
{
if (properties != null)
{
return;
}
URL url = null;
try
{
String configProperty = System.getProperty("dspace.configuration");
if (configFile != null)
{
info("Loading provided config file: " + configFile);
loadedFile = new File(configFile);
url = loadedFile.toURL();
}
// Has the default configuration location been overridden?
else if (configProperty != null)
{
info("Loading system provided config property (-Ddspace.configuration): " + configProperty);
// Load the overriding configuration
loadedFile = new File(configProperty);
url = loadedFile.toURL();
}
// Load configuration from default location
else
{
url = ConfigurationManager.class.getResource("/dspace.cfg");
if (url != null)
{
info("Loading from classloader: " + url);
loadedFile = new File(url.getPath());
}
}
if (url == null)
{
fatal("Cannot find dspace.cfg");
throw new RuntimeException("Cannot find dspace.cfg");
}
else
{
properties = new Properties();
properties.load(url.openStream());
// walk values, interpolating any embedded references.
for (Enumeration pe = properties.propertyNames(); pe.hasMoreElements(); )
{
String key = (String)pe.nextElement();
String value = interpolate(key, 1);
if (value != null)
properties.setProperty(key, value);
}
}
}
catch (IOException e)
{
fatal("Can't load configuration: " + url, e);
// FIXME: Maybe something more graceful here, but with the
// configuration we can't do anything
throw new RuntimeException("Cannot load configuration: " + url, e);
}
// Load in default license
File licenseFile = new File(getProperty("dspace.dir") + File.separator
+ "config" + File.separator + "default.license");
try
{
FileInputStream fir = new FileInputStream(licenseFile);
InputStreamReader ir = new InputStreamReader(fir, "UTF-8");
BufferedReader br = new BufferedReader(ir);
String lineIn;
license = "";
while ((lineIn = br.readLine()) != null)
{
license = license + lineIn + '\n';
}
br.close();
}
catch (IOException e)
{
fatal("Can't load license: " + licenseFile.toString() , e);
// FIXME: Maybe something more graceful here, but with the
// configuration we can't do anything
throw new RuntimeException("Cannot load license: " + licenseFile.toString(),e);
}
try
{
/*
* Initialize Logging once ConfigurationManager is initialized.
*
* This is selection from a property in dspace.cfg, if the property
* is absent then nothing will be configured and the application
* will use the defaults provided by log4j.
*
* Property format is:
*
* log.init.config = ${dspace.dir}/config/log4j.properties
* or
* log.init.config = ${dspace.dir}/config/log4j.xml
*
* See default log4j initialization documentation here:
* http://logging.apache.org/log4j/docs/manual.html
*
* If there is a problem with the file referred to in
* "log.configuration" it needs to be sent to System.err
* so do not instantiate another Logging configuration.
*
*/
String dsLogConfiguration = ConfigurationManager.getProperty("log.init.config");
if (dsLogConfiguration == null || System.getProperty("dspace.log.init.disable") != null)
{
/*
* Do nothing if log config not set in dspace.cfg or "dspace.log.init.disable"
* system property set. Leave it upto log4j to properly init its logging
* via classpath or system properties.
*/
info("Using default log4j provided log configuration," +
"if uninitended, check your dspace.cfg for (log.init.config)");
}
else
{
info("Using dspace provided log configuration (log.init.config)");
File logConfigFile = new File(dsLogConfiguration);
if(logConfigFile.exists())
{
info("Loading: " + dsLogConfiguration);
OptionConverter.selectAndConfigure(logConfigFile.toURL(), null,
org.apache.log4j.LogManager.getLoggerRepository());
}
else
{
info("File does not exist: " + dsLogConfiguration);
}
}
}
catch (MalformedURLException e)
{
fatal("Can't load dspace provided log4j configuration", e);
throw new RuntimeException("Cannot load dspace provided log4j configuration",e);
}
}
/**
* Recursively interpolate variable references in value of
* property named "key".
* @return new value if it contains interpolations, or null
* if it had no variable references.
*/
private static String interpolate(String key, int level)
{
if (level > RECURSION_LIMIT)
throw new IllegalArgumentException("ConfigurationManager: Too many levels of recursion in configuration property variable interpolation, property="+key);
String value = (String)properties.get(key);
int from = 0;
StringBuffer result = null;
while (from < value.length())
{
int start = value.indexOf("${", from);
if (start >= 0)
{
int end = value.indexOf("}", start);
if (end < 0)
break;
String var = value.substring(start+2, end);
if (result == null)
result = new StringBuffer(value.substring(from, start));
else
result.append(value.substring(from, start));
if (properties.containsKey(var))
{
String ivalue = interpolate(var, level+1);
if (ivalue != null)
{
result.append(ivalue);
properties.setProperty(var, ivalue);
}
else
result.append((String)properties.getProperty(var));
}
else
{
log.warn("Interpolation failed in value of property \""+key+
"\", there is no property named \""+var+"\"");
}
from = end+1;
}
else
break;
}
if (result != null && from < value.length())
result.append(value.substring(from));
return (result == null) ? null : result.toString();
}
/**
* Command-line interface for running configuration tasks. Possible
* arguments:
* <ul>
* <li><code>-property name</code> prints the value of the property
* <code>name</code> from <code>dspace.cfg</code> to the standard
* output. If the property does not exist, nothing is written.</li>
* </ul>
*
* @param argv
* command-line arguments
*/
public static void main(String[] argv)
{
if ((argv.length == 2) && argv[0].equals("-property"))
{
String val = getProperty(argv[1]);
if (val != null)
{
System.out.println(val);
}
else
{
System.out.println("");
}
System.exit(0);
}
else
{
System.err
.println("Usage: ConfigurationManager OPTION\n -property prop.name get value of prop.name from dspace.cfg");
}
System.exit(1);
}
private static void info(String string)
{
if (!isConfigured())
{
System.out.println("INFO: " + string);
}
else
{
log.info(string);
}
}
private static void warn(String string)
{
if (!isConfigured())
{
System.out.println("WARN: " + string);
}
else
{
log.warn(string);
}
}
private static void fatal(String string, Exception e)
{
if (!isConfigured())
{
System.out.println("FATAL: " + string);
e.printStackTrace();
}
else
{
log.fatal(string, e);
}
}
private static void fatal(String string)
{
if (!isConfigured())
{
System.out.println("FATAL: " + string);
}
else
{
log.fatal(string);
}
}
/*
* Only current solution available to detect
* if log4j is truly configured.
*/
private static boolean isConfigured()
{
Enumeration en = org.apache.log4j.LogManager.getRootLogger()
.getAllAppenders();
if (!(en instanceof org.apache.log4j.helpers.NullEnumeration))
{
return true;
}
else
{
Enumeration cats = Category.getCurrentCategories();
while (cats.hasMoreElements())
{
Category c = (Category) cats.nextElement();
if (!(c.getAllAppenders() instanceof org.apache.log4j.helpers.NullEnumeration))
return true;
}
}
return false;
}
}
| true | false | null | null |
diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index 30dd0e534..e2cf17a06 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -1,3013 +1,3007 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.common.model;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.Specification;
import net.sf.freecol.common.model.Map.Direction;
import net.sf.freecol.common.model.Map.Position;
import net.sf.freecol.common.model.Region.RegionType;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.util.RandomChoice;
import net.sf.freecol.common.util.Utils;
import org.w3c.dom.Element;
/**
* Represents a player. The player can be either a human player or an AI-player.
*
* <br>
* <br>
*
* In addition to storing the name, nation e.t.c. of the player, it also stores
* various defaults for the player. One example of this is the
* {@link #getEntryLocation entry location}.
*/
public class Player extends FreeColGameObject implements Nameable {
private static final Logger logger = Logger.getLogger(Player.class.getName());
public static final int SCORE_SETTLEMENT_DESTROYED = -40;
public static final int SCORE_INDEPENDENCE_DECLARED = 100;
public static final int SCORE_INDEPENDENCE_GRANTED = 1000;
/**
* The XML tag name for the set of founding fathers.
*/
private static final String FOUNDING_FATHER_TAG = "foundingFathers";
/**
* The XML tag name for the stance array.
*/
private static final String STANCE_TAG = "stance";
/**
* The XML tag name for the tension array.
*/
private static final String TENSION_TAG = "tension";
/**
* The index of this player
*/
private int index;
/**
* Constants for describing the stance towards a player.
*/
public static enum Stance {
WAR, CEASE_FIRE, PEACE, ALLIANCE
}
/**
* Only used by AI - stores the tension levels, 0-1000 with 1000 maximum
* hostility.
*/
// TODO: move this to AIPlayer
private java.util.Map<Player, Tension> tension = new HashMap<Player, Tension>();
/**
* Stores the stance towards the other players. One of: WAR, CEASE_FIRE,
* PEACE and ALLIANCE.
*/
private java.util.Map<String, Stance> stance = new HashMap<String, Stance>();
private static final Color noNationColor = Color.BLACK;
/**
* Nation/NationType related variables.
*/
/**
* The name of this player. This defaults to the user name in case of a
* human player and the rulerName of the NationType in case of an AI player.
*/
private String name;
public static final String UNKNOWN_ENEMY = "unknown enemy";
/**
* The NationType of this player.
*/
private NationType nationType;
/**
* The nation ID of this player, e.g. "model.nation.dutch".
*/
private String nationID;
/**
* The name this player uses for the New World.
*/
private String newLandName = null;
// Represented on the network as "color.getRGB()":
private Color color = Color.BLACK;
private boolean admin;
/**
* The current score of this player.
*/
private int score;
private int gold;
// only used to store the number of native settlements
private int numberOfSettlements;
/** The market for Europe. */
private Market market;
private Europe europe;
private Monarch monarch;
private boolean ready;
/** True if this is an AI player. */
private boolean ai;
/** True if player has been attacked by privateers. */
private boolean attackedByPrivateers = false;
private int oldSoL;
private int crosses;
private int bells;
private boolean dead = false;
// any founding fathers in this Player's congress
final private Set<FoundingFather> allFathers = new HashSet<FoundingFather>();
private FoundingFather currentFather;
/** The current tax rate for this player. */
private int tax = 0;
private PlayerType playerType;
public static enum PlayerType {
NATIVE, COLONIAL, REBEL, INDEPENDENT, ROYAL, UNDEAD
}
private int crossesRequired = 12;
// No need for a persistent storage of these variables:
private int colonyNameIndex = 0;
private EnumMap<RegionType, Integer> regionNameIndex = new EnumMap<RegionType, Integer>(RegionType.class);
private Location entryLocation;
/**
* The Units this player owns.
*/
private final java.util.Map<String, Unit> units = new HashMap<String, Unit>();
private final Iterator<Unit> nextActiveUnitIterator = new UnitIterator(this, new ActivePredicate());
private final Iterator<Unit> nextGoingToUnitIterator = new UnitIterator(this, new GoingToPredicate());
// Settlements this player owns
final private List<Settlement> settlements = new ArrayList<Settlement>();
// Trade routes of this player
private List<TradeRoute> tradeRoutes = new ArrayList<TradeRoute>();
// Model messages for this player
private final Set<ModelMessage> modelMessages = new HashSet<ModelMessage>();
// Temporary variables:
protected boolean[][] canSeeTiles = null;
/**
* Contains the abilities and modifiers of this type.
*/
private FeatureContainer featureContainer = new FeatureContainer();
/**
*
* This constructor should only be used by subclasses.
*
*/
protected Player() {
// empty constructor
}
/**
*
* Creates an new AI <code>Player</code> with the specified name.
*
*
*
* @param game The <code>Game</code> this <code>Player</code> belongs
* to.
*
* @param name The name that this player will use.
*
* @param admin Whether or not this AI player shall be considered an Admin.
*
* @param ai Whether or not this AI player shall be considered an AI player
* (usually true here).
*
* @param nation The nation of the <code>Player</code>.
*
*/
public Player(Game game, String name, boolean admin, boolean ai, Nation nation) {
this(game, name, admin, nation);
this.ai = ai;
}
/**
*
* Creates a new <code>Player</code> with specified name.
*
*
*
* @param game The <code>Game</code> this <code>Player</code> belongs
* to.
*
* @param name The name that this player will use.
*
* @param admin 'true' if this Player is an admin,
*
* 'false' otherwise.
*
*/
public Player(Game game, String name, boolean admin) {
this(game, name, admin, game.getVacantNation());
}
/**
*
* Creates a new (human) <code>Player</code> with specified name.
*
* @param game The <code>Game</code> this <code>Player</code> belongs
* to.
*
* @param name The name that this player will use.
*
* @param admin 'true' if this Player is an admin,
*
* 'false' otherwise.
*
* @param newNation The nation of the <code>Player</code>.
*
*/
public Player(Game game, String name, boolean admin, Nation newNation) {
super(game);
this.name = name;
this.admin = admin;
if (newNation != null && newNation.getType() != null) {
this.nationType = newNation.getType();
this.color = newNation.getColor();
this.nationID = newNation.getId();
try {
featureContainer.add(nationType.getFeatureContainer());
} catch (Throwable error) {
error.printStackTrace();
}
if (nationType.isEuropean()) {
/*
* Setting the amount of gold to
* "getGameOptions().getInteger(GameOptions.STARTING_MONEY)"
*
* just before starting the game. See
* "net.sf.freecol.server.control.PreGameController".
*/
gold = 0;
europe = new Europe(game, this);
if (!nationType.isREF()) {
// colonial nation
monarch = new Monarch(game, this, "");
playerType = PlayerType.COLONIAL;
} else {
// Royal expeditionary force
playerType = PlayerType.ROYAL;
}
} else {
// indians
gold = 1500;
playerType = PlayerType.NATIVE;
}
} else {
// virtual "enemy privateer" player
// or undead ?
this.nationID = "model.nation.unknownEnemy";
this.color = noNationColor;
this.playerType = PlayerType.COLONIAL;
}
market = new Market(getGame(), this);
crosses = 0;
bells = 0;
currentFather = null;
}
/**
*
* Initiates a new <code>Player</code> from an <code>Element</code> and
* registers this <code>Player</code> at the specified game.
*
* @param game The <code>Game</code> this object belongs to.
* @param in The input stream containing the XML.
* @throws XMLStreamException if a problem was encountered during parsing.
*/
public Player(Game game, XMLStreamReader in) throws XMLStreamException {
super(game, in);
readFromXML(in);
}
/**
* Initiates a new <code>Player</code> from an <code>Element</code> and
* registers this <code>Player</code> at the specified game.
*
* @param game The <code>Game</code> this object belongs to.
* @param e An XML-element that will be used to initialize this object.
*
*/
public Player(Game game, Element e) {
super(game, e);
readFromXMLElement(e);
}
/**
* Initiates a new <code>Player</code> with the given ID. The object
* should later be initialized by calling either {@link
* #readFromXML(XMLStreamReader)} or {@link #readFromXMLElement(Element)}.
*
* @param game The <code>Game</code> in which this object belong.
* @param id The unique identifier for this object.
*/
public Player(Game game, String id) {
super(game, id);
}
/**
* Returns the index of this Player.
*
* @return an <code>int</code> value
*/
public int getIndex() {
return index;
}
/**
* Get the <code>FeatureContainer</code> value.
*
* @return a <code>FeatureContainer</code> value
*/
public final FeatureContainer getFeatureContainer() {
return featureContainer;
}
/**
* Set the <code>FeatureContainer</code> value.
*
* @param newFeatureContainer The new FeatureContainer value.
*/
public final void setFeatureContainer(final FeatureContainer newFeatureContainer) {
this.featureContainer = newFeatureContainer;
}
public boolean hasAbility(String id) {
return featureContainer.hasAbility(id);
}
/**
* Returns this Player's Market.
*
* @return This Player's Market.
*/
public Market getMarket() {
return market;
}
/**
* Resets this Player's Market.
*/
public void reinitialiseMarket() {
market = new Market(getGame(), this);
}
/**
* Checks if this player owns the given <code>Settlement</code>.
*
* @param s The <code>Settlement</code>.
* @return <code>true</code> if this <code>Player</code> owns the given
* <code>Settlement</code>.
*/
public boolean hasSettlement(Settlement s) {
return settlements.contains(s);
}
/**
* Adds the given <code>Settlement</code> to this <code>Player</code>'s
* list of settlements.
*
* @param s
*/
public void addSettlement(Settlement s) {
if (!settlements.contains(s)) {
settlements.add(s);
if (s.getOwner() != this) {
s.setOwner(this);
}
}
}
/**
* Removes the given <code>Settlement</code> from this <code>Player</code>'s
* list of settlements.
*
* @param s The <code>Settlement</code> to remove.
*/
public void removeSettlement(Settlement s) {
if (settlements.contains(s)) {
if (s.getOwner() == this) {
throw new IllegalStateException(
"Cannot remove the ownership of the given settlement before it has been given to another player.");
}
settlements.remove(s);
}
}
public int getNumberOfSettlements() {
return numberOfSettlements;
}
public void setNumberOfSettlements(int number) {
numberOfSettlements = number;
}
/**
* Adds a <code>ModelMessage</code> for this player.
*
* @param modelMessage The <code>ModelMessage</code>.
*/
public void addModelMessage(ModelMessage modelMessage) {
modelMessages.add(modelMessage);
}
/**
* Returns all ModelMessages for this player.
*
* @return all ModelMessages for this player.
*/
public Collection<ModelMessage> getModelMessages() {
return modelMessages;
}
/**
* Returns all new ModelMessages for this player.
*
* @return all new ModelMessages for this player.
*/
public List<ModelMessage> getNewModelMessages() {
ArrayList<ModelMessage> out = new ArrayList<ModelMessage>();
for (ModelMessage message : modelMessages) {
if (message.hasBeenDisplayed()) {
continue;
} else {
out.add(0, message);
}
}
return out;
}
/**
* Removes all undisplayed model messages for this player.
*/
public void removeModelMessages() {
Iterator<ModelMessage> messageIterator = modelMessages.iterator();
while (messageIterator.hasNext()) {
ModelMessage message = messageIterator.next();
if (message.hasBeenDisplayed()) {
messageIterator.remove();
}
}
}
/**
* Removes all the model messages for this player.
*/
public void clearModelMessages() {
modelMessages.clear();
}
/**
* Checks if this player is a "royal expeditionary force.
*
* @return <code>true</code> is the given nation is a royal expeditionary
* force and <code>false</code> otherwise.
*/
public boolean isREF() {
return nationType != null && nationType.isREF();
}
/**
* Returns the current score of the player.
*
* @return an <code>int</code> value
*/
public int getScore() {
return score;
}
/**
* Modifies the score of the player by the given value.
*
* @param value an <code>int</code> value
*/
public void modifyScore(int value) {
score += value;
}
/**
* Get the <code>Unit</code> value.
*
* @return a <code>List<Unit></code> value
*/
public final Unit getUnit(String id) {
return units.get(id);
}
/**
* Set the <code>Unit</code> value.
*
* @param newUnit The new Units value.
*/
public final void setUnit(final Unit newUnit) {
if (newUnit != null) {
units.put(newUnit.getId(), newUnit);
}
}
/**
* Remove Unit.
*
* @param oldUnit an <code>Unit</code> value
*/
public void removeUnit(final Unit oldUnit) {
if (oldUnit != null) {
units.remove(oldUnit.getId());
}
}
/**
* Gets the total percentage of rebels in all this player's colonies.
*
* @return The total percentage of rebels in all this player's colonies.
*/
public int getSoL() {
int sum = 0;
int number = 0;
for (Colony c : getColonies()) {
sum += c.getSoL();
number++;
}
if (number > 0) {
return sum / number;
} else {
return 0;
}
}
/**
* Declares independence.
*/
public void declareIndependence() {
if (getSoL() < 50) {
throw new IllegalStateException("Cannot declare independence. SoL is only: " + getSoL());
}
if (playerType != PlayerType.COLONIAL) {
throw new IllegalStateException("Independence has already been declared.");
}
setPlayerType(PlayerType.REBEL);
featureContainer.addAbility(new Ability("model.ability.independenceDeclared"));
changeRelationWithPlayer(getREFPlayer(), Stance.WAR);
setTax(0);
// Reset all arrears
for (GoodsType goodsType : FreeCol.getSpecification().getGoodsTypeList()) {
resetArrears(goodsType);
}
// Dispose all units in Europe.
ArrayList<String> unitNames = new ArrayList<String>();
for (Unit unit : europe.getUnitList()) {
unitNames.add(unit.getName());
unit.dispose();
}
if (!unitNames.isEmpty()) {
addModelMessage(this, ModelMessage.MessageType.UNIT_LOST, "model.player.independence.unitsSeized",
"%units%", Utils.join(", ", unitNames));
}
for (Colony colony : getColonies()) {
int sol = colony.getSoL();
if (sol > 50) {
List<Unit> veterans = new ArrayList<Unit>();
for (Unit unit : colony.getTile().getUnitList()) {
if (unit.hasAbility("model.ability.expertSoldier")) {
veterans.add(unit);
}
}
int limit = veterans.size() * (sol - 50) / 100;
if (limit > 0) {
for (int index = 0; index < limit; index++) {
Unit unit = veterans.get(index);
// TODO: use a new upgrade type?
unit.setType(unit.getType().getPromotion());
}
addModelMessage(colony, ModelMessage.MessageType.DEFAULT, "model.player.continentalArmyMuster",
"%colony%", colony.getName(), "%number%", String.valueOf(limit));
}
}
}
europe.dispose();
europe = null;
monarch = null;
modifyScore(SCORE_INDEPENDENCE_DECLARED);
}
/**
* Gives independence to this <code>Player</code>.
*/
public void giveIndependence() {
if (!isEuropean()) {
throw new IllegalStateException("The player \"" + getName() + "\" is not european");
}
if (playerType != PlayerType.REBEL) {
throw new IllegalStateException("The player \"" + getName() + "\" is already independent");
}
setPlayerType(PlayerType.INDEPENDENT);
changeRelationWithPlayer(getREFPlayer(), Stance.PEACE);
modifyScore(SCORE_INDEPENDENCE_GRANTED - getGame().getTurn().getNumber());
addModelMessage(this, ModelMessage.MessageType.DEFAULT, "model.player.independence");
}
/**
* Gets the <code>Player</code> controlling the "Royal Expeditionary
* Force" for this player.
*
* @return The player, or <code>null</code> if this player does not have a
* royal expeditionary force.
*/
public Player getREFPlayer() {
return getGame().getPlayer(getNation().getRefId());
}
/**
* Gets the name this player has chosen for the new land.
*
* @return The name of the new world as chosen by the <code>Player</code>.
* If no land name was chosen, the default name is returned.
*/
public String getNewLandName() {
if (newLandName == null) {
return Messages.message(nationID + ".newLandName");
} else {
return newLandName;
}
}
/**
* Returns true if the player already selected a new name for the discovered
* land.
*
* @return true if the player already set a name for the newly discovered
* land, otherwise false.
*/
public boolean isNewLandNamed() {
return newLandName != null;
}
/**
* Returns the <code>Colony</code> with the given name.
*
* @param name The name of the <code>Colony</code>.
* @return The <code>Colony</code> or <code>null</code> if this player
* does not have a <code>Colony</code> with the specified name.
*/
public Colony getColony(String name) {
for (Colony colony : getColonies()) {
if (colony.getName().equals(name)) {
return colony;
}
}
return null;
}
/**
* Creates a unique colony name. This is done by fetching a new default
* colony name from the list of default names.
*
* @return A <code>String</code> containing a new unused colony name from
* the list, if any is available, and otherwise an automatically
* generated name.
*/
public String getDefaultColonyName() {
String prefix = nationID + ".newColonyName.";
String name = null;
do {
if (Messages.containsKey(prefix + Integer.toString(colonyNameIndex))) {
name = Messages.message(prefix + Integer.toString(colonyNameIndex));
colonyNameIndex++;
}
} while (getGame().getColony(name) != null);
if (name == null) {
do {
name = Messages.message("Colony") + colonyNameIndex;
colonyNameIndex++;
} while (getColony(name) != null);
}
return name;
}
/**
* Creates a unique region name by fetching a new default name
* from the list of default names if possible.
*
* @param regionType a <code>RegionType</code> value
* @return a <code>String</code> value
*/
public String getDefaultRegionName(RegionType regionType) {
String prefix = nationID + ".region." + regionType.toString().toLowerCase() + ".";
String name = null;
int index = 1;
Integer newIndex = regionNameIndex.get(regionType);
if (newIndex != null) {
index = newIndex.intValue();
}
do {
if (Messages.containsKey(prefix + Integer.toString(index))) {
name = Messages.message(prefix + Integer.toString(index));
index++;
}
} while (getGame().getMap().getRegion(name) != null);
if (name == null) {
do {
name = Messages.message("model.region." + regionType.toString().toLowerCase()) + index;
index++;
} while (getGame().getMap().getRegion(name) != null);
}
regionNameIndex.put(regionType, index);
return name;
}
/**
* Sets the name this player uses for the new land.
*
* @param newLandName This <code>Player</code>'s name for the new world.
*/
public void setNewLandName(String newLandName) {
this.newLandName = newLandName;
}
/**
* Checks if this player is european. This includes the "Royal Expeditionay
* Force".
*
* @return <i>true</i> if this player is european and <i>false</i>
* otherwise.
*/
public boolean isEuropean() {
return nationType != null && nationType.isEuropean();
}
/**
* Checks if this player is indian. This method returns the opposite of
* {@link #isEuropean()}.
*
* @return <i>true</i> if this player is indian and <i>false</i>
* otherwise.
*/
public boolean isIndian() {
return playerType == PlayerType.NATIVE;
}
/**
* Checks whether this player is at war with any other player.
*
* @return <i>true</i> if this player is at war with any other.
*/
public boolean isAtWar() {
for (Player player : getGame().getPlayers()) {
if (getStance(player) == Stance.WAR) {
return true;
}
}
return false;
}
/**
* Returns the price of the given land.
*
* @param tile The <code>Tile</code> to get the price for.
* @return The price of the land.
*/
public int getLandPrice(Tile tile) {
Player nationOwner = tile.getOwner();
if (nationOwner == null || nationOwner == this || nationOwner.isEuropean() || tile.getSettlement() != null) {
return 0;
}
int price = 0;
for (GoodsType type : FreeCol.getSpecification().getGoodsTypeList()) {
price += tile.potential(type);
}
price = price * Specification.getSpecification().getIntegerOption("model.option.landPriceFactor").getValue()
+ 100;
return (int) featureContainer.applyModifier(price, "model.modifier.landPaymentModifier", null, getGame()
.getTurn());
}
/**
* Buys the given land.
*
* @param tile The <code>Tile</code> to buy.
*/
public void buyLand(Tile tile) {
Player owner = tile.getOwner();
if (owner == null) {
throw new IllegalStateException("The Tile is not owned by any nation!");
}
if (owner == this) {
throw new IllegalStateException("The Player already owns the Tile.");
}
if (owner.isEuropean()) {
throw new IllegalStateException("The owner is an european player");
}
int price = getLandPrice(tile);
modifyGold(-price);
owner.modifyGold(price);
tile.setOwner(this);
tile.setOwningSettlement(null);
}
/**
* Returns whether this player has met with the <code>Player</code> if the
* given <code>nation</code>.
*
* @param player The Player.
* @return <code>true</code> if this <code>Player</code> has contacted
* the given nation.
*/
public boolean hasContacted(Player player) {
if (player == null) {
return true;
} else {
return stance.containsKey(player.getId());
}
}
/**
* Sets whether this player has contacted the given player.
*
* @param player The <code>Player</code>.
* @param contacted <code>true</code> if this <code>Player</code> has
* contacted the given <code>Player</code>.
*/
public void setContacted(Player player, boolean contacted) {
if (player == null || player == this || player == getGame().getUnknownEnemy()) {
return;
}
if (contacted && !hasContacted(player)) {
stance.put(player.getId(), Stance.PEACE);
if (isEuropean() && !isAI()) {
boolean contactedIndians = false;
boolean contactedEuro = false;
for (Player player1 : getGame().getPlayers()) {
if (hasContacted(player1)) {
if (player1.isEuropean()) {
contactedEuro = true;
if (contactedIndians) {
break;
}
} else {
contactedIndians = true;
if (contactedEuro) {
break;
}
}
}
}
// these dialogs should only appear on the first event
if (player.isEuropean()) {
if (!contactedEuro) {
addModelMessage(this, ModelMessage.MessageType.FOREIGN_DIPLOMACY, player,
"EventPanel.MEETING_EUROPEANS");
}
} else {
if (!contactedIndians) {
addModelMessage(this, ModelMessage.MessageType.FOREIGN_DIPLOMACY, player,
"EventPanel.MEETING_NATIVES");
}
// special cases for Aztec/Inca
if (player.getNationType() == FreeCol.getSpecification().getNationType("model.nationType.aztec")) {
addModelMessage(this, ModelMessage.MessageType.FOREIGN_DIPLOMACY, player,
"EventPanel.MEETING_AZTEC");
} else if (player.getNationType() == FreeCol.getSpecification().getNationType(
"model.nationType.inca")) {
addModelMessage(this, ModelMessage.MessageType.FOREIGN_DIPLOMACY, player,
"EventPanel.MEETING_INCA");
}
}
} else if (!isEuropean()) {
tension.put(player, new Tension(0));
}
}
if (!contacted) {
stance.remove(player.getId());
}
}
/**
* Returns whether this player has been attacked by privateers.
*
* @return <code>true</code> if this <code>Player</code> has been
* attacked by privateers.
*/
public boolean hasBeenAttackedByPrivateers() {
return attackedByPrivateers;
}
/** Sets the variable attackedByPrivateers to true. */
public void setAttackedByPrivateers() {
attackedByPrivateers = true;
}
/**
* Gets the default <code>Location</code> where the units arriving from
* {@link Europe} will be put.
*
* @return The <code>Location</code>.
* @see Unit#getEntryLocation
*/
public Location getEntryLocation() {
return entryLocation;
}
/**
* Sets the <code>Location</code> where the units arriving from
* {@link Europe} will be put as a default.
*
* @param entryLocation The <code>Location</code>.
* @see #getEntryLocation
*/
public void setEntryLocation(Location entryLocation) {
this.entryLocation = entryLocation;
}
/**
* Checks if this <code>Player</code> has explored the given
* <code>Tile</code>.
*
* @param tile The <code>Tile</code>.
* @return <i>true</i> if the <code>Tile</code> has been explored and
* <i>false</i> otherwise.
*/
public boolean hasExplored(Tile tile) {
return tile.isExplored();
}
/**
* Sets the given tile to be explored by this player and updates the
* player's information about the tile.
*
* @param tile The <code>Tile</code> to set explored.
* @see Tile#updatePlayerExploredTile(Player)
*/
public void setExplored(Tile tile) {
logger.warning("Implemented by ServerPlayer");
}
/**
* Sets the tiles within the given <code>Unit</code>'s line of sight to
* be explored by this player.
*
* @param unit The <code>Unit</code>.
* @see #setExplored(Tile)
* @see #hasExplored
*/
public void setExplored(Unit unit) {
if (getGame() == null || getGame().getMap() == null || unit == null || unit.getLocation() == null
|| unit.getTile() == null || isIndian()) {
return;
}
if (canSeeTiles == null) {
resetCanSeeTiles();
}
Iterator<Position> positionIterator = getGame().getMap().getCircleIterator(unit.getTile().getPosition(), true,
unit.getLineOfSight());
while (positionIterator.hasNext()) {
Map.Position p = positionIterator.next();
canSeeTiles[p.getX()][p.getY()] = true;
}
}
/**
* Forces an update of the <code>canSeeTiles</code>. This method should
* be used to invalidate the current <code>canSeeTiles</code>. The method
* {@link #resetCanSeeTiles} will be called whenever it is needed.
*/
public void invalidateCanSeeTiles() {
canSeeTiles = null;
}
/**
* Resets this player's "can see"-tiles. This is done by setting all the
* tiles within a {@link Unit}s line of sight visible. The other tiles are
* made unvisible. <br>
* <br>
* Use {@link #invalidateCanSeeTiles} whenever possible.
*/
public void resetCanSeeTiles() {
Map map = getGame().getMap();
if (map != null) {
canSeeTiles = new boolean[map.getWidth()][map.getHeight()];
if (!getGameOptions().getBoolean(GameOptions.FOG_OF_WAR)) {
Iterator<Position> positionIterator = getGame().getMap().getWholeMapIterator();
while (positionIterator.hasNext()) {
Map.Position p = positionIterator.next();
canSeeTiles[p.getX()][p.getY()] = hasExplored(getGame().getMap().getTile(p));
}
} else {
Iterator<Unit> unitIterator = getUnitIterator();
while (unitIterator.hasNext()) {
Unit unit = unitIterator.next();
if (!(unit.getLocation() instanceof Tile)) {
continue;
}
Map.Position position = unit.getTile().getPosition();
if (position == null) {
logger.warning("position == null");
}
canSeeTiles[position.getX()][position.getY()] = true;
/*
* if (getGame().getViewOwner() == null &&
* !hasExplored(map.getTile(position))) {
*
* logger.warning("Trying to set a non-explored Tile to be
* visible (1). Unit: " + unit.getName() + ", Tile: " +
* position);
*
* throw new IllegalStateException("Trying to set a
* non-explored Tile to be visible. Unit: " + unit.getName() + ",
* Tile: " + position); }
*/
Iterator<Position> positionIterator = map.getCircleIterator(position, true, unit.getLineOfSight());
while (positionIterator.hasNext()) {
Map.Position p = positionIterator.next();
canSeeTiles[p.getX()][p.getY()] = true;
/*
* if (getGame().getViewOwner() == null &&
* !hasExplored(map.getTile(p))) {
*
* logger.warning("Trying to set a non-explored Tile to
* be visible (2). Unit: " + unit.getName() + ", Tile: " +
* p);
*
* throw new IllegalStateException("Trying to set a
* non-explored Tile to be visible. Unit: " +
* unit.getName() + ", Tile: " + p); }
*/
}
}
for (Settlement settlement : getSettlements()) {
Map.Position position = settlement.getTile().getPosition();
canSeeTiles[position.getX()][position.getY()] = true;
/*
* if (getGame().getViewOwner() == null &&
* !hasExplored(map.getTile(position))) {
*
* logger.warning("Trying to set a non-explored Tile to be
* visible (3). Settlement: " + settlement + "(" +
* settlement.getTile().getPosition() + "), Tile: " +
* position);
*
* throw new IllegalStateException("Trying to set a
* non-explored Tile to be visible. Settlement: " +
* settlement + "(" + settlement.getTile().getPosition() +
* "), Tile: " + position); }
*/
Iterator<Position> positionIterator = map.getCircleIterator(position, true, settlement
.getLineOfSight());
while (positionIterator.hasNext()) {
Map.Position p = positionIterator.next();
canSeeTiles[p.getX()][p.getY()] = true;
/*
* if (getGame().getViewOwner() == null &&
* !hasExplored(map.getTile(p))) {
*
* logger.warning("Trying to set a non-explored Tile to
* be visible (4). Settlement: " + settlement + "(" +
* settlement.getTile().getPosition() + "), Tile: " +
* p);
*
* throw new IllegalStateException("Trying to set a
* non-explored Tile to be visible. Settlement: " +
* settlement + "(" + settlement.getTile().getPosition() +
* "), Tile: " + p); }
*/
}
}
}
}
}
/**
* Checks if this <code>Player</code> can see the given <code>Tile</code>.
* The <code>Tile</code> can be seen if it is in a {@link Unit}'s line of
* sight.
*
* @param tile The given <code>Tile</code>.
* @return <i>true</i> if the <code>Player</code> can see the given
* <code>Tile</code> and <i>false</i> otherwise.
*/
public boolean canSee(Tile tile) {
if (tile == null) {
return false;
}
if (canSeeTiles == null) {
resetCanSeeTiles();
if (canSeeTiles == null) {
return false;
}
}
return canSeeTiles[tile.getX()][tile.getY()];
}
/**
* Returns the type of this player.
*
* @return The player type.
*/
public PlayerType getPlayerType() {
return playerType;
}
/**
* Checks if this <code>Player</code> can build colonies.
*
* @return <code>true</code> if this player is european, not the royal
* expeditionary force and not currently fighting the war of
* independence.
*/
public boolean canBuildColonies() {
return nationType.hasAbility("model.ability.foundColony");
}
/**
* Checks if this <code>Player</code> can get founding fathers.
*
* @return <code>true</code> if this player is european, not the royal
* expeditionary force and not currently fighting the war of
* independence.
*/
public boolean canHaveFoundingFathers() {
return nationType.hasAbility("model.ability.electFoundingFather");
}
/**
* Sets the player type.
*
* @param type The new player type.
* @see #getPlayerType
*/
public void setPlayerType(PlayerType type) {
playerType = type;
}
/**
* Determines whether this player has a certain Founding father.
*
* @param someFather a <code>FoundingFather</code> value
* @return Whether this player has this Founding father
* @see FoundingFather
*/
public boolean hasFather(FoundingFather someFather) {
return allFathers.contains(someFather);
}
/**
* Returns the number of founding fathers in this players congress. Used to
* calculate number of bells needed to recruit new fathers.
*
* @return The number of founding fathers in this players congress
*/
public int getFatherCount() {
return allFathers.size();
}
/**
* Sets this players liberty bell production to work towards recruiting
* <code>father</code> to its congress.
*
* @param someFather a <code>FoundingFather</code> value
* @see FoundingFather
*/
public void setCurrentFather(FoundingFather someFather) {
currentFather = someFather;
}
/**
* Gets the {@link FoundingFather founding father} this player is working
* towards.
*
* @return The current FoundingFather or null if there is none
* @see #setCurrentFather
* @see FoundingFather
*/
public FoundingFather getCurrentFather() {
return currentFather;
}
/**
* Gets called when this player's turn has ended.
*/
public void endTurn() {
removeModelMessages();
resetCanSeeTiles();
}
/**
* Checks if this <code>Player</code> can move units to
* <code>Europe</code>.
*
* @return <code>true</code> if this <code>Player</code> has an instance
* of <code>Europe</code>.
*/
public boolean canMoveToEurope() {
return getEurope() != null;
}
/**
* Returns the europe object that this player has.
*
* @return The europe object that this player has or <code>null</code> if
* this <code>Player</code> does not have an instance
* <code>Europe</code>.
*/
public Europe getEurope() {
return europe;
}
/**
* Describe <code>getEuropeName</code> method here.
*
* @return a <code>String</code> value
*/
public String getEuropeName() {
if (europe == null) {
return null;
} else {
return Messages.message(nationID + ".europe");
}
}
/**
* Returns the monarch object this player has.
*
* @return The monarch object this player has or <code>null</code> if this
* <code>Player</code> does not have an instance
* <code>Monarch</code>.
*/
public Monarch getMonarch() {
return monarch;
}
/**
* Sets the monarch object this player has.
*
* @param monarch The monarch object this player should have.
*/
public void setMonarch(Monarch monarch) {
this.monarch = monarch;
}
/**
* Returns the amount of gold that this player has.
*
* @return The amount of gold that this player has or <code>-1</code> if
* the amount of gold is unknown.
*/
public int getGold() {
return gold;
}
/**
* Modifies the amount of gold that this player has. The argument can be
* both positive and negative.
*
* @param amount The amount of gold that should be added to this player's
* gold amount (can be negative!).
* @exception IllegalArgumentException if the player gets a negative amount
* of gold after adding <code>amount</code>.
*/
public void modifyGold(int amount) {
if (this.gold == -1) {
return;
}
if ((gold + amount) >= 0) {
modifyScore((gold + amount) / 1000 - gold / 1000);
gold += amount;
} else {
// This can happen if the server and the client get out of synch.
// Perhaps it can also happen if the client tries to adjust gold
// for another player, where the balance is unknown. Just keep
// going and do the best thing possible, we don't want to crash
// the game here.
logger.warning("Cannot add " + amount + " gold for " + this + ": would be negative!");
gold = 0;
}
}
/**
* Determines whether this player is an AI player.
*
* @return Whether this player is an AI player.
*/
public boolean isAI() {
return ai;
}
/**
* Sets whether this player is an AI player.
*
* @param ai <code>true</code> if this <code>Player</code> is controlled
* by the computer.
*/
public void setAI(boolean ai) {
this.ai = ai;
}
/**
* Gets a new active unit.
*
* @return A <code>Unit</code> that can be made active.
*/
public Unit getNextActiveUnit() {
return nextActiveUnitIterator.next();
}
/**
* Gets a new going_to unit.
*
* @return A <code>Unit</code> that can be made active.
*/
public Unit getNextGoingToUnit() {
return nextGoingToUnitIterator.next();
}
/**
* Checks if a new active unit can be made active.
*
* @return <i>true</i> if this is the case and <i>false</i> otherwise.
*/
public boolean hasNextActiveUnit() {
return nextActiveUnitIterator.hasNext();
}
/**
* Checks if a new active unit can be made active.
*
* @return <i>true</i> if this is the case and <i>false</i> otherwise.
*/
public boolean hasNextGoingToUnit() {
return nextGoingToUnitIterator.hasNext();
}
/**
* Checks if this player is an admin.
*
* @return <i>true</i> if the player is an admin and <i>false</i>
* otherwise.
*/
public boolean isAdmin() {
return admin;
}
/**
* Checks if this player is dead. A <code>Player</code> dies when it
* looses the game.
*
* @return <code>true</code> if this <code>Player</code> is dead.
*/
public boolean isDead() {
return dead;
}
/**
* Sets this player to be dead or not.
*
* @param dead Should be set to <code>true</code> when this
* <code>Player</code> dies.
* @see #isDead
*/
public void setDead(boolean dead) {
this.dead = dead;
}
/**
* Returns the name of this player.
*
* @return The name of this player.
*/
public String getName() {
return name;
}
/**
* Returns the name of this player.
*
* @return The name of this player.
*/
public String toString() {
return getName();
}
/**
* Set the <code>Name</code> value.
*
* @param newName The new Name value.
*/
public void setName(String newName) {
this.name = newName;
}
/**
* Returns the nation type of this player.
*
* @return The nation type of this player.
*/
public NationType getNationType() {
return nationType;
}
/**
* Sets the nation type of this player.
*
* @param newNationType a <code>NationType</code> value
*/
public void setNationType(NationType newNationType) {
if (nationType != null) {
featureContainer.remove(nationType.getFeatureContainer());
}
nationType = newNationType;
featureContainer.add(newNationType.getFeatureContainer());
}
/**
* Return this Player's nation.
*
* @return a <code>String</code> value
*/
public Nation getNation() {
return FreeCol.getSpecification().getNation(nationID);
}
/**
* Sets the nation for this player.
*
* @param newNation The new nation for this player.
*/
public void setNation(Nation newNation) {
final String oldNationID = nationID;
nationID = newNation.getId();
firePropertyChange("nationID", oldNationID, nationID);
}
/**
* Return the ID of this Player's nation.
*
* @return a <code>String</code> value
*/
public String getNationID() {
return nationID;
}
/**
* Returns the nation of this player as a String.
*
* @return The nation of this player as a String.
*/
public String getNationAsString() {
return Messages.message(nationID + ".name");
}
/**
* Get the <code>RulerName</code> value.
*
* @return a <code>String</code> value
*/
public final String getRulerName() {
return Messages.message(nationID + ".ruler");
}
/**
* Returns the color of this player.
*
* @return The color of this player.
*/
public Color getColor() {
return color;
}
/**
* Sets the color for this player.
*
* @param c The new color for this player.
*/
public void setColor(Color c) {
color = c;
}
/**
* Checks if this <code>Player</code> is ready to start the game.
*
* @return <code>true</code> if this <code>Player</code> is ready to
* start the game.
*/
public boolean isReady() {
return ready;
}
/**
* Sets this <code>Player</code> to be ready/not ready for starting the
* game.
*
* @param ready This indicates if the player is ready to start the game.
*/
public void setReady(boolean ready) {
this.ready = ready;
}
/**
* Gets an <code>Iterator</code> containing all the units this player
* owns.
*
* @return The <code>Iterator</code>.
* @see Unit
*/
public Iterator<Unit> getUnitIterator() {
return units.values().iterator();
}
public List<Unit> getUnits() {
return new ArrayList<Unit>(units.values());
}
/**
* Returns a list of all Settlements this player owns.
*
* @return The settlements this player owns.
*/
public List<Settlement> getSettlements() {
return settlements;
}
/**
* Returns a list of all Colonies this player owns.
*
* @return The colonies this player owns.
*/
public List<Colony> getColonies() {
ArrayList<Colony> colonies = new ArrayList<Colony>();
for (Settlement s : settlements) {
if (s instanceof Colony) {
colonies.add((Colony) s);
} else {
throw new RuntimeException("getColonies can only be called for players whose settlements are colonies.");
}
}
return colonies;
}
/**
* Returns a list of all IndianSettlements this player owns.
*
* @return The indian settlements this player owns.
*/
public List<IndianSettlement> getIndianSettlements() {
ArrayList<IndianSettlement> indianSettlements = new ArrayList<IndianSettlement>();
for (Settlement s : settlements) {
if (s instanceof IndianSettlement) {
indianSettlements.add((IndianSettlement) s);
} else {
throw new RuntimeException(
"getIndianSettlements can only be called for players whose settlements are IndianSettlements.");
}
}
return indianSettlements;
}
/**
* Returns the closest <code>Location</code> in which the given ship can
* get repaired. This is the closest {@link Colony} with a drydock, or
* {@link Europe} if this player has no colonies with a drydock.
*
* @param unit The ship that needs a location to be repaired.
* @return The closest <code>Location</code> in which the ship can be
* repaired.
* @exception IllegalArgumentException if the <code>unit</code> is not a
* ship.
*/
public Location getRepairLocation(Unit unit) {
if (!unit.isNaval()) {
throw new IllegalArgumentException();
}
Location closestLocation = null;
int shortestDistance = Integer.MAX_VALUE;
for (Colony colony : getColonies()) {
if (colony == null || colony.getTile() == unit.getTile()) {
// This happens when is called from damageAllShips because
// the colony is being captured and can't be repaired in that
// colony
continue;
}
int distance;
if (colony.hasAbility("model.ability.repairUnits")
&& (distance = unit.getTile().getDistanceTo(colony.getTile())) < shortestDistance) {
closestLocation = colony;
shortestDistance = distance;
}
}
if (closestLocation != null) {
return closestLocation;
}
return getEurope();
}
/**
* Increments the player's cross count, with benefits thereof.
*
* @param num The number of crosses to add.
* @see #reduceCrosses
*/
public void incrementCrosses(int num) {
if (!canRecruitUnits()) {
return;
}
crosses += num;
}
/**
* Sets the number of crosses this player possess.
*
* @see #incrementCrosses(int)
*/
public void reduceCrosses() {
if (!canRecruitUnits()) {
return;
}
int cost = getGameOptions().getBoolean(GameOptions.SAVE_PRODUCTION_OVERFLOW) ? crossesRequired : crosses;
if (cost > this.crosses) {
this.crosses = 0;
}
else {
this.crosses -= cost;
}
}
/**
* Gets the number of crosses this player possess.
*
* @return The number.
* @see #reduceCrosses
*/
public int getCrosses() {
if (!canRecruitUnits()) {
return 0;
}
return crosses;
}
/**
* Get the <code>TradeRoutes</code> value.
*
* @return a <code>List<TradeRoute></code> value
*/
public final List<TradeRoute> getTradeRoutes() {
return tradeRoutes;
}
/**
*
* Set the <code>TradeRoutes</code> value.
*
*
*
* @param newTradeRoutes The new TradeRoutes value.
*
*/
public final void setTradeRoutes(final List<TradeRoute> newTradeRoutes) {
this.tradeRoutes = newTradeRoutes;
}
/**
* Checks to see whether or not a colonist can emigrate, and does so if
* possible.
*
* @return Whether a new colonist should immigrate.
*/
public boolean checkEmigrate() {
if (!canRecruitUnits()) {
return false;
}
return getCrossesRequired() <= crosses;
}
/**
* Gets the number of crosses required to cause a new colonist to emigrate.
*
* @return The number of crosses required to cause a new colonist to
* emigrate.
*/
public int getCrossesRequired() {
if (!canRecruitUnits()) {
return 0;
}
return crossesRequired;
}
/**
* Sets the number of crosses required to cause a new colonist to emigrate.
*
* @param crossesRequired The number of crosses required to cause a new
* colonist to emigrate.
*/
public void setCrossesRequired(int crossesRequired) {
if (!canRecruitUnits()) {
return;
}
this.crossesRequired = crossesRequired;
}
/**
* Checks if this <code>Player</code> can recruit units by producing
* crosses.
*
* @return <code>true</code> if units can be recruited by this
* <code>Player</code>.
*/
public boolean canRecruitUnits() {
return playerType == PlayerType.COLONIAL;
}
/**
* Updates the amount of crosses needed to emigrate a <code>Unit</code>
* from <code>Europe</code>.
*/
public void updateCrossesRequired() {
if (!canRecruitUnits()) {
return;
}
crossesRequired += (int) featureContainer.applyModifier(Specification.getSpecification().getIntegerOption(
"model.option.crossesIncrement").getValue(), "model.modifier.religiousUnrestBonus");
// The book I have tells me the crosses needed is:
// [(colonist count in colonies + total colonist count) * 2] + 8.
// So every unit counts as 2 unless they're in a colony,
// wherein they count as 4.
/*
* int count = 8; Map map = getGame().getMap(); Iterator<Position>
* tileIterator = map.getWholeMapIterator(); while
* (tileIterator.hasNext()) { Tile t = map.getTile(tileIterator.next());
* if (t != null && t.getFirstUnit() != null &&
* t.getFirstUnit().getOwner().equals(this)) { Iterator<Unit>
* unitIterator = t.getUnitIterator(); while (unitIterator.hasNext()) {
* Unit u = unitIterator.next(); Iterator<Unit> childUnitIterator =
* u.getUnitIterator(); while (childUnitIterator.hasNext()) { // Unit
* childUnit = (Unit) childUnitIterator.next();
* childUnitIterator.next(); count += 2; } count += 2; } } if (t != null &&
* t.getColony() != null && t.getColony().getOwner() == this) { count +=
* t.getColony().getUnitCount() * 4; // Units in colonies // count
* doubly. // -sjm } } Iterator<Unit> europeUnitIterator =
* getEurope().getUnitIterator(); while (europeUnitIterator.hasNext()) {
* europeUnitIterator.next(); count += 2; } if (nation == ENGLISH) {
* count = (count * 2) / 3; } setCrossesRequired(count);
*/
}
/**
* Modifies the hostiliy against the given player.
*
* @param player The <code>Player</code>.
* @param addToTension The amount to add to the current tension level.
*/
public void modifyTension(Player player, int addToTension) {
modifyTension(player, addToTension, null);
}
public void modifyTension(Player player, int addToTension, IndianSettlement origin) {
if (player == this || player == null) {
return;
}
if (tension.get(player) == null) {
tension.put(player, new Tension(addToTension));
} else {
tension.get(player).modify(addToTension);
}
if (origin != null && isIndian() && origin.getOwner() == player) {
for (Settlement settlement : settlements) {
if (settlement instanceof IndianSettlement && !origin.equals(settlement)) {
((IndianSettlement) settlement).propagatedAlarm(player, addToTension);
}
}
}
}
/**
* Sets the hostility against the given player.
*
* @param player The <code>Player</code>.
* @param newTension The <code>Tension</code>.
*/
public void setTension(Player player, Tension newTension) {
if (player == this || player == null) {
return;
}
tension.put(player, newTension);
}
/**
* Gets the hostility this player has against the given player.
*
* @param player The <code>Player</code>.
* @return An object representing the tension level.
*/
public Tension getTension(Player player) {
if (player == null) {
return new Tension();
} else {
return tension.get(player);
}
}
private static int getNearbyColonyBonus(Player owner, Tile tile) {
Game game = tile.getGame();
Map map = game.getMap();
Iterator<Position> it = map.getCircleIterator(tile.getPosition(), false, 3);
while (it.hasNext()) {
Tile ct = map.getTile(it.next());
if (ct.getColony() != null && ct.getColony().getOwner() == owner) {
return 45;
}
}
it = map.getCircleIterator(tile.getPosition(), false, 4);
while (it.hasNext()) {
Tile ct = map.getTile(it.next());
if (ct.getColony() != null && ct.getColony().getOwner() == owner) {
return 25;
}
}
it = map.getCircleIterator(tile.getPosition(), false, 5);
while (it.hasNext()) {
Tile ct = map.getTile(it.next());
if (ct.getColony() != null && ct.getColony().getOwner() == owner) {
return 20;
}
}
it = map.getCircleIterator(tile.getPosition(), false, 6);
while (it.hasNext()) {
Tile ct = map.getTile(it.next());
if (ct.getColony() != null && ct.getColony().getOwner() == owner) {
return 30;
}
}
it = map.getCircleIterator(tile.getPosition(), false, 7);
while (it.hasNext()) {
Tile ct = map.getTile(it.next());
if (ct.getColony() != null && ct.getColony().getOwner() == owner) {
return 15;
}
}
it = map.getCircleIterator(tile.getPosition(), false, 8);
while (it.hasNext()) {
Tile ct = map.getTile(it.next());
if (ct.getColony() != null && ct.getColony().getOwner() == owner) {
return 5;
}
}
return 0;
}
/**
* Gets the value of building a <code>Colony</code> on the given tile.
* This method adds bonuses to the colony value if the tile is close to (but
* not overlapping with) another friendly colony. Penalties for enemy
* units/colonies are added as well.
*
* @param tile The <code>Tile</code>
* @return The value of building a colony on the given tile.
* @see Tile#getColonyValue()
*/
public int getColonyValue(Tile tile) {
int value = tile.getColonyValue();
if (value == 0) {
return 0;
} else {
Iterator<Position> it = getGame().getMap().getCircleIterator(tile.getPosition(), true, 4);
while (it.hasNext()) {
Tile ct = getGame().getMap().getTile(it.next());
if (ct.getColony() != null && ct.getColony().getOwner() != this) {
if (getStance(ct.getColony().getOwner()) == Stance.WAR) {
value -= Math.max(0, 20 - tile.getDistanceTo(tile) * 4);
} else {
value -= Math.max(0, 8 - tile.getDistanceTo(tile) * 2);
}
}
Iterator<Unit> ui = ct.getUnitIterator();
while (ui.hasNext()) {
Unit u = ui.next();
if (u.getOwner() != this && u.isOffensiveUnit() && u.getOwner().isEuropean()
&& getStance(u.getOwner()) == Stance.WAR) {
value -= Math.max(0, 40 - tile.getDistanceTo(tile) * 9);
}
}
}
return Math.max(0, value + getNearbyColonyBonus(this, tile));
}
}
/**
* Returns the stance towards a given player. <BR>
* <BR>
* One of: WAR, CEASE_FIRE, PEACE and ALLIANCE.
*
* @param player The <code>Player</code>.
* @return The stance.
*/
public Stance getStance(Player player) {
if (player == null) {
return Stance.PEACE;
} else {
return stance.get(player.getId());
}
}
/**
* Returns a string describing the given stance.
*
* @param stance The stance.
* @return A matching string.
*/
public static String getStanceAsString(Stance stance) {
return Messages.message("model.stance." + stance.toString().toLowerCase());
}
/**
* Sets the stance towards a given player. <BR>
* <BR>
* One of: WAR, CEASE_FIRE, PEACE and ALLIANCE.
* This only sets this player stance,
*<code>changeRelationsWithPlayer</code> should be used to set both players
*
* @param player The <code>Player</code>.
* @param newStance The stance.
*/
public void setStance(Player player, Stance newStance) {
if (player == null) {
throw new IllegalArgumentException("Player must not be 'null'.");
}
if (player == this) {
throw new IllegalArgumentException("Cannot set the stance towards ourselves.");
}
Stance oldStance = stance.get(player.getId());
if (newStance.equals(oldStance)) {
return;
}
if (newStance == Stance.CEASE_FIRE && oldStance != Stance.WAR) {
throw new IllegalStateException("Cease fire can only be declared when at war.");
}
stance.put(player.getId(), newStance);
if (oldStance == Stance.PEACE && newStance == Stance.WAR) {
modifyTension(player, Tension.TENSION_ADD_DECLARE_WAR_FROM_PEACE);
} else if (oldStance == Stance.CEASE_FIRE && newStance == Stance.WAR) {
modifyTension(player, Tension.TENSION_ADD_DECLARE_WAR_FROM_CEASE_FIRE);
}
}
public void changeRelationWithPlayer(Player player,Stance newStance){
setStance(player, newStance);
if (player.getStance(this) != newStance) {
getGame().getModelController().setStance(this, player, newStance);
player.setStance(this, newStance);
}
}
/**
* Gets the price for a recruit in europe.
*
* @return The price of a single recruit in {@link Europe}.
*/
public int getRecruitPrice() {
// return Math.max(0, (getCrossesRequired() - crosses) * 10);
return getEurope().getRecruitPrice();
}
/**
* Increments the player's bell count, with benefits thereof.
*
* @param num The number of bells to add.
*/
public void incrementBells(int num) {
if (!canHaveFoundingFathers()) {
return;
}
bells += num;
}
/**
* Gets the current amount of bells this <code>Player</code> has.
*
* @return This player's number of bells earned towards the current Founding
* Father.
* @see Goods#BELLS
* @see #incrementBells
*/
public int getBells() {
if (!canHaveFoundingFathers()) {
return 0;
}
return bells;
}
/**
* Adds a founding father to this player's continental congress.
*
* @param father a <code>FoundingFather</code> value
* @see FoundingFather
*/
public void addFather(FoundingFather father) {
allFathers.add(father);
addModelMessage(this, ModelMessage.MessageType.DEFAULT, "model.player.foundingFatherJoinedCongress",
"%foundingFather%", father.getName(), "%description%", father.getDescription());
featureContainer.add(father.getFeatureContainer());
List<AbstractUnit> units = father.getUnits();
if (units != null) {
// TODO: make use of armed, mounted, etc.
for (int index = 0; index < units.size(); index++) {
AbstractUnit unit = units.get(index);
String uniqueID = getId() + "newTurn" + father.getId() + index;
getGame().getModelController().createUnit(uniqueID, getEurope(), this, unit.getUnitType());
}
}
java.util.Map<UnitType, UnitType> upgrades = father.getUpgrades();
if (upgrades != null) {
Iterator<Unit> unitIterator = getUnitIterator();
while (unitIterator.hasNext()) {
Unit unit = unitIterator.next();
UnitType newType = upgrades.get(unit.getType());
if (newType != null) {
unit.setType(newType);
}
}
}
for (String event : father.getEvents().keySet()) {
if (event.equals("model.event.resetNativeAlarm")) {
// reduce indian tension and alarm
for (Player player : getGame().getPlayers()) {
if (!player.isEuropean() && player.getTension(this) != null) {
player.getTension(this).setValue(0);
for (IndianSettlement is : player.getIndianSettlements()) {
if (is.getAlarm(this) != null) {
is.getAlarm(this).setValue(0);
}
}
}
}
} else if (event.equals("model.event.boycottsLifted")) {
for (GoodsType goodsType : FreeCol.getSpecification().getGoodsTypeList()) {
resetArrears(goodsType);
}
} else if (event.equals("model.event.freeBuilding")) {
BuildingType type = FreeCol.getSpecification().getBuildingType(father.getEvents().get(event));
for (Colony colony : getColonies()) {
if (colony.canBuild(type)) {
colony.addBuilding(colony.createBuilding(type));
}
}
} else if (event.equals("model.event.seeAllColonies")) {
exploreAllColonies();
} else if (event.equals("model.event.increaseSonsOfLiberty")) {
int value = Integer.parseInt(father.getEvents().get(event));
for (Colony colony : getColonies()) {
/*
* The number of bells to be generated in order to get the
* appropriate SoL is determined by the formula: int
* membership = ... in "colony.updateSoL()":
*/
int requiredBells = ((colony.getSoL() + value) * Colony.BELLS_PER_REBEL * colony.getUnitCount()) / 100;
colony.addGoods(Goods.BELLS, requiredBells - colony.getGoodsCount(Goods.BELLS));
}
} else if (event.equals("model.event.newRecruits")) {
for (int index = 0; index < 3; index++) {
UnitType recruitable = getEurope().getRecruitable(index);
if (featureContainer.hasAbility("model.ability.canNotRecruitUnit", recruitable)) {
- // this creates client/server
- // desynchronization, see bug report[ 2030153
- // ] Stateman becomes scout instead, this
- // should only happen on the server, and new
- // UnitTypes should be transmitted to the
- // client
getEurope().setRecruitable(index, generateRecruitable("newRecruits" + index));
}
}
}
}
}
/**
* Prepares this <code>Player</code> for a new turn.
*/
public void newTurn() {
int newSoL = 0;
// reducing tension levels if nation is native
if (isIndian()) {
for (Tension tension1 : tension.values()) {
if (tension1.getValue() > 0) {
tension1.modify(-(4 + tension1.getValue() / 100));
}
}
}
// settlements
ArrayList<Settlement> settlements = new ArrayList<Settlement>(getSettlements());
for (Settlement settlement : settlements) {
logger.finest("Calling newTurn for settlement " + settlement.toString());
settlement.newTurn();
if (isEuropean()) {
Colony colony = (Colony) settlement;
newSoL += colony.getSoL();
}
}
/*
* Moved founding fathers infront of units so that naval units will get
* their Magellan bonus the turn Magellan joins the congress.
*/
if (isEuropean()) {
if (!hasAbility("model.ability.independenceDeclared") &&
getBells() >= getTotalFoundingFatherCost() &&
currentFather != null) {
addFather(currentFather);
currentFather = null;
bells -= getGameOptions().getBoolean(GameOptions.SAVE_PRODUCTION_OVERFLOW) ?
getTotalFoundingFatherCost() : bells;
}
// CO: since the pioneer already finishes faster, changing
// it at both locations would double the bonus.
/**
* Create new collection to avoid to concurrent modification.
*/
for (Unit unit : new ArrayList<Unit>(units.values())) {
logger.finest("Calling newTurn for unit " + unit.getName() + " " + unit.getId());
unit.newTurn();
}
if (getEurope() != null) {
logger.finest("Calling newTurn for player " + getName() + "'s Europe");
getEurope().newTurn();
}
if (getMarket() != null) {
logger.finest("Calling newTurn for player " + getName() + "'s Market");
getMarket().newTurn();
}
int numberOfColonies = settlements.size();
if (numberOfColonies > 0) {
newSoL = newSoL / numberOfColonies;
if (oldSoL / 10 != newSoL / 10) {
if (newSoL > oldSoL) {
addModelMessage(this, ModelMessage.MessageType.SONS_OF_LIBERTY, "model.player.SoLIncrease",
"%oldSoL%", String.valueOf(oldSoL), "%newSoL%", String.valueOf(newSoL));
} else {
addModelMessage(this, ModelMessage.MessageType.SONS_OF_LIBERTY, "model.player.SoLDecrease",
"%oldSoL%", String.valueOf(oldSoL), "%newSoL%", String.valueOf(newSoL));
}
}
}
// remember SoL for check changes at next turn
oldSoL = newSoL;
} else {
for (Iterator<Unit> unitIterator = getUnitIterator(); unitIterator.hasNext();) {
Unit unit = unitIterator.next();
if (logger.isLoggable(Level.FINEST)) {
logger.finest("Calling newTurn for unit " + unit.getName() + " " + unit.getId());
}
unit.newTurn();
}
}
}
private void exploreAllColonies() {
// explore all tiles surrounding colonies
ArrayList<Tile> tiles = new ArrayList<Tile>();
Iterator<Position> tileIterator = getGame().getMap().getWholeMapIterator();
while (tileIterator.hasNext()) {
Tile tile = getGame().getMap().getTile((tileIterator.next()));
if (tile.getColony() != null) {
tiles.add(tile);
for (Direction direction : Direction.values()) {
Tile addTile = getGame().getMap().getNeighbourOrNull(direction, tile);
if (addTile != null) {
tiles.add(addTile);
}
}
}
}
getGame().getModelController().exploreTiles(this, tiles);
}
/**
* This method writes an XML-representation of this object to the given
* stream. <br>
* <br>
* Only attributes visible to the given <code>Player</code> will be added
* to that representation if <code>showAll</code> is set to
* <code>false</code>.
*
* @param out The target stream.
* @param player The <code>Player</code> this XML-representation should be
* made for, or <code>null</code> if
* <code>showAll == true</code>.
* @param showAll Only attributes visible to <code>player</code> will be
* added to the representation if <code>showAll</code> is set
* to <i>false</i>.
* @param toSavedGame If <code>true</code> then information that is only
* needed when saving a game is added.
* @throws XMLStreamException if there are any problems writing to the
* stream.
*/
protected void toXMLImpl(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame)
throws XMLStreamException {
// Start element:
out.writeStartElement(getXMLElementTagName());
out.writeAttribute("ID", getId());
out.writeAttribute("index", String.valueOf(index));
out.writeAttribute("username", name);
out.writeAttribute("nationID", nationID);
if (nationType != null) {
out.writeAttribute("nationType", nationType.getId());
}
out.writeAttribute("color", Integer.toString(color.getRGB()));
out.writeAttribute("admin", Boolean.toString(admin));
out.writeAttribute("ready", Boolean.toString(ready));
out.writeAttribute("dead", Boolean.toString(dead));
out.writeAttribute("playerType", playerType.toString());
out.writeAttribute("ai", Boolean.toString(ai));
out.writeAttribute("tax", Integer.toString(tax));
out.writeAttribute("numberOfSettlements", Integer.toString(numberOfSettlements));
if (getGame().isClientTrusted() || showAll || equals(player)) {
out.writeAttribute("gold", Integer.toString(gold));
out.writeAttribute("crosses", Integer.toString(crosses));
out.writeAttribute("bells", Integer.toString(bells));
if (currentFather != null) {
out.writeAttribute("currentFather", currentFather.getId());
}
out.writeAttribute("crossesRequired", Integer.toString(crossesRequired));
out.writeAttribute("attackedByPrivateers", Boolean.toString(attackedByPrivateers));
out.writeAttribute("oldSoL", Integer.toString(oldSoL));
out.writeAttribute("score", Integer.toString(score));
} else {
out.writeAttribute("gold", Integer.toString(-1));
out.writeAttribute("crosses", Integer.toString(-1));
out.writeAttribute("bells", Integer.toString(-1));
out.writeAttribute("crossesRequired", Integer.toString(-1));
}
if (newLandName != null) {
out.writeAttribute("newLandName", newLandName);
}
if (entryLocation != null) {
out.writeAttribute("entryLocation", entryLocation.getId());
}
// attributes end here
for (Entry<Player, Tension> entry : tension.entrySet()) {
out.writeStartElement(TENSION_TAG);
out.writeAttribute("player", entry.getKey().getId());
out.writeAttribute("value", String.valueOf(entry.getValue().getValue()));
out.writeEndElement();
}
for (Entry<String, Stance> entry : stance.entrySet()) {
out.writeStartElement(STANCE_TAG);
out.writeAttribute("player", entry.getKey());
out.writeAttribute("value", entry.getValue().toString());
out.writeEndElement();
}
for (TradeRoute route : getTradeRoutes()) {
route.toXML(out, this);
}
if (market != null) {
market.toXML(out, player, showAll, toSavedGame);
}
if (getGame().isClientTrusted() || showAll || equals(player)) {
out.writeStartElement(FOUNDING_FATHER_TAG);
out.writeAttribute(ARRAY_SIZE, Integer.toString(allFathers.size()));
int index = 0;
for (FoundingFather father : allFathers) {
out.writeAttribute("x" + Integer.toString(index), father.getId());
index++;
}
out.writeEndElement();
if (europe != null) {
europe.toXML(out, player, showAll, toSavedGame);
}
if (monarch != null) {
monarch.toXML(out, player, showAll, toSavedGame);
}
}
out.writeEndElement();
}
/**
* Initialize this object from an XML-representation of this object.
*
* @param in The input stream with the XML.
*/
protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException {
setId(in.getAttributeValue(null, "ID"));
index = Integer.parseInt(in.getAttributeValue(null, "index"));
name = in.getAttributeValue(null, "username");
nationID = in.getAttributeValue(null, "nationID");
if (!name.equals(UNKNOWN_ENEMY)) {
nationType = FreeCol.getSpecification().getNationType(in.getAttributeValue(null, "nationType"));
}
color = new Color(Integer.parseInt(in.getAttributeValue(null, "color")));
admin = getAttribute(in, "admin", false);
gold = Integer.parseInt(in.getAttributeValue(null, "gold"));
crosses = Integer.parseInt(in.getAttributeValue(null, "crosses"));
bells = Integer.parseInt(in.getAttributeValue(null, "bells"));
oldSoL = getAttribute(in, "oldSoL", 0);
score = getAttribute(in, "score", 0);
ready = getAttribute(in, "ready", false);
ai = getAttribute(in, "ai", false);
dead = getAttribute(in, "dead", false);
tax = Integer.parseInt(in.getAttributeValue(null, "tax"));
numberOfSettlements = getAttribute(in, "numberOfSettlements", 0);
playerType = Enum.valueOf(PlayerType.class, in.getAttributeValue(null, "playerType"));
currentFather = FreeCol.getSpecification().getType(in, "currentFather", FoundingFather.class, null);
crossesRequired = getAttribute(in, "crossesRequired", 12);
newLandName = getAttribute(in, "newLandName", null);
attackedByPrivateers = getAttribute(in, "attackedByPrivateers", false);
final String entryLocationStr = in.getAttributeValue(null, "entryLocation");
if (entryLocationStr != null) {
entryLocation = (Location) getGame().getFreeColGameObject(entryLocationStr);
if (entryLocation == null) {
entryLocation = new Tile(getGame(), entryLocationStr);
}
}
featureContainer = new FeatureContainer();
if (nationType != null) {
featureContainer.add(nationType.getFeatureContainer());
}
tension = new HashMap<Player, Tension>();
stance = new HashMap<String, Stance>();
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (in.getLocalName().equals(TENSION_TAG)) {
Player player = (Player) getGame().getFreeColGameObject(in.getAttributeValue(null, "player"));
tension.put(player, new Tension(getAttribute(in, "value", 0)));
in.nextTag(); // close element
} else if (in.getLocalName().equals(FOUNDING_FATHER_TAG)) {
int length = Integer.parseInt(in.getAttributeValue(null, ARRAY_SIZE));
for (int index = 0; index < length; index++) {
String fatherId = in.getAttributeValue(null, "x" + String.valueOf(index));
FoundingFather father = FreeCol.getSpecification().getFoundingFather(fatherId);
allFathers.add(father);
// add only features, no other effects
featureContainer.add(father.getFeatureContainer());
}
in.nextTag();
} else if (in.getLocalName().equals(STANCE_TAG)) {
String playerId = in.getAttributeValue(null, "player");
stance.put(playerId, Enum.valueOf(Stance.class, in.getAttributeValue(null, "value")));
in.nextTag(); // close element
} else if (in.getLocalName().equals(Europe.getXMLElementTagName())) {
europe = updateFreeColGameObject(in, Europe.class);
} else if (in.getLocalName().equals(Monarch.getXMLElementTagName())) {
monarch = updateFreeColGameObject(in, Monarch.class);
} else if (in.getLocalName().equals(TradeRoute.getXMLElementTagName())) {
TradeRoute route = new TradeRoute(getGame(), in);
getTradeRoutes().add(route);
} else if (in.getLocalName().equals(Market.getXMLElementTagName())) {
market = updateFreeColGameObject(in, Market.class);
} else {
logger.warning("Unknown tag: " + in.getLocalName() + " loading player");
in.nextTag();
}
}
// sanity check: we should be on the closing tag
if (!in.getLocalName().equals(Player.getXMLElementTagName())) {
logger.warning("Error parsing xml: expecting closing tag </" + Player.getXMLElementTagName() + "> "
+ "found instead: " + in.getLocalName());
}
if (market == null) {
market = new Market(getGame(), this);
}
invalidateCanSeeTiles();
}
/**
* Gets the tag name of the root element representing this object.
*
* @return "player"
*/
public static String getXMLElementTagName() {
return "player";
}
/**
* Generates a random unit type. The unit type that is returned represents
* the type of a unit that is recruitable in Europe.
*
* @param unique a <code>String</code> value
* @return A random unit type of a unit that is recruitable in Europe.
*/
public UnitType generateRecruitable(String unique) {
ArrayList<RandomChoice<UnitType>> recruitableUnits = new ArrayList<RandomChoice<UnitType>>();
for (UnitType unitType : FreeCol.getSpecification().getUnitTypeList()) {
if (unitType.isRecruitable() &&
!featureContainer.hasAbility("model.ability.canNotRecruitUnit", unitType)) {
recruitableUnits.add(new RandomChoice<UnitType>(unitType, unitType.getRecruitProbability()));
}
}
int totalProbability = RandomChoice.getTotalProbability(recruitableUnits);
System.out.println("Unique is " + unique);
System.out.println("Total probability is " + totalProbability);
int random = getGame().getModelController().getRandom(getId() + "newRecruitableUnit" + unique,
totalProbability);
System.out.println("Random is " + random);
return RandomChoice.select(recruitableUnits, random);
}
/**
* Gets the number of bells needed for recruiting the next founding father.
*
* @return How many more bells the <code>Player</code> needs in order to
* recruit the next founding father.
* @see Goods#BELLS
* @see #incrementBells
*/
public int getRemainingFoundingFatherCost() {
return getTotalFoundingFatherCost() - getBells();
}
/**
* Returns how many bells in total are needed to earn the Founding Father we
* are trying to recruit.
*
* @return Total number of bells the <code>Player</code> needs to recruit
* the next founding father.
* @see Goods#BELLS
* @see #incrementBells
*/
public int getTotalFoundingFatherCost() {
return (getFatherCount() * getFatherCount() * Specification.getSpecification()
.getIntegerOption("model.option.foundingFatherFactor").getValue() + 50);
}
/**
* Returns how many total bells will be produced if no colonies are lost and
* nothing unexpected happens.
*
* @return Total number of bells this <code>Player</code>'s
* <code>Colony</code>s will make.
* @see Goods#BELLS
* @see #incrementBells
*/
public int getBellsProductionNextTurn() {
int bellsNextTurn = 0;
for (Colony colony : getColonies()) {
bellsNextTurn += colony.getProductionOf(Goods.BELLS);
}
return bellsNextTurn;
}
/**
* Returns the arrears due for a type of goods.
*
* @param type a <code>GoodsType</code> value
* @return The arrears due for this type of goods.
*/
public int getArrears(GoodsType type) {
MarketData data = getMarket().getMarketData(type);
if (data == null) {
return Integer.MIN_VALUE;
} else {
return data.getArrears();
}
}
/**
* Returns the arrears due for a type of goods.
*
* @param goods The goods.
* @return The arrears due for this type of goods.
*/
public int getArrears(Goods goods) {
return getArrears(goods.getType());
}
/**
* Sets the arrears for a type of goods.
*
* @param goodsType a <code>GoodsType</code> value
*/
public void setArrears(GoodsType goodsType) {
MarketData data = getMarket().getMarketData(goodsType);
if (data == null) {
data = new MarketData(goodsType);
getMarket().putMarketData(goodsType, data);
}
data.setArrears(Specification.getSpecification().getIntegerOption("model.option.arrearsFactor").getValue()
* 100 * data.getPaidForSale());
}
/**
* Sets the arrears for these goods.
*
* @param goods The goods.
*/
public void setArrears(Goods goods) {
setArrears(goods.getType());
}
/**
* Resets the arrears for this type of goods to zero.
*
* @param goodsType a <code>GoodsType</code> value
*/
public void resetArrears(GoodsType goodsType) {
MarketData data = getMarket().getMarketData(goodsType);
if (data == null) {
data = new MarketData(goodsType);
getMarket().putMarketData(goodsType, data);
}
data.setArrears(0);
}
/**
* Resets the arrears for these goods to zero. This is the same as calling:
* <br>
* <br>
* <code>resetArrears(goods.getType());</code>
*
* @param goods The goods to reset the arrears for.
* @see #resetArrears(GoodsType)
*/
public void resetArrears(Goods goods) {
resetArrears(goods.getType());
}
/**
* Returns true if type of goods can be traded in Europe.
*
* @param type The goods type.
* @return True if there are no arrears due for this type of goods.
*/
public boolean canTrade(GoodsType type) {
return canTrade(type, Market.EUROPE);
}
/**
* Returns true if type of goods can be traded at specified place.
*
* @param type The GoodsType.
* @param marketAccess Way the goods are traded (Europe OR Custom)
* @return <code>true</code> if type of goods can be traded.
*/
public boolean canTrade(GoodsType type, int marketAccess) {
MarketData data = getMarket().getMarketData(type);
if (data == null) {
return true;
} else {
return (data.getArrears() == 0 || (marketAccess == Market.CUSTOM_HOUSE && getGameOptions().getBoolean(
GameOptions.CUSTOM_IGNORE_BOYCOTT)));
}
}
/**
* Returns true if type of goods can be traded at specified place
*
* @param goods The goods.
* @param marketAccess Place where the goods are traded (Europe OR Custom)
* @return True if type of goods can be traded.
*/
public boolean canTrade(Goods goods, int marketAccess) {
return canTrade(goods.getType(), marketAccess);
}
/**
* Returns true if type of goods can be traded in Europe.
*
* @param goods The goods.
* @return True if there are no arrears due for this type of goods.
*/
public boolean canTrade(Goods goods) {
return canTrade(goods, Market.EUROPE);
}
/**
* Returns the current tax.
*
* @return The current tax.
*/
public int getTax() {
return tax;
}
/**
* Sets the current tax. If Thomas Paine has already joined the Continental
* Congress, the bellsBonus is adjusted accordingly.
*
* @param amount The new tax.
*/
public void setTax(int amount) {
if (amount != tax) {
tax = amount;
for (Ability ability : featureContainer.getAbilitySet("model.ability.addTaxToBells")) {
FreeColGameObjectType source = ability.getSource();
if (source != null) {
Set<Modifier> bellsBonus = featureContainer.getModifierSet("model.goods.bells");
for (Modifier modifier : bellsBonus) {
if (source.equals(modifier.getSource())) {
modifier.setValue(amount);
return;
}
}
}
}
}
}
/**
* Returns the current sales.
*
* @param goodsType a <code>GoodsType</code> value
* @return The current sales.
*/
public int getSales(GoodsType goodsType) {
MarketData data = getMarket().getMarketData(goodsType);
if (data == null) {
return 0;
} else {
return data.getSales();
}
}
/**
* Modifies the current sales.
*
* @param goodsType a <code>GoodsType</code> value
* @param amount The new sales.
*/
public void modifySales(GoodsType goodsType, int amount) {
MarketData data = getMarket().getMarketData(goodsType);
if (data == null) {
data = new MarketData(goodsType);
getMarket().putMarketData(goodsType, data);
}
int oldSales = data.getSales();
data.setSales(oldSales + amount);
}
/**
* Returns the current incomeBeforeTaxes.
*
* @param goodsType The GoodsType.
* @return The current incomeBeforeTaxes.
*/
public int getIncomeBeforeTaxes(GoodsType goodsType) {
MarketData data = getMarket().getMarketData(goodsType);
if (data == null) {
return 0;
} else {
return data.getIncomeBeforeTaxes();
}
}
/**
* Modifies the current incomeBeforeTaxes.
*
* @param goodsType The GoodsType.
* @param amount The new incomeBeforeTaxes.
*/
public void modifyIncomeBeforeTaxes(GoodsType goodsType, int amount) {
MarketData data = getMarket().getMarketData(goodsType);
if (data == null) {
data = new MarketData(goodsType);
getMarket().putMarketData(goodsType, data);
}
int oldAmount = data.getIncomeBeforeTaxes();
data.setIncomeBeforeTaxes(oldAmount += amount);
}
/**
* Returns the current incomeAfterTaxes.
*
* @param goodsType The GoodsType.
* @return The current incomeAfterTaxes.
*/
public int getIncomeAfterTaxes(GoodsType goodsType) {
MarketData data = getMarket().getMarketData(goodsType);
if (data == null) {
return 0;
} else {
return data.getIncomeAfterTaxes();
}
}
/**
* Modifies the current incomeAfterTaxes.
*
* @param goodsType The GoodsType.
* @param amount The new incomeAfterTaxes.
*/
public void modifyIncomeAfterTaxes(GoodsType goodsType, int amount) {
MarketData data = getMarket().getMarketData(goodsType);
if (data == null) {
data = new MarketData(goodsType);
getMarket().putMarketData(goodsType, data);
}
int oldAmount = data.getIncomeAfterTaxes();
data.setIncomeAfterTaxes(oldAmount + amount);
}
/**
* Returns the difficulty level.
*
* @return The difficulty level.
*/
public DifficultyLevel getDifficulty() {
int level = getGame().getGameOptions().getInteger(GameOptions.DIFFICULTY);
return FreeCol.getSpecification().getDifficultyLevel(level);
}
/**
* Returns the most valuable goods available in one of the player's
* colonies. The goods must not be boycotted, and the amount will not exceed
* 100.
*
* @return A goods object, or null.
*/
public Goods getMostValuableGoods() {
Goods goods = null;
if (!isEuropean()) {
return goods;
}
int value = 0;
for (Colony colony : getColonies()) {
List<Goods> colonyGoods = colony.getCompactGoods();
for (Goods currentGoods : colonyGoods) {
if (getArrears(currentGoods) == 0) {
// never discard more than 100 units
if (currentGoods.getAmount() > 100) {
currentGoods.setAmount(100);
}
int goodsValue = market.getSalePrice(currentGoods);
if (goodsValue > value) {
value = goodsValue;
goods = currentGoods;
}
}
}
}
return goods;
}
/**
* Checks if the given <code>Player</code> equals this object.
*
* @param o The <code>Player</code> to compare against this object.
* @return <i>true</i> if the two <code>Player</code> are equal and none
* of both have <code>nation == null</code> and <i>false</i>
* otherwise.
*/
public boolean equals(Player o) {
if (o == null) {
return false;
} else if (getId() == null || o.getId() == null) {
// This only happens in the client code with the virtual "enemy
// privateer" player
// This special player is not properly associated to the Game and
// therefore has no ID
// TODO: remove this hack when the virtual "enemy privateer" player
// is better implemented
return false;
} else {
return getId().equals(o.getId());
}
}
/**
* A predicate that can be applied to a unit.
*/
public abstract class UnitPredicate {
public abstract boolean obtains(Unit unit);
}
/**
* A predicate for determining active units.
*/
public class ActivePredicate extends UnitPredicate {
/**
* Returns true if the unit is active (and going nowhere).
*/
public boolean obtains(Unit unit) {
return (!unit.isDisposed() && (unit.getMovesLeft() > 0) && (unit.getState() == UnitState.ACTIVE)
&& (unit.getDestination() == null) && !(unit.getLocation() instanceof WorkLocation) && unit
.getTile() != null);
}
}
/**
* A predicate for determining units going somewhere.
*/
public class GoingToPredicate extends UnitPredicate {
/**
* Returns true if the unit has order to go somewhere.
*/
public boolean obtains(Unit unit) {
return (!unit.isDisposed() && (unit.getMovesLeft() > 0) && (unit.getDestination() != null)
&& !(unit.getLocation() instanceof WorkLocation) && unit.getTile() != null);
}
}
/**
* An <code>Iterator</code> of {@link Unit}s that can be made active.
*/
public class UnitIterator implements Iterator<Unit> {
private Iterator<Unit> unitIterator = null;
private Player owner;
private Unit nextUnit = null;
private UnitPredicate predicate;
/**
* Creates a new <code>NextActiveUnitIterator</code>.
*
* @param owner The <code>Player</code> that needs an iterator of it's
* units.
* @param predicate An object for deciding whether a <code>Unit</code>
* should be included in the <code>Iterator</code> or not.
*/
public UnitIterator(Player owner, UnitPredicate predicate) {
this.owner = owner;
this.predicate = predicate;
}
public boolean hasNext() {
if (nextUnit != null && predicate.obtains(nextUnit)) {
return true;
}
if (unitIterator == null) {
unitIterator = createUnitIterator();
}
while (unitIterator.hasNext()) {
nextUnit = unitIterator.next();
if (predicate.obtains(nextUnit)) {
return true;
}
}
unitIterator = createUnitIterator();
while (unitIterator.hasNext()) {
nextUnit = unitIterator.next();
if (predicate.obtains(nextUnit)) {
return true;
}
}
nextUnit = null;
return false;
}
public Unit next() {
if (nextUnit == null || !predicate.obtains(nextUnit)) {
hasNext();
}
Unit temp = nextUnit;
nextUnit = null;
return temp;
}
/**
* Removes from the underlying collection the last element returned by
* the iterator (optional operation).
*
* @exception UnsupportedOperationException no matter what.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Returns an <code>Iterator</code> for the units of this player that
* can be active.
*/
private Iterator<Unit> createUnitIterator() {
ArrayList<Unit> units = new ArrayList<Unit>();
Map map = getGame().getMap();
Iterator<Position> tileIterator = map.getWholeMapIterator();
while (tileIterator.hasNext()) {
Tile t = map.getTile(tileIterator.next());
if (t != null && t.getFirstUnit() != null && t.getFirstUnit().getOwner().equals(owner)) {
Iterator<Unit> unitIterator = t.getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = unitIterator.next();
Iterator<Unit> childUnitIterator = u.getUnitIterator();
while (childUnitIterator.hasNext()) {
Unit childUnit = childUnitIterator.next();
if (predicate.obtains(childUnit)) {
units.add(childUnit);
}
}
if (predicate.obtains(u)) {
units.add(u);
}
}
}
}
return units.iterator();
}
}
}
| true | false | null | null |
diff --git a/java/eve-core/src/main/java/com/almende/eve/rpc/jsonrpc/JSONResponse.java b/java/eve-core/src/main/java/com/almende/eve/rpc/jsonrpc/JSONResponse.java
index 5c8efc91..04054b1e 100644
--- a/java/eve-core/src/main/java/com/almende/eve/rpc/jsonrpc/JSONResponse.java
+++ b/java/eve-core/src/main/java/com/almende/eve/rpc/jsonrpc/JSONResponse.java
@@ -1,170 +1,177 @@
package com.almende.eve.rpc.jsonrpc;
import java.io.IOException;
+import java.util.logging.Logger;
import com.almende.eve.rpc.jsonrpc.jackson.JOM;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JSONResponse {
protected ObjectNode resp = JOM.createObjectNode();
+ private static final Logger logger = Logger.getLogger(JSONResponse.class.getName());
public JSONResponse () {
init(null, null, null);
}
public JSONResponse (String json)
throws JSONRPCException, JsonParseException, JsonMappingException,
IOException {
ObjectMapper mapper = JOM.getInstance();
- init(mapper.readValue(json, ObjectNode.class));
+ try {
+ init(mapper.readValue(json, ObjectNode.class));
+ } catch (JsonParseException e){
+ logger.warning("Failed to parse JSON: '"+json+"'");
+ throw e;
+ }
}
public JSONResponse (ObjectNode response) throws JSONRPCException {
init(response);
}
public JSONResponse (Object result) {
init(null, result, null);
}
public JSONResponse (Object id, Object result) {
init(id, result, null);
}
public JSONResponse (JSONRPCException error) {
init(null, null, error);
}
public JSONResponse (Object id, JSONRPCException error) {
init(id, null, error);
}
private void init (ObjectNode response) throws JSONRPCException {
if (response == null || response.isNull()) {
throw new JSONRPCException(JSONRPCException.CODE.INVALID_REQUEST,
"Response is null");
}
if (response.has("jsonrpc") && response.get("jsonrpc").isTextual()) {
if (!response.get("jsonrpc").asText().equals("2.0")) {
throw new JSONRPCException(JSONRPCException.CODE.INVALID_REQUEST,
"Value of member 'jsonrpc' must be '2.0'");
}
}
boolean hasError = response.has("error") && !response.get("error").isNull();
/* TODO: cleanup
if (hasResult && hasError) {
throw new JSONRPCException(JSONRPCException.CODE.INVALID_REQUEST,
"Response contains both members 'result' and 'error' but may not contain both.");
}
if (!hasResult && !hasError) {
throw new JSONRPCException(JSONRPCException.CODE.INVALID_REQUEST,
"Response is missing member 'result' or 'error'");
}
*/
if (hasError) {
if (!(response.get("error").isObject())) {
throw new JSONRPCException(JSONRPCException.CODE.INVALID_REQUEST,
"Member 'error' is no ObjectNode");
}
}
Object id = response.get("id");
Object result = response.get("result");
JSONRPCException error = null;
if (hasError) {
error = new JSONRPCException((ObjectNode)response.get("error"));
}
init(id, result, error);
}
private void init(Object id, Object result, JSONRPCException error) {
setVersion();
setId(id);
setResult(result);
setError(error);
}
public void setId(Object id) {
ObjectMapper mapper = JOM.getInstance();
resp.put("id", mapper.convertValue(id, JsonNode.class));
}
public Object getId() {
ObjectMapper mapper = JOM.getInstance();
return mapper.convertValue(resp.get("id"), JsonNode.class);
}
public void setResult(Object result) {
if (result != null) {
ObjectMapper mapper = JOM.getInstance();
resp.put("result", mapper.convertValue(result, JsonNode.class));
setError(null);
}
else {
if (resp.has("result")) {
resp.remove("result");
}
}
}
public JsonNode getResult() {
return resp.get("result");
}
public <T> T getResult(Class<T> type) {
ObjectMapper mapper = JOM.getInstance();
return mapper.convertValue(resp.get("result"), type);
}
public void setError(JSONRPCException error) {
if (error != null) {
resp.put("error", error.getObjectNode());
setResult(null);
}
else {
if (resp.has("error")) {
resp.remove("error");
}
}
}
public JSONRPCException getError() throws JSONRPCException {
if (resp.has("error")) {
ObjectNode error = (ObjectNode) resp.get("error");
return new JSONRPCException(error);
}
else {
return null;
}
}
/* TODO: gives issues with Jackson
public boolean isError() {
return (resp.get("error") != null);
}
*/
private void setVersion() {
resp.put("jsonrpc", "2.0");
}
public ObjectNode getObjectNode() {
return resp;
}
@Override
public String toString() {
ObjectMapper mapper = JOM.getInstance();
try {
return mapper.writeValueAsString(resp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/OldSoar/trunk/visualsoar/Source/edu/umich/visualsoar/MainFrame.java b/OldSoar/trunk/visualsoar/Source/edu/umich/visualsoar/MainFrame.java
index 00c1610ca..a55589814 100644
--- a/OldSoar/trunk/visualsoar/Source/edu/umich/visualsoar/MainFrame.java
+++ b/OldSoar/trunk/visualsoar/Source/edu/umich/visualsoar/MainFrame.java
@@ -1,3793 +1,3817 @@
package edu.umich.visualsoar;
import edu.umich.visualsoar.misc.*;
import edu.umich.visualsoar.dialogs.*;
import edu.umich.visualsoar.operatorwindow.*;
import edu.umich.visualsoar.graph.*;
import edu.umich.visualsoar.datamap.*;
import edu.umich.visualsoar.ruleeditor.*;
import edu.umich.visualsoar.util.*;
import edu.umich.visualsoar.parser.ParseException;
import edu.umich.visualsoar.parser.TokenMgrError;
// 3P
import threepenny.*;
import java.awt.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.text.*;
import java.io.*;
import javax.swing.undo.*;
import javax.swing.event.*;
import javax.swing.border.TitledBorder;
import java.util.*;
// The global application class
/**
* This is the main project window of Visual Soar
* @author Brad Jones
*/
public class MainFrame extends JFrame
{
/////////////////////////////////////////
// Static Members
/////////////////////////////////////////
private static MainFrame s_mainFrame;
////////////////////////////////////////
// Data Members
////////////////////////////////////////
private OperatorWindow operatorWindow;
private CustomDesktopPane DesktopPane = new CustomDesktopPane();
private TemplateManager d_templateManager = new TemplateManager();
private JSplitPane operatorDesktopSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
private JSplitPane feedbackDesktopSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
public FeedbackList feedbackList = new FeedbackList();
Preferences prefs = Preferences.getInstance();
// 3P
// Soar Tool Interface (STI) object, message time, and menu objects
private SoarToolJavaInterface soarToolJavaInterface = null;
private javax.swing.Timer soarToolPumpMessageTimer = null;
private JMenu soarRuntimeAgentMenu = null;
////////////////////////////////////////
// Access to data members
////////////////////////////////////////
// 3P
// Access to the STI object
public SoarToolJavaInterface GetSoarToolJavaInterface() { return soarToolJavaInterface; }
// Dialogs
AboutDialog aboutDialog = new AboutDialog(this);
public NameDialog nameDialog = new NameDialog(this);
//Actions
Action newProjectAction = new NewProjectAction();
Action openProjectAction = new OpenProjectAction();
Action openFileAction = new OpenFileAction();
Action closeProjectAction = new CloseProjectAction();
PerformableAction saveAllFilesAction = new SaveAllFilesAction();
PerformableAction exportAgentAction = new ExportAgentAction();
PerformableAction saveDataMapAndProjectAction = new SaveDataMapAndProjectAction();
Action preferencesAction = new PreferencesAction();
PerformableAction commitAction = new CommitAction();
Action exitAction = new ExitAction();
Action cascadeAction = new CascadeAction();
Action tileWindowsAction = new TileWindowsAction();
Action reTileWindowsAction = new ReTileWindowsAction();
Action sendProductionsAction = new SendProductionsAction();
Action checkAllProductionsAction = new CheckAllProductionsAction();
Action searchDataMapCreateAction = new SearchDataMapCreateAction();
Action searchDataMapTestAction = new SearchDataMapTestAction();
Action searchDataMapCreateNoTestAction = new SearchDataMapCreateNoTestAction();
Action searchDataMapTestNoCreateAction = new SearchDataMapTestNoCreateAction();
Action searchDataMapNoTestNoCreateAction = new SearchDataMapNoTestNoCreateAction();
Action generateDataMapAction = new GenerateDataMapAction();
Action saveProjectAsAction = new SaveProjectAsAction();
Action contactUsAction = new ContactUsAction();
Action findInProjectAction = new FindInProjectAction();
Action replaceInProjectAction = new ReplaceInProjectAction();
// 3P
// Menu handlers for STI init, term, and "Send Raw Command"
Action soarRuntimeInitAction = new SoarRuntimeInitAction();
Action soarRuntimeTermAction = new SoarRuntimeTermAction();
Action soarRuntimeSendRawCommandAction = new SoarRuntimeSendRawCommandAction();
////////////////////////////////////////
// Constructors
////////////////////////////////////////
/**
* Private constructor not used
*/
private MainFrame() {}
/**
* Constructs the operatorWindow, the DesktopPane, the SplitPane, the menubar and the file chooser
* 3P Also initializes the STI library
* @param s the name of the window
*/
public MainFrame(String s)
{
// Set the Title of the window
super(s);
File templateFolder = Preferences.getInstance().getTemplateFolder();
// Use Java toolkit to access user's screen size and set Visual Soar window to 90% of that size
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setSize( ((int) (d.getWidth() * .9)), ((int) (d.getHeight() * .9)) );
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
Container contentPane = getContentPane();
operatorDesktopSplit.setRightComponent(DesktopPane);
operatorDesktopSplit.setOneTouchExpandable(true);
JScrollPane sp = new JScrollPane(feedbackList);
sp.setBorder(new TitledBorder("Feedback"));
feedbackDesktopSplit.setTopComponent(operatorDesktopSplit);
feedbackDesktopSplit.setBottomComponent(sp);
feedbackDesktopSplit.setOneTouchExpandable(true);
feedbackDesktopSplit.setDividerLocation( ((int) (d.getHeight() * .65)) );
contentPane.add(feedbackDesktopSplit, BorderLayout.CENTER);
setJMenuBar(createMainMenu());
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
//If the user has modifed files that have not been saved,
//we need to ask the user what to do about it.
if (MainFrame.getMainFrame().isModified())
{
String[] buttons = { "Save all files, then exit.",
"Exit without Saving" };
String selectedValue = (String)
JOptionPane.showInputDialog(
MainFrame.getMainFrame(),
"This project has unsaved files. What should I do?",
"Abandon Project",
JOptionPane.QUESTION_MESSAGE,
null,
buttons,
buttons[0]);
//If user hits Cancel button
if (selectedValue == null)
{
return;
}
//If user selects Save all files, then exit
if (selectedValue.equals(buttons[0]))
{
MainFrame.getMainFrame().saveAllFilesAction.perform();
}
//If user selects Exit without Saving
if (selectedValue.equals(buttons[1]))
{
//Make all files as unchanged
CustomInternalFrame[] frames = DesktopPane.getAllCustomFrames();
for(int i = 0; i < frames.length; ++i)
{
frames[i].setModified(false);
}
}
}//if
exitAction.actionPerformed(
new ActionEvent(e.getSource(),e.getID(),"Exit"));
}//windowClosing()
});//addWindowListener()
if(templateFolder != null)
d_templateManager.load(templateFolder);
// 3P Initialize the STI library
SoarRuntimeInit();
}
////////////////////////////////////////
// Methods
////////////////////////////////////////
/**
* This method scans open windows on the VisualSoar desktop for unsaved
* changes. It returns true if any are found.
*/
public boolean isModified()
{
CustomInternalFrame[] frames = DesktopPane.getAllCustomFrames();
for(int i = 0; i < frames.length; ++i)
{
if (frames[i].isModified()) return true;
}
return false;
}
/**
* Method updates the FeedBack list window
* @param v the vector list of feedback data
*/
public void setFeedbackListData(Vector v)
{
feedbackList.setListData(v);
}
/**
* Gets the project TemplateManager
* @return a <code>TemplateManager</code> in charge of all template matters.
*/
public TemplateManager getTemplateManager()
{
return d_templateManager;
}
/**
* Gets the project OperatorWindow
* @return the project's only <code>OperatorWindow</code>.
*/
public OperatorWindow getOperatorWindow()
{
return operatorWindow;
}
/**
* Gets the project CustomDesktopPane
* @see CustomDesktopPane
* @return the project's only <code>CustomDesktopPane</code>.
*/
public CustomDesktopPane getDesktopPane()
{
return DesktopPane;
}
/**
* A helper function to create the file menu
* @return The file menu
*/
private JMenu createFileMenu()
{
JMenu fileMenu = new JMenu("File");
// The File Menu
JMenuItem newProjectItem = new JMenuItem("New Project...");
newProjectItem.addActionListener(newProjectAction);
newProjectAction.addPropertyChangeListener(
new ActionButtonAssociation(newProjectAction,newProjectItem));
JMenuItem openProjectItem = new JMenuItem("Open Project...");
openProjectItem.addActionListener(openProjectAction);
openProjectAction.addPropertyChangeListener(
new ActionButtonAssociation(openProjectAction,openProjectItem));
JMenuItem openFileItem = new JMenuItem("Open File...");
openFileItem.addActionListener(openFileAction);
openFileAction.addPropertyChangeListener(
new ActionButtonAssociation(openFileAction, openFileItem));
JMenuItem closeProjectItem = new JMenuItem("Close Project");
closeProjectItem.addActionListener(closeProjectAction);
closeProjectAction.addPropertyChangeListener(
new ActionButtonAssociation(closeProjectAction,closeProjectItem));
JMenuItem commitItem = new JMenuItem("Save");
commitItem.addActionListener(commitAction);
commitAction.addPropertyChangeListener(
new ActionButtonAssociation(commitAction,commitItem));
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(exitAction);
exitAction.addPropertyChangeListener(
new ActionButtonAssociation(exitAction,exitItem));
JMenuItem checkAllProductionsItem = new JMenuItem("Check All Productions Against DataMap");
checkAllProductionsItem.addActionListener(checkAllProductionsAction);
checkAllProductionsAction.addPropertyChangeListener(
new ActionButtonAssociation(checkAllProductionsAction,checkAllProductionsItem));
JMenuItem generateDataMapItem = new JMenuItem("Generate Datamap from Operator Hierarchy");
generateDataMapItem.addActionListener(generateDataMapAction);
generateDataMapAction.addPropertyChangeListener(
new ActionButtonAssociation(generateDataMapAction, generateDataMapItem));
JMenuItem saveProjectAsItem = new JMenuItem("Save Project As...");
saveProjectAsItem.addActionListener(saveProjectAsAction);
saveProjectAsAction.addPropertyChangeListener(
new ActionButtonAssociation(saveProjectAsAction,saveProjectAsItem));
/*
JMenuItem checkCoverageItem = new JMenuItem("Check Coverage");
checkCoverageItem.addActionListener(checkCoverageAction);
checkCoverageAction.addPropertyChangeListener(
new ActionButtonAssociation(checkCoverageAction,checkCoverageItem));
*/
// JMenuItem sendProductionsItem = new JMenuItem("Send Productions");
// sendProductionsItem.addActionListener(sendProductionsAction);
fileMenu.add(newProjectItem);
fileMenu.add(openProjectItem);
fileMenu.add(openFileItem);
fileMenu.add(closeProjectItem);
fileMenu.addSeparator();
fileMenu.add(commitItem);
fileMenu.add(saveProjectAsItem);
// fileMenu.add(checkCoverageItem);
// fileMenu.add(sendProductionsItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
// register mnemonics and accelerators
fileMenu.setMnemonic('F');
newProjectItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,Event.CTRL_MASK));
newProjectItem.setMnemonic(KeyEvent.VK_N);
openProjectItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,Event.CTRL_MASK));
openProjectItem.setMnemonic(KeyEvent.VK_O);
openFileItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,Event.CTRL_MASK));
openFileItem.setMnemonic(KeyEvent.VK_F);
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,Event.ALT_MASK));
exitItem.setMnemonic(KeyEvent.VK_X);
return fileMenu;
}
/**
* A helper function to create the edit menu
* @return The edit menu
*/
private JMenu createEditMenu()
{
JMenu editMenu = new JMenu("Edit");
JMenuItem preferencesItem = new JMenuItem("Preferences...");
preferencesItem.addActionListener(preferencesAction);
editMenu.add(preferencesItem);
return editMenu;
}
/**
* A helper function to create the search menu
* @return The search menu
*/
private JMenu createSearchMenu()
{
JMenu searchMenu = new JMenu("Search");
JMenuItem findInProjectItem = new JMenuItem("Find In Project");
findInProjectItem.addActionListener(findInProjectAction);
findInProjectAction.addPropertyChangeListener(
new ActionButtonAssociation(findInProjectAction,findInProjectItem));
JMenuItem replaceInProjectItem = new JMenuItem("Replace In Project");
replaceInProjectItem.addActionListener(replaceInProjectAction);
replaceInProjectAction.addPropertyChangeListener(
new ActionButtonAssociation(replaceInProjectAction, replaceInProjectItem));
searchMenu.add(findInProjectAction);
searchMenu.add(replaceInProjectAction);
searchMenu.setMnemonic(KeyEvent.VK_A);
return searchMenu;
}
/**
* A helper function to create the Datamap menu
* @return The datamap menu
*/
private JMenu createDatamapMenu()
{
JMenu datamapMenu = new JMenu("Datamap");
JMenuItem checkAllProductionsItem = new JMenuItem("Check All Productions Against DataMap");
checkAllProductionsItem.addActionListener(checkAllProductionsAction);
checkAllProductionsAction.addPropertyChangeListener(
new ActionButtonAssociation(checkAllProductionsAction,checkAllProductionsItem));
JMenuItem searchDataMapTestItem = new JMenuItem("Search Datamap for untested WMEs");
searchDataMapTestItem.addActionListener(searchDataMapTestAction);
searchDataMapTestAction.addPropertyChangeListener(
new ActionButtonAssociation(searchDataMapTestAction,searchDataMapTestItem));
JMenuItem searchDataMapCreateItem = new JMenuItem("Search Datamap for non Created WMEs");
searchDataMapCreateItem.addActionListener(searchDataMapCreateAction);
searchDataMapCreateAction.addPropertyChangeListener(
new ActionButtonAssociation(searchDataMapCreateAction,searchDataMapCreateItem));
JMenuItem searchDataMapTestNoCreateItem = new JMenuItem("Search Datamap for WME's tested but never created");
searchDataMapTestNoCreateItem.addActionListener(searchDataMapTestNoCreateAction);
searchDataMapTestNoCreateAction.addPropertyChangeListener(
new ActionButtonAssociation(searchDataMapTestNoCreateAction,searchDataMapTestNoCreateItem));
JMenuItem searchDataMapCreateNoTestItem = new JMenuItem("Search Datamap for WME's created but never tested");
searchDataMapCreateNoTestItem.addActionListener(searchDataMapCreateNoTestAction);
searchDataMapCreateNoTestAction.addPropertyChangeListener(
new ActionButtonAssociation(searchDataMapCreateNoTestAction,searchDataMapCreateNoTestItem));
JMenuItem searchDataMapNoTestNoCreateItem = new JMenuItem("Search Datamap for WME's never tested and never created");
searchDataMapNoTestNoCreateItem.addActionListener(searchDataMapNoTestNoCreateAction);
searchDataMapNoTestNoCreateAction.addPropertyChangeListener(
new ActionButtonAssociation(searchDataMapNoTestNoCreateAction,searchDataMapNoTestNoCreateItem));
JMenuItem generateDataMapItem = new JMenuItem("Generate Datamap from Operator Hierarchy");
generateDataMapItem.addActionListener(generateDataMapAction);
generateDataMapAction.addPropertyChangeListener(
new ActionButtonAssociation(generateDataMapAction, generateDataMapItem));
datamapMenu.add(checkAllProductionsItem);
datamapMenu.add(generateDataMapItem);
datamapMenu.add(searchDataMapTestItem);
datamapMenu.add(searchDataMapCreateItem);
datamapMenu.add(searchDataMapTestNoCreateItem);
datamapMenu.add(searchDataMapCreateNoTestItem);
datamapMenu.add(searchDataMapNoTestNoCreateItem);
datamapMenu.setMnemonic(KeyEvent.VK_D);
return datamapMenu;
}
/**
* A helper function to create the view menu
* @return The view menu
*/
private JMenu createViewMenu()
{
final JMenu viewMenu = new JMenu("View");
// View Menu
JMenuItem cascadeItem = new JMenuItem("Cascade Windows");
cascadeItem.addActionListener(cascadeAction);
cascadeItem.addPropertyChangeListener(
new ActionButtonAssociation(cascadeAction,cascadeItem));
viewMenu.add(cascadeItem);
JMenuItem tileWindowItem = new JMenuItem("Tile Windows");
tileWindowItem.addActionListener(tileWindowsAction);
tileWindowItem.addPropertyChangeListener(
new ActionButtonAssociation(tileWindowsAction,tileWindowItem));
viewMenu.add(tileWindowItem);
JMenuItem reTileWindowItem = new JMenuItem("Re-tile Windows");
reTileWindowItem.addActionListener(reTileWindowsAction);
reTileWindowItem.addPropertyChangeListener(
new ActionButtonAssociation(reTileWindowsAction,reTileWindowItem));
viewMenu.add(reTileWindowItem);
viewMenu.addSeparator();
viewMenu.addMenuListener(
new MenuListener()
{
public void menuCanceled(MenuEvent e) {}
public void menuDeselected(MenuEvent e)
{
for(int i = viewMenu.getMenuComponentCount() - 1; i > 2; --i)
{
viewMenu.remove(i);
}
}
public void menuSelected(MenuEvent e)
{
JInternalFrame[] frames = DesktopPane.getAllFrames();
for(int i = 0; i < frames.length; ++i)
{
JMenuItem menuItem = new JMenuItem(frames[i].getTitle());
menuItem.addActionListener(new WindowMenuListener(frames[i]));
viewMenu.add(menuItem);
}
}
});
viewMenu.setMnemonic('V');
//cascadeWindowItem.setMnemonic(KeyEvent.VK_C);
tileWindowItem.setMnemonic(KeyEvent.VK_T);
tileWindowItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,Event.CTRL_MASK));
reTileWindowItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,Event.CTRL_MASK | Event.SHIFT_MASK));
return viewMenu;
}
/**
* When the Soar Runtime|Agent menu is selected, this listener
* populates the menu with the agents that are currently
* connected to via the STI.
* @Author ThreePenny
*/
class SoarRuntimeAgentMenuListener extends MenuAdapter
{
public void menuSelected(MenuEvent e)
{
// Remove our existing items
soarRuntimeAgentMenu.removeAll();
// Check to see if we have an STI connection
SoarToolJavaInterface sti=GetSoarToolJavaInterface();
if (sti == null)
{
// Add a "not connected" menu item
JMenuItem menuItem=new JMenuItem("<not connected>");
menuItem.setEnabled(false);
soarRuntimeAgentMenu.add(menuItem);
return;
}
// Get the connection names
String[] connectionNames=sti.GetConnectionNames();
// If we don't have any connections then display the
// appropriate menu item.
if (connectionNames == null || connectionNames.length == 0)
{
// Add the "no agents" menu item
JMenuItem menuItem=new JMenuItem("<no agents>");
menuItem.setEnabled(false);
soarRuntimeAgentMenu.add(menuItem);
return;
}
// Add each name
int i;
for (i=0; i < connectionNames.length; i++)
{
// Get this connection name
String sConnectionName=connectionNames[i];
// Create the connection menu and add a listener to it
// which contains the connection index.
JCheckBoxMenuItem connectionMenuItem=new JCheckBoxMenuItem(sConnectionName);
connectionMenuItem.addActionListener(
new AgentConnectionActionListener(connectionMenuItem, sConnectionName));
// Set the state based on whether or not we are connected to this agent
boolean bConnected=sti.IsConnectionEnabledByName(sConnectionName);
connectionMenuItem.setState(bConnected);
// Add the menu item
soarRuntimeAgentMenu.add(connectionMenuItem);
}
}
}
/**
* Listener activated when the user clicks on an Agent in the Soar
* Runtime |Agents menu. When the user clicks on an agent in the menu,
* it is activated/deactivated.
* @Author ThreePenny
*/
class AgentConnectionActionListener implements ActionListener
{
// Index of this agent connection in the menu
private String m_sAgentConnectionName;
// Menu item that this action is for
// TODO: Is there a way to just retrieve this without storing it?
private JCheckBoxMenuItem m_assocatedMenuItem;
// Constructor
public AgentConnectionActionListener(JCheckBoxMenuItem assocatedMenuItem, String sAgentConnectionName)
{
m_sAgentConnectionName = sAgentConnectionName;
m_assocatedMenuItem = assocatedMenuItem;
}
// Disable the default constructor
private AgentConnectionActionListener() {}
// Called when the action has been performed
public void actionPerformed(ActionEvent e)
{
// Check to see if we have an STI connection
SoarToolJavaInterface sti=GetSoarToolJavaInterface();
if (sti == null)
{
// TODO
// Assert or throw some kind of exception?
return;
}
// Set the connection state
sti.EnableConnectionByName(m_sAgentConnectionName, m_assocatedMenuItem.getState() == true);
}
}
/**
* Creates the "Soar Runtime" menu which appears in the MainFrame
* @Author ThreePenny
* @return a <code>soarRuntimeMenu</code> JMenu
*/
private JMenu createSoarRuntimeMenu()
{
// Add the menu as set the mnemonic
JMenu soarRuntimeMenu = new JMenu("Soar Runtime");
soarRuntimeMenu.setMnemonic('S');
// Add the menu items
JMenuItem connectMenuItem=soarRuntimeMenu.add(soarRuntimeInitAction);
JMenuItem disconnectMenuItem=soarRuntimeMenu.add(soarRuntimeTermAction);
JMenuItem sendRawCommandMenuItem=soarRuntimeMenu.add(soarRuntimeSendRawCommandAction);
// Build the "Connected Agents" menu
soarRuntimeAgentMenu = new JMenu("Connected Agents");
soarRuntimeAgentMenu.addMenuListener(
new SoarRuntimeAgentMenuListener());
soarRuntimeAgentMenu.setEnabled(false);
// Add the "Connected Agents" menu
soarRuntimeMenu.add(soarRuntimeAgentMenu);
// Set the mnemonics
connectMenuItem.setMnemonic('C');
disconnectMenuItem.setMnemonic('D');
sendRawCommandMenuItem.setMnemonic('R');
soarRuntimeAgentMenu.setMnemonic('A');
return soarRuntimeMenu;
}
/**
* A helper function to create the help menu
* @return The help menu
*/
private JMenu createHelpMenu()
{
JMenu helpMenu = new JMenu("Help");
// Help menu
helpMenu.add(contactUsAction);
helpMenu.setMnemonic('H');
return helpMenu;
}
/**
* A Helper function that creates the main menu bar
* @return The MenuBar just created
*/
private JMenuBar createMainMenu()
{
JMenuBar MenuBar = new JMenuBar();
// The Main Menu Bar
MenuBar.add(createFileMenu());
MenuBar.add(createEditMenu());
MenuBar.add(createSearchMenu());
MenuBar.add(createDatamapMenu());
MenuBar.add(createViewMenu());
// 3P
// Add the Soar Runtime menu
MenuBar.add(createSoarRuntimeMenu());
MenuBar.add(createHelpMenu());
return MenuBar;
}
/**
* Creates a rule window opening with the given file name
* @param re the ruleeditor file that the rule editor should open
*/
public void addRuleEditor(RuleEditor re)
{
DesktopPane.add(re);
re.moveToFront();
if (Preferences.getInstance().isAutoTilingEnabled())
{
DesktopPane.performTileAction();
}
else
{
re.reshape(0, 0 , 300, 200);
}
DesktopPane.revalidate();
}
/**
* Creates a datamap window with the given datamap.
* @param dm the datamap that the window should open
* @see DataMap
*/
public void addDataMap(DataMap dm)
{
DesktopPane.add(dm);
dm.moveToFront();
DesktopPane.revalidate();
if (Preferences.getInstance().isAutoTilingEnabled())
{
DesktopPane.performTileAction();
}
else
{
dm.reshape(0, 0, 200, 300);
}
}
/**
* Makes the specified rule editor window the selected window
* and brings the window to the front of the frame.
* @param re the specified rule editor window
*/
public void showRuleEditor(RuleEditor re)
{
try
{
if (re.isIcon())
re.setIcon(false);
re.setSelected(true);
re.moveToFront();
}
catch (java.beans.PropertyVetoException pve) { System.err.println("Guess we can't do that");}
}
/**
* Gets rid of the operator window
*/
public void removeOperatorWindow()
{
operatorDesktopSplit.setLeftComponent(null);
}
/**
* This class is used to bring an internal frame to the front
* if it is selected from the view menu
*/
class WindowMenuListener implements ActionListener
{
JInternalFrame internalFrame;
public WindowMenuListener(JInternalFrame jif)
{
internalFrame = jif;
}
private WindowMenuListener() {}
public void actionPerformed(ActionEvent e)
{
internalFrame.toFront();
try
{
internalFrame.setIcon(false);
internalFrame.setSelected(true);
internalFrame.moveToFront();
} catch (java.beans.PropertyVetoException pve) {
System.err.println("Guess we can't do that"); }
}
}
/**
* Sets the main window
*/
public static void setMainFrame(MainFrame mainFrame)
{
s_mainFrame = mainFrame;
}
/**
* Gets the main window
*/
public static MainFrame getMainFrame()
{
return s_mainFrame;
}
/**
* enables the corresponding actions for when a project is opened
*/
private void projectActionsEnable(boolean areEnabled)
{
// Enable various actions
saveAllFilesAction.setEnabled(areEnabled);
checkAllProductionsAction.setEnabled(areEnabled);
searchDataMapTestAction.setEnabled(areEnabled);
searchDataMapCreateAction.setEnabled(areEnabled);
searchDataMapTestNoCreateAction.setEnabled(areEnabled);
searchDataMapCreateNoTestAction.setEnabled(areEnabled);
searchDataMapNoTestNoCreateAction.setEnabled(areEnabled);
generateDataMapAction.setEnabled(areEnabled);
//checkCoverageAction.setEnabled(true);
closeProjectAction.setEnabled(areEnabled);
findInProjectAction.setEnabled(areEnabled);
replaceInProjectAction.setEnabled(areEnabled);
commitAction.setEnabled(areEnabled);
saveProjectAsAction.setEnabled(areEnabled);
}
/*########################################################################################
Actions
########################################################################################/*
/**
* Runs through all the Rule Editors in the Desktop Pane and tells them to save
* themselves
*/
class SaveAllFilesAction extends PerformableAction
{
public SaveAllFilesAction()
{
super("Save All");
setEnabled(false);
}
public void perform()
{
try
{
JInternalFrame[] jif = DesktopPane.getAllFrames();
for(int i = 0; i < jif.length; ++i)
{
if(jif[i] instanceof RuleEditor)
{
RuleEditor re = (RuleEditor)jif[i];
re.write();
}
}
}
catch(java.io.IOException ioe)
{
JOptionPane.showMessageDialog(MainFrame.this, "Error Writing File", "IO Error", JOptionPane.ERROR_MESSAGE);
}
}
public void actionPerformed(ActionEvent event)
{
perform();
}
}
/**
* Exit command
* First closes all the RuleEditor windows
* if all the closes go successfully, then it closes
* the operator hierarchy then exits
*/
class ExitAction extends AbstractAction
{
public ExitAction()
{
super("Exit");
}
public void actionPerformed(ActionEvent event)
{
JInternalFrame[] frames = DesktopPane.getAllFrames();
prefs.write();
try
{
for(int i = 0; i < frames.length; ++i)
{
frames[i].setClosed(true);
}
// 3P
// Close down the STI library
SoarRuntimeTerm();
dispose();
commitAction.perform();
System.exit(0);
}
catch (java.beans.PropertyVetoException pve) {}
}
}
/**
* Attempts to save the datamap
* @see OperatorWindow.saveHierarchy()
*/
class SaveDataMapAndProjectAction extends PerformableAction
{
public SaveDataMapAndProjectAction()
{
super("Save DataMap And Project Action");
}
public void perform()
{
if(operatorWindow != null)
{
operatorWindow.saveHierarchy();
}
}
public void actionPerformed(ActionEvent event)
{
perform();
Vector v = new Vector();
v.add("DataMap and Project Saved");
setFeedbackListData(v);
}
}
/**
* Attempts to open a new project by creating a new OperatorWindow
* @param file .vsa project file that is to be opened
* @see OperatorWindow
*/
public void tryOpenProject (File file) throws FileNotFoundException, IOException
{
operatorWindow = new OperatorWindow(file);
operatorDesktopSplit.setLeftComponent(operatorWindow);
projectActionsEnable(true);
operatorDesktopSplit.setDividerLocation(.30);
}
/**
* Open Project Action
* a filechooser is created to determine project file
* Opens a project by creating a new OperatorWindow
* @see OperatorWindow
* @see SoarFileFilter
*/
class OpenProjectAction extends AbstractAction
{
public OpenProjectAction()
{
super("Open Project...");
}
public void actionPerformed(ActionEvent event)
{
try
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new SoarFileFilter());
fileChooser.setCurrentDirectory(Preferences.getInstance().getOpenFolder());
int state = fileChooser.showOpenDialog(MainFrame.this);
File file = fileChooser.getSelectedFile();
if (file != null && state == JFileChooser.APPROVE_OPTION)
{
operatorWindow = new OperatorWindow(file);
if(file.getParent() != null)
Preferences.getInstance().setOpenFolder(file.getParentFile());
operatorDesktopSplit.setLeftComponent(new JScrollPane(operatorWindow));
projectActionsEnable(true);
operatorDesktopSplit.setDividerLocation(.30);
}
}
catch(FileNotFoundException fnfe)
{
JOptionPane.showMessageDialog(MainFrame.this, "File Not Found!", "File Not Found", JOptionPane.ERROR_MESSAGE);
}
catch(IOException ioe)
{
JOptionPane.showMessageDialog(MainFrame.this, "Error Reading File", "IOException", JOptionPane.ERROR_MESSAGE);
ioe.printStackTrace();
}
catch(NumberFormatException nfe)
{
nfe.printStackTrace();
JOptionPane.showMessageDialog(MainFrame.this, "Error Reading File, Data Incorrectly Formatted", "Bad File", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Open a text file unrelated to the project in a rule editor
* Opened file is not necessarily part of project and not soar formatted
*/
class OpenFileAction extends AbstractAction
{
public OpenFileAction()
{
super("Open File...");
}
public void actionPerformed(ActionEvent event)
{
try
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TextFileFilter());
fileChooser.setCurrentDirectory(Preferences.getInstance().getOpenFolder());
int state = fileChooser.showOpenDialog(MainFrame.this);
File file = fileChooser.getSelectedFile();
if(file != null && state == JFileChooser.APPROVE_OPTION)
{
try
{
boolean oldPref = Preferences.getInstance().isHighlightingEnabled();
Preferences.getInstance().setHighlightingEnabled(false); // Turn off highlighting
RuleEditor ruleEditor = new RuleEditor(file);
ruleEditor.setVisible(true);
addRuleEditor(ruleEditor);
Preferences.getInstance().setHighlightingEnabled(oldPref); // Turn it back to what it was
}
catch(IOException IOE)
{
JOptionPane.showMessageDialog(MainFrame.this, "There was an error reading file: " +
file.getName(), "I/O Error", JOptionPane.ERROR_MESSAGE);
}
}
}
catch(NumberFormatException nfe)
{
nfe.printStackTrace();
JOptionPane.showMessageDialog(MainFrame.this, "Error Reading File, Data Incorrectly Formatted", "Bad File", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* New Project Action
* Creates a dialog that gets the new project name and then creates the new
* project by creating a new Operator Window.
* @see NewAgentDialog
* @see OperatorWindow
*/
class NewProjectAction extends AbstractAction
{
public NewProjectAction()
{
super("New Project...");
}
public void actionPerformed(ActionEvent event)
{
// redo this a dialog should just pass back data to the main window for processing
NewAgentDialog newAgentDialog = new NewAgentDialog(MainFrame.this);
newAgentDialog.show();
if (newAgentDialog.wasApproved())
{
String agentName = newAgentDialog.getNewAgentName();
String path = newAgentDialog.getNewAgentPath();
String agentFileName = path + File.separator + agentName + ".vsa";
operatorWindow = new OperatorWindow(agentName,agentFileName,true);
Preferences.getInstance().setOpenFolder(new File(path));
operatorDesktopSplit.setLeftComponent(new JScrollPane(operatorWindow));
projectActionsEnable(true);
exportAgentAction.perform();
operatorDesktopSplit.setDividerLocation(.30);
}
}
}
/**
* Close Project Action
* Closes all open windows in the desktop pane
*/
class CloseProjectAction extends AbstractAction
{
public CloseProjectAction()
{
super("Close Project");
setEnabled(false);
}
public void actionPerformed(ActionEvent event)
{
JInternalFrame[] frames = DesktopPane.getAllFrames();
try
{
for(int i = 0; i < frames.length; ++i)
{
frames[i].setClosed(true);
}
commitAction.perform();
operatorDesktopSplit.setLeftComponent(null);
projectActionsEnable(false);
}
catch (java.beans.PropertyVetoException pve) {}
}
}
/**
* Export Agent
* Writes all the <operator>_source.soar files necesary for sourcing agent
* files written in into the TSI
*/
class ExportAgentAction extends PerformableAction
{
public ExportAgentAction()
{
super("Export Agent");
}
public void perform()
{
DefaultTreeModel tree = (DefaultTreeModel)operatorWindow.getModel();
OperatorRootNode root = (OperatorRootNode)tree.getRoot();
try
{
root.startSourcing();
}
catch (IOException exception)
{
JOptionPane.showMessageDialog(MainFrame.this, "IO Error exporting agent.", "Agent Export Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
public void actionPerformed(ActionEvent event) {
perform();
Vector v = new Vector();
v.add("Export Finished");
setFeedbackListData(v);
}
}
/**
* Creates and shows the preferences dialog
*/
class PreferencesAction extends AbstractAction
{
public PreferencesAction()
{
super("Preferences Action");
}
public void actionPerformed(ActionEvent e)
{
PreferencesDialog theDialog = new PreferencesDialog(MainFrame.getMainFrame());
theDialog.setVisible(true);
//to realize the change immediately... takes too long
/* if (theDialog.wasApproved())
{
// make the change realized...
JInternalFrame[] theFrames = DesktopPane.getAllFrames();
for (int i = 0; i < theFrames.length; i++)
{
if (theFrames[i] instanceof RuleEditor)
{
((RuleEditor)theFrames[i]).recolorSyntax();
}
}
}
*/
}
}
/**
* This is where the user user wants some info about the authors
* @see AboutDialog
*/
class ContactUsAction extends AbstractAction
{
public ContactUsAction()
{
super("About Visual Soar");
}
public void actionPerformed(ActionEvent e)
{
aboutDialog.setVisible(true);
}
}
/**
* Message timer listener which is used to pump the STI messages
* in the background. Incoming commands are received here and
* processeed through the ProcessSoarToolJavaCommand method.
* @author ThreePenny
*/
class SoarRuntimePumpMessagesTimerListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
// Return if we don't have a tools interface
if (soarToolJavaInterface == null)
{
return;
}
// Pump our messages
soarToolJavaInterface.PumpMessages(true /* bProcessAllPendingMessages */);
// Process all of our commands
while (soarToolJavaInterface.IsIncomingCommandAvailable() == true)
{
// Get our command object
SoarToolJavaCommand commandObject=new SoarToolJavaCommand();
soarToolJavaInterface.GetIncomingCommand(commandObject);
// Process the command
ProcessSoarToolJavaCommand(commandObject);
// Pop the command
soarToolJavaInterface.PopIncomingCommand();
}
}
}
/**
* Processes incoming STI commands from the runtime
* @author ThreePenny
*/
protected void ProcessSoarToolJavaCommand(SoarToolJavaCommand command)
{
switch (command.GetCommandID())
{
// Edit Production command
case 1001:
// BUGBUG: JDK complains that STI_kEditProduction needs to be a constant
// Seems defined as 'final' which I thought was a Java constant.
//case command.STI_kEditProduction:
{
// Edit the production
EditProductionByName(command.GetStringParam());
break;
}
}
}
/**
* Edits a production (in the project) based on its name.
* @author ThreePenny
*/
protected void EditProductionByName(String sProductionName)
{
// TODO: Should we match case?
// Find the rule and open it
getOperatorWindow().findInProjectAndOpenRule(sProductionName, false /* match case */);
// Bring our window to the front
toFront();
}
/**
* Handles Soar Runtime|Connect menu option
* @author ThreePenny
*/
class SoarRuntimeInitAction extends AbstractAction
{
public SoarRuntimeInitAction()
{
super("Connect");
}
public void actionPerformed(ActionEvent e)
{
// Initialize the soar runtime
if (!SoarRuntimeInit())
-
{
// Unable to connect!
soarToolJavaInterface=null;
JOptionPane.showMessageDialog(MainFrame.this, "Unable to connect to the Soar Tool Interface (STI)", "STI Error", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Initializes the Soar Tool Interface (STI) object and enabled/disables
* menu items as needed.
* @author ThreePenny
*/
boolean SoarRuntimeInit()
{
// Stop any "pump messages" timers that are currently running
if (soarToolPumpMessageTimer != null)
{
soarToolPumpMessageTimer.stop();
soarToolPumpMessageTimer=null;
}
// Term our interface if we have one already
if (soarToolJavaInterface != null)
{
soarToolJavaInterface.Term();
soarToolJavaInterface=null;
}
- // Create and initialize our interface object
- soarToolJavaInterface = new SoarToolJavaInterface();
- if (soarToolJavaInterface.Init("VisualSoar", false /* bIsRuntime */) == true)
+ // Load the interface object
+ try
+ {
+ soarToolJavaInterface = new SoarToolJavaInterface();
+ }
+ catch (java.lang.UnsatisfiedLinkError ule)
+ {
+ JOptionPane.showMessageDialog(
+ MainFrame.this,
+ "I was unable to load the Soar Tools Interface (STI) library.\n"
+ + "Therefore this part of the VisualSoar functionality will not \n"
+ + "be available while you are running VisualSoar. To enable \n"
+ + "the STI, make sure that the SoarToolJavaInterface1 library \n"
+ + "is in your PATH and restart VisualSoar.",
+ "DLL Load Error",
+ JOptionPane.ERROR_MESSAGE);
+
+ // Disable all related menu items
+ soarRuntimeTermAction.setEnabled(false);
+ soarRuntimeInitAction.setEnabled(false);
+ soarRuntimeSendRawCommandAction.setEnabled(false);
+ soarRuntimeAgentMenu.setEnabled(false);
+
+ return false;
+ }
+
+ //Initialize the interface object
+ if (soarToolJavaInterface.Init("VisualSoar", false /* bIsRuntime */) == true)
{
// Create our pump messages timer to be fired every 1000 ms
soarToolPumpMessageTimer = new javax.swing.Timer(1000, new SoarRuntimePumpMessagesTimerListener());
soarToolPumpMessageTimer.start();
// Enable/Disable menu items
soarRuntimeTermAction.setEnabled(true);
soarRuntimeInitAction.setEnabled(false);
soarRuntimeSendRawCommandAction.setEnabled(true);
soarRuntimeAgentMenu.setEnabled(true);
// Success!
return true;
}
else
{
// Failure
return false;
}
}
/**
* Terminates the Soar Tool Interface (STI) object and enabled/disables
* menu items as needed.
* @author ThreePenny
*/
void SoarRuntimeTerm()
{
// Stop any "pump messages" timers that are currently running
if (soarToolPumpMessageTimer != null)
{
soarToolPumpMessageTimer.stop();
soarToolPumpMessageTimer=null;
}
// Term our interface object
if (soarToolJavaInterface != null)
{
soarToolJavaInterface.Term();
soarToolJavaInterface=null;
}
// Enable/Disable menu items
soarRuntimeTermAction.setEnabled(false);
soarRuntimeInitAction.setEnabled(true);
soarRuntimeSendRawCommandAction.setEnabled(false);
soarRuntimeAgentMenu.setEnabled(false);
}
/**
* Handles Soar Runtime|Disconnect menu option
* @author ThreePenny
*/
class SoarRuntimeTermAction extends AbstractAction
{
public SoarRuntimeTermAction()
{
// Set the name and default to being disabled
super("Disconnect");
setEnabled(false);
}
public void actionPerformed(ActionEvent e)
{
// Terminate the soar runtime
SoarRuntimeTerm();
}
}
/**
* Handles Soar Runtime|Send Raw Command menu option
* @author ThreePenny
*/
class SoarRuntimeSendRawCommandAction extends AbstractAction
{
public SoarRuntimeSendRawCommandAction()
{
// Set the name and default to being disabled
super("Send Raw Command");
setEnabled(false);
}
public void actionPerformed(ActionEvent e)
{
SoarRuntimeSendRawCommandDialog theDialog = new SoarRuntimeSendRawCommandDialog(MainFrame.this, GetSoarToolJavaInterface());
theDialog.setVisible(true);
}
}
class SendProductionsAction extends AbstractAction
{
public SendProductionsAction()
{
super("Send Productions");
}
public void actionPerformed(ActionEvent e)
{
try
{
String serverName = JOptionPane.showInputDialog(MainFrame.getMainFrame(),"Server Name");
String serverPort = JOptionPane.showInputDialog(MainFrame.getMainFrame(),"Server Port");
int port = Integer.parseInt(serverPort);
java.net.Socket socket = new java.net.Socket(serverName,port);
//operatorWindow.sendProductions(
// new BufferedWriter(
// new OutputStreamWriter(socket.getOutputStream())));
}
catch(IOException ioe)
{
System.err.println("IOError");
}
catch(NumberFormatException nfe)
{
System.err.println("Hey, how about you enter a number?");
}
}
}
/*
class CheckCoverageAction extends AbstractAction
{
public CheckCoverageAction()
{
super("Check Coverage");
setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
DataMapCoverageChecker dmcc = new DataMapCoverageChecker(getOperatorWindow().getDatamap());
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
OperatorNode on = (OperatorNode)bfe.nextElement();
try
{
Vector productions = on.parseProductions();
if(productions != null)
{
OperatorNode parent = (OperatorNode)on.getParent();
SoarIdentifierVertex siv = parent.getStateIdVertex(getOperatorWindow().getDatamap());
if(siv == null)
dmcc.check(getOperatorWindow().getDatamap().getTopstate(),productions);
else
dmcc.check(siv,productions);
}
}
catch(ParseException pe) {}
catch(java.io.IOException ioe) {}
}
System.out.println("Place to Break when done");
}
}
*/
/**
* This class is responsible for comparing all productions in the project
* with the project's model of working memory - the datamap.
* Operation status is displayed in a progress bar.
* Results are displayed in the feedback list
*/
class CheckAllProductionsAction extends AbstractAction
{
JProgressBar progressBar;
JDialog progressDialog;
int numNodes;
public CheckAllProductionsAction()
{
super("Check All Productions");
setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
numNodes = 0;
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
numNodes++;
bfe.nextElement();
}
System.out.println("Nodes: " + numNodes);
progressBar = new JProgressBar(0, numNodes);
progressDialog = new JDialog(MainFrame.this, "Checking Productions");
progressDialog.getContentPane().setLayout(new FlowLayout());
progressDialog.getContentPane().add(progressBar);
progressBar.setStringPainted(true);
progressDialog.setLocationRelativeTo(MainFrame.this);
progressDialog.pack();
progressDialog.show();
(new UpdateThread()).start();
}
class UpdateThread extends Thread
{
Runnable update, finish;
int value, min, max;
java.util.List errors = new LinkedList();
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
OperatorNode current;
Vector parsedProds, vecErrors = new Vector();
int nodeNum = 0;
public UpdateThread()
{
progressBar.getMaximum();
progressBar.getMinimum();
update = new Runnable()
{
public void run()
{
value = progressBar.getValue() + 1;
updateProgressBar(value);
//System.out.println("Value is " + value);
}
};
finish = new Runnable()
{
public void run()
{
updateProgressBar(min);
System.out.println("Done");
progressDialog.dispose();
}
};
}
public void run()
{
checkNodes();
//checkNodesLog();
}
private void updateProgressBar(int value)
{
progressBar.setValue(value);
}
public void checkNodes()
{
try
{
boolean anyErrors = false;
checkingNodes: while(bfe.hasMoreElements())
{
current = (OperatorNode)bfe.nextElement();
// If the node has a rule editor open, get the rules from the
// window, otherwise, open the associated file
try
{
parsedProds = current.parseProductions();
}
catch(ParseException pe)
{
anyErrors = true;
String errString;
String parseError = pe.toString();
int i = parseError.lastIndexOf("line ");
String lineNum = parseError.substring(i + 5);
i = lineNum.indexOf(',');
lineNum = "(" + lineNum.substring(0, i) + "): ";
errString = current.getFileName() + lineNum + "Unable to check productions due to parse error";
errors.add(errString);
}
catch(TokenMgrError tme)
{
tme.printStackTrace();
}
if (parsedProds!= null)
{
operatorWindow.checkProductions((OperatorNode)current.getParent(), parsedProds, errors);
}
if (errors.isEmpty())
{
if(parsedProds != null)
{
vecErrors.add("No errors detected in " + current.getFileName());
}
}
else
{
anyErrors = true;
Enumeration e = new EnumerationIteratorWrapper(errors.iterator());
while(e.hasMoreElements())
{
try
{
String errorString = e.nextElement().toString();
String numberString = errorString.substring(errorString.indexOf("(")+1,errorString.indexOf(")"));
if(errorString.endsWith("Unable to check productions due to parse error"))
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true,true));
}
else
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true));
}
} catch(NumberFormatException nfe)
{
System.out.println("Never happen");
}
}
}
errors.clear();
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // while parsing operator nodes
if(!anyErrors)
vecErrors.add("There were no errors detected in this project.");
feedbackList.setListData(vecErrors);
SwingUtilities.invokeLater(finish);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
} // end of checkNodes()
/**
* Similar to checkNodes(), but this generates a log file.
*/
public void checkNodesLog()
{
try
{
FileWriter fw = new FileWriter("CheckingProductions.log");
boolean anyErrors = false;
checkingNodes: while(bfe.hasMoreElements())
{
current = (OperatorNode)bfe.nextElement();
try
{
fw.write("Looking at node " + current.toString());
fw.write('\n');
}
catch(IOException e)
{
e.printStackTrace();
}
// If the node has a rule editor open, get the rules from the
// window, otherwise, open the associated file
try
{
parsedProds = current.parseProductions();
try
{
fw.write("Parsed Productions for node " + current.toString());
fw.write('\n');
}
catch(IOException e)
{
e.printStackTrace();
}
}
catch(ParseException pe)
{
try
{
fw.write("There was a parse error when attempting to parse productions for node " + current.toString());
fw.write('\n');
}
catch(IOException e)
{
e.printStackTrace();
}
anyErrors = true;
String errString;
String parseError = pe.toString();
int i = parseError.lastIndexOf("line ");
String lineNum = parseError.substring(i + 5);
i = lineNum.indexOf(',');
lineNum = "(" + lineNum.substring(0, i) + "): ";
errString = current.getFileName() + lineNum + "Unable to check productions due to parse error";
errors.add(errString);
}
catch(TokenMgrError tme)
{
tme.printStackTrace();
}
if (parsedProds!= null)
{
try
{
fw.write("About to check individual productions for node " + current.toString());
fw.write('\n');
}
catch(IOException e)
{
e.printStackTrace();
}
operatorWindow.checkProductionsLog((OperatorNode)current.getParent(), parsedProds, errors, fw);
}
if (errors.isEmpty())
{
if(parsedProds != null)
{
try
{
fw.write("No errors detected for node " + current.toString());
fw.write('\n');
}
catch(IOException e)
{
e.printStackTrace();
}
vecErrors.add("No errors detected in " + current.getFileName());
}
}
else
{
try
{
fw.write("Errors were detected for node " + current.toString());
fw.write('\n');
}
catch(IOException e)
{
e.printStackTrace();
}
anyErrors = true;
Enumeration e = new EnumerationIteratorWrapper(errors.iterator());
while(e.hasMoreElements())
{
try
{
String errorString = e.nextElement().toString();
String numberString = errorString.substring(errorString.indexOf("(")+1,errorString.indexOf(")"));
if(errorString.endsWith("Unable to check productions due to parse error"))
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true,true));
}
else
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true));
}
} catch(NumberFormatException nfe)
{
System.out.println("Never happen");
}
}
}
errors.clear();
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
try
{
fw.write("Check for the node " + current.toString() + " completed. Getting next node\n");
fw.write( nodeNum + " nodes out of " + numNodes + " total nodes have been completed.");
fw.write('\n');
fw.write('\n');
}
catch(IOException e)
{
e.printStackTrace();
}
} // while parsing operator nodes
if(!anyErrors)
vecErrors.add("There were no errors detected in this project.");
feedbackList.setListData(vecErrors);
SwingUtilities.invokeLater(finish);
fw.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
} // end of CheckNodesLog()
} // end of CheckProductions Action
/**
* This action searches all Datamaps to find WMEs that
* are never tested by any production within the project.
* i.e. not in the condition side of any production and not in the output-link.
* Operation status is displayed in a progress bar.
* Results are displayed in the feedback list
* Double-clicking on an item in the feedback list
* should display the rogue node in the datamap.
*/
class SearchDataMapTestAction extends AbstractAction
{
JProgressBar progressBar;
JDialog progressDialog;
int numNodes;
public SearchDataMapTestAction()
{
super("Check All Productions");
setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
numNodes = 0;
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
numNodes++;
bfe.nextElement();
}
System.out.println("Nodes: " + (numNodes * 2));
progressBar = new JProgressBar(0, numNodes * 2);
progressDialog = new JDialog(MainFrame.this, "Checking Productions");
progressDialog.getContentPane().setLayout(new FlowLayout());
progressDialog.getContentPane().add(progressBar);
progressBar.setStringPainted(true);
progressDialog.setLocationRelativeTo(MainFrame.this);
progressDialog.pack();
progressDialog.show();
(new UpdateThread()).start();
} // end of constructor
class UpdateThread extends Thread
{
Runnable update, finish;
int value, min, max;
java.util.List errors = new LinkedList();
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
OperatorNode current;
Vector parsedProds, vecErrors = new Vector();
int nodeNum = 0;
public UpdateThread()
{
progressBar.getMaximum();
progressBar.getMinimum();
update = new Runnable()
{
public void run()
{
value = progressBar.getValue() + 1;
updateProgressBar(value);
//System.out.println("Value is " + value);
}
};
finish = new Runnable()
{
public void run()
{
updateProgressBar(min);
System.out.println("Done");
progressDialog.dispose();
}
};
}
public void run()
{
initializeNodes();
if(checkNodes())
searchDataMap();
SwingUtilities.invokeLater(finish);
}
private void updateProgressBar(int value)
{
progressBar.setValue(value);
}
/**
* This initializes the status of all the edges to zero, which means that
* the edges have not been used by a production in any way.
*/
public void initializeNodes()
{
Enumeration edges = operatorWindow.getDatamap().getEdges();
while(edges.hasMoreElements())
{
NamedEdge currentEdge = (NamedEdge)edges.nextElement();
currentEdge.resetTestedStatus();
currentEdge.resetErrorNoted();
// initialize the output-link as already tested
if(currentEdge.getName().equals("output-link"))
{
currentEdge.setOutputLinkTested(operatorWindow.getDatamap());
}
}
} // end of searchDataMap()
/**
* Simply go through all the nodes, checking productions
* and marking the named edges in the datamap when either tested
* or created by a production.
* @return false if encountered a parse error
*/
public boolean checkNodes()
{
try
{
boolean anyErrors = false;
checkingNodes: while(bfe.hasMoreElements())
{
current = (OperatorNode)bfe.nextElement();
// If the node has a rule editor open, get the rules from the
// window, otherwise, open the associated file
try
{
parsedProds = current.parseProductions();
}
catch(ParseException pe)
{
anyErrors = true;
String errString;
String parseError = pe.toString();
int i = parseError.lastIndexOf("line ");
String lineNum = parseError.substring(i + 5);
i = lineNum.indexOf(',');
lineNum = "(" + lineNum.substring(0, i) + "): ";
errString = current.getFileName() + lineNum + "Unable to Search DataMap for extra WMEs due to parse error";
errors.add(errString);
}
catch(TokenMgrError tme)
{
tme.printStackTrace();
}
if (parsedProds!= null)
{
operatorWindow.checkProductions((OperatorNode)current.getParent(), parsedProds, errors);
}
if (!errors.isEmpty())
{
anyErrors = true;
Enumeration e = new EnumerationIteratorWrapper(errors.iterator());
while(e.hasMoreElements())
{
try
{
String errorString = e.nextElement().toString();
String numberString = errorString.substring(errorString.indexOf("(")+1,errorString.indexOf(")"));
if(errorString.endsWith("Unable to Search DataMap for extra WMEs due to parse error"))
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true,true));
feedbackList.setListData(vecErrors);
SwingUtilities.invokeLater(finish);
return false;
}
} catch(NumberFormatException nfe)
{
System.out.println("Never happen");
}
}
}
errors.clear();
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // while parsing operator nodes
feedbackList.setListData(vecErrors);
return true;
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return false; // should never get here unless try failed
} // end of checkNodes()
/**
* Search through the datamap and look for extra WMEs
* by looking at the status of the named edge (as determined
* by the check nodes function) and the edge's location within
* the datamap.
* Extra WMEs are classified in this action by never being tested by a
* production, not including any item within the output-link.
* Send results to the feedback list
*/
public void searchDataMap()
{
OperatorNode operatorNode;
vecErrors.clear(); // clear out errors just in case
vecErrors.add("Attributes never tested in productions in this agent:");
// Go through all of the nodes examining the nodes' datamap if they have one
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
operatorNode = (OperatorNode)bfe.nextElement();
operatorNode.searchTestDataMap(operatorWindow.getDatamap(), vecErrors);
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // end of while looking at all nodes
// do case of no errors
if(vecErrors.size() == 1)
{
vecErrors.clear();
vecErrors.add("No errors. All attributes were tested in productions within this agents");
}
// Add list of errors to feedback list
feedbackList.setListData(vecErrors);
} // end of searchDataMap()
} // end of UpdateThread class
} // end of SearchDataMapTestAction
/**
* This action searches all Datamaps to find WMEs that
* are never created by any production within the project.
* i.e. not in the action side of any production and not in the output-link.
* Operation status is displayed in a progress bar.
* Results are displayed in the feedback list
* Double-clicking on an item in the feedback list
* should display the rogue node in the datamap.
*/
class SearchDataMapCreateAction extends AbstractAction
{
JProgressBar progressBar;
JDialog progressDialog;
int numNodes;
public SearchDataMapCreateAction()
{
super("Check All Productions");
setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
numNodes = 0;
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
numNodes++;
bfe.nextElement();
}
System.out.println("Nodes: " + (numNodes * 2));
progressBar = new JProgressBar(0, numNodes * 2);
progressDialog = new JDialog(MainFrame.this, "Checking Productions");
progressDialog.getContentPane().setLayout(new FlowLayout());
progressDialog.getContentPane().add(progressBar);
progressBar.setStringPainted(true);
progressDialog.setLocationRelativeTo(MainFrame.this);
progressDialog.pack();
progressDialog.show();
(new UpdateThread()).start();
} // end of constructor
class UpdateThread extends Thread
{
Runnable update, finish;
int value, min, max;
java.util.List errors = new LinkedList();
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
OperatorNode current;
Vector parsedProds, vecErrors = new Vector();
int nodeNum = 0;
public UpdateThread()
{
progressBar.getMaximum();
progressBar.getMinimum();
update = new Runnable()
{
public void run()
{
value = progressBar.getValue() + 1;
updateProgressBar(value);
//System.out.println("Value is " + value);
}
};
finish = new Runnable()
{
public void run()
{
updateProgressBar(min);
System.out.println("Done");
progressDialog.dispose();
}
};
}
public void run()
{
initializeNodes();
if(checkNodes())
searchDataMap();
SwingUtilities.invokeLater(finish);
}
private void updateProgressBar(int value)
{
progressBar.setValue(value);
}
/**
* This initializes the status of all the edges to zero, which means that
* the edges have not been used by a production in any way.
*/
public void initializeNodes()
{
Enumeration edges = operatorWindow.getDatamap().getEdges();
while(edges.hasMoreElements())
{
NamedEdge currentEdge = (NamedEdge)edges.nextElement();
currentEdge.resetTestedStatus();
currentEdge.resetErrorNoted();
// initialize the input-link as already tested
if(currentEdge.getName().equals("input-link"))
currentEdge.setInputLinkCreated(operatorWindow.getDatamap());
}
} // end of searchDataMap()
/**
* Simply go through all the nodes, checking productions
* and marking the named edges in the datamap when either tested
* or created by a production.
* @return false if encountered a parse error
*/
public boolean checkNodes()
{
try
{
boolean anyErrors = false;
checkingNodes: while(bfe.hasMoreElements())
{
current = (OperatorNode)bfe.nextElement();
// If the node has a rule editor open, get the rules from the
// window, otherwise, open the associated file
try
{
parsedProds = current.parseProductions();
}
catch(ParseException pe)
{
anyErrors = true;
String errString;
String parseError = pe.toString();
int i = parseError.lastIndexOf("line ");
String lineNum = parseError.substring(i + 5);
i = lineNum.indexOf(',');
lineNum = "(" + lineNum.substring(0, i) + "): ";
errString = current.getFileName() + lineNum + "Unable to Search DataMap for extra WMEs due to parse error";
errors.add(errString);
}
catch(TokenMgrError tme)
{
tme.printStackTrace();
}
if (parsedProds!= null)
{
operatorWindow.checkProductions((OperatorNode)current.getParent(), parsedProds, errors);
}
if (!errors.isEmpty())
{
anyErrors = true;
Enumeration e = new EnumerationIteratorWrapper(errors.iterator());
while(e.hasMoreElements())
{
try
{
String errorString = e.nextElement().toString();
String numberString = errorString.substring(errorString.indexOf("(")+1,errorString.indexOf(")"));
if(errorString.endsWith("Unable to Search DataMap for extra WMEs due to parse error"))
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true,true));
feedbackList.setListData(vecErrors);
SwingUtilities.invokeLater(finish);
return false;
}
} catch(NumberFormatException nfe)
{
System.out.println("Never happen");
}
}
}
errors.clear();
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // while parsing operator nodes
feedbackList.setListData(vecErrors);
return true;
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return false; // should never get here unless try failed
} // end of checkNodes()
/**
* Search through the datamap and look for extra WMEs
* by looking at the status of the named edge (as determined
* by the check nodes function) and the edge's location within
* the datamap.
* Extra WMEs are classified in this action by never being created by a
* production, not including any item within the input-link.
* Send results to the feedback list
*/
public void searchDataMap()
{
OperatorNode operatorNode;
vecErrors.clear(); // clear out errors just in case
vecErrors.add("Attributes never created in productions in this agent:");
// Go through all of the nodes examining the nodes' datamap if they have one
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
operatorNode = (OperatorNode)bfe.nextElement();
operatorNode.searchCreateDataMap(operatorWindow.getDatamap(), vecErrors);
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // end of while looking at all nodes
// do case of no errors
if(vecErrors.size() == 1)
{
vecErrors.clear();
vecErrors.add("No errors. All attributes were created in productions within this agents");
}
// Add list of errors to feedback list
feedbackList.setListData(vecErrors);
} // end of searchDataMap()
} // end of UpdateThread class
} // end of SearchDataMapCreateAction
/**
* This action searches all Datamaps to find WMEs that
* are never tested by some production within the project, but never created.
* i.e. not in the action side of any production and not in the output-link.
* Operation status is displayed in a progress bar.
* Results are displayed in the feedback list
* Double-clicking on an item in the feedback list
* should display the rogue node in the datamap.
*/
class SearchDataMapTestNoCreateAction extends AbstractAction
{
JProgressBar progressBar;
JDialog progressDialog;
int numNodes;
public SearchDataMapTestNoCreateAction()
{
super("Searching DataMap");
setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
numNodes = 0;
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
numNodes++;
bfe.nextElement();
}
System.out.println("Nodes: " + (numNodes * 2));
progressBar = new JProgressBar(0, numNodes * 2);
progressDialog = new JDialog(MainFrame.this, "Checking Productions");
progressDialog.getContentPane().setLayout(new FlowLayout());
progressDialog.getContentPane().add(progressBar);
progressBar.setStringPainted(true);
progressDialog.setLocationRelativeTo(MainFrame.this);
progressDialog.pack();
progressDialog.show();
(new UpdateThread()).start();
} // end of constructor
class UpdateThread extends Thread
{
Runnable update, finish;
int value, min, max;
java.util.List errors = new LinkedList();
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
OperatorNode current;
Vector parsedProds, vecErrors = new Vector();
int nodeNum = 0;
public UpdateThread()
{
progressBar.getMaximum();
progressBar.getMinimum();
update = new Runnable()
{
public void run()
{
value = progressBar.getValue() + 1;
updateProgressBar(value);
//System.out.println("Value is " + value);
}
};
finish = new Runnable()
{
public void run()
{
updateProgressBar(min);
System.out.println("Done");
progressDialog.dispose();
}
};
}
public void run()
{
initializeNodes();
if(checkNodes())
searchDataMap();
SwingUtilities.invokeLater(finish);
}
private void updateProgressBar(int value)
{
progressBar.setValue(value);
}
/**
* This initializes the status of all the edges to zero, which means that
* the edges have not been used by a production in any way.
*/
public void initializeNodes()
{
Enumeration edges = operatorWindow.getDatamap().getEdges();
while(edges.hasMoreElements())
{
NamedEdge currentEdge = (NamedEdge)edges.nextElement();
currentEdge.resetTestedStatus();
currentEdge.resetErrorNoted();
// initialize the input-link as already tested
if(currentEdge.getName().equals("input-link"))
currentEdge.setInputLinkCreated(operatorWindow.getDatamap());
// initialize the output-link as already tested
if(currentEdge.getName().equals("output-link"))
currentEdge.setOutputLinkTested(operatorWindow.getDatamap());
}
} // end of initializeNodes()
/**
* Simply go through all the nodes, checking productions
* and marking the named edges in the datamap when either tested
* or created by a production.
* @return false if encountered a parse error
*/
public boolean checkNodes()
{
try
{
boolean anyErrors = false;
checkingNodes: while(bfe.hasMoreElements())
{
current = (OperatorNode)bfe.nextElement();
// If the node has a rule editor open, get the rules from the
// window, otherwise, open the associated file
try
{
parsedProds = current.parseProductions();
}
catch(ParseException pe)
{
anyErrors = true;
String errString;
String parseError = pe.toString();
int i = parseError.lastIndexOf("line ");
String lineNum = parseError.substring(i + 5);
i = lineNum.indexOf(',');
lineNum = "(" + lineNum.substring(0, i) + "): ";
errString = current.getFileName() + lineNum + "Unable to Search DataMap for extra WMEs due to parse error";
errors.add(errString);
}
catch(TokenMgrError tme)
{
tme.printStackTrace();
}
if (parsedProds!= null)
{
operatorWindow.checkProductions((OperatorNode)current.getParent(), parsedProds, errors);
}
if (!errors.isEmpty())
{
anyErrors = true;
Enumeration e = new EnumerationIteratorWrapper(errors.iterator());
while(e.hasMoreElements())
{
try
{
String errorString = e.nextElement().toString();
String numberString = errorString.substring(errorString.indexOf("(")+1,errorString.indexOf(")"));
if(errorString.endsWith("Unable to Search DataMap for extra WMEs due to parse error"))
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true,true));
feedbackList.setListData(vecErrors);
SwingUtilities.invokeLater(finish);
return false;
}
} catch(NumberFormatException nfe)
{
System.out.println("Never happen");
}
}
}
errors.clear();
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // while parsing operator nodes
feedbackList.setListData(vecErrors);
return true;
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return false; // should never get here unless try failed
} // end of checkNodes()
/**
* Search through the datamap and look for extra WMEs
* by looking at the status of the named edge (as determined
* by the check nodes function) and the edge's location within
* the datamap.
* Extra WMEs are classified in this action by being tested by some production
* within the project, but never created by any production;
* not including any item within the input-link.
* Send results to the feedback list
*/
public void searchDataMap()
{
OperatorNode operatorNode;
vecErrors.clear(); // clear out errors just in case
vecErrors.add("Attributes that were tested but never created in the productions of this agent:");
// Go through all of the nodes examining the nodes' datamap if they have one
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
operatorNode = (OperatorNode)bfe.nextElement();
operatorNode.searchTestNoCreateDataMap(operatorWindow.getDatamap(), vecErrors);
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // end of while looking at all nodes
// do case of no errors
if(vecErrors.size() == 1)
{
vecErrors.clear();
vecErrors.add("No errors. All attributes that were tested, were also created.");
}
// Add list of errors to feedback list
feedbackList.setListData(vecErrors);
} // end of searchDataMap()
} // end of UpdateThread class
} // end of SearchDataMapTestNoCreateAction
/**
* This action searches all Datamaps to find WMEs that
* are created by some production within the project, but never tested.
* i.e. not in the action side of any production and not in the output-link.
* Operation status is displayed in a progress bar.
* Results are displayed in the feedback list
* Double-clicking on an item in the feedback list
* should display the rogue node in the datamap.
*/
class SearchDataMapCreateNoTestAction extends AbstractAction
{
JProgressBar progressBar;
JDialog progressDialog;
int numNodes;
public SearchDataMapCreateNoTestAction()
{
super("Searching DataMap");
setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
numNodes = 0;
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
numNodes++;
bfe.nextElement();
}
System.out.println("Nodes: " + (numNodes * 2));
progressBar = new JProgressBar(0, numNodes * 2);
progressDialog = new JDialog(MainFrame.this, "Checking Productions");
progressDialog.getContentPane().setLayout(new FlowLayout());
progressDialog.getContentPane().add(progressBar);
progressBar.setStringPainted(true);
progressDialog.setLocationRelativeTo(MainFrame.this);
progressDialog.pack();
progressDialog.show();
(new UpdateThread()).start();
} // end of constructor
class UpdateThread extends Thread
{
Runnable update, finish;
int value, min, max;
java.util.List errors = new LinkedList();
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
OperatorNode current;
Vector parsedProds, vecErrors = new Vector();
int nodeNum = 0;
public UpdateThread()
{
progressBar.getMaximum();
progressBar.getMinimum();
update = new Runnable()
{
public void run()
{
value = progressBar.getValue() + 1;
updateProgressBar(value);
//System.out.println("Value is " + value);
}
};
finish = new Runnable()
{
public void run()
{
updateProgressBar(min);
System.out.println("Done");
progressDialog.dispose();
}
};
}
public void run()
{
initializeNodes();
if(checkNodes())
searchDataMap();
SwingUtilities.invokeLater(finish);
}
private void updateProgressBar(int value)
{
progressBar.setValue(value);
}
/**
* This initializes the status of all the edges to zero, which means that
* the edges have not been used by a production in any way.
*/
public void initializeNodes()
{
Enumeration edges = operatorWindow.getDatamap().getEdges();
while(edges.hasMoreElements())
{
NamedEdge currentEdge = (NamedEdge)edges.nextElement();
currentEdge.resetTestedStatus();
currentEdge.resetErrorNoted();
// initialize the input-link as already tested
if(currentEdge.getName().equals("input-link"))
currentEdge.setInputLinkCreated(operatorWindow.getDatamap());
// initialize the output-link as already tested
if(currentEdge.getName().equals("output-link"))
currentEdge.setOutputLinkTested(operatorWindow.getDatamap());
}
} // end of initializeNodes()
/**
* Simply go through all the nodes, checking productions
* and marking the named edges in the datamap when either tested
* or created by a production.
* @return false if encountered a parse error
*/
public boolean checkNodes()
{
try
{
boolean anyErrors = false;
checkingNodes: while(bfe.hasMoreElements())
{
current = (OperatorNode)bfe.nextElement();
// If the node has a rule editor open, get the rules from the
// window, otherwise, open the associated file
try
{
parsedProds = current.parseProductions();
}
catch(ParseException pe)
{
anyErrors = true;
String errString;
String parseError = pe.toString();
int i = parseError.lastIndexOf("line ");
String lineNum = parseError.substring(i + 5);
i = lineNum.indexOf(',');
lineNum = "(" + lineNum.substring(0, i) + "): ";
errString = current.getFileName() + lineNum + "Unable to Search DataMap for extra WMEs due to parse error";
errors.add(errString);
}
catch(TokenMgrError tme)
{
tme.printStackTrace();
}
if (parsedProds!= null)
{
operatorWindow.checkProductions((OperatorNode)current.getParent(), parsedProds, errors);
}
if (!errors.isEmpty())
{
anyErrors = true;
Enumeration e = new EnumerationIteratorWrapper(errors.iterator());
while(e.hasMoreElements())
{
try
{
String errorString = e.nextElement().toString();
String numberString = errorString.substring(errorString.indexOf("(")+1,errorString.indexOf(")"));
if(errorString.endsWith("Unable to Search DataMap for extra WMEs due to parse error"))
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true,true));
feedbackList.setListData(vecErrors);
SwingUtilities.invokeLater(finish);
return false;
}
} catch(NumberFormatException nfe)
{
System.out.println("Never happen");
}
}
}
errors.clear();
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // while parsing operator nodes
feedbackList.setListData(vecErrors);
return true;
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return false; // should never get here unless try failed
} // end of checkNodes()
/**
* Search through the datamap and look for extra WMEs
* by looking at the status of the named edge (as determined
* by the check nodes function) and the edge's location within
* the datamap.
* Extra WMEs are classified in this action by being created by some production
* within the project, but never tested by any production;
* not including any item within the output-link.
* Send results to the feedback list
*/
public void searchDataMap()
{
OperatorNode operatorNode;
vecErrors.clear(); // clear out errors just in case
vecErrors.add("Attributes that were created but never tested in the productions of this agent:");
// Go through all of the nodes examining the nodes' datamap if they have one
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
operatorNode = (OperatorNode)bfe.nextElement();
operatorNode.searchCreateNoTestDataMap(operatorWindow.getDatamap(), vecErrors);
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // end of while looking at all nodes
// do case of no errors
if(vecErrors.size() == 1)
{
vecErrors.clear();
vecErrors.add("No errors. All attributes that were created, were also tested.");
}
// Add list of errors to feedback list
feedbackList.setListData(vecErrors);
} // end of searchDataMap()
} // end of UpdateThread class
} // end of SearchDataMapCreateNoTestAction
///////////////////////////
/**
* This action searches all Datamaps to find WMEs that
* are never tested by some production within the project and are never created.
* i.e. not in the action or condition side of any production and not in the io link.
* Operation status is displayed in a progress bar.
* Results are displayed in the feedback list
* Double-clicking on an item in the feedback list
* should display the rogue node in the datamap.
*/
class SearchDataMapNoTestNoCreateAction extends AbstractAction
{
JProgressBar progressBar;
JDialog progressDialog;
int numNodes;
public SearchDataMapNoTestNoCreateAction()
{
super("Searching DataMap");
setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
numNodes = 0;
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
numNodes++;
bfe.nextElement();
}
System.out.println("Nodes: " + (numNodes * 2));
progressBar = new JProgressBar(0, numNodes * 2);
progressDialog = new JDialog(MainFrame.this, "Checking Productions");
progressDialog.getContentPane().setLayout(new FlowLayout());
progressDialog.getContentPane().add(progressBar);
progressBar.setStringPainted(true);
progressDialog.setLocationRelativeTo(MainFrame.this);
progressDialog.pack();
progressDialog.show();
(new UpdateThread()).start();
} // end of constructor
class UpdateThread extends Thread
{
Runnable update, finish;
int value, min, max;
java.util.List errors = new LinkedList();
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
OperatorNode current;
Vector parsedProds, vecErrors = new Vector();
int nodeNum = 0;
public UpdateThread()
{
progressBar.getMaximum();
progressBar.getMinimum();
update = new Runnable()
{
public void run()
{
value = progressBar.getValue() + 1;
updateProgressBar(value);
//System.out.println("Value is " + value);
}
};
finish = new Runnable()
{
public void run()
{
updateProgressBar(min);
System.out.println("Done");
progressDialog.dispose();
}
};
}
public void run()
{
initializeNodes();
if(checkNodes())
searchDataMap();
SwingUtilities.invokeLater(finish);
}
private void updateProgressBar(int value)
{
progressBar.setValue(value);
}
/**
* This initializes the status of all the edges to zero, which means that
* the edges have not been used by a production in any way.
*/
public void initializeNodes()
{
Enumeration edges = operatorWindow.getDatamap().getEdges();
while(edges.hasMoreElements())
{
NamedEdge currentEdge = (NamedEdge)edges.nextElement();
currentEdge.resetTestedStatus();
currentEdge.resetErrorNoted();
// initialize the input-link as already tested
if(currentEdge.getName().equals("input-link"))
currentEdge.setInputLinkCreated(operatorWindow.getDatamap());
// initialize the output-link as already tested
if(currentEdge.getName().equals("output-link"))
currentEdge.setOutputLinkTested(operatorWindow.getDatamap());
}
} // end of initializeNodes()
/**
* Simply go through all the nodes, checking productions
* and marking the named edges in the datamap when either tested
* or created by a production.
* @return false if encountered a parse error
*/
public boolean checkNodes()
{
try
{
boolean anyErrors = false;
checkingNodes: while(bfe.hasMoreElements())
{
current = (OperatorNode)bfe.nextElement();
// If the node has a rule editor open, get the rules from the
// window, otherwise, open the associated file
try
{
parsedProds = current.parseProductions();
}
catch(ParseException pe)
{
anyErrors = true;
String errString;
String parseError = pe.toString();
int i = parseError.lastIndexOf("line ");
String lineNum = parseError.substring(i + 5);
i = lineNum.indexOf(',');
lineNum = "(" + lineNum.substring(0, i) + "): ";
errString = current.getFileName() + lineNum + "Unable to Search DataMap for extra WMEs due to parse error";
errors.add(errString);
}
catch(TokenMgrError tme)
{
tme.printStackTrace();
}
if (parsedProds!= null)
{
operatorWindow.checkProductions((OperatorNode)current.getParent(), parsedProds, errors);
}
if (!errors.isEmpty())
{
anyErrors = true;
Enumeration e = new EnumerationIteratorWrapper(errors.iterator());
while(e.hasMoreElements())
{
try
{
String errorString = e.nextElement().toString();
String numberString = errorString.substring(errorString.indexOf("(")+1,errorString.indexOf(")"));
if(errorString.endsWith("Unable to Search DataMap for extra WMEs due to parse error"))
{
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true,true));
feedbackList.setListData(vecErrors);
SwingUtilities.invokeLater(finish);
return false;
}
} catch(NumberFormatException nfe)
{
System.out.println("Never happen");
}
}
}
errors.clear();
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // while parsing operator nodes
feedbackList.setListData(vecErrors);
return true;
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return false; // should never get here unless try failed
} // end of checkNodes()
/**
* Search through the datamap and look for extra WMEs
* by looking at the status of the named edge (as determined
* by the check nodes function) and the edge's location within
* the datamap.
* Extra WMEs are classified in this action by being tested by some production
* within the project, but never created by any production;
* not including any item within the input-link.
* Send results to the feedback list
*/
public void searchDataMap()
{
OperatorNode operatorNode;
vecErrors.clear(); // clear out errors just in case
vecErrors.add("Attributes that were never tested and never created in the productions of this agent:");
// Go through all of the nodes examining the nodes' datamap if they have one
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
operatorNode = (OperatorNode)bfe.nextElement();
operatorNode.searchNoTestNoCreateDataMap(operatorWindow.getDatamap(), vecErrors);
updateProgressBar(++nodeNum);
SwingUtilities.invokeLater(update);
} // end of while looking at all nodes
// do case of no errors
if(vecErrors.size() == 1)
{
vecErrors.clear();
vecErrors.add("No errors. All attributes were either tested or created.");
}
// Add list of errors to feedback list
feedbackList.setListData(vecErrors);
} // end of searchDataMap()
} // end of UpdateThread class
} // end of SearchDataMapNoTestNoCreateAction
/**
* This class is responsible for comparing all productions in the project
* with the project's datamaps and 'fixing' any discrepencies
* by adding missing productions to the datamap.
* Operation status is displayed in a progress bar.
* Add productions in the datamap are displayed as green until the user validates them.
* Results are displayed in the feedback list
*/
class GenerateDataMapAction extends AbstractAction
{
JProgressBar progressBar;
JDialog progressDialog;
public GenerateDataMapAction()
{
super("Generate Datamap from Operator Hierarchy");
setEnabled(false);
}
public void actionPerformed(ActionEvent ae)
{
int numNodes = 0;
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
while(bfe.hasMoreElements())
{
numNodes++;
bfe.nextElement();
}
System.out.println("Nodes: " + numNodes);
progressBar = new JProgressBar(0, numNodes * 7);
progressDialog = new JDialog(MainFrame.this, "Generating Datamap from Productions");
progressDialog.getContentPane().setLayout(new FlowLayout());
progressDialog.getContentPane().add(progressBar);
progressBar.setStringPainted(true);
progressDialog.setLocationRelativeTo(MainFrame.this);
progressDialog.pack();
progressDialog.show();
(new UpdateThread()).start();
}
class UpdateThread extends Thread
{
Runnable update, finish;
int value, min, max;
java.util.List errors = new LinkedList();
java.util.List generations = new LinkedList();
int repCount = 0;
Enumeration bfe = operatorWindow.breadthFirstEnumeration();
OperatorNode current;
Vector parsedProds, vecErrors = new Vector();
int nodeNum = 0;
public UpdateThread()
{
progressBar.getMaximum();
progressBar.getMinimum();
update = new Runnable()
{
public void run()
{
value = progressBar.getValue() + 1;
updateProgressBar(value);
//System.out.println("Value is " + value);
}
};
finish = new Runnable()
{
public void run()
{
updateProgressBar(min);
System.out.println("Done");
progressDialog.dispose();
}
};
}
public void run()
{
checkNodes();
repCount = 0;
JOptionPane.showMessageDialog(null, "DataMap Generation Completed", "DataMap Generator", JOptionPane.INFORMATION_MESSAGE);
}
private void updateProgressBar(int value)
{
progressBar.setValue(value);
}
public void checkNodes()
{
try
{
do
{
repCount++;
errors.clear();
bfe = operatorWindow.breadthFirstEnumeration();
checkingNodes: while(bfe.hasMoreElements())
{
current = (OperatorNode)bfe.nextElement();
generations.clear();
// If the node has a rule editor open, get the rules from the
// window, otherwise, open the associated file
// is this how to get the rule editor?
try
{
parsedProds = current.parseProductions();
}
catch(ParseException pe)
{
String errString;
String parseError = pe.toString();
int i = parseError.lastIndexOf("line ");
String lineNum = parseError.substring(i + 5);
i = lineNum.indexOf(',');
lineNum = "(" + lineNum.substring(0, i) + "): ";
errString = current.getFileName() + lineNum + "Unable to generate datamap due to parse error";
errors.add(errString);
}
catch(TokenMgrError tme)
{
tme.printStackTrace();
}
if (parsedProds!= null)
{
operatorWindow.generateProductions((OperatorNode)current.getParent(), parsedProds, generations, current);
operatorWindow.checkProductions((OperatorNode)current.getParent(), parsedProds, errors);
}
Enumeration e = new EnumerationIteratorWrapper(generations.iterator());
while(e.hasMoreElements())
{
try
{
String errorString = e.nextElement().toString();
String numberString = errorString.substring(errorString.indexOf("(")+1,errorString.indexOf(")"));
vecErrors.add(
new FeedbackListObject(current,Integer.parseInt(numberString),errorString,true,true, true));
}
catch(NumberFormatException nfe)
{
System.out.println("Never happen");
}
}
feedbackList.setListData(vecErrors);
value = progressBar.getValue() + 1;
updateProgressBar(value);
//if(errors.isEmpty())
// updateProgressBar(progressBar.getMaximum());
SwingUtilities.invokeLater(update);
} // while parsing operator nodes
} while(!(errors.isEmpty()) && repCount < 5);
SwingUtilities.invokeLater(finish);
} // end of try
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
} // End of class GenerateDataMapAction
class FindInProjectAction extends AbstractAction
{
public FindInProjectAction()
{
super("Find In Project");
setEnabled(false);
}
/**
* Prompts the user for a string to find in the project
* finds all instances of the string in the project
* and displays a FindInProjectList in the DesktopPane with all instances
* or tells the user that no instances were found
* @see FindDialog
*/
public void actionPerformed(ActionEvent e)
{
FindDialog theDialog = new FindDialog(MainFrame.this, operatorWindow);
theDialog.setVisible(true);
}
}
class ReplaceInProjectAction extends AbstractAction
{
public ReplaceInProjectAction()
{
super("Replace In Project");
setEnabled(false);
}
/**
* Prompts the user for a string to find in the project
* and a string to replace the found string with.
* Goes through all found instances and opens rules editors
* for all files with matching strings.
* @see ReplaceInProjectDialog
*/
public void actionPerformed(ActionEvent e)
{
ReplaceInProjectDialog replaceDialog = new ReplaceInProjectDialog(MainFrame.this, operatorWindow);
replaceDialog.setVisible(true);
}
}
class CommitAction extends PerformableAction
{
public CommitAction()
{
super("Commit");
setEnabled(false);
}
public void perform()
{
saveAllFilesAction.perform();
if(operatorWindow != null)
{
exportAgentAction.perform();
saveDataMapAndProjectAction.perform();
}
}
public void actionPerformed(ActionEvent e)
{
perform();
Vector v = new Vector();
v.add("Save Finished");
setFeedbackListData(v);
}
}
class SaveProjectAsAction extends AbstractAction
{
public SaveProjectAsAction()
{
super("Save Project As");
setEnabled(false);
}
public void actionPerformed(ActionEvent e)
{
SaveProjectAsDialog spad = new SaveProjectAsDialog(MainFrame.getMainFrame());
spad.show();
OperatorRootNode orn = (OperatorRootNode)(operatorWindow.getModel().getRoot());
File oldProjectFile = new File(orn.getProjectFile());
if (spad.wasApproved())
{
String newName = spad.getNewAgentName();
String newPath = spad.getNewAgentPath();
if(OperatorWindow.isProjectNameValid(newName))
{
operatorWindow.saveProjectAs(newName, newPath);
// Regenerate the *_source.soar files in the old project
try
{
OperatorWindow oldOpWin = new OperatorWindow(oldProjectFile);
OperatorRootNode oldOrn = (OperatorRootNode)oldOpWin.getModel().getRoot();
oldOrn.startSourcing();
}
catch (IOException exception)
{
JOptionPane.showMessageDialog(MainFrame.this, "IO Error exporting agent.", "Agent Export Error", JOptionPane.ERROR_MESSAGE);
return;
}
JInternalFrame[] jif = DesktopPane.getAllFrames();
for(int i = 0; i < jif.length; ++i)
{
if(jif[i] instanceof RuleEditor)
{
RuleEditor oldRuleEditor = (RuleEditor)jif[i];
OperatorNode newNode = oldRuleEditor.getNode();
oldRuleEditor.fileRenamed( newNode.getFileName() ); // Update the Rule editor with the correct updated file name
}
}
saveAllFilesAction.perform(); // Save all open Rule Editors to the new project directory
exportAgentAction.perform();
saveDataMapAndProjectAction.perform(); // Save DataMap and Project file (.vsa)
}
else
{
JOptionPane.showMessageDialog(MainFrame.this, "That is not a valid name for the project", "Invalid Name", JOptionPane.ERROR_MESSAGE);
}
}
}
}
class TileWindowsAction extends AbstractAction
{
public TileWindowsAction()
{
super("Tile Windows");
}
public void actionPerformed(ActionEvent e)
{
DesktopPane.performTileAction();
}
}
class ReTileWindowsAction extends AbstractAction
{
public ReTileWindowsAction()
{
super("Re-tile Windows");
}
public void actionPerformed(ActionEvent e)
{
DesktopPane.performReTileAction();
}
}
class CascadeAction extends AbstractAction
{
public CascadeAction()
{
super("Cascade Windows");
}
public void actionPerformed(ActionEvent e)
{
DesktopPane.performCascadeAction();
}
}
}
| false | false | null | null |
diff --git a/framework/src/org/apache/tapestry/ApplicationRuntimeException.java b/framework/src/org/apache/tapestry/ApplicationRuntimeException.java
index b1d2d9f72..7c3fc1b64 100644
--- a/framework/src/org/apache/tapestry/ApplicationRuntimeException.java
+++ b/framework/src/org/apache/tapestry/ApplicationRuntimeException.java
@@ -1,124 +1,124 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation", "Tapestry"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* or "Tapestry", nor may "Apache" or "Tapestry" appear in their
* name, without prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE TAPESTRY CONTRIBUTOR COMMUNITY
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.tapestry;
/**
* General wrapper for any exception (normal or runtime) that may occur during
* runtime processing for the application. This is exception is used
* when the intent is to communicate a low-level failure to the user or
- * developer; it is not expected to be caught. The {@link #getRootCause() rootCause}
+ * developer; it is not expected to be caught. The {@link #getCause() rootCause}
* property is a <em>nested</em> exception (Tapestry supported this concept
* long before the JDK did).
*
* @author Howard Lewis Ship
* @version $Id$
**/
public class ApplicationRuntimeException extends RuntimeException implements ILocatable
{
private Throwable _rootCause;
private transient ILocation _location;
private transient Object _component;
public ApplicationRuntimeException(Throwable rootCause)
{
this(rootCause.getMessage(), rootCause);
}
public ApplicationRuntimeException(String message)
{
this(message, null, null, null);
}
public ApplicationRuntimeException(String message, Throwable rootCause)
{
this(message, null, null, rootCause);
}
public ApplicationRuntimeException(
String message,
Object component,
ILocation location,
Throwable rootCause)
{
super(message);
_rootCause = rootCause;
_component = component;
_location = Tapestry.findLocation(new Object[] { location, rootCause, component });
}
public ApplicationRuntimeException(String message, ILocation location, Throwable rootCause)
{
this(message, null, location, rootCause);
}
public Throwable getCause()
{
return _rootCause;
}
public ILocation getLocation()
{
return _location;
}
public Object getComponent()
{
return _component;
}
}
\ No newline at end of file
diff --git a/framework/src/org/apache/tapestry/parse/LocalizationToken.java b/framework/src/org/apache/tapestry/parse/LocalizationToken.java
index 0f63bb316..283f4dafd 100644
--- a/framework/src/org/apache/tapestry/parse/LocalizationToken.java
+++ b/framework/src/org/apache/tapestry/parse/LocalizationToken.java
@@ -1,128 +1,128 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation", "Tapestry"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* or "Tapestry", nor may "Apache" or "Tapestry" appear in their
* name, without prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE TAPESTRY CONTRIBUTOR COMMUNITY
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.tapestry.parse;
import java.util.Map;
import org.apache.tapestry.ILocation;
/**
* Represents localized text from the template.
*
* @see TokenType#LOCALIZATION
*
* @author Howard Lewis Ship
* @version $Id$
* @since 3.0
*
**/
public class LocalizationToken extends TemplateToken
{
private String _tag;
private String _key;
private boolean _raw;
private Map _attributes;
/**
* Creates a new token.
*
*
* @param tag the tag of the element from the template
* @param key the localization key specified
* @param raw if true, then the localized value contains markup that should not be escaped
- * @param attribute any additional attributes (beyond those used to define key and raw)
+ * @param attributes any additional attributes (beyond those used to define key and raw)
* that were specified. This value is retained, not copied.
* @param location location of the tag which defines this token
*
**/
public LocalizationToken(String tag, String key, boolean raw, Map attributes, ILocation location)
{
super(TokenType.LOCALIZATION, location);
_tag = tag;
_key = key;
_raw = raw;
_attributes = attributes;
}
/**
* Returns any attributes for the token, which may be null. Do not modify
* the return value.
*
**/
public Map getAttributes()
{
return _attributes;
}
public boolean isRaw()
{
return _raw;
}
public String getTag()
{
return _tag;
}
public String getKey()
{
return _key;
}
}
diff --git a/framework/src/org/apache/tapestry/util/JanitorThread.java b/framework/src/org/apache/tapestry/util/JanitorThread.java
index f7372bd63..5ca09abc4 100644
--- a/framework/src/org/apache/tapestry/util/JanitorThread.java
+++ b/framework/src/org/apache/tapestry/util/JanitorThread.java
@@ -1,271 +1,271 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation", "Tapestry"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* or "Tapestry", nor may "Apache" or "Tapestry" appear in their
* name, without prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE TAPESTRY CONTRIBUTOR COMMUNITY
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.tapestry.util;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.tapestry.Tapestry;
/**
* A basic kind of janitor, an object that periodically invokes
* {@link ICleanable#executeCleanup()} on a set of objects.
*
* <p>The JanitorThread holds a <em>weak reference</em> to
* the objects it operates on.
*
* @author Howard Lewis Ship
* @version $Id$
* @since 1.0.5
*
**/
public class JanitorThread extends Thread
{
/**
* Default number of seconds between janitor runs, about 30 seconds.
*
**/
public static final long DEFAULT_INTERVAL_MILLIS = 30 * 1024;
private long interval = DEFAULT_INTERVAL_MILLIS;
private boolean lockInterval = false;
private static JanitorThread shared = null;
/**
- * A {@link List} of {@link WeakReference}s to {@link IJanitor} instances.
+ * A {@link List} of {@link WeakReference}s to {@link ICleanable} instances.
*
**/
private List references = new ArrayList();
/**
* Creates a new daemon Janitor.
*
**/
public JanitorThread()
{
this(null);
}
/**
* Creates new Janitor with the given name. The thread
* will have minimum priority and be a daemon.
*
**/
public JanitorThread(String name)
{
super(name);
setDaemon(true);
setPriority(MIN_PRIORITY);
}
/**
* Returns a shared instance of JanitorThread. In most cases,
* the shared instance should be used, rather than creating
* a new instance; the exception being when particular
* scheduling is of concern. It is also bad policy to
* change the sleep interval on the shared janitor
* (though nothing prevents this, either).
*
**/
public synchronized static JanitorThread getSharedJanitorThread()
{
if (shared == null)
{
shared = new JanitorThread("Shared-JanitorThread");
shared.lockInterval = true;
shared.start();
}
return shared;
}
public long getInterval()
{
return interval;
}
/**
* Updates the property, then interrupts the thread.
*
- * @param the interval, in milliseconds, between sweeps.
+ * @param value the interval, in milliseconds, between sweeps.
*
* @throws IllegalStateException always, if the receiver is the shared JanitorThread
* @throws IllegalArgumentException if value is less than 1
**/
public void setInterval(long value)
{
if (lockInterval)
throw new IllegalStateException(Tapestry.getMessage("JanitorThread.interval-locked"));
if (value < 1)
throw new IllegalArgumentException(Tapestry.getMessage("JanitorThread.illegal-interval"));
interval = value;
interrupt();
}
/**
* Adds a new cleanable object to the list of references. Care should be taken that
* objects are not added multiple times; they will be
* cleaned too often.
*
**/
public void add(ICleanable cleanable)
{
WeakReference reference = new WeakReference(cleanable);
synchronized (references)
{
references.add(reference);
}
}
/**
* Runs through the list of targets and invokes
* {@link ICleanable#executeCleanup()}
* on each of them. {@link WeakReference}s that have been invalidated
* are weeded out.
*
**/
protected void sweep()
{
synchronized (references)
{
Iterator i = references.iterator();
while (i.hasNext())
{
WeakReference ref = (WeakReference) i.next();
ICleanable cleanable = (ICleanable) ref.get();
if (cleanable == null)
i.remove();
else
cleanable.executeCleanup();
}
}
}
/**
* Waits for the next run, by sleeping for the desired period.
*
*
**/
protected void waitForNextPass()
{
try
{
sleep(interval);
}
catch (InterruptedException ex)
{
// Ignore.
}
}
/**
* Alternates between {@link #waitForNextPass()} and
* {@link #sweep()}.
*
**/
public void run()
{
while (true)
{
waitForNextPass();
sweep();
}
}
public String toString()
{
StringBuffer buffer = new StringBuffer("JanitorThread@");
buffer.append(Integer.toHexString(hashCode()));
buffer.append("[interval=");
buffer.append(interval);
buffer.append(" count=");
synchronized (references)
{
buffer.append(references.size());
}
buffer.append(']');
return buffer.toString();
}
}
\ No newline at end of file
diff --git a/framework/src/org/apache/tapestry/valid/UrlValidator.java b/framework/src/org/apache/tapestry/valid/UrlValidator.java
index c97711fdb..ebab52135 100644
--- a/framework/src/org/apache/tapestry/valid/UrlValidator.java
+++ b/framework/src/org/apache/tapestry/valid/UrlValidator.java
@@ -1,311 +1,317 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation", "Tapestry"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* or "Tapestry", nor may "Apache" or "Tapestry" appear in their
* name, without prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE TAPESTRY CONTRIBUTOR COMMUNITY
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.tapestry.valid;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Vector;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.form.IFormComponent;
import org.apache.tapestry.util.StringSplitter;
+/**
+ *
+ * @version $Id$
+ * @since 3.0
+ *
+ **/
public class UrlValidator extends BaseValidator {
private int _minimumLength;
private String _minimumLengthMessage;
private String _invalidUrlFormatMessage;
private String _disallowedProtocolMessage;
private Collection _allowedProtocols;
private String _scriptPath = "/org/apache/tapestry/valid/UrlValidator.script"; //$NON-NLS-1$
public UrlValidator() {
}
private UrlValidator(boolean required) {
super(required);
}
public String toString(IFormComponent field, Object value) {
if (value == null)
return null;
return value.toString();
}
public Object toObject(IFormComponent field, String input)
throws ValidatorException {
if (checkRequired(field, input))
return null;
if (_minimumLength > 0 && input.length() < _minimumLength)
throw new ValidatorException(
buildMinimumLengthMessage(field),
ValidationConstraint.MINIMUM_WIDTH);
if (!isValidUrl(input))
throw new ValidatorException(
buildInvalidUrlFormatMessage(field),
ValidationConstraint.URL_FORMAT);
if (!isAllowedProtocol(input)) {
throw new ValidatorException(
buildDisallowedProtocolMessage(field),
ValidationConstraint.DISALLOWED_PROTOCOL);
}
return input;
}
public int getMinimumLength() {
return _minimumLength;
}
public void setMinimumLength(int minimumLength) {
_minimumLength = minimumLength;
}
public void renderValidatorContribution(
IFormComponent field,
IMarkupWriter writer,
IRequestCycle cycle) {
if (!isClientScriptingEnabled())
return;
Map symbols = new HashMap();
if (isRequired())
symbols.put("requiredMessage", buildRequiredMessage(field)); //$NON-NLS-1$
if (_minimumLength > 0)
symbols.put("minimumLengthMessage", //$NON-NLS-1$
buildMinimumLengthMessage(field));
symbols.put("urlFormatMessage", buildInvalidUrlFormatMessage(field)); //$NON-NLS-1$
symbols.put("urlDisallowedProtocolMessage", //$NON-NLS-1$
buildDisallowedProtocolMessage(field));
symbols.put("urlRegexpProtocols", buildUrlRegexpProtocols()); //$NON-NLS-1$
processValidatorScript(_scriptPath, cycle, field, symbols);
}
private String buildUrlRegexpProtocols() {
if(_allowedProtocols == null) {
return null;
}
String regexp = "/("; //$NON-NLS-1$
Iterator iter = _allowedProtocols.iterator();
while (iter.hasNext()) {
String protocol = (String) iter.next();
regexp += protocol;
if (iter.hasNext()) {
regexp += "|"; //$NON-NLS-1$
}
}
regexp += "):///"; //$NON-NLS-1$
return regexp;
}
public String getScriptPath() {
return _scriptPath;
}
public void setScriptPath(String scriptPath) {
_scriptPath = scriptPath;
}
protected boolean isValidUrl(String url) {
boolean bIsValid;
try {
new URL(url);
bIsValid = true;
} catch (MalformedURLException mue) {
bIsValid = false;
}
return bIsValid;
}
protected boolean isAllowedProtocol(String url) {
boolean bIsAllowed = false;
if (_allowedProtocols != null) {
URL oUrl;
try {
oUrl = new URL(url);
} catch (MalformedURLException e) {
return false;
}
String actualProtocol = oUrl.getProtocol();
Iterator iter = _allowedProtocols.iterator();
while (iter.hasNext()) {
String protocol = (String) iter.next();
if (protocol.equals(actualProtocol)) {
bIsAllowed = true;
break;
}
}
} else {
bIsAllowed = true;
}
return bIsAllowed;
}
public String getInvalidUrlFormatMessage() {
return _invalidUrlFormatMessage;
}
public String getMinimumLengthMessage() {
return _minimumLengthMessage;
}
public void setInvalidUrlFormatMessage(String string) {
_invalidUrlFormatMessage = string;
}
public String getDisallowedProtocolMessage() {
return _disallowedProtocolMessage;
}
public void setDisallowedProtocolMessage(String string) {
_disallowedProtocolMessage = string;
}
public void setMinimumLengthMessage(String string) {
_minimumLengthMessage = string;
}
protected String buildMinimumLengthMessage(IFormComponent field) {
String pattern = getPattern(_minimumLengthMessage, "field-too-short", //$NON-NLS-1$
field.getPage().getLocale());
return formatString(
pattern,
Integer.toString(_minimumLength),
field.getDisplayName());
}
protected String buildInvalidUrlFormatMessage(IFormComponent field) {
String pattern = getPattern(_invalidUrlFormatMessage, "invalid-url-format", //$NON-NLS-1$
field.getPage().getLocale());
return formatString(pattern, field.getDisplayName());
}
protected String buildDisallowedProtocolMessage(IFormComponent field) {
if(_allowedProtocols == null) {
return null;
}
String pattern = getPattern(_disallowedProtocolMessage, "disallowed-protocol", //$NON-NLS-1$
field.getPage().getLocale());
String allowedProtocols = ""; //$NON-NLS-1$
Iterator iter = _allowedProtocols.iterator();
while (iter.hasNext()) {
String protocol = (String) iter.next();
if (!allowedProtocols.equals("")) { //$NON-NLS-1$
if(iter.hasNext()) {
allowedProtocols += ", "; //$NON-NLS-1$
} else {
allowedProtocols += " or "; //$NON-NLS-1$
}
}
allowedProtocols += protocol;
}
return formatString(pattern, allowedProtocols);
}
protected String getPattern(String override, String key, Locale locale) {
if (override != null)
return override;
ResourceBundle strings;
String string;
try {
strings = ResourceBundle.getBundle("net.sf.cendil.tapestry.valid.ValidationStrings", //$NON-NLS-1$
locale);
string = strings.getString(key);
} catch (Exception exc) {
strings = ResourceBundle.getBundle("org.apache.tapestry.valid.ValidationStrings", //$NON-NLS-1$
locale);
string = strings.getString(key);
}
return string;
}
/**
- * @param collection
+ * @param protocols comma separated list of allowed protocols
*/
public void setAllowedProtocols(String protocols) {
StringSplitter spliter = new StringSplitter(',');
//String[] aProtocols = protocols.split(","); //$NON-NLS-1$
String[] aProtocols = spliter.splitToArray(protocols); //$NON-NLS-1$
_allowedProtocols = new Vector();
for (int i = 0; i < aProtocols.length; i++) {
_allowedProtocols.add(aProtocols[i]);
}
}
}
\ No newline at end of file
diff --git a/framework/src/org/apache/tapestry/valid/ValidatorException.java b/framework/src/org/apache/tapestry/valid/ValidatorException.java
index 5d7f9031c..1b4ff0f97 100644
--- a/framework/src/org/apache/tapestry/valid/ValidatorException.java
+++ b/framework/src/org/apache/tapestry/valid/ValidatorException.java
@@ -1,116 +1,116 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation", "Tapestry"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* or "Tapestry", nor may "Apache" or "Tapestry" appear in their
* name, without prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE TAPESTRY CONTRIBUTOR COMMUNITY
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.tapestry.valid;
import org.apache.tapestry.IRender;
/**
* Thrown by a {@link IValidator} when submitted input is not valid.
*
* @author Howard Lewis Ship
* @version $Id$
* @since 1.0.8
*
**/
public class ValidatorException extends Exception
{
private IRender _errorRenderer;
private ValidationConstraint _constraint;
public ValidatorException(String errorMessage)
{
this(errorMessage, null, null);
}
public ValidatorException(String errorMessage, ValidationConstraint constraint)
{
this(errorMessage, null, constraint);
}
/**
* Creates a new instance.
* @param errorMessage the default error message to be used (this may be
* overriden by the {@link IValidationDelegate})
- * @param renderer to use to render the error message (may be null)
+ * @param errorRenderer to use to render the error message (may be null)
* @param constraint a validation constraint that has been compromised, or
* null if no constraint is applicable
*
**/
public ValidatorException(
String errorMessage,
IRender errorRenderer,
ValidationConstraint constraint)
{
super(errorMessage);
_errorRenderer = errorRenderer;
_constraint = constraint;
}
public ValidationConstraint getConstraint()
{
return _constraint;
}
/** @since 3.0 **/
public IRender getErrorRenderer()
{
return _errorRenderer;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/Honeychest/src/syam/Honeychest/Actions.java b/Honeychest/src/syam/Honeychest/Actions.java
index 95c7185..a792a50 100644
--- a/Honeychest/src/syam/Honeychest/Actions.java
+++ b/Honeychest/src/syam/Honeychest/Actions.java
@@ -1,225 +1,226 @@
package syam.Honeychest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
+import syam.Honeychest.config.MessageManager;
import syam.Honeychest.util.TextFileHandler;
/**
* プラグインに必要なユーティリティが含まれています
* @author syam
*/
public class Actions {
public final static Logger log = Honeychest.log;
private static final String logPrefix = Honeychest.logPrefix;
private static final String msgPrefix = Honeychest.msgPrefix;
public static Honeychest plugin;
public Actions(Honeychest instance){
plugin = instance;
}
/*
* TODO:
* ・ハニーチェスト破壊時の扱いをどうするか設定可能にする (現在は破壊禁止)
* ・MCBansとの連携 グローバルBAN
* ・評価システム ex 4回の窃盗 または 4アイテムの窃盗でBAN
* ・設定ファイルからBANメッセージ、窃盗時の処理を変更する
* ・チェストオーナーを設定し、オーナーがアイテムを出した場合は窃盗とカウントしない
* ・予め指定した特定のアイテムのみ窃盗とカウントする
* ・/honeychest list で設置済みハニーチェストの座標等の情報を表示する
* ・特定のアイテムを通常クリック時にそのチェストがハニーチェストか表示する
* ・リファクタリング
*/
/****************************************/
// メッセージ送信系関数
/****************************************/
/**
* メッセージをユニキャスト
* @param sender Sender (null可)
* @param player Player (null可)l
* @param message メッセージ
*/
public static void message(CommandSender sender, Player player, String message){
if (message != null){
message = message
.replaceAll("&([0-9a-fk-or])", "\u00A7$1")
.replaceAll("%version", Honeychest.getInstance().getDescription().getVersion());
if (player != null){
player.sendMessage(message);
}
else if (sender != null){
sender.sendMessage(message);
}
}
}
/**
* メッセージをブロードキャスト
* @param message メッセージ
*/
public static void broadcastMessage(String message){
if (message != null){
message = message
.replaceAll("&([0-9a-fk-or])", "\u00A7$1")
.replaceAll("%version", Honeychest.getInstance().getDescription().getVersion());
Bukkit.broadcastMessage(message);
}
}
/**
* メッセージをワールドキャスト
* @param world
* @param message
*/
public static void worldcastMessage(World world, String message){
if (world != null && message != null){
message = message
.replaceAll("&([0-9a-fk-or])", "\u00A7$1")
.replaceAll("%version", Honeychest.getInstance().getDescription().getVersion());
for(Player player: world.getPlayers()){
log.info("[Worldcast]["+world.getName()+"]: " + message);
player.sendMessage(message);
}
}
}
/**
* メッセージをパーミッションキャスト(指定した権限ユーザにのみ送信)
* @param permission 受信するための権限ノード
* @param message メッセージ
*/
public static void permcastMessage(String permission, String message){
// 動かなかった どうして?
//int i = Bukkit.getServer().broadcast(message, permission);
// OK
int i = 0;
for (Player player : Bukkit.getServer().getOnlinePlayers()){
if (player.hasPermission(permission)){
Actions.message(null, player, message);
i++;
}
}
log.info("Received "+i+"players: "+message);
}
/****************************************/
// ヘルプメッセージ
/****************************************/
public static void sendHelp(CommandSender sender){
message(sender, null, "&c===================================");
message(sender, null, "&bHoneychest version &3%version &bby syamn");
- message(sender, null, " &b<>&f = 必要, &b[]&f = オプション");
- message(sender, null, " /honeychest(/hc)&7 - Honeychest設置/破壊");
- message(sender, null, " /honeychest save(/hc s)&7 - Honeychestデータ保存");
- message(sender, null, " /honeychest reload(/hc r)&7 - Honeychestデータ再読み込み");
- message(sender, null, " /honeychest help(/hc h)&7 - このコマンドヘルプを表示");
+ message(sender, null, MessageManager.getString("Help.helpMessage1"));
+ message(sender, null, MessageManager.getString("Help.helpMessage2"));
+ message(sender, null, MessageManager.getString("Help.helpMessage3"));
+ message(sender, null, MessageManager.getString("Help.helpMessage4"));
+ message(sender, null, MessageManager.getString("Help.helpMessage5"));
message(sender, null, "&c===================================");
}
/****************************************/
// ユーティリティ
/****************************************/
/**
* 文字配列をまとめる
* @param s つなげるString配列
* @param glue 区切り文字 通常は半角スペース
* @return
*/
public static String combine(String[] s, String glue)
{
int k = s.length;
if (k == 0){ return null; }
StringBuilder out = new StringBuilder();
out.append(s[0]);
for (int x = 1; x < k; x++){
out.append(glue).append(s[x]);
}
return out.toString();
}
/**
* コマンドをコンソールから実行する
* @param command
*/
public static void executeCommandOnConsole(String command){
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
}
/**
* 文字列の中に全角文字が含まれているか判定
* @param s 判定する文字列
* @return 1文字でも全角文字が含まれていればtrue 含まれていなければfalse
* @throws UnsupportedEncodingException
*/
public static boolean containsZen(String s)
throws UnsupportedEncodingException {
for (int i = 0; i < s.length(); i++) {
String s1 = s.substring(i, i + 1);
if (URLEncoder.encode(s1,"MS932").length() >= 4) {
return true;
}
}
return false;
}
/**
* 現在の日時を yyyy-MM-dd HH:mm:ss 形式の文字列で返す
* @return
*/
public static String getDatetime(){
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(date);
}
/**
* 座標データを ワールド名:x, y, z の形式の文字列にして返す
* @param loc
* @return
*/
public static String getLocationString(Location loc){
return loc.getWorld().getName()+":"+loc.getX()+","+loc.getY()+","+loc.getZ();
}
public static String getBlockLocationString(Location loc){
return loc.getWorld().getName()+":"+loc.getBlockX()+","+loc.getBlockY()+","+loc.getBlockZ();
}
/**
* デバッグ用 syamnがオンラインならメッセージを送る
* @param msg
*/
public static void debug(String msg){
OfflinePlayer syamn = Bukkit.getServer().getOfflinePlayer("syamn");
if (syamn.isOnline()){
Actions.message(null, (Player) syamn, msg);
}
}
/****************************************/
/* ログ操作系 */
/****************************************/
/**
* ログファイルに書き込み
* @param file ログファイル名
* @param line ログ内容
*/
public static void log(String filepath, String line){
TextFileHandler r = new TextFileHandler(filepath);
try{
r.appendLine("[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "] " + line);
} catch (IOException ex) {}
}
/****************************************/
// Honeychest
/****************************************/
}
diff --git a/Honeychest/src/syam/Honeychest/HoneychestCommand.java b/Honeychest/src/syam/Honeychest/HoneychestCommand.java
index a7aec52..333eb23 100644
--- a/Honeychest/src/syam/Honeychest/HoneychestCommand.java
+++ b/Honeychest/src/syam/Honeychest/HoneychestCommand.java
@@ -1,94 +1,94 @@
package syam.Honeychest;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import syam.Honeychest.config.MessageManager;
public class HoneychestCommand implements CommandExecutor {
public final static Logger log = Honeychest.log;
private static final String logPrefix = Honeychest.logPrefix;
private static final String msgPrefix = Honeychest.msgPrefix;
private Honeychest plugin;
public HoneychestCommand(Honeychest instance){
this.plugin = instance;
}
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args){
// 引数無しはハニーチェスト管理モード
if (args.length == 0){
// コンソールチェック
if (!(sender instanceof Player)){
Actions.message(sender, null, MessageManager.getString("Commands.notFromConsole"));
return true;
}
Player player = (Player) sender;
// 権限チェック
if (!player.hasPermission("honeychest.admin")){
Actions.message(null, player, MessageManager.getString("Commands.permissionDenied"));
return true;
}
if (HoneyData.isCreator(player)){
// 管理モード終了
HoneyData.setCreator(player, false);
Actions.message(null, player, MessageManager.getString("Commands.manageFinish"));
}else{
// 管理モード開始
HoneyData.setCreator(player, true);
String tool = Material.getMaterial(plugin.getHCConfig().getToolId()).name();
Actions.message(null, player, MessageManager.getString("Commands.manageStart", tool));
}
return true;
}
// /honeychest save - ハニーチェストデータ保存
if (args.length >= 1 && (args[0].equalsIgnoreCase("save") || args[0].equalsIgnoreCase("s"))){
// 権限チェック
if (!sender.hasPermission("honeychest.admin")){
Actions.message(sender, null, MessageManager.getString("Commands.permissionDenied"));
return true;
}
if(!HoneyData.saveData()){
Actions.message(sender, null, MessageManager.getString("Commands.dataSaveError"));
}else{
Actions.message(sender, null, MessageManager.getString("Commands.dataSaved"));
}
return true;
}
// /honeychest reload - ハニーチェストデータを読み込み
- if (args.length >= 1 && (args[0].equalsIgnoreCase("reload") || args[0].equalsIgnoreCase("r"))){
+ if (args.length >= 1 && (args[0].equalsIgnoreCase("load") || args[0].equalsIgnoreCase("l"))){
// 権限チェック
if (!sender.hasPermission("honeychest.admin")){
Actions.message(sender, null, MessageManager.getString("Commands.permissionDenied"));
return true;
}
if(!HoneyData.saveData()){
Actions.message(sender, null, MessageManager.getString("Commands.dataLoadError"));
}else{
Actions.message(sender, null, MessageManager.getString("Commands.dataLoaded"));
}
return true;
}
// /honeychest help - ヘルプを表示
if (args.length >= 1 && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("h"))){
Actions.sendHelp(sender);
return true;
}
return false;
}
}
| false | false | null | null |
diff --git a/src/me/ThaH3lper/com/SkillsCollection/SkillSwarm.java b/src/me/ThaH3lper/com/SkillsCollection/SkillSwarm.java
index 2b78242..754b07a 100644
--- a/src/me/ThaH3lper/com/SkillsCollection/SkillSwarm.java
+++ b/src/me/ThaH3lper/com/SkillsCollection/SkillSwarm.java
@@ -1,67 +1,67 @@
package me.ThaH3lper.com.SkillsCollection;
import me.ThaH3lper.com.EpicBoss;
import me.ThaH3lper.com.API.BossSkillEvent;
import me.ThaH3lper.com.Mobs.AllMobs;
import me.ThaH3lper.com.Mobs.EpicMobs;
import me.ThaH3lper.com.Mobs.MobCommon;
import me.ThaH3lper.com.Mobs.MobHandler;
import me.ThaH3lper.com.Skills.SkillHandler;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
public class SkillSwarm {
//- swarm type:amount:radious =HP chance
// $boss
public static void ExecuteSwarm(LivingEntity l, String skill, Player player)
{
String[] base = skill.split(" ");
String[] data = base[1].split(":");
float chance = Float.parseFloat(base[base.length-1]);
if(EpicBoss.r.nextFloat() < chance)
{
if(SkillHandler.CheckHealth(base[base.length-2], l, skill))
{
BossSkillEvent event = new BossSkillEvent(l, skill, player, false);
Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isChanceled())
return;
int amount = Integer.parseInt(data[1]);
int radious = Integer.parseInt(data[2]);
if(data[0].contains("$"))
{
String s = data[0].replace("$", "");
EpicMobs em = MobCommon.getEpicMob(s);
if(em != null)
{
- for(int i = 0; i <= amount; i++)
+ for(int i = 1; i <= amount; i++)
{
double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2));
double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2));
Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z);
MobHandler.SpawnMob(s, loc);
}
}
}
else
{
for(int i = 0; i <= amount; i++)
{
double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2));
double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2));
Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z);
AllMobs.spawnMob(data[0], loc);
}
}
}
}
}
}
| true | true | public static void ExecuteSwarm(LivingEntity l, String skill, Player player)
{
String[] base = skill.split(" ");
String[] data = base[1].split(":");
float chance = Float.parseFloat(base[base.length-1]);
if(EpicBoss.r.nextFloat() < chance)
{
if(SkillHandler.CheckHealth(base[base.length-2], l, skill))
{
BossSkillEvent event = new BossSkillEvent(l, skill, player, false);
Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isChanceled())
return;
int amount = Integer.parseInt(data[1]);
int radious = Integer.parseInt(data[2]);
if(data[0].contains("$"))
{
String s = data[0].replace("$", "");
EpicMobs em = MobCommon.getEpicMob(s);
if(em != null)
{
for(int i = 0; i <= amount; i++)
{
double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2));
double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2));
Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z);
MobHandler.SpawnMob(s, loc);
}
}
}
else
{
for(int i = 0; i <= amount; i++)
{
double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2));
double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2));
Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z);
AllMobs.spawnMob(data[0], loc);
}
}
}
}
}
| public static void ExecuteSwarm(LivingEntity l, String skill, Player player)
{
String[] base = skill.split(" ");
String[] data = base[1].split(":");
float chance = Float.parseFloat(base[base.length-1]);
if(EpicBoss.r.nextFloat() < chance)
{
if(SkillHandler.CheckHealth(base[base.length-2], l, skill))
{
BossSkillEvent event = new BossSkillEvent(l, skill, player, false);
Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isChanceled())
return;
int amount = Integer.parseInt(data[1]);
int radious = Integer.parseInt(data[2]);
if(data[0].contains("$"))
{
String s = data[0].replace("$", "");
EpicMobs em = MobCommon.getEpicMob(s);
if(em != null)
{
for(int i = 1; i <= amount; i++)
{
double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2));
double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2));
Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z);
MobHandler.SpawnMob(s, loc);
}
}
}
else
{
for(int i = 0; i <= amount; i++)
{
double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2));
double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2));
Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z);
AllMobs.spawnMob(data[0], loc);
}
}
}
}
}
|
diff --git a/src/sai_cas/servlet/CrossMatchServlet.java b/src/sai_cas/servlet/CrossMatchServlet.java
index fe2401e..e6c20a3 100644
--- a/src/sai_cas/servlet/CrossMatchServlet.java
+++ b/src/sai_cas/servlet/CrossMatchServlet.java
@@ -1,211 +1,211 @@
package sai_cas.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.File;
import java.util.List;
import java.util.Calendar;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.*;
import sai_cas.db.*;
import sai_cas.output.VOTableQueryResultsOutputter;
import sai_cas.vo.*;
import sai_cas.Votable;
import sai_cas.VotableException;
public class CrossMatchServlet extends HttpServlet {
static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("sai_cas.CrossMatchServlet");
public class CrossMatchServletException extends Exception
{
CrossMatchServletException()
{
super();
}
CrossMatchServletException(String s)
{
super(s);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
String cat = null, tab = null, radString = null;
List<FileItem> fileItemList = null;
FileItemFactory factory = new DiskFileItemFactory();
try
{
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setSizeMax(50000000);
/* Request size <= 50Mb */
fileItemList = sfu.parseRequest(request);
}
catch (FileUploadException e)
{
throw new ServletException(e.getMessage());
/* Nothing ...*/
}
FileItem fi = null;
for (FileItem fi0: fileItemList)
{
if (fi0.getFieldName().equals("file"))//(!fi0.isFormField())
{
fi = fi0;
}
if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField())
{
tab = fi0.getString();
}
if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField())
{
cat = fi0.getString();
}
if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField())
{
radString = fi0.getString();
}
}
File uploadedFile = null;
Connection conn = null;
DBInterface dbi = null;
VOTableQueryResultsOutputter voqro = new VOTableQueryResultsOutputter();
try
{
double rad = 0;
rad = Double.parseDouble(radString);
if (fi == null)
{
throw new ServletException("File should be specified" + fileItemList.size() );
}
long size = fi.getSize();
if (size > 10000000)
{
throw new CrossMatchServletException("File is too big");
}
if (size == 0)
{
throw new CrossMatchServletException("File must not be empty");
}
uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/"));
try
{
fi.write(uploadedFile);
}
catch (Exception e)
{
throw new CrossMatchServletException("Error in writing your data in the temporary file");
}
logger.debug("File written");
String tempUser = "cas_user_tmp";
String tempPasswd = "aspen";
conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd);
dbi = new DBInterface(conn,tempUser);
Votable vot = new Votable (uploadedFile);
String userDataSchema = dbi.getUserDataSchemaName();
String tableName = vot.insertDataToDB(dbi,userDataSchema);
dbi.analyze(userDataSchema, tableName);
String[] raDecArray = dbi.getRaDecColumns(cat, tab);
String[] raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema,
tableName);
if (raDecArray1 == null)
{
voqro.printError(out, "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch");
}
else
{
response.setHeader("Content-Disposition",
"attachment; filename=" + cat + "_" +
fi.getName() + "_" + String.valueOf(rad) + ".dat");
dbi.executeQuery("select * from " + userDataSchema + "." + tableName +
" AS a LEFT JOIN " + cat + "." + tab + " AS b "+
"ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+
raDecArray[0]+",b."+raDecArray[1]+","+rad+")");
voqro.setResource(cat + "_" + fi.getName() );
- voqro.setResourceDescription("This is the table obtained by"+
- "crossmatching the table "+cat+"."+tab + "with the " +
- "user supplied table from the file" + fi.getName()+"\n"+
+ voqro.setResourceDescription("This is the table obtained by "+
+ "crossmatching the table "+cat+"."+tab + " with the " +
+ "user supplied table from the file " + fi.getName()+"\n"+
"Radius of the crossmatch: "+rad+"deg");
voqro.setTable("main" );
voqro.print(out,dbi);
}
}
catch (VotableException e)
{
voqro.printError(out, "Error occured: " + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)");
}
catch (NumberFormatException e)
{
voqro.printError(out, "Error occured: " + e.getMessage());
}
catch (CrossMatchServletException e)
{
voqro.printError(out, "Error occured: " + e.getMessage());
}
catch (DBException e)
{
logger.error("DBException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
catch (SQLException e)
{
logger.error("SQLException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
finally
{
DBInterface.close(dbi,conn,false);
/* Always rollback */
try
{
uploadedFile.delete();
}
catch (Exception e)
{
}
}
}
}
| true | true | public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
String cat = null, tab = null, radString = null;
List<FileItem> fileItemList = null;
FileItemFactory factory = new DiskFileItemFactory();
try
{
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setSizeMax(50000000);
/* Request size <= 50Mb */
fileItemList = sfu.parseRequest(request);
}
catch (FileUploadException e)
{
throw new ServletException(e.getMessage());
/* Nothing ...*/
}
FileItem fi = null;
for (FileItem fi0: fileItemList)
{
if (fi0.getFieldName().equals("file"))//(!fi0.isFormField())
{
fi = fi0;
}
if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField())
{
tab = fi0.getString();
}
if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField())
{
cat = fi0.getString();
}
if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField())
{
radString = fi0.getString();
}
}
File uploadedFile = null;
Connection conn = null;
DBInterface dbi = null;
VOTableQueryResultsOutputter voqro = new VOTableQueryResultsOutputter();
try
{
double rad = 0;
rad = Double.parseDouble(radString);
if (fi == null)
{
throw new ServletException("File should be specified" + fileItemList.size() );
}
long size = fi.getSize();
if (size > 10000000)
{
throw new CrossMatchServletException("File is too big");
}
if (size == 0)
{
throw new CrossMatchServletException("File must not be empty");
}
uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/"));
try
{
fi.write(uploadedFile);
}
catch (Exception e)
{
throw new CrossMatchServletException("Error in writing your data in the temporary file");
}
logger.debug("File written");
String tempUser = "cas_user_tmp";
String tempPasswd = "aspen";
conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd);
dbi = new DBInterface(conn,tempUser);
Votable vot = new Votable (uploadedFile);
String userDataSchema = dbi.getUserDataSchemaName();
String tableName = vot.insertDataToDB(dbi,userDataSchema);
dbi.analyze(userDataSchema, tableName);
String[] raDecArray = dbi.getRaDecColumns(cat, tab);
String[] raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema,
tableName);
if (raDecArray1 == null)
{
voqro.printError(out, "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch");
}
else
{
response.setHeader("Content-Disposition",
"attachment; filename=" + cat + "_" +
fi.getName() + "_" + String.valueOf(rad) + ".dat");
dbi.executeQuery("select * from " + userDataSchema + "." + tableName +
" AS a LEFT JOIN " + cat + "." + tab + " AS b "+
"ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+
raDecArray[0]+",b."+raDecArray[1]+","+rad+")");
voqro.setResource(cat + "_" + fi.getName() );
voqro.setResourceDescription("This is the table obtained by"+
"crossmatching the table "+cat+"."+tab + "with the " +
"user supplied table from the file" + fi.getName()+"\n"+
"Radius of the crossmatch: "+rad+"deg");
voqro.setTable("main" );
voqro.print(out,dbi);
}
}
catch (VotableException e)
{
voqro.printError(out, "Error occured: " + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)");
}
catch (NumberFormatException e)
{
voqro.printError(out, "Error occured: " + e.getMessage());
}
catch (CrossMatchServletException e)
{
voqro.printError(out, "Error occured: " + e.getMessage());
}
catch (DBException e)
{
logger.error("DBException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
catch (SQLException e)
{
logger.error("SQLException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
finally
{
DBInterface.close(dbi,conn,false);
/* Always rollback */
try
{
uploadedFile.delete();
}
catch (Exception e)
{
}
}
}
| public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
String cat = null, tab = null, radString = null;
List<FileItem> fileItemList = null;
FileItemFactory factory = new DiskFileItemFactory();
try
{
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setSizeMax(50000000);
/* Request size <= 50Mb */
fileItemList = sfu.parseRequest(request);
}
catch (FileUploadException e)
{
throw new ServletException(e.getMessage());
/* Nothing ...*/
}
FileItem fi = null;
for (FileItem fi0: fileItemList)
{
if (fi0.getFieldName().equals("file"))//(!fi0.isFormField())
{
fi = fi0;
}
if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField())
{
tab = fi0.getString();
}
if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField())
{
cat = fi0.getString();
}
if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField())
{
radString = fi0.getString();
}
}
File uploadedFile = null;
Connection conn = null;
DBInterface dbi = null;
VOTableQueryResultsOutputter voqro = new VOTableQueryResultsOutputter();
try
{
double rad = 0;
rad = Double.parseDouble(radString);
if (fi == null)
{
throw new ServletException("File should be specified" + fileItemList.size() );
}
long size = fi.getSize();
if (size > 10000000)
{
throw new CrossMatchServletException("File is too big");
}
if (size == 0)
{
throw new CrossMatchServletException("File must not be empty");
}
uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/"));
try
{
fi.write(uploadedFile);
}
catch (Exception e)
{
throw new CrossMatchServletException("Error in writing your data in the temporary file");
}
logger.debug("File written");
String tempUser = "cas_user_tmp";
String tempPasswd = "aspen";
conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd);
dbi = new DBInterface(conn,tempUser);
Votable vot = new Votable (uploadedFile);
String userDataSchema = dbi.getUserDataSchemaName();
String tableName = vot.insertDataToDB(dbi,userDataSchema);
dbi.analyze(userDataSchema, tableName);
String[] raDecArray = dbi.getRaDecColumns(cat, tab);
String[] raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema,
tableName);
if (raDecArray1 == null)
{
voqro.printError(out, "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch");
}
else
{
response.setHeader("Content-Disposition",
"attachment; filename=" + cat + "_" +
fi.getName() + "_" + String.valueOf(rad) + ".dat");
dbi.executeQuery("select * from " + userDataSchema + "." + tableName +
" AS a LEFT JOIN " + cat + "." + tab + " AS b "+
"ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+
raDecArray[0]+",b."+raDecArray[1]+","+rad+")");
voqro.setResource(cat + "_" + fi.getName() );
voqro.setResourceDescription("This is the table obtained by "+
"crossmatching the table "+cat+"."+tab + " with the " +
"user supplied table from the file " + fi.getName()+"\n"+
"Radius of the crossmatch: "+rad+"deg");
voqro.setTable("main" );
voqro.print(out,dbi);
}
}
catch (VotableException e)
{
voqro.printError(out, "Error occured: " + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)");
}
catch (NumberFormatException e)
{
voqro.printError(out, "Error occured: " + e.getMessage());
}
catch (CrossMatchServletException e)
{
voqro.printError(out, "Error occured: " + e.getMessage());
}
catch (DBException e)
{
logger.error("DBException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
catch (SQLException e)
{
logger.error("SQLException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
finally
{
DBInterface.close(dbi,conn,false);
/* Always rollback */
try
{
uploadedFile.delete();
}
catch (Exception e)
{
}
}
}
|
diff --git a/src/impl/java/org/wyona/yanel/impl/navigation/SitetreeDOMImpl.java b/src/impl/java/org/wyona/yanel/impl/navigation/SitetreeDOMImpl.java
index 3dff02aa3..2d74b37f5 100644
--- a/src/impl/java/org/wyona/yanel/impl/navigation/SitetreeDOMImpl.java
+++ b/src/impl/java/org/wyona/yanel/impl/navigation/SitetreeDOMImpl.java
@@ -1,192 +1,197 @@
/*
* Copyright 2008 Wyona
*
* 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.wyona.org/licenses/APACHE-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.wyona.yanel.impl.navigation;
import org.wyona.yanel.core.map.Realm;
import org.wyona.yanel.core.navigation.Node;
import org.wyona.yanel.core.navigation.Sitetree;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
- * Based on DOM, whereas persistance is done through the src configuration, for example within realm.xml
- * <repo-navigation class="org.wyona.yanel.impl.navigation.SitetreeDOMImpl">
- * <src>data-repo/data/sitetree.xml</src>
- * </repo-navigation>
+ * Based on DOM, whereas persistance is done through the <code>src</code> configuration, for example within <code>realm.xml</code>
+ * <pre>
+ * <repo-navigation class="org.wyona.yanel.impl.navigation.SitetreeDOMImpl">
+ * <src>data-repo/data/sitetree.xml</src>
+ * </repo-navigation>
+ * </pre>
*
- * or .yanel-rc
+ * or <code>.yanel-rc</code>
*
- * <yanel:custom-config>
- * <s:repo-navigation xmlns:s="http://www.wyona.org/yanel/sitetree-dom-impl/1.0" class="org.wyona.yanel.impl.navigation.SitetreeDOMImpl">
- * <s:src>yanelrepo:/sitetree.xml</s:src>
- * </s:repo-navigation>
- * </yanel:custom-config>
+ * <pre>
+ * <yanel:custom-config>
+ * <s:repo-navigation xmlns:s="http://www.wyona.org/yanel/sitetree-dom-impl/1.0" class="org.wyona.yanel.impl.navigation.SitetreeDOMImpl">
+ * <s:src>yanelrepo:/sitetree.xml</s:src>
+ * </s:repo-navigation>
+ * </yanel:custom-config>
+ * </pre>
*
- * Please note that the class org.wyona.yanel.core.map.Realm is using the RealmConfigPathResolver whereas that a resource might use a different resolver implementation!
+ * Please note that the class <code>org.wyona.yanel.core.map.Realm</code>
+ * is using the <code>RealmConfigPathResolver</code> whereas that a resource might use a different resolver implementation!
*/
public class SitetreeDOMImpl implements Sitetree {
private static Logger log = Logger.getLogger(SitetreeDOMImpl.class);
private static String SITETREE_NAMESPACE = "http://www.wyona.org/yanel/sitetree/1.0";
// IMPORTANT: Consider memory and redundancy issues!
private Document sitetreeDoc;
private String src;
private String systemId;
/**
* @see
*/
public void init(Document configDoc, javax.xml.transform.URIResolver resolver) {
NodeList nl = configDoc.getDocumentElement().getElementsByTagName("src");
if (nl.getLength() == 1) {
src = nl.item(0).getFirstChild().getNodeValue();
if(log.isDebugEnabled()) {
log.debug("src: " + src + ", " + nl.item(0).getNodeName());
}
try {
javax.xml.transform.Source source = resolver.resolve(src, null);
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
systemId = source.getSystemId();
//sitetreeDoc = parser.parse(new java.io.FileInputStream(source.getSystemId()));
sitetreeDoc = parser.parse(((javax.xml.transform.stream.StreamSource) source).getInputStream());
} catch (Exception e) {
log.error(e, e);
}
} else {
log.error("Number of elements with tag name \"src\" is not equal one!");
}
}
/**
*
*/
public Node getSitetreeNode() {
return new NodeDOMImpl(sitetreeDoc.getDocumentElement(), this);
}
/**
*
*/
public Node getNode(Realm realm, String path) {
//log.debug("Path: " + path);
try {
if (path.equals("/")) {
if (sitetreeDoc != null) {
return new NodeDOMImpl(sitetreeDoc.getDocumentElement(), this);
}
log.error("It seems like the sitetree '" + src + "' was not initialized properly!");
return null;
} else if (path.startsWith("/") && path.length() > 1) {
Element element = getElement(sitetreeDoc.getDocumentElement(), path);
if (element != null) {
return new NodeDOMImpl(element, this);
}
log.error("No node for path: " + path);
return null;
} else {
log.error("Path is not valid: " + path);
return null;
}
} catch(Exception e) {
log.error(e);
return null;
}
}
/**
* @see
*/
public Node createNode(String name, String label) {
Element newElement = sitetreeDoc.createElementNS(SITETREE_NAMESPACE, "node");
newElement.setAttributeNS(SITETREE_NAMESPACE, "name", name);
Element labelElement = sitetreeDoc.createElementNS(SITETREE_NAMESPACE, "label");
labelElement.appendChild(sitetreeDoc.createTextNode(label));
newElement.appendChild(labelElement);
return new NodeDOMImpl(newElement, this);
}
/**
* @param parent Parent element
* @param path Subtree path
*/
private org.w3c.dom.Element getElement(org.w3c.dom.Element parent, String path) throws Exception {
String[] names = path.split("/");
//log.debug("Path: " + path);
//log.debug("Length: " + names.length);
String childName = null;
String subtreePath = null;
if (names.length > 1) {
childName = names[1];
//log.debug("Child: " + childName);
if (names.length > 2) {
subtreePath = "/" + names[2];
for (int i = 3; i < names.length; i++) {
subtreePath = subtreePath + "/" + names[i];
}
log.debug("Subtree path: " + subtreePath);
} else {
//log.debug("No subtree.");
}
} else {
//log.debug("The end: " + path);
}
if (childName != null) {
//log.debug("Child: " + childName);
NodeList nl = parent.getChildNodes();
Element child = null;
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE && nl.item(i).getNodeName().equals("node") && ((Element) nl.item(i)).getAttribute("name").equals(childName)) {
child = (Element) nl.item(i);
break;
}
}
if (child != null) {
if (subtreePath != null) {
log.debug("Subtree path: " + subtreePath);
return getElement(child, subtreePath);
}
return child;
}
log.error("No such node: " + path);
return null;
}
return sitetreeDoc.getDocumentElement();
}
/**
- * Save sitetree to file system (based on resolved source system id
+ * Save sitetree to file system (based on resolved source system id)
*/
public void save() {
try {
org.wyona.commons.xml.XMLHelper.writeDocument(sitetreeDoc, new java.io.FileOutputStream(systemId));
log.warn("Sitetree has been written into file system: " + systemId);
//log.warn("Sitetree has been written into persistent repository: " + systemId);
} catch(Exception e) {
log.error(e, e);
}
}
}
| false | false | null | null |
diff --git a/src/com/dmdirc/ui/swing/dialogs/paste/PasteDialog.java b/src/com/dmdirc/ui/swing/dialogs/paste/PasteDialog.java
index fb274c83b..fae1c1c9d 100644
--- a/src/com/dmdirc/ui/swing/dialogs/paste/PasteDialog.java
+++ b/src/com/dmdirc/ui/swing/dialogs/paste/PasteDialog.java
@@ -1,245 +1,247 @@
/*
* Copyright (c) 2006-2008 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.ui.swing.dialogs.paste;
import com.dmdirc.Main;
import com.dmdirc.ui.swing.MainFrame;
import com.dmdirc.ui.swing.UIUtilities;
import com.dmdirc.ui.swing.components.InputTextFrame;
import com.dmdirc.ui.swing.components.StandardDialog;
import com.dmdirc.ui.swing.components.SwingInputHandler;
import com.dmdirc.ui.swing.components.TextAreaInputField;
import com.dmdirc.ui.swing.components.TextLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
+import net.miginfocom.layout.ComponentWrapper;
+import net.miginfocom.layout.LayoutCallback;
import net.miginfocom.swing.MigLayout;
/**
* Allows the user to modify global client preferences.
*/
public final class PasteDialog extends StandardDialog implements ActionListener,
KeyListener {
/**
* 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 = 4;
/** Number of lines Label. */
private TextLabel infoLabel;
/** Text area scrollpane. */
private JScrollPane scrollPane;
/** Text area. */
private TextAreaInputField textField;
/** Parent frame. */
private final InputTextFrame parent;
/** Edit button. */
private JButton editButton;
/**
* Creates a new instance of PreferencesDialog.
*
* @param newParent The frame that owns this dialog
* @param text text to show in the paste dialog
*/
public PasteDialog(final InputTextFrame newParent, final String text) {
super((MainFrame) Main.getUI().getMainWindow(), false);
this.parent = newParent;
initComponents(text);
initListeners();
setFocusTraversalPolicy(new PasteDialogFocusTraversalPolicy(
getCancelButton(), editButton, getOkButton()));
setFocusable(true);
getOkButton().requestFocus();
getOkButton().setSelected(true);
setLocationRelativeTo((MainFrame) Main.getUI().getMainWindow());
}
/**
* Initialises GUI components.
*
* @param text text to show in the dialog
*/
private void initComponents(final String text) {
scrollPane = new JScrollPane();
textField = new TextAreaInputField(text);
editButton = new JButton("Edit");
infoLabel = new TextLabel();
UIUtilities.addUndoManager(textField);
orderButtons(new JButton(), new JButton());
getOkButton().setText("Send");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Multi-line paste");
setResizable(false);
infoLabel.setText("This will be sent as " + parent.getContainer().getNumLines(textField.getText()) + " lines. Are you sure you want to continue?");
textField.setColumns(50);
textField.setRows(10);
new SwingInputHandler(textField, parent.getCommandParser(), parent).setTypes(false, false, true, false);
scrollPane.setViewportView(textField);
scrollPane.setVisible(false);
getContentPane().setLayout(new MigLayout("fill, hidemode 3, pack"));
+ ((MigLayout) getContentPane().getLayout()).addLayoutCallback(new LayoutCallback() {
+
+ @Override
+ public void correctBounds(ComponentWrapper comp) {
+ super.correctBounds(comp);
+ setLocationRelativeTo((MainFrame) Main.getUI().getMainWindow());
+ }
+ });
getContentPane().add(infoLabel, "wrap, growx, pushx, span 3");
getContentPane().add(scrollPane, "wrap, grow, push, span 3");
getContentPane().add(getLeftButton(), "right, sg button");
getContentPane().add(editButton, "right, sg button");
getContentPane().add(getRightButton(), "right, sg button");
}
/**
* Initialises listeners for this dialog.
*/
private void initListeners() {
getOkButton().addActionListener(this);
getCancelButton().addActionListener(this);
editButton.addActionListener(this);
textField.addKeyListener(this);
getRootPane().getActionMap().put("rightArrowAction",
new AbstractAction("rightArrowAction") {
private static final long serialVersionUID = 1;
/** {@inheritDoc} */
@Override
public void actionPerformed(final ActionEvent evt) {
final JButton button = (JButton) getFocusTraversalPolicy().
getComponentAfter(PasteDialog.this, getFocusOwner());
button.requestFocus();
button.setSelected(true);
}
});
getRootPane().getActionMap().put("leftArrowAction",
new AbstractAction("leftArrowAction") {
private static final long serialVersionUID = 1;
/** {@inheritDoc} */
@Override
public void actionPerformed(final ActionEvent evt) {
final JButton button = (JButton) getFocusTraversalPolicy().
getComponentBefore(PasteDialog.this, getFocusOwner());
button.requestFocus();
button.setSelected(true);
}
});
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "rightArrowAction");
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "leftArrowAction");
textField.getActionMap().put("ctrlEnterAction",
new AbstractAction("ctrlEnterAction") {
private static final long serialVersionUID = 1;
/** {@inheritDoc} */
@Override
public void actionPerformed(final ActionEvent evt) {
getOkButton().doClick();
}
});
textField.getInputMap(JComponent.WHEN_FOCUSED).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK), "ctrlEnterAction");
}
/**
* Handles the actions for the dialog.
*
* @param actionEvent Action event
*/
@Override
public void actionPerformed(final ActionEvent actionEvent) {
if (getOkButton().equals(actionEvent.getSource())) {
if (!textField.getText().isEmpty()) {
final String[] lines = textField.getText().split("\n");
for (String line : lines) {
parent.getContainer().sendLine(line);
parent.getInputHandler().addToBuffer(line);
}
}
dispose();
} else if (editButton.equals(actionEvent.getSource())) {
editButton.setEnabled(false);
setResizable(true);
scrollPane.setVisible(true);
infoLabel.setText("This will be sent as " + parent.getContainer().getNumLines(textField.getText()) + " lines.");
pack();
} else if (getCancelButton().equals(actionEvent.getSource())) {
dispose();
}
}
-
- /** {@inheritDoc} */
- @Override
- public void validate() {
- super.validate();
-
- setLocationRelativeTo((MainFrame) Main.getUI().getMainWindow());
- }
/** {@inheritDoc} */
@Override
public void keyTyped(final KeyEvent e) {
infoLabel.setText("This will be sent as " + parent.getContainer().getNumLines(textField.getText()) + " lines.");
}
/** {@inheritDoc} */
@Override
public void keyPressed(final KeyEvent e) {
//Ignore.
}
/** {@inheritDoc} */
@Override
public void keyReleased(final KeyEvent e) {
//Ignore.
}
}
| false | false | null | null |
diff --git a/extensions/gdx-tools/src/com/badlogic/gdx/tools/imagepacker/TexturePacker.java b/extensions/gdx-tools/src/com/badlogic/gdx/tools/imagepacker/TexturePacker.java
index e38ce21dd..3eb2fafb6 100644
--- a/extensions/gdx-tools/src/com/badlogic/gdx/tools/imagepacker/TexturePacker.java
+++ b/extensions/gdx-tools/src/com/badlogic/gdx/tools/imagepacker/TexturePacker.java
@@ -1,987 +1,998 @@
/*******************************************************************************
* 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.tools.imagepacker;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import javax.imageio.ImageIO;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class TexturePacker {
static Pattern indexPattern = Pattern.compile(".+_(\\d+)(_.*|$)");
static public boolean quiet;
ArrayList<Image> images = new ArrayList();
HashMap<String, Image> imageCrcs = new HashMap();
FileWriter writer;
int uncompressedSize, compressedSize;
int xPadding, yPadding;
final Filter filter;
int minWidth, minHeight;
int maxWidth, maxHeight;
final Settings settings;
+ /** Used by squeeze method when ignoreBlankImages is false to add empty region for blank input images during the pack. */
+ BufferedImage emptyImage = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
+
public TexturePacker (Settings settings) {
this.settings = settings;
this.filter = new Filter(Direction.none, null, -1, -1, null, null);
}
public TexturePacker (Settings settings, File inputDir, Filter filter, File outputDir, File packFile) throws IOException {
this.settings = settings;
this.filter = filter;
// Collect and squeeze images.
File[] files = inputDir.listFiles(filter);
if (files == null) return;
for (File file : files) {
if (file.isDirectory()) continue;
String imageName = file.getAbsolutePath().substring(inputDir.getAbsolutePath().length()) + "\n";
if (imageName.startsWith("/") || imageName.startsWith("\\")) imageName = imageName.substring(1);
int dotIndex = imageName.lastIndexOf('.');
if (dotIndex != -1) imageName = imageName.substring(0, dotIndex);
addImage(ImageIO.read(file), imageName);
}
if (images.isEmpty()) return;
log(inputDir.toString());
if (filter.format != null)
log("Format: " + filter.format);
else
log("Format: " + settings.defaultFormat + " (default)");
if (filter.minFilter != null && filter.magFilter != null)
log("Filter: " + filter.minFilter + ", " + filter.magFilter);
else
log("Filter: " + settings.defaultFilterMin + ", " + settings.defaultFilterMag + " (default)");
if (filter.direction != Direction.none) log("Repeat: " + filter.direction);
process(outputDir, packFile, inputDir.getName());
}
static void log (String message) {
if (!quiet) System.out.println(message);
}
public void addImage (BufferedImage image, String name) {
Image squeezed = squeeze(image, name, false);
if (squeezed != null) {
if (settings.alias) {
String crc = hash(squeezed);
Image existing = imageCrcs.get(crc);
if (existing != null) {
existing.aliases.add(squeezed);
return;
}
imageCrcs.put(crc, squeezed);
}
images.add(squeezed);
}
}
public void process (File outputDir, File packFile, String prefix) throws IOException {
if (images.isEmpty()) return;
minWidth = filter.width != -1 ? filter.width : settings.minWidth;
minHeight = filter.height != -1 ? filter.height : settings.minHeight;
maxWidth = filter.width != -1 ? filter.width : settings.maxWidth;
maxHeight = filter.height != -1 ? filter.height : settings.maxHeight;
if (settings.edgePadding) {
xPadding = !filter.direction.isX() ? settings.padding : 0;
yPadding = !filter.direction.isY() ? settings.padding : 0;
} else {
xPadding = images.size() > 1 && !filter.direction.isX() ? settings.padding : 0;
yPadding = images.size() > 1 && !filter.direction.isY() ? settings.padding : 0;
}
outputDir.mkdirs();
writer = new FileWriter(packFile, true);
try {
while (!images.isEmpty())
if (!writePage(prefix, outputDir)) break;
if (writer != null) {
log("Pixels eliminated: " + (1 - compressedSize / (float)uncompressedSize) * 100 + "%");
log("");
}
} finally {
writer.close();
}
}
private boolean writePage (String prefix, File outputDir) throws IOException {
// Try reasonably hard to pack images into the smallest POT size.
Comparator bestComparator = null;
Comparator secondBestComparator = imageComparators.get(0);
int bestWidth = 99999, bestHeight = 99999;
int secondBestWidth = 99999, secondBestHeight = 99999;
int bestUsedPixels = 0;
int width = minWidth, height = minHeight;
int grownPixels = 0, grownPixels2 = 0;
int i = 0, ii = 0;
while (true) {
for (Comparator comparator : imageComparators) {
// Pack as many images as possible, sorting the images different ways.
Collections.sort(images, comparator);
int usedPixels = insert(null, new ArrayList(images), width, height);
// Store the best pack, in case not all images fit on the max texture size.
if (usedPixels > bestUsedPixels) {
secondBestComparator = comparator;
secondBestWidth = width;
secondBestHeight = height;
}
// If all images fit and this sort is the best so far, take note.
if (usedPixels == -1) {
if (width * height < bestWidth * bestHeight) {
bestComparator = comparator;
bestWidth = width;
bestHeight = height;
}
}
}
if (width == maxWidth && height == maxHeight) break;
if (bestComparator != null) break;
if (settings.pot) {
// 64,64 -> 128,64 -> 256,64 etc 64,128 -> 64,256 etc -> 128,128 -> 256,128 etc.
if (i % 3 == 0) {
grownPixels += MathUtils.nextPowerOfTwo(width + 1) - width;
width = MathUtils.nextPowerOfTwo(width + 1);
if (width > maxWidth) {
i++;
width -= grownPixels;
grownPixels = 0;
}
} else if (i % 3 == 1) {
grownPixels += MathUtils.nextPowerOfTwo(height + 1) - height;
height = MathUtils.nextPowerOfTwo(height + 1);
if (height > maxHeight) {
i++;
height -= grownPixels;
grownPixels = 0;
}
} else {
ii++;
if (ii % 2 == 1)
width = MathUtils.nextPowerOfTwo(width + 1);
else
height = MathUtils.nextPowerOfTwo(height + 1);
i++;
}
} else {
// 64-127,64 -> 64,64-127 -> 128-255,128 -> 128,128-255 etc.
int incr = 2;
if (i % 3 == 0) {
if (width + incr >= MathUtils.nextPowerOfTwo(width)) {
width -= grownPixels;
grownPixels = 0;
i++;
} else {
width += incr;
grownPixels += incr;
}
} else if (i % 3 == 1) {
if (height + incr >= MathUtils.nextPowerOfTwo(height)) {
height -= grownPixels;
grownPixels = 0;
i++;
} else {
height += incr;
grownPixels += incr;
}
} else {
if (width == MathUtils.nextPowerOfTwo(width) && height == MathUtils.nextPowerOfTwo(height)) ii++;
if (ii % 2 == 1)
width += incr;
else
height += incr;
i++;
}
}
width = Math.min(maxWidth, width);
height = Math.min(maxHeight, height);
}
if (bestComparator != null) {
Collections.sort(images, bestComparator);
} else {
Collections.sort(images, secondBestComparator);
bestWidth = secondBestWidth;
bestHeight = secondBestHeight;
}
width = bestWidth;
height = bestHeight;
if (settings.pot) {
width = MathUtils.nextPowerOfTwo(width);
height = MathUtils.nextPowerOfTwo(height);
}
if (width > maxWidth || height > maxHeight) {
System.out.println("ERROR: Images do not fit on max size: " + maxWidth + "x" + maxHeight);
return false;
}
int type;
switch (filter.format != null ? filter.format : settings.defaultFormat) {
case RGBA8888:
case RGBA4444:
type = BufferedImage.TYPE_INT_ARGB;
break;
case RGB565:
case RGB888:
type = BufferedImage.TYPE_INT_RGB;
break;
case Alpha:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
default:
throw new RuntimeException("Luminance Alpha format is not supported.");
}
int imageNumber = 1;
File outputFile = new File(outputDir, prefix + imageNumber + ".png");
while (outputFile.exists())
outputFile = new File(outputDir, prefix + ++imageNumber + ".png");
writer.write("\n" + outputFile.getName() + "\n");
Format format;
if (filter.format != null) {
writer.write("format: " + filter.format + "\n");
format = filter.format;
} else {
writer.write("format: " + settings.defaultFormat + "\n");
format = settings.defaultFormat;
}
if (filter.minFilter == null || filter.magFilter == null)
writer.write("filter: " + settings.defaultFilterMin + "," + settings.defaultFilterMag + "\n");
else
writer.write("filter: " + filter.minFilter + "," + filter.magFilter + "\n");
writer.write("repeat: " + filter.direction + "\n");
BufferedImage canvas = new BufferedImage(width, height, type);
insert(canvas, images, bestWidth, bestHeight);
log("Writing " + canvas.getWidth() + "x" + canvas.getHeight() + ": " + outputFile);
ImageIO.write(canvas, "png", outputFile);
if (!settings.pot) ImageIO.write(squeeze(ImageIO.read(outputFile), "", true), "png", outputFile);
compressedSize += canvas.getWidth() * canvas.getHeight();
return true;
}
private int insert (BufferedImage canvas, ArrayList<Image> images, int width, int height) throws IOException {
if (settings.debug && canvas != null) {
Graphics g = canvas.getGraphics();
g.setColor(Color.green);
g.drawRect(0, 0, width - 1, height - 1);
}
int x = 0, y = 0;
if (settings.edgePadding) {
if (!filter.direction.isX()) {
x = xPadding;
width -= xPadding;
}
if (!filter.direction.isY()) {
y = yPadding;
height -= yPadding;
}
} else {
// Pretend image is larger so padding on right and bottom edges is ignored.
if (!filter.direction.isX()) width += xPadding;
if (!filter.direction.isY()) height += yPadding;
}
Node root = new Node(x, y, width, height);
int usedPixels = 0;
for (int i = images.size() - 1; i >= 0; i--) {
Image image = images.get(i);
Node node = root.insert(image, false);
if (node == null) {
if (settings.rotate) node = root.insert(image, true);
if (node == null) continue;
}
usedPixels += image.getWidth() * image.getHeight();
images.remove(i);
if (canvas != null) {
node.writePackEntry();
Graphics2D g = (Graphics2D)canvas.getGraphics();
if (image.rotate) {
g.translate(node.left, node.top);
g.rotate(-90 * MathUtils.degreesToRadians);
g.translate(-node.left, -node.top);
g.translate(-image.getWidth(), 0);
}
if (settings.duplicatePadding) {
int amount = settings.padding / 2;
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
// Copy corner pixels to fill corners of the padding.
g.drawImage(image, node.left - amount, node.top - amount, node.left, node.top, 0, 0, 1, 1, null);
g.drawImage(image, node.left + imageWidth, node.top - amount, node.left + imageWidth + amount, node.top, 0, 0, 1,
1, null);
g.drawImage(image, node.left - amount, node.top + imageHeight, node.left, node.top + imageHeight + amount, 0, 0,
1, 1, null);
g.drawImage(image, node.left + imageWidth, node.top + imageHeight, node.left + imageWidth + amount, node.top
+ imageHeight + amount, 0, 0, 1, 1, null);
// Copy edge picels into padding.
g.drawImage(image, node.left, node.top - amount, node.left + imageWidth, node.top, 0, 0, imageWidth, 1, null);
g.drawImage(image, node.left, node.top + imageHeight, node.left + imageWidth, node.top + imageHeight + amount, 0,
imageHeight - 1, imageWidth, imageHeight, null);
g.drawImage(image, node.left - amount, node.top, node.left, node.top + imageHeight, 0, 0, 1, imageHeight, null);
g.drawImage(image, node.left + imageWidth, node.top, node.left + imageWidth + amount, node.top + imageHeight,
imageWidth - 1, 0, imageWidth, imageHeight, null);
}
g.drawImage(image, node.left, node.top, null);
if (image.rotate) {
g.translate(image.getWidth(), 0);
g.translate(node.left, node.top);
g.rotate(90 * MathUtils.degreesToRadians);
g.translate(-node.left, -node.top);
}
if (settings.debug) {
g.setColor(Color.magenta);
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
if (image.rotate)
g.drawRect(node.left, node.top, imageHeight - 1, imageWidth - 1);
else
g.drawRect(node.left, node.top, imageWidth - 1, imageHeight - 1);
}
}
}
return images.isEmpty() ? -1 : usedPixels;
}
private Image squeeze (BufferedImage source, String name, boolean skipTopLeft) {
if (source == null) return null;
if (!filter.accept(source)) return null;
uncompressedSize += source.getWidth() * source.getHeight();
WritableRaster alphaRaster = source.getAlphaRaster();
if (alphaRaster == null || !settings.stripWhitespace || name.contains("_ws"))
return new Image(name, source, 0, 0, source.getWidth(), source.getHeight());
final byte[] a = new byte[1];
int top = 0;
int bottom = source.getHeight();
if (!filter.direction.isY()) {
if (!skipTopLeft) {
outer:
for (int y = 0; y < source.getHeight(); y++) {
for (int x = 0; x < source.getWidth(); x++) {
alphaRaster.getDataElements(x, y, a);
int alpha = a[0];
if (alpha < 0) alpha += 256;
if (alpha > settings.alphaThreshold) break outer;
}
top++;
}
}
outer:
for (int y = source.getHeight(); --y >= top;) {
for (int x = 0; x < source.getWidth(); x++) {
alphaRaster.getDataElements(x, y, a);
int alpha = a[0];
if (alpha < 0) alpha += 256;
if (alpha > settings.alphaThreshold) break outer;
}
bottom--;
}
}
int left = 0;
int right = source.getWidth();
if (!filter.direction.isX()) {
if (!skipTopLeft) {
outer:
for (int x = 0; x < source.getWidth(); x++) {
for (int y = top; y < bottom; y++) {
alphaRaster.getDataElements(x, y, a);
int alpha = a[0];
if (alpha < 0) alpha += 256;
if (alpha > settings.alphaThreshold) break outer;
}
left++;
}
}
outer:
for (int x = source.getWidth(); --x >= left;) {
for (int y = top; y < bottom; y++) {
alphaRaster.getDataElements(x, y, a);
int alpha = a[0];
if (alpha < 0) alpha += 256;
if (alpha > settings.alphaThreshold) break outer;
}
right--;
}
}
int newWidth = right - left;
int newHeight = bottom - top;
if (newWidth <= 0 || newHeight <= 0) {
- log("Ignoring blank input image: " + name);
- return null;
+ if (settings.ignoreBlankImages) {
+ log("Ignoring blank input image: " + name);
+ return null;
+ } else {
+ return new Image(name, emptyImage, 0, 0, 1, 1);
+ }
}
return new Image(name, source, left, top, newWidth, newHeight);
}
static private String hash (BufferedImage image) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA1");
WritableRaster raster = image.getRaster();
final byte[] pixel = new byte[4];
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
raster.getDataElements(x, y, pixel);
digest.update(pixel);
}
}
return new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
private class Node {
int left, top, width, height;
Node child1, child2;
Image image;
public Node (int left, int top, int width, int height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
}
/** Returns true if the image was inserted. If canvas != null, an entry is written to the pack file. */
public Node insert (Image image, boolean rotate) throws IOException {
if (this.image != null) return null;
if (child1 != null) {
Node newNode = child1.insert(image, rotate);
if (newNode != null) return newNode;
return child2.insert(image, rotate);
}
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
if (rotate) {
int temp = imageWidth;
imageWidth = imageHeight;
imageHeight = temp;
}
int neededWidth = imageWidth + xPadding;
int neededHeight = imageHeight + yPadding;
if (neededWidth > width || neededHeight > height) return null;
if (neededWidth == width && neededHeight == height) {
this.image = image;
image.rotate = rotate;
return this;
}
int dw = width - neededWidth;
int dh = height - neededHeight;
if (dw > dh) {
child1 = new Node(left, top, neededWidth, height);
child2 = new Node(left + neededWidth, top, width - neededWidth, height);
} else {
child1 = new Node(left, top, width, neededHeight);
child2 = new Node(left, top + neededHeight, width, height - neededHeight);
}
return child1.insert(image, rotate);
}
void writePackEntry () throws IOException {
writePackEntry(image, false);
for (Image alias : image.aliases)
writePackEntry(alias, true);
}
private void writePackEntry (Image image, boolean alias) throws IOException {
String imageName = image.name;
imageName = imageName.replace("\\", "/");
log("Packing... " + imageName + (alias ? " (alias)" : ""));
Matcher matcher = indexPattern.matcher(imageName);
int index = -1;
if (matcher.matches()) index = Integer.parseInt(matcher.group(1));
int underscoreIndex = imageName.indexOf('_');
if (underscoreIndex != -1) imageName = imageName.substring(0, underscoreIndex);
writer.write(imageName + "\n");
writer.write(" rotate: " + image.rotate + "\n");
writer.write(" xy: " + left + ", " + top + "\n");
writer.write(" size: " + image.getWidth() + ", " + image.getHeight() + "\n");
writer.write(" orig: " + image.originalWidth + ", " + image.originalHeight + "\n");
writer.write(" offset: " + image.offsetX + ", " + (image.originalHeight - image.getHeight() - image.offsetY) + "\n");
writer.write(" index: " + index + "\n");
}
}
static private class Image extends BufferedImage {
final String name;
final int offsetX, offsetY;
final int originalWidth, originalHeight;
boolean rotate;
ArrayList<Image> aliases = new ArrayList();
public Image (String name, BufferedImage src, int left, int top, int newWidth, int newHeight) {
super(src.getColorModel(), src.getRaster().createWritableChild(left, top, newWidth, newHeight, 0, 0, null), src
.getColorModel().isAlphaPremultiplied(), null);
this.name = name;
offsetX = left;
offsetY = top;
originalWidth = src.getWidth();
originalHeight = src.getHeight();
}
public String toString () {
return name;
}
}
static private ArrayList<Comparator> imageComparators = new ArrayList();
static {
imageComparators.add(new Comparator<Image>() {
public int compare (Image image1, Image image2) {
int diff = image1.getHeight() - image2.getHeight();
if (diff != 0) return diff;
return image1.getWidth() - image2.getWidth();
}
});
imageComparators.add(new Comparator<Image>() {
public int compare (Image image1, Image image2) {
int diff = image1.getWidth() - image2.getWidth();
if (diff != 0) return diff;
return image1.getHeight() - image2.getHeight();
}
});
imageComparators.add(new Comparator<Image>() {
public int compare (Image image1, Image image2) {
return image1.getWidth() * image1.getHeight() - image2.getWidth() * image2.getHeight();
}
});
}
static private class Filter implements FilenameFilter {
Direction direction;
Format format;
TextureFilter minFilter;
TextureFilter magFilter;
int width = -1;
int height = -1;
Settings settings;
public Filter (Direction direction, Format format, int width, int height, TextureFilter minFilter, TextureFilter magFilter) {
this.direction = direction;
this.format = format;
this.width = width;
this.height = height;
this.minFilter = minFilter;
this.magFilter = magFilter;
}
public boolean accept (File dir, String name) {
switch (direction) {
case none:
if (name.contains("_x") || name.contains("_y")) return false;
break;
case x:
if (!name.contains("_x") || name.contains("_xy")) return false;
break;
case y:
if (!name.contains("_y") || name.contains("_xy")) return false;
break;
case xy:
if (!name.contains("_xy")) return false;
break;
}
if (format != null) {
if (!name.contains("_" + formatToAbbrev.get(format))) return false;
} else {
// Return if name has a format.
for (String f : formatToAbbrev.values())
if (name.contains("_" + f)) return false;
}
if (minFilter != null && magFilter != null) {
if (!name.contains("_" + filterToAbbrev.get(minFilter) + "," + filterToAbbrev.get(magFilter) + ".")
&& !name.contains("_" + filterToAbbrev.get(minFilter) + "," + filterToAbbrev.get(magFilter) + "_")) return false;
} else {
// Return if the name has a filter.
for (String f : filterToAbbrev.values()) {
String tag = "_" + f + ",";
int tagIndex = name.indexOf(tag);
if (tagIndex != -1) {
String rest = name.substring(tagIndex + tag.length());
for (String f2 : filterToAbbrev.values())
if (rest.startsWith(f2 + ".") || rest.startsWith(f2 + "_")) return false;
}
}
}
return true;
}
public boolean accept (BufferedImage image) {
if (width != -1 && image.getWidth() != width) return false;
if (height != -1 && image.getHeight() != height) return false;
return true;
}
}
static private enum Direction {
x, y, xy, none;
public boolean isX () {
return this == x || this == xy;
}
public boolean isY () {
return this == y || this == xy;
}
}
static final HashMap<TextureFilter, String> filterToAbbrev = new HashMap();
static {
filterToAbbrev.put(TextureFilter.Linear, "l");
filterToAbbrev.put(TextureFilter.Nearest, "n");
filterToAbbrev.put(TextureFilter.MipMap, "m");
filterToAbbrev.put(TextureFilter.MipMapLinearLinear, "mll");
filterToAbbrev.put(TextureFilter.MipMapLinearNearest, "mln");
filterToAbbrev.put(TextureFilter.MipMapNearestLinear, "mnl");
filterToAbbrev.put(TextureFilter.MipMapNearestNearest, "mnn");
}
static final HashMap<Format, String> formatToAbbrev = new HashMap();
static {
formatToAbbrev.put(Format.RGBA8888, "rgba8");
formatToAbbrev.put(Format.RGBA4444, "rgba4");
formatToAbbrev.put(Format.RGB565, "rgb565");
formatToAbbrev.put(Format.Alpha, "a");
}
static public class Settings {
public Format defaultFormat = Format.RGBA8888;
public TextureFilter defaultFilterMin = TextureFilter.Nearest;
public TextureFilter defaultFilterMag = TextureFilter.Nearest;
public int alphaThreshold = 0;
public boolean pot = true;
public int padding = 2;
public boolean duplicatePadding = true;
public boolean debug = false;
public boolean rotate = false;
public int minWidth = 128;
public int minHeight = 128;
public int maxWidth = 1024;
public int maxHeight = 1024;
public boolean stripWhitespace = false;
public boolean incremental;
public boolean alias = true;
public boolean edgePadding = true;
- // to save the increment file local to where the texture pack run
+ /** True if blank images should be ignored when building the texture pack or false if empty regions should be created for
+ * them. */
+ public boolean ignoreBlankImages = true;
+
+ /** Specifies the crc file path used when incremental is enabled, if not specified the file is created in the user folder,
+ * inside the .texturepacker folder. */
public String incrementalFilePath = null;
HashMap<String, Long> crcs = new HashMap();
HashMap<String, String> packSections = new HashMap();
}
static private void process (Settings settings, File rootDir, File inputDir, File outputDir, File packFile) throws IOException {
if (inputDir.getName().startsWith(".")) return;
// Abort if nothing has changed.
boolean skip = false;
if (settings.incremental) {
File[] files = inputDir.listFiles();
if (files == null) return;
boolean noneHaveChanged = true;
int childCountNow = 0;
// added flag to generate the crc file using local paths in case the incrementalFilePath is
// specified.
boolean useAbsolutePaths = true;
if (settings.incrementalFilePath != null) useAbsolutePaths = false;
for (File file : files) {
if (file.isDirectory()) continue;
String path = file.getAbsolutePath();
if (!useAbsolutePaths) {
String rootFolderAbsolutePath = rootDir.getAbsolutePath();
if (isSubPath(rootFolderAbsolutePath, path)) path = removeSubPath(rootFolderAbsolutePath, path);
}
Long crcOld = settings.crcs.get(path);
long crcNow = crc(file);
if (crcOld == null || crcOld != crcNow) noneHaveChanged = false;
settings.crcs.put(path, crcNow);
childCountNow++;
}
String path = inputDir.getAbsolutePath();
-
+
if (!useAbsolutePaths) {
String rootFolderAbsolutePath = rootDir.getAbsolutePath();
- if (isSubPath(rootFolderAbsolutePath, path))
- path = removeSubPath(rootFolderAbsolutePath, path);
+ if (isSubPath(rootFolderAbsolutePath, path)) path = removeSubPath(rootFolderAbsolutePath, path);
}
-
+
Long childCountOld = settings.crcs.get(path);
if (childCountOld == null || childCountNow != childCountOld) noneHaveChanged = false;
settings.crcs.put(path, (long)childCountNow);
if (outputDir.exists()) {
boolean foundPage = false;
String prefix = inputDir.getName();
for (File file : outputDir.listFiles()) {
if (file.getName().startsWith(prefix)) {
foundPage = true;
break;
}
}
if (!foundPage) noneHaveChanged = false;
}
String section = settings.packSections.get(inputDir.getName());
if (noneHaveChanged && section != null) {
FileWriter writer = new FileWriter(packFile, true);
writer.append(section);
writer.close();
log(inputDir.toString());
log("Skipping unchanged directory.");
log("");
skip = true;
}
}
if (!skip) {
// Clean existing page images.
if (outputDir.exists()) {
String prefix = inputDir.getName();
for (File file : outputDir.listFiles())
if (file.getName().startsWith(prefix) && file.getName().endsWith(".png")) file.delete();
}
// Just check all combinations, because we are extremely lazy.
ArrayList<TextureFilter> filters = new ArrayList();
filters.add(null);
filters.addAll(Arrays.asList(TextureFilter.values()));
ArrayList<Format> formats = new ArrayList();
formats.add(null);
formats.addAll(Arrays.asList(Format.values()));
for (int i = 0, n = formats.size(); i < n; i++) {
Format format = formats.get(i);
for (int ii = 0, nn = filters.size(); ii < nn; ii++) {
TextureFilter min = filters.get(ii);
for (int iii = 0; iii < nn; iii++) {
TextureFilter mag = filters.get(iii);
if ((min == null && mag != null) || (min != null && mag == null)) continue;
Filter filter = new Filter(Direction.none, format, -1, -1, min, mag);
new TexturePacker(settings, inputDir, filter, outputDir, packFile);
for (int width = settings.minWidth; width <= settings.maxWidth; width <<= 1) {
filter = new Filter(Direction.x, format, width, -1, min, mag);
new TexturePacker(settings, inputDir, filter, outputDir, packFile);
}
for (int height = settings.minHeight; height <= settings.maxHeight; height <<= 1) {
filter = new Filter(Direction.y, format, -1, height, min, mag);
new TexturePacker(settings, inputDir, filter, outputDir, packFile);
}
for (int width = settings.minWidth; width <= settings.maxWidth; width <<= 1) {
for (int height = settings.minHeight; height <= settings.maxHeight; height <<= 1) {
filter = new Filter(Direction.xy, format, width, height, min, mag);
new TexturePacker(settings, inputDir, filter, outputDir, packFile);
}
}
}
}
}
}
// Process subdirectories.
File[] files = inputDir.listFiles();
if (files == null) return;
for (File file : files)
if (file.isDirectory()) process(settings, rootDir, file, outputDir, packFile);
}
static public void process (Settings settings, String input, String output) {
process(settings, input, output, "pack");
}
static public void process (Settings settings, String input, String output, String packFileName) {
try {
File inputDir = new File(input);
File outputDir = new File(output);
if (!inputDir.isDirectory()) {
System.out.println("Not a directory: " + inputDir);
return;
}
File packFile = new File(outputDir, packFileName);
// Load incremental file.
File incrmentalFile = null;
if (settings.incremental && packFile.exists()) {
settings.crcs.clear();
// if localIncrementFile
String incrementalFilePath = settings.incrementalFilePath;
if (incrementalFilePath == null)
incrementalFilePath = System.getProperty("user.home") + "/.texturepacker/" + hash(inputDir.getAbsolutePath());
incrmentalFile = new File(incrementalFilePath);
if (incrmentalFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(incrmentalFile));
while (true) {
String path = reader.readLine();
if (path == null) break;
String crc = reader.readLine();
if (crc == null) break;
settings.crcs.put(path, Long.parseLong(crc));
}
reader.close();
}
// Store the pack file text for each section.
BufferedReader reader = new BufferedReader(new FileReader(packFile));
StringBuilder buffer = new StringBuilder(2048);
while (true) {
String imageName = reader.readLine();
if (imageName == null) break;
if (imageName.length() == 0) continue;
String pageName = imageName.replaceAll("\\d+.png$", "");
String section = settings.packSections.get(pageName);
if (section != null) buffer.append(section);
// buffer.append("****start\n");
buffer.append('\n');
buffer.append(imageName);
buffer.append('\n');
while (true) {
String line = reader.readLine();
if (line == null || line.length() == 0) break;
buffer.append(line);
buffer.append('\n');
}
settings.packSections.put(pageName, buffer.toString());
buffer.setLength(0);
}
reader.close();
}
// Clean pack file.
packFile.delete();
process(settings, inputDir, inputDir, outputDir, packFile);
// Write incrmental file.
if (incrmentalFile != null) {
incrmentalFile.getParentFile().mkdirs();
FileWriter writer = new FileWriter(incrmentalFile);
for (Entry<String, Long> entry : settings.crcs.entrySet()) {
writer.write(entry.getKey() + "\n");
writer.write(entry.getValue() + "\n");
}
writer.close();
}
} catch (IOException ex) {
throw new GdxRuntimeException("Error packing images: " + input, ex);
}
}
static private String hash (String value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA1");
digest.update(value.getBytes());
return new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
static private long crc (File file) {
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[4096];
CRC32 crc32 = new CRC32();
while (true) {
int length = input.read(buffer);
if (length == -1) break;
crc32.update(buffer, 0, length);
}
input.close();
return crc32.getValue();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
static boolean isSubPath (String path, String subPath) {
if (subPath.length() < path.length()) return false;
String subPathSubString = subPath.substring(0, path.length());
return subPathSubString.equals(path);
}
static boolean isAbsolutePath (String path) {
return new File(path).isAbsolute();
}
static String removeSubPath (String path, String subPath) {
return subPath.replace(path, "");
}
static public void main (String[] args) throws Exception {
String input, output;
if (args.length != 2) {
System.out.println("Usage: INPUTDIR OUTPUTDIR");
return;
}
input = args[0];
output = args[1];
Settings settings = new Settings();
settings.alias = true;
process(settings, input, output);
}
}
| false | false | null | null |
diff --git a/api/src/main/java/org/qi4j/object/ObjectBuilderFactory.java b/api/src/main/java/org/qi4j/object/ObjectBuilderFactory.java
index 29bbdead6..2e35487cd 100644
--- a/api/src/main/java/org/qi4j/object/ObjectBuilderFactory.java
+++ b/api/src/main/java/org/qi4j/object/ObjectBuilderFactory.java
@@ -1,38 +1,45 @@
/*
* Copyright (c) 2007, Rickard Öberg. All Rights Reserved.
* Copyright (c) 2007, Niclas Hedhman. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.qi4j.object;
-import org.qi4j.composite.NoSuchCompositeException;
import org.qi4j.composite.ConstructionException;
/**
* This factory creates builders for POJO's.
*/
public interface ObjectBuilderFactory
{
/**
* Create a builder for creating new objects of the given type.
*
- * @param type an object class which will be instantiated
- * @return a ObjectBuilder for creation of objects of the given type
- * @throws org.qi4j.composite.ConstructionException
- * thrown if instantiation fails
+ * @param type an object class which will be instantiated.
+ * @return an {@code ObjectBuilder} for creation of objects of the given type.
+ * @throws ConstructionException Thrown if instantiation fails.
+ * @throws NoSuchObjectException Thrown if {@code type} class is not an object.
*/
<T> ObjectBuilder<T> newObjectBuilder( Class<T> type )
- throws NoSuchObjectException;
+ throws NoSuchObjectException, ConstructionException;
+ /**
+ * Create new objects of the given type.
+ *
+ * @param type an object class which will be instantiated.
+ * @return new objects.
+ * @throws ConstructionException Thrown if instantiation fails.
+ * @throws NoSuchObjectException Thrown if {@code type} class is not an object.
+ */
<T> T newObject( Class<T> type )
- throws NoSuchCompositeException, ConstructionException;
+ throws NoSuchObjectException, ConstructionException;
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/rs/pedjaapps/KernelTuner/gpu.java b/src/rs/pedjaapps/KernelTuner/gpu.java
index 216c143..0c82f49 100755
--- a/src/rs/pedjaapps/KernelTuner/gpu.java
+++ b/src/rs/pedjaapps/KernelTuner/gpu.java
@@ -1,443 +1,443 @@
package rs.pedjaapps.KernelTuner;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import rs.pedjaapps.KernelTuner.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.widget.Toast;
public class gpu extends Activity{
public String gpu2dcurent;
public String gpu3dcurent ;
public String gpu2dmax;
public String gpu3dmax;
public String selected2d;
public String selected3d;
public int new3d;
public int new2d;
String board = android.os.Build.DEVICE;
public String[] gpu2ds ;//= {"160", "200", "228", "266"};
public String[] gpu3ds ;//= {"200", "228", "266", "300", "320"};
private ProgressDialog pd = null;
private Object data = null;
public SharedPreferences preferences;
public String[] gpu2d(String[] gpu2d){
gpu2ds=gpu2d;
return gpu2d;
}
public String[] gpu3d(String[] gpu3d){
gpu3ds=gpu3d;
return gpu3d;
}
private class changegpu extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... args) {
//Log.i("MyApp", "Background thread starting");
Process localProcess;
try {
localProcess = Runtime.getRuntime().exec("su");
DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
localDataOutputStream.writeBytes("chmod 777 /sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk\n");
//localDataOutputStream.writeBytes("chmod 777 /sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/gpuclk\n");
if(board.equals("shooter") || board.equals("shooteru") || board.equals("pyramid")){
//3d freqs for shooter,shooteru,pyramid(msm8x60)
if(selected3d.equals("200")){
new3d=200000000;
}
else if(selected3d.equals("228")){
new3d=228571000;
}
else if(selected3d.equals("266")){
new3d=266667000;
}
else if(selected3d.equals("300")){
new3d=300000000;
}
else if(selected3d.equals("320")){
new3d=320000000;
}
//2d freqs for shooter,shooteru,pyramid(msm8x60)
if(selected2d.equals("160")){
new2d=160000000;
}
else if(selected2d.equals("200")){
new2d=200000000;
//System.out.println("new clock = " +new2d);
}
else if(selected2d.equals("228")){
new2d=228571000;
//System.out.println("new clock = " +new2d);
}
else if(selected2d.equals("266")){
new2d=266667000;
//System.out.println("new clock = " +new2d);
}
}
//freqs for one s and one xl
else if(board.equals("evita") || board.equals("ville")){
// 3d freqs for evita
if(selected3d.equals("200")){
new3d=200000000;
}
else if(selected3d.equals("300")){
new3d=300000000;
}
else if(selected3d.equals("400")){
new3d=400000000;
}
else if(selected3d.equals("500")){
new3d=500000000;
}
//2d freqs for evita
if(selected2d.equals("200")){
new2d=200000000;
}
else if(selected2d.equals("300")){
new2d=300000000;
}
}
localDataOutputStream.writeBytes("echo " + new3d + " > /sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk\n");
localDataOutputStream.writeBytes("chmod 777 /sys/devices/platform/kgsl-2d1.1/kgsl/kgsl-2d1/max_gpuclk\n");
localDataOutputStream.writeBytes("chmod 777 /sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk\n");
localDataOutputStream.writeBytes("echo " + new2d + " > /sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk\n");
localDataOutputStream.writeBytes("echo " + new2d + " > /sys/devices/platform/kgsl-2d1.1/kgsl/kgsl-2d1/max_gpuclk\n");
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localDataOutputStream.close();
localProcess.waitFor();
localProcess.destroy();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(Object result) {
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
- editor.putString("gpu3d", selected3d);
- editor.putString("gpu2d", selected2d);
+ editor.putString("gpu3d", String.valueOf(new3d));
+ editor.putString("gpu2d", String.valueOf(new2d));
// value to store
editor.commit();
// Pass the result data back to the main activity
gpu.this.data = result;
gpu.this.pd.dismiss();
gpu.this.finish();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gpu);
//System.out.println(android.os.Build.BOARD);
if(board.equals("shooter") || board.equals("shooteru") || board.equals("pyramid")){
gpu2d(new String[]{"160", "200", "228", "266"});
gpu3d(new String[]{"200", "228", "266", "300", "320"});
}
else if(board.equals("evita") || board.equals("ville") | board.equals("jet")){
gpu2d(new String[]{"200", "300"});
gpu3d(new String[]{"200", "300", "400", "500"});
}
readgpu2dcurent();
readgpu3dcurent();
readgpu2dmax();
readgpu3dmax();
TextView tv5 = (TextView)findViewById(R.id.textView5);
TextView tv2 = (TextView)findViewById(R.id.textView7);
tv5.setText(gpu3dcurent.substring(0, gpu3dcurent.length()-6)+"Mhz");
tv2.setText(gpu2dcurent.substring(0, gpu2dcurent.length()-6)+"Mhz");
//setprogress2d();
//setprogress3d();
Button apply = (Button)findViewById(R.id.button2);
apply.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
gpu.this.pd = ProgressDialog.show(gpu.this, "Working..", "Applying settings...", true, false);
new changegpu().execute();
}
});
Button cancel = (Button)findViewById(R.id.button1);
cancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
gpu.this.finish();
}
});
}
public void createSpinner2D(){
final Spinner spinner = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, gpu2ds);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected2d = parent.getItemAtPosition(pos).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//do nothing
}
});
ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(gpu2dmax.substring(0, gpu2dmax.length()-6));
//set the default according to value
spinner.setSelection(spinnerPosition);
}
public void createSpinner3D(){
final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, gpu3ds);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected3d = parent.getItemAtPosition(pos).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//do nothing
}
});
ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(gpu3dmax.substring(0, gpu3dmax.length()-6));
//set the default according to value
spinner.setSelection(spinnerPosition);
}
public void readgpu3dcurent(){
try {
File myFile = new File("/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/gpuclk");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
gpu3dcurent = aBuffer.trim();
myReader.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
public void readgpu2dcurent(){
try {
File myFile = new File("/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/gpuclk");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
gpu2dcurent = aBuffer.trim();
myReader.close();
} catch (Exception e) {
}
}
public void readgpu3dmax(){
try {
File myFile = new File("/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
gpu3dmax = aBuffer.trim();
//Log.d("max gpu 3d clock",gpu3dmax);
createSpinner3D();
myReader.close();
} catch (Exception e) {
//Log.e("max gpu 3d clock","not found");
}
}
public void readgpu2dmax(){
try {
File myFile = new File("/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
gpu2dmax = aBuffer.trim();
createSpinner2D();
myReader.close();
} catch (Exception e) {
}
}
}
| true | false | null | null |
diff --git a/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java b/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
index fd9df75..53cd8b3 100644
--- a/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
+++ b/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
@@ -1,183 +1,192 @@
package hudson.plugins.msbuild;
import hudson.Launcher;
import hudson.Util;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Project;
import hudson.tasks.Builder;
import hudson.util.ArgumentListBuilder;
import java.io.IOException;
import java.util.Map;
+import net.sf.json.JSONObject;
+
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
/**
* Sample {@link Builder}.
*
* <p>
* When the user configures the project and enables this builder,
* {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked
* and a new {@link MsBuildBuilder} is created. The created
* instance is persisted to the project configuration XML by using
* XStream, so this allows you to use instance fields (like {@link #name})
* to remember the configuration.
*
* <p>
* When a build is performed, the {@link #perform(Build, Launcher, BuildListener)} method
* will be invoked.
*
* @author [email protected]
*
*/
public class MsBuildBuilder extends Builder {
private final String msBuildFile;
private final String cmdLineArgs;
/**
* When this builder is created in the project configuration step,
* the builder object will be created from the strings below.
* @param msBuildFile The name/location of the msbuild file
* @param targets Whitespace separated list of command line arguments
*/
@DataBoundConstructor
public MsBuildBuilder(String msBuildFile,String cmdLineArgs) {
super();
if(msBuildFile==null || msBuildFile.trim().length()==0)
this.msBuildFile = "";
else
this.msBuildFile = msBuildFile;
if(cmdLineArgs==null || cmdLineArgs.trim().length()==0)
this.cmdLineArgs = "";
else
this.cmdLineArgs = cmdLineArgs;
}
/**
* We'll use these from the <tt>config.jelly</tt>.
*/
public String getCmdLineArgs(){
return cmdLineArgs;
}
public String getMsBuildFile(){
return msBuildFile;
}
public boolean perform(Build<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException {
Project proj = build.getProject();
ArgumentListBuilder args = new ArgumentListBuilder();
//Get the path to the nant installation
listener.getLogger().println("Path To MSBuild.exe: " + DESCRIPTOR.getPathToMsBuild());
String msbuildExe = DESCRIPTOR.getPathToMsBuild();
//Create a new commandline target with the name of the executable as the first
//paramater
String execName=msbuildExe;
args.add(execName);
//Remove all tabs, carriage returns, and newlines and replace them with
//whitespaces, so that we can add them as parameters to the executable
String normalizedTarget = cmdLineArgs.replaceAll("[\t\r\n]+"," ");
if(normalizedTarget.trim().length()>0)
args.addTokenized(normalizedTarget);
//If a msbuild file is specified, then add it as an argument, otherwise
//msbuild will search for any file that ends in .proj or .sln
if(msBuildFile != null && msBuildFile.trim().length() > 0){
args.add(msBuildFile);
}
//According to the Ant builder source code, in order to launch a program
//from the command line in windows, we must wrap it into cmd.exe. This
//way the return code can be used to determine whether or not the build failed.
if(!launcher.isUnix()) {
args.prepend("cmd.exe","/C");
args.add("&&","exit","%%ERRORLEVEL%%");
}
//Try to execute the command
listener.getLogger().println("Executing command: "+args.toString());
Map<String,String> env = build.getEnvVars();
try {
int r = launcher.launch(args.toCommandArray(),env,listener.getLogger(),proj.getModuleRoot()).join();
return r==0;
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace( listener.fatalError("command execution failed") );
return false;
}
}
public Descriptor<Builder> getDescriptor() {
// see Descriptor javadoc for more about what a descriptor is.
return DESCRIPTOR;
}
/**
* Descriptor should be singleton.
*/
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
/**
* Descriptor for {@link MsBuildBuilder}. Used as a singleton.
* The class is marked as public so that it can be accessed from views.
*/
public static final class DescriptorImpl extends Descriptor<Builder> {
/**
* To persist global configuration information,
* simply store it in a field and call save().
*
* <p>
* If you don't want fields to be persisted, use <tt>transient</tt>.
*/
public static String PARAMETERNAME_PATH_TO_MSBUILD = "pathToMsBuild";
private static String DEFAULT_PATH_TO_MSBUILD = "msbuild.exe";
private String pathToMsBuild;
DescriptorImpl() {
super(MsBuildBuilder.class);
load();
if(pathToMsBuild==null || pathToMsBuild.length()==0){
pathToMsBuild = DEFAULT_PATH_TO_MSBUILD;
save();
}
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Build a Visual Studio project or solution using MSBuild.";
}
@Override
public boolean configure(StaplerRequest req) throws FormException{
// to persist global configuration information,
// set that to properties and call save().
pathToMsBuild = req.getParameter("descriptor."+PARAMETERNAME_PATH_TO_MSBUILD);
if(pathToMsBuild == null || pathToMsBuild.length()==0){
pathToMsBuild = DEFAULT_PATH_TO_MSBUILD;
}
save();
return true;
}
/**
* This method returns the path to the msbuild.exe file for executing msbuild
*/
public String getPathToMsBuild() {
return pathToMsBuild;
}
- public Builder newInstance(StaplerRequest req) {
- return req.bindParameters(MsBuildBuilder.class,"msBuildBuilder.");
- }
+
+ @Override
+ public Builder newInstance(StaplerRequest arg0, JSONObject arg1) throws FormException {
+ String buildFile= arg1.getString("msBuildFile");
+ String cmdLineArg= arg1.getString("cmdLineArgs");
+ MsBuildBuilder builder = new MsBuildBuilder(buildFile,cmdLineArg);
+
+ return builder;
+ }
+
}
}
| false | false | null | null |
diff --git a/plugin/src/test/java/com/xebia/os/maven/couchdocsplugin/CouchFunctionsImplTest.java b/plugin/src/test/java/com/xebia/os/maven/couchdocsplugin/CouchFunctionsImplTest.java
index c6f11ce..9ee9b7a 100644
--- a/plugin/src/test/java/com/xebia/os/maven/couchdocsplugin/CouchFunctionsImplTest.java
+++ b/plugin/src/test/java/com/xebia/os/maven/couchdocsplugin/CouchFunctionsImplTest.java
@@ -1,134 +1,157 @@
/*
Copyright 2012 Xebia Nederland B.V.
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.xebia.os.maven.couchdocsplugin;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import org.codehaus.plexus.util.IOUtil;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import com.google.common.base.Optional;
import com.xebia.os.maven.couchdocsplugin.CouchDatabaseException;
import com.xebia.os.maven.couchdocsplugin.CouchFunctionsImpl;
import com.xebia.os.maven.couchdocsplugin.LocalDocument;
import com.xebia.os.maven.couchdocsplugin.RemoteDocument;
import com.xebia.os.maven.couchdocsplugin.junit.ConditionalTestRunner;
import com.xebia.os.maven.couchdocsplugin.junit.EnvironmentCondition;
import com.xebia.os.maven.couchdocsplugin.junit.EnvironmentCondition.Kind;
/**
* Integration test for the {@link CouchFunctionsImpl}.
*
* <p>This test requires manual intervention.</p>
*
* <ul>
* <li>Make sure CouchDB is running, update the BASE_URL below as needed.</li>
* </ul>
*
* @author Barend Garvelink <[email protected]> (https://github.com/barend)
*/
@RunWith(ConditionalTestRunner.class)
@EnvironmentCondition(name = "COUCHDB_INTEGRATION_TESTS", kind = Kind.ENVIRONMENT_VARIABLE)
public class CouchFunctionsImplTest {
private static final String BASE_URL = "http://admin:admin@localhost:5984";
@Rule public TemporaryFolder tempDir = new TemporaryFolder();
@Test
public void playScenario() throws IOException {
final String databaseName = "test-database-" + (new SecureRandom()).nextLong();
final CouchFunctionsImpl impl = new CouchFunctionsImpl(BASE_URL);
// 0. isExistentDatabase() -> false
assertFalse("The database randomly named \"" + databaseName + "\" should not exist at the start of the test.",
impl.isExistentDatabase(databaseName));
// 1. createDatabase().
impl.createDatabase(databaseName);
// 2. isExistentDatabase() -> true
assertTrue("The database \"" + databaseName + "\" should have been created and isExistentDatabase() should find it.",
impl.isExistentDatabase(databaseName));
// 3. download() -> not found
Optional<RemoteDocument> remoteDoc = impl.download(databaseName, "_design/Demo");
assertFalse("The document \"_design/Demo\" should not exist in the database.", remoteDoc.isPresent());
// 4. upload()
File file = newTempFile("/design_doc.js");
LocalDocument localDoc = new LocalDocument(file);
localDoc.load();
assertEquals("The local document should have the id \"_design/Demo\".", "_design/Demo", localDoc.getId());
impl.upload(databaseName, localDoc);
// 5. download() -> found
remoteDoc = impl.download(databaseName, "_design/Demo");
assertTrue("The document \"_design/Demo\" should now exist in the database, it was just uploaded.", remoteDoc.isPresent());
// 6. delete()
impl.delete(databaseName, remoteDoc.get());
// 7. download() -> not found
remoteDoc = impl.download(databaseName, "_design/Demo");
assertFalse("The document \"_design/Demo\" should no longer exist in the database.", remoteDoc.isPresent());
// 8. deleteDatabase()
impl.deleteDatabase(databaseName);
// 9. isExistentDatabase() -> false
assertFalse("The database randomly named \"" + databaseName + "\" should no longer exist.",
impl.isExistentDatabase(databaseName));
}
+ /**
+ * Proves that {@linkplain https://github.com/xebia/couch-docs-maven-plugin/issues/7} is absent.
+ */
+ @Test
+ public void createDatabaseWithWeirdCharactersInTheName() throws IOException {
+ final String databaseName = "test/da+ta(ba)$_$e-" + (new SecureRandom()).nextLong();
+ final CouchFunctionsImpl impl = new CouchFunctionsImpl(BASE_URL);
+
+ // 0. isExistentDatabase() -> false
+ assertFalse("The database randomly named \"" + databaseName + "\" should not exist at the start of the test.",
+ impl.isExistentDatabase(databaseName));
+
+ // 1. createDatabase().
+ impl.createDatabase(databaseName);
+
+ // 2. isExistentDatabase() -> true
+ assertTrue("The database \"" + databaseName + "\" should have been created and isExistentDatabase() should find it.",
+ impl.isExistentDatabase(databaseName));
+
+ // 3. clean up
+ impl.deleteDatabase(databaseName);
+ }
+
@Test
public void shouldWrapServerErrors() throws IOException {
try {
final CouchFunctionsImpl impl = new CouchFunctionsImpl(BASE_URL);
impl.createDatabase("Database-Names-Cannot-Have-Capital-Letters");
fail("An exception should have been thrown.");
} catch (CouchDatabaseException e) {
assertEquals(400, e.getResponseCode());
}
}
private File newTempFile(final String source) throws IOException, FileNotFoundException {
File result = tempDir.newFile();
final InputStream dummyData = UpdateCouchDocsTest.class.getResourceAsStream(source);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(result);
IOUtil.copy(dummyData, fos);
} finally {
IOUtil.close(dummyData);
IOUtil.close(fos);
}
return result;
}
}
| true | false | null | null |
diff --git a/de.walware.statet.r.sweave/src/de/walware/statet/r/internal/sweave/editors/RweaveTexDocumentProvider.java b/de.walware.statet.r.sweave/src/de/walware/statet/r/internal/sweave/editors/RweaveTexDocumentProvider.java
index 00f89965..d143e7d0 100644
--- a/de.walware.statet.r.sweave/src/de/walware/statet/r/internal/sweave/editors/RweaveTexDocumentProvider.java
+++ b/de.walware.statet.r.sweave/src/de/walware/statet/r/internal/sweave/editors/RweaveTexDocumentProvider.java
@@ -1,110 +1,109 @@
/*******************************************************************************
* Copyright (c) 2007-2008 WalWare/StatET-Project (www.walware.de/goto/statet).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.r.internal.sweave.editors;
import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.ui.editors.text.ForwardingDocumentProvider;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.texteditor.IDocumentProvider;
import de.walware.eclipsecommons.ltk.IDocumentModelProvider;
import de.walware.eclipsecommons.ltk.ISourceUnit;
import de.walware.statet.base.core.StatetCore;
import de.walware.statet.r.internal.sweave.Rweave;
import de.walware.statet.r.sweave.Sweave;
public class RweaveTexDocumentProvider extends TextFileDocumentProvider implements IDocumentModelProvider {
public static class SweaveSourceFileInfo extends FileInfo {
public ISourceUnit fWorkingCopy;
}
private IDocumentSetupParticipant fDocumentSetupParticipant;
public RweaveTexDocumentProvider() {
fDocumentSetupParticipant = new RweaveTexDocumentSetupParticipant();
final IDocumentProvider provider = new ForwardingDocumentProvider(Rweave.R_TEX_PARTITIONING,
fDocumentSetupParticipant, new TextFileDocumentProvider());
setParentDocumentProvider(provider);
}
@Override
protected FileInfo createEmptyFileInfo() {
return new SweaveSourceFileInfo();
}
@Override
public void connect(final Object element) throws CoreException {
super.connect(element);
final IDocument document = getDocument(element);
if (document instanceof IDocumentExtension3) {
final IDocumentExtension3 extension= (IDocumentExtension3) document;
if (extension.getDocumentPartitioner(Rweave.R_TEX_PARTITIONING) == null) {
fDocumentSetupParticipant.setup(document);
}
}
}
@Override
public void disconnect(final Object element) {
final FileInfo info = getFileInfo(element);
if (info instanceof SweaveSourceFileInfo) {
final SweaveSourceFileInfo rinfo = (SweaveSourceFileInfo) info;
if (rinfo.fCount == 1 && rinfo.fWorkingCopy != null) {
rinfo.fWorkingCopy.disconnect();
rinfo.fWorkingCopy = null;
}
}
super.disconnect(element);
}
@Override
protected FileInfo createFileInfo(final Object element) throws CoreException {
final FileInfo info = super.createFileInfo(element);
if (!(info instanceof SweaveSourceFileInfo)) {
return null;
}
final IAdaptable adaptable = (IAdaptable) element;
final SweaveSourceFileInfo rinfo = (SweaveSourceFileInfo) info;
setUpSynchronization(info);
- final ISourceUnit pUnit = StatetCore.PERSISTENCE_CONTEXT.getUnit(
- adaptable.getAdapter(IFile.class), Sweave.R_TEX_UNIT_TYPE_ID, true);
- if (pUnit != null) {
+ final Object ifile = adaptable.getAdapter(IFile.class);
+ if (ifile != null) {
+ final ISourceUnit pUnit = StatetCore.PERSISTENCE_CONTEXT.getUnit(ifile, Sweave.R_TEX_UNIT_TYPE_ID, true);
rinfo.fWorkingCopy = StatetCore.EDITOR_CONTEXT.getUnit(pUnit, Sweave.R_TEX_UNIT_TYPE_ID, true);
}
-
return rinfo;
}
public ISourceUnit getWorkingCopy(final Object element) {
final FileInfo fileInfo = getFileInfo(element);
if (fileInfo instanceof SweaveSourceFileInfo) {
return ((SweaveSourceFileInfo) fileInfo).fWorkingCopy;
}
return null;
}
}
diff --git a/de.walware.statet.r.ui/src/de/walware/statet/r/internal/ui/editors/RDocumentProvider.java b/de.walware.statet.r.ui/src/de/walware/statet/r/internal/ui/editors/RDocumentProvider.java
index f0642d7d..a4c73e8b 100644
--- a/de.walware.statet.r.ui/src/de/walware/statet/r/internal/ui/editors/RDocumentProvider.java
+++ b/de.walware.statet.r.ui/src/de/walware/statet/r/internal/ui/editors/RDocumentProvider.java
@@ -1,213 +1,213 @@
/*******************************************************************************
* Copyright (c) 2005-2008 WalWare/StatET-Project (www.walware.de/goto/statet).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.r.internal.ui.editors;
import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.editors.text.ForwardingDocumentProvider;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.services.IDisposable;
import org.eclipse.ui.texteditor.IDocumentProvider;
import de.walware.eclipsecommons.ltk.IDocumentModelProvider;
import de.walware.eclipsecommons.ltk.IProblem;
import de.walware.eclipsecommons.ltk.ISourceUnit;
import de.walware.eclipsecommons.ltk.ui.SourceAnnotationModel;
import de.walware.eclipsecommons.ltk.ui.SourceProblemAnnotation;
import de.walware.eclipsecommons.ltk.ui.SourceProblemAnnotation.PresentationConfig;
import de.walware.eclipsecommons.preferences.IPreferenceAccess;
import de.walware.eclipsecommons.preferences.PreferencesUtil;
import de.walware.statet.base.core.StatetCore;
import de.walware.statet.r.core.RCore;
import de.walware.statet.r.core.rmodel.IRSourceUnit;
import de.walware.statet.r.core.rsource.IRDocumentPartitions;
import de.walware.statet.r.internal.ui.RUIPlugin;
import de.walware.statet.r.ui.editors.RDocumentSetupParticipant;
import de.walware.statet.r.ui.editors.REditorOptions;
public class RDocumentProvider extends TextFileDocumentProvider implements IDocumentModelProvider, IDisposable {
public static final PresentationConfig PROBLEM = new PresentationConfig(1,""); //$NON-NLS-1$
public static final String R_ERROR_ANNOTATION_TYPE = "de.walware.statet.r.ui.error"; //$NON-NLS-1$
public static final String R_WARNING_ANNOTATION_TYPE = "de.walware.statet.r.ui.warning"; //$NON-NLS-1$
public static final String R_INFO_ANNOTATION_TYPE = "de.walware.statet.r.ui.info"; //$NON-NLS-1$
public static class RSourceFileInfo extends FileInfo {
public IRSourceUnit fWorkingCopy;
}
private class RAnnotationModel extends SourceAnnotationModel {
public RAnnotationModel(final IResource resource) {
super(resource);
}
@Override
protected boolean isHandlingTemporaryProblems() {
return fHandleTemporaryProblems;
}
@Override
protected SourceProblemAnnotation createAnnotation(final IProblem problem) {
switch (problem.getSeverity()) {
case IProblem.SEVERITY_ERROR:
return new SourceProblemAnnotation(R_ERROR_ANNOTATION_TYPE, problem, SourceProblemAnnotation.ERROR_CONFIG);
case IProblem.SEVERITY_WARNING:
return new SourceProblemAnnotation(R_WARNING_ANNOTATION_TYPE, problem, SourceProblemAnnotation.WARNING_CONFIG);
default:
return new SourceProblemAnnotation(R_INFO_ANNOTATION_TYPE, problem, SourceProblemAnnotation.INFO_CONFIG);
}
}
}
private IDocumentSetupParticipant fDocumentSetupParticipant;
private IEclipsePreferences.IPreferenceChangeListener fEditorPrefListener;
private boolean fHandleTemporaryProblems;
public RDocumentProvider() {
fDocumentSetupParticipant = new RDocumentSetupParticipant();
final IDocumentProvider provider = new ForwardingDocumentProvider(IRDocumentPartitions.R_DOCUMENT_PARTITIONING,
fDocumentSetupParticipant, new TextFileDocumentProvider());
setParentDocumentProvider(provider);
final IPreferenceAccess access = PreferencesUtil.getInstancePrefs();
RUIPlugin.getDefault().registerPluginDisposable(this);
fEditorPrefListener = new IEclipsePreferences.IPreferenceChangeListener() {
public void preferenceChange(final PreferenceChangeEvent event) {
if (event.getKey().equals(REditorOptions.PREF_PROBLEMCHECKING_ENABLED.getKey())) {
updateEditorPrefs();
}
}
};
access.addPreferenceNodeListener(REditorOptions.PREF_PROBLEMCHECKING_ENABLED.getQualifier(), fEditorPrefListener);
fHandleTemporaryProblems = access.getPreferenceValue(REditorOptions.PREF_PROBLEMCHECKING_ENABLED);
}
public void dispose() {
if (fEditorPrefListener != null) {
final IPreferenceAccess access = PreferencesUtil.getInstancePrefs();
access.removePreferenceNodeListener(REditorOptions.PREF_PROBLEMCHECKING_ENABLED.getQualifier(), fEditorPrefListener);
fEditorPrefListener = null;
}
}
private void updateEditorPrefs() {
final IPreferenceAccess access = PreferencesUtil.getInstancePrefs();
final boolean newHandleTemporaryProblems = access.getPreferenceValue(REditorOptions.PREF_PROBLEMCHECKING_ENABLED);
if (fHandleTemporaryProblems != newHandleTemporaryProblems) {
fHandleTemporaryProblems = newHandleTemporaryProblems;
if (fHandleTemporaryProblems) {
RCore.getRModelManger().refresh(StatetCore.EDITOR_CONTEXT);
}
else {
final ISourceUnit[] units = RCore.getRModelManger().getWorkingCopies(StatetCore.EDITOR_CONTEXT);
for (final ISourceUnit u : units) {
final IAnnotationModel model = getAnnotationModel(u);
if (model instanceof RAnnotationModel) {
((RAnnotationModel) model).clearProblems("r"); //$NON-NLS-1$
}
}
}
}
}
@Override
protected FileInfo createEmptyFileInfo() {
return new RSourceFileInfo();
}
@Override
protected IAnnotationModel createAnnotationModel(final IFile file) {
return new RAnnotationModel(file);
}
@Override
public void connect(final Object element) throws CoreException {
super.connect(element);
final IDocument document = getDocument(element);
if (document instanceof IDocumentExtension3) {
final IDocumentExtension3 extension= (IDocumentExtension3) document;
if (extension.getDocumentPartitioner(IRDocumentPartitions.R_DOCUMENT_PARTITIONING) == null) {
fDocumentSetupParticipant.setup(document);
}
}
}
@Override
public void disconnect(final Object element) {
final FileInfo info = getFileInfo(element);
if (info instanceof RSourceFileInfo) {
final RSourceFileInfo rinfo = (RSourceFileInfo) info;
if (rinfo.fCount == 1 && rinfo.fWorkingCopy != null) {
rinfo.fWorkingCopy.disconnect();
rinfo.fWorkingCopy = null;
}
}
super.disconnect(element);
}
@Override
protected FileInfo createFileInfo(final Object element) throws CoreException {
final FileInfo info = super.createFileInfo(element);
if (!(info instanceof RSourceFileInfo)) {
return null;
}
final IAdaptable adaptable = (IAdaptable) element;
final RSourceFileInfo rinfo = (RSourceFileInfo) info;
setUpSynchronization(info);
- final ISourceUnit pUnit = StatetCore.PERSISTENCE_CONTEXT.getUnit(
- adaptable.getAdapter(IFile.class), "r", true); //$NON-NLS-1$
- if (pUnit != null) {
+ final Object ifile = adaptable.getAdapter(IFile.class);
+ if (ifile != null) {
+ final ISourceUnit pUnit = StatetCore.PERSISTENCE_CONTEXT.getUnit(ifile, "r", true); //$NON-NLS-1$
rinfo.fWorkingCopy = (IRSourceUnit) StatetCore.EDITOR_CONTEXT.getUnit(pUnit, "r", true); //$NON-NLS-1$
}
return rinfo;
}
public IRSourceUnit getWorkingCopy(final Object element) {
final FileInfo fileInfo = getFileInfo(element);
if (fileInfo instanceof RSourceFileInfo) {
return ((RSourceFileInfo) fileInfo).fWorkingCopy;
}
return null;
}
@Override
public IAnnotationModel getAnnotationModel(Object element) {
if (element instanceof ISourceUnit) {
element = new FileEditorInput((IFile) ((ISourceUnit) element).getResource());
}
return super.getAnnotationModel(element);
}
}
| false | false | null | null |
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/failover/SipStandardBalancerNodeService.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/failover/SipStandardBalancerNodeService.java
index 608a1fe5d..cb1d9cd1d 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/failover/SipStandardBalancerNodeService.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/failover/SipStandardBalancerNodeService.java
@@ -1,477 +1,477 @@
/*
* 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.failover;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.catalina.Container;
import org.apache.catalina.Engine;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.ProtocolHandler;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.startup.SipProtocolHandler;
import org.mobicents.servlet.sip.startup.SipStandardService;
import org.mobicents.servlet.sip.utils.Inet6Util;
import org.mobicents.tools.sip.balancer.NodeRegisterRMIStub;
import org.mobicents.tools.sip.balancer.SIPNode;
/**
* <p>Sip Servlet implementation of the <code>Service</code> interface.</p>
*
* <p>This implementation extends the <code>SipStandardService</code> (that allows Tomcat to become a converged container)
* with the failover features.<br/>
* This implementation will send heartbeats and health information to the sip balancers configured for this service
* (configured in the server.xml as balancers attribute fo the Service Tag)</p>
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public class SipStandardBalancerNodeService extends SipStandardService implements SipBalancerNodeService {
private static final String BALANCER_SIP_PORT_CHAR_SEPARATOR = ":";
private static final String BALANCERS_CHAR_SEPARATOR = ";";
private static final int DEFAULT_LB_SIP_PORT = 5065;
//the logger
private static transient Logger logger = Logger.getLogger(SipStandardBalancerNodeService.class);
/**
* The descriptive information string for this implementation.
*/
private static final String info =
"org.mobicents.servlet.sip.startup.failover.SipStandardBalancerNodeService/1.0";
//the balancers to send heartbeat to and our health info
private String balancers;
//the balancers names to send heartbeat to and our health info
private Map<String, BalancerDescription> register = new ConcurrentHashMap<String, BalancerDescription>();
//heartbeat interval, can be modified through JMX
private long heartBeatInterval = 5000;
private Timer heartBeatTimer = new Timer();
private TimerTask hearBeatTaskToRun = null;
private boolean started = false;
- private boolean displayBalancerWarining = true;
+ private boolean displayBalancerWarning = true;
private boolean displayBalancerFound = true;
@Override
public String getInfo() {
return (info);
}
@Override
public void initialize() throws LifecycleException {
super.initialize();
}
@Override
public void start() throws LifecycleException {
super.start();
if (!started) {
if (balancers != null && balancers.length() > 0) {
String[] balancerDescriptions = balancers.split(BALANCERS_CHAR_SEPARATOR);
for (String balancerDescription : balancerDescriptions) {
String balancerAddress = balancerDescription;
int sipPort = DEFAULT_LB_SIP_PORT;
if(balancerDescription.indexOf(BALANCER_SIP_PORT_CHAR_SEPARATOR) != -1) {
String[] balancerDescriptionSplitted = balancerDescription.split(BALANCER_SIP_PORT_CHAR_SEPARATOR);
balancerAddress = balancerDescriptionSplitted[0];
try {
sipPort = Integer.parseInt(balancerDescriptionSplitted[1]);
} catch (NumberFormatException e) {
throw new LifecycleException("Impossible to parse the following sip balancer port " + balancerDescriptionSplitted[1], e);
}
}
if(Inet6Util.isValidIP6Address(balancerAddress) || Inet6Util.isValidIPV4Address(balancerAddress)) {
try {
this.addBalancer(InetAddress.getByName(balancerAddress).getHostAddress(), sipPort);
} catch (UnknownHostException e) {
throw new LifecycleException("Impossible to parse the following sip balancer address " + balancerAddress, e);
}
} else {
this.addBalancer(balancerAddress, sipPort, 0);
}
}
}
started = true;
}
this.hearBeatTaskToRun = new BalancerPingTimerTask();
this.heartBeatTimer.scheduleAtFixedRate(this.hearBeatTaskToRun, 0,
this.heartBeatInterval);
if(logger.isDebugEnabled()) {
logger.debug("Created and scheduled tasks for sending heartbeats to the sip balancer.");
}
}
@Override
public void stop() throws LifecycleException {
// Force removal from load balancer upon shutdown
// added for Issue 308 (http://code.google.com/p/mobicents/issues/detail?id=308)
ArrayList<SIPNode> info = getConnectorsAsSIPNode();
removeNodesFromBalancers(info);
//cleaning
// balancerNames.clear();
register.clear();
if(hearBeatTaskToRun != null) {
this.hearBeatTaskToRun.cancel();
}
this.hearBeatTaskToRun = null;
started = false;
super.stop();
}
/**
* {@inheritDoc}
*/
public long getHeartBeatInterval() {
return heartBeatInterval;
}
/**
* {@inheritDoc}
*/
public void setHeartBeatInterval(long heartBeatInterval) {
if (heartBeatInterval < 100)
return;
this.heartBeatInterval = heartBeatInterval;
this.hearBeatTaskToRun.cancel();
this.hearBeatTaskToRun = new BalancerPingTimerTask();
this.heartBeatTimer.scheduleAtFixedRate(this.hearBeatTaskToRun, 0,
this.heartBeatInterval);
}
/**
*
* @param hostName
* @param index
* @return
*/
private InetAddress fetchHostAddress(String hostName, int index) {
if (hostName == null)
throw new NullPointerException("Host name cant be null!!!");
InetAddress[] hostAddr = null;
try {
hostAddr = InetAddress.getAllByName(hostName);
} catch (UnknownHostException uhe) {
throw new IllegalArgumentException(
"HostName is not a valid host name or it doesnt exists in DNS",
uhe);
}
if (index < 0 || index >= hostAddr.length) {
throw new IllegalArgumentException(
"Index in host address array is wrong, it should be [0]<x<["
+ hostAddr.length + "] and it is [" + index + "]");
}
InetAddress address = hostAddr[index];
return address;
}
/**
* {@inheritDoc}
*/
public String[] getBalancers() {
return this.register.keySet().toArray(new String[register.keySet().size()]);
}
/**
* {@inheritDoc}
*/
public boolean addBalancer(String addr, int sipPort) {
if (addr == null)
throw new NullPointerException("addr cant be null!!!");
InetAddress address = null;
try {
address = InetAddress.getByName(addr);
} catch (UnknownHostException e) {
throw new IllegalArgumentException(
"Somethign wrong with host creation.", e);
}
String balancerName = address.getCanonicalHostName();
if (register.get(balancerName) != null) {
logger.info("Sip balancer " + balancerName + " already present, not added");
return false;
}
if(logger.isDebugEnabled()) {
logger.debug("Adding following balancer name : " + balancerName +"/address:"+ addr);
}
BalancerDescription balancerDescription = new BalancerDescription(address, sipPort);
register.put(balancerName, balancerDescription);
//notify the sip factory
if(sipApplicationDispatcher.getSipFactory().getLoadBalancerToUse() == null) {
sipApplicationDispatcher.getSipFactory().setLoadBalancerToUse(balancerDescription);
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean addBalancer(String hostName, int sipPort, int index) {
return this.addBalancer(fetchHostAddress(hostName, index)
.getHostAddress(), sipPort);
}
/**
* {@inheritDoc}
*/
public boolean removeBalancer(String addr, int sipPort) {
if (addr == null)
throw new NullPointerException("addr cant be null!!!");
InetAddress address = null;
try {
address = InetAddress.getByName(addr);
} catch (UnknownHostException e) {
throw new IllegalArgumentException(
"Something wrong with host creation.", e);
}
BalancerDescription balancerDescription = new BalancerDescription(address, sipPort);
String keyToRemove = null;
Iterator<String> keyIterator = register.keySet().iterator();
while (keyIterator.hasNext() && keyToRemove ==null) {
String key = keyIterator.next();
if(register.get(key).equals(balancerDescription)) {
keyToRemove = key;
}
}
if(keyToRemove !=null ) {
if(logger.isDebugEnabled()) {
logger.debug("Removing following balancer name : " + keyToRemove +"/address:"+ addr);
}
register.remove(keyToRemove);
if(sipApplicationDispatcher.getSipFactory().getLoadBalancerToUse() != null &&
sipApplicationDispatcher.getSipFactory().getLoadBalancerToUse().equals(balancerDescription)) {
sipApplicationDispatcher.getSipFactory().setLoadBalancerToUse(null);
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public boolean removeBalancer(String hostName, int sipPort, int index) {
InetAddress[] hostAddr = null;
try {
hostAddr = InetAddress.getAllByName(hostName);
} catch (UnknownHostException uhe) {
throw new IllegalArgumentException(
"HostName is not a valid host name or it doesnt exists in DNS",
uhe);
}
if (index < 0 || index >= hostAddr.length) {
throw new IllegalArgumentException(
"Index in host address array is wrong, it should be [0]<x<["
+ hostAddr.length + "] and it is [" + index + "]");
}
InetAddress address = hostAddr[index];
return this.removeBalancer(address.getHostAddress(), sipPort);
}
private ArrayList<SIPNode> getConnectorsAsSIPNode() {
ArrayList<SIPNode> info = new ArrayList<SIPNode>();
// Gathering info about server' sip listening points
for (Connector connector : connectors) {
ProtocolHandler protocolHandler = connector.getProtocolHandler();
if(protocolHandler instanceof SipProtocolHandler) {
SipProtocolHandler sipProtocolHandler = (SipProtocolHandler) protocolHandler;
String address = sipProtocolHandler.getIpAddress();
// From Vladimir: for some reason I get "localhost" here instead of IP and this confiuses the LB
if(address.equals("localhost")) address = "127.0.0.1";
int port = sipProtocolHandler.getPort();
String transport = sipProtocolHandler.getSignalingTransport();
String[] transports = new String[] {transport};
String hostName = null;
try {
InetAddress[] aArray = InetAddress
.getAllByName(address);
if (aArray != null && aArray.length > 0) {
// Damn it, which one we should pick?
hostName = aArray[0].getCanonicalHostName();
}
} catch (UnknownHostException e) {
logger.error("An exception occurred while trying to retrieve the hostname of a sip connector", e);
}
Engine e = null;
for (Container c = connector.getContainer(); e == null && c != null; c = c.getParent())
{
if (c != null && c instanceof Engine)
{
e = (Engine) c;
}
}
String jvmRoute = null;
if(e != null) {
jvmRoute = e.getJvmRoute();
}
SIPNode node = new SIPNode(hostName, address, port,
transports, jvmRoute);
info.add(node);
}
}
return info;
}
/**
* @param info
*/
private void sendKeepAliveToBalancers(ArrayList<SIPNode> info) {
for(BalancerDescription balancerDescription:new HashSet<BalancerDescription>(register.values())) {
try {
Registry registry = LocateRegistry.getRegistry(balancerDescription.getAddress().getHostAddress(),2000);
NodeRegisterRMIStub reg=(NodeRegisterRMIStub) registry.lookup("SIPBalancer");
reg.handlePing(info);
- displayBalancerWarining = true;
+ displayBalancerWarning = true;
if(displayBalancerFound) {
logger.info("SIP Load Balancer Found!");
displayBalancerFound = false;
}
} catch (Exception e) {
- if(displayBalancerWarining) {
+ if(displayBalancerWarning) {
logger.warn("Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running.");
- logger.error("Cannot access the SIP load balancer RMI registry: " , e);
- displayBalancerWarining = false;
+// logger.error("Cannot access the SIP load balancer RMI registry: " , e);
+ displayBalancerWarning = false;
}
displayBalancerFound = true;
}
}
if(logger.isDebugEnabled()) {
logger.debug("Finished gathering");
logger.debug("Gathered info[" + info + "]");
}
}
/**
* @param info
*/
public void sendSwitchoverInstruction(String fromJvmRoute, String toJvmRoute) {
logger.info("switching over from " + fromJvmRoute + " to " + toJvmRoute);
if(fromJvmRoute == null || toJvmRoute == null) {
return;
}
for(BalancerDescription balancerDescription:new HashSet<BalancerDescription>(register.values())) {
try {
Registry registry = LocateRegistry.getRegistry(balancerDescription.getAddress().getHostAddress(),2000);
NodeRegisterRMIStub reg=(NodeRegisterRMIStub) registry.lookup("SIPBalancer");
reg.switchover(fromJvmRoute, toJvmRoute);
- displayBalancerWarining = true;
+ displayBalancerWarning = true;
if(displayBalancerFound) {
logger.info("SIP Load Balancer Found!");
displayBalancerFound = false;
}
} catch (Exception e) {
- if(displayBalancerWarining) {
+ if(displayBalancerWarning) {
logger.warn("Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running.");
- logger.error("Cannot access the SIP load balancer RMI registry: " , e);
- displayBalancerWarining = false;
+// logger.error("Cannot access the SIP load balancer RMI registry: " , e);
+ displayBalancerWarning = false;
}
displayBalancerFound = true;
}
}
if(logger.isDebugEnabled()) {
logger.debug("Finished gathering");
logger.debug("Gathered info[" + info + "]");
}
}
/**
* @param info
*/
private void removeNodesFromBalancers(ArrayList<SIPNode> info) {
for(BalancerDescription balancerDescription:new HashSet<BalancerDescription>(register.values())) {
try {
Registry registry = LocateRegistry.getRegistry(balancerDescription.getAddress().getHostAddress(),2000);
NodeRegisterRMIStub reg=(NodeRegisterRMIStub) registry.lookup("SIPBalancer");
reg.forceRemoval(info);
- displayBalancerWarining = true;
+ displayBalancerWarning = true;
if(displayBalancerFound) {
logger.info("SIP Load Balancer Found!");
displayBalancerFound = false;
}
} catch (Exception e) {
- if(displayBalancerWarining) {
+ if(displayBalancerWarning) {
logger.warn("Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running.");
- logger.error("Cannot access the SIP load balancer RMI registry: " , e);
- displayBalancerWarining = false;
+// logger.error("Cannot access the SIP load balancer RMI registry: " , e);
+ displayBalancerWarning = false;
}
displayBalancerFound = true;
}
}
if(logger.isDebugEnabled()) {
logger.debug("Finished gathering");
logger.debug("Gathered info[" + info + "]");
}
}
/**
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
class BalancerPingTimerTask extends TimerTask {
@SuppressWarnings("unchecked")
@Override
public void run() {
if(logger.isDebugEnabled()) {
logger.debug("Start");
}
ArrayList<SIPNode> info = getConnectorsAsSIPNode();
sendKeepAliveToBalancers(info);
}
}
/**
* @param balancers the balancers to set
*/
public void setBalancers(String balancers) {
this.balancers = balancers;
}
}
| false | false | null | null |
diff --git a/main/src/main/src/com/google/android/apps/dashclock/calendar/CalendarSettingsActivity.java b/main/src/main/src/com/google/android/apps/dashclock/calendar/CalendarSettingsActivity.java
index 9b62544..d7ed355 100644
--- a/main/src/main/src/com/google/android/apps/dashclock/calendar/CalendarSettingsActivity.java
+++ b/main/src/main/src/com/google/android/apps/dashclock/calendar/CalendarSettingsActivity.java
@@ -1,92 +1,92 @@
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.calendar;
import com.google.android.apps.dashclock.configuration.BaseSettingsActivity;
import net.nurik.roman.dashclock.R;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.Pair;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CalendarSettingsActivity extends BaseSettingsActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setIcon(R.drawable.ic_extension_calendar);
}
@Override
protected void setupSimplePreferencesScreen() {
// Add 'general' preferences.
addPreferencesFromResource(R.xml.pref_calendar);
bindSelectedCalendarsPreference();
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference(CalendarExtension.PREF_LOOK_AHEAD_HOURS));
}
private void bindSelectedCalendarsPreference() {
CalendarSelectionPreference preference = (CalendarSelectionPreference) findPreference(
CalendarExtension.PREF_SELECTED_CALENDARS);
final List<Pair<String, Boolean>> allCalendars = CalendarExtension.getAllCalendars(this);
Set<String> allVisibleCalendarsSet = new HashSet<String>();
for (Pair<String, Boolean> pair : allCalendars) {
if (pair.second) {
allVisibleCalendarsSet.add(pair.first);
}
}
Preference.OnPreferenceChangeListener calendarsChangeListener
= new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
int numSelected = 0;
int numTotal = allCalendars.size();
try {
//noinspection check,unchecked
Set<String> selectedCalendars = (Set<String>) value;
if (selectedCalendars != null) {
numSelected = selectedCalendars.size();
}
} catch (ClassCastException ignored) {
}
preference.setSummary(getResources().getQuantityString(
R.plurals.pref_calendar_selected_summary_template,
- numTotal, numSelected, numTotal));
+ numSelected, numSelected, numTotal));
return true;
}
};
preference.setOnPreferenceChangeListener(calendarsChangeListener);
calendarsChangeListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(this)
.getStringSet(preference.getKey(), allVisibleCalendarsSet));
}
}
diff --git a/main/src/main/src/com/google/android/apps/dashclock/gmail/GmailSettingsActivity.java b/main/src/main/src/com/google/android/apps/dashclock/gmail/GmailSettingsActivity.java
index 81f41a7..ef9592b 100644
--- a/main/src/main/src/com/google/android/apps/dashclock/gmail/GmailSettingsActivity.java
+++ b/main/src/main/src/com/google/android/apps/dashclock/gmail/GmailSettingsActivity.java
@@ -1,97 +1,97 @@
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.gmail;
import com.google.android.apps.dashclock.configuration.BaseSettingsActivity;
import net.nurik.roman.dashclock.R;
import android.os.Bundle;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class GmailSettingsActivity extends BaseSettingsActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setIcon(R.drawable.ic_extension_gmail);
}
@Override
protected void setupSimplePreferencesScreen() {
// In the simplified UI, fragments are not used at all and we instead
// use the older PreferenceActivity APIs.
// Add 'general' preferences.
addPreferencesFromResource(R.xml.pref_gmail);
addAccountsPreference();
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference(GmailExtension.PREF_LABEL));
}
private void addAccountsPreference() {
final String[] accounts = GmailExtension.getAllAccountNames(this);
Set<String> allAccountsSet = new HashSet<String>();
allAccountsSet.addAll(Arrays.asList(accounts));
MultiSelectListPreference accountsPreference = new MultiSelectListPreference(this);
accountsPreference.setKey(GmailExtension.PREF_ACCOUNTS);
accountsPreference.setTitle(R.string.pref_gmail_accounts_title);
accountsPreference.setEntries(accounts);
accountsPreference.setEntryValues(accounts);
accountsPreference.setDefaultValue(allAccountsSet);
getPreferenceScreen().addPreference(accountsPreference);
Preference.OnPreferenceChangeListener accountsChangeListener
= new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
int numSelected = 0;
int numTotal = accounts.length;
try {
//noinspection unchecked
Set<String> selectedAccounts = (Set<String>) value;
if (selectedAccounts != null) {
numSelected = selectedAccounts.size();
}
} catch (ClassCastException ignored) {
}
preference.setSummary(getResources().getQuantityString(
R.plurals.pref_gmail_accounts_summary_template,
- numTotal, numSelected, numTotal));
+ numSelected, numSelected, numTotal));
return true;
}
};
accountsPreference.setOnPreferenceChangeListener(accountsChangeListener);
accountsChangeListener.onPreferenceChange(accountsPreference,
PreferenceManager
.getDefaultSharedPreferences(this)
.getStringSet(accountsPreference.getKey(), allAccountsSet));
}
}
| false | false | null | null |
diff --git a/core/src/main/java/quickfix/FieldType.java b/core/src/main/java/quickfix/FieldType.java
index c8cb3a3..32dc654 100644
--- a/core/src/main/java/quickfix/FieldType.java
+++ b/core/src/main/java/quickfix/FieldType.java
@@ -1,100 +1,101 @@
/*******************************************************************************
* Copyright (c) quickfixengine.org All rights reserved.
*
* This file is part of the QuickFIX FIX Engine
*
* This file may be distributed under the terms of the quickfixengine.org
* license as defined by quickfixengine.org and appearing in the file
* LICENSE included in the packaging of this file.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
* THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* See http://www.quickfixengine.org/LICENSE for licensing information.
*
* Contact [email protected] if any conditions of this licensing
* are not clear to you.
******************************************************************************/
package quickfix;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
+import java.util.Date;
/**
* A field type enum class.
*/
public class FieldType {
private int ordinal;
private String name;
private Class javaType;
private static HashMap values = new HashMap();
private static ArrayList ordinalToValue = new ArrayList();
private FieldType(String name) {
this(name, String.class);
}
private FieldType(String name, Class javaType) {
this.javaType = javaType;
this.name = name;
ordinal = ordinalToValue.size();
ordinalToValue.add(this);
values.put(name, this);
}
public String getName() {
return name;
}
public int getOrdinal() {
return ordinal;
}
public Class getJavaType() {
return javaType;
}
public static FieldType fromOrdinal(int ordinal) {
if (ordinal < 0 || ordinal >= ordinalToValue.size()) {
throw new RuntimeError("invalid field type ordinal: " + ordinal);
}
return (FieldType) ordinalToValue.get(ordinal);
}
public static FieldType fromName(String fixVersion, String name) {
FieldType type = (FieldType) values.get(name);
return type != null ? type : FieldType.Unknown;
}
public final static FieldType Unknown = new FieldType("UNKNOWN");
public final static FieldType String = new FieldType("STRING");
public final static FieldType Char = new FieldType("CHAR");
public final static FieldType Price = new FieldType("PRICE", Double.class);
public final static FieldType Int = new FieldType("INT", Integer.class);
public final static FieldType Amt = new FieldType("AMT", Double.class);
public final static FieldType Qty = new FieldType("QTY", Double.class);
public final static FieldType Currency = new FieldType("CURRENCY");
public final static FieldType MultipleValueString = new FieldType("MULTIPLEVALUESTRING");
public final static FieldType Exchange = new FieldType("EXCHANGE");
- public final static FieldType UtcTimeStamp = new FieldType("UTCTIMESTAMP", Calendar.class);
+ public final static FieldType UtcTimeStamp = new FieldType("UTCTIMESTAMP", Date.class);
public final static FieldType Boolean = new FieldType("BOOLEAN", Boolean.class);
public final static FieldType LocalMktDate = new FieldType("LOCALMKTDATE");
public final static FieldType Data = new FieldType("DATA");
public final static FieldType Float = new FieldType("FLOAT", Double.class);
public final static FieldType PriceOffset = new FieldType("PRICEOFFSET", Double.class);
public final static FieldType MonthYear = new FieldType("MONTHYEAR");
public final static FieldType DayOfMonth = new FieldType("DAYOFMONTH", Integer.class);
- public final static FieldType UtcDateOnly = new FieldType("UTCDATEONLY", Calendar.class);
- public final static FieldType UtcDate = new FieldType("UTCDATEONLY", Calendar.class);
- public final static FieldType UtcTimeOnly = new FieldType("UTCTIMEONLY", Calendar.class);
+ public final static FieldType UtcDateOnly = new FieldType("UTCDATEONLY", Date.class);
+ public final static FieldType UtcDate = new FieldType("UTCDATEONLY", Date.class);
+ public final static FieldType UtcTimeOnly = new FieldType("UTCTIMEONLY", Date.class);
public final static FieldType Time = new FieldType("TIME");
public final static FieldType NumInGroup = new FieldType("NUMINGROUP", Integer.class);
public final static FieldType Percentage = new FieldType("PERCENTAGE", Double.class);
public final static FieldType SeqNum = new FieldType("SEQNUM", Integer.class);
public final static FieldType Length = new FieldType("LENGTH", Integer.class);
public final static FieldType Country = new FieldType("COUNTRY");
}
\ No newline at end of file
| false | false | null | null |
diff --git a/activejdbc/src/main/java/activejdbc/Errors.java b/activejdbc/src/main/java/activejdbc/Errors.java
index a85b9067..6bcb89d2 100644
--- a/activejdbc/src/main/java/activejdbc/Errors.java
+++ b/activejdbc/src/main/java/activejdbc/Errors.java
@@ -1,188 +1,188 @@
/*
Copyright 2009-2010 Igor Polevoy
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 activejdbc;
import activejdbc.validation.Validator;
import activejdbc.validation.ValidatorAdapter;
import java.util.*;
/**
* Collection of error messages generated by validation process.
*
* @author Igor Polevoy
* @see {@link activejdbc.Messages}
*/
public class Errors implements Map<String, String> {
private Locale locale;
private Map<String, Validator> validators = new HashMap<String, Validator>();
/**
* Adds a validator whose validation failed.
*
* @param attributeName name of attribute for which validation failed.
* @param validator validator.
*/
protected void addValidator(String attributeName, Validator validator){
validators.put(attributeName, validator);
}
/**
* Sets a locale on this instance. All messages returned from {@link #get(Object)}
* methods will be returned according to rules of Java Resource Bundles.
*
* @param locale locale instance to configure this object.
*/
public void setLocale(Locale locale) {
this.locale = locale;
}
/**
* Provides a message from a resource bundle <code>activejdbc_messages</code>.
* If an there was no validation error generated for the requested attribute, returns null.
*
* @param attributeName name of attribute in error.
* @return a message from a resource bundle <code>activejdbc_messages</code> as configured in a corresponding
* validator. If an there was no validation error generated for the requested attribute, returns null.
*/
public String get(Object attributeName) {
if(attributeName == null) throw new NullPointerException("attributeName cannot be null");
Validator v = validators.get(attributeName);
return v == null? null:v.formatMessage(locale);
}
/**
* Provides a message from the resource bundle <code>activejdbc_messages</code> which is merged
* with parameters. This methods expects the message in the resource bundle to be parametrized.
* This message is configured for a validator using a Fluent Interface when declaring a validator:
* <pre>
public class Temperature extends Model {
static{
validateRange("temp", 0, 100).message("temperature cannot be less than {0} or more than {1}");
}
}
* </pre>
*
* @param attributeName name of attribute in error.
* @param params list of parameters for a message. The order of parameters in this list will correspond to the
* numeric order in the parameters listed in the message and has nothing to do with a physical order. This means
* that the 0th parameter in the list will correspond to <code>{0}</code>, 1st to <code>{1}</code> and so on.
* @return a message from the resource bundle <code>activejdbc_messages</code> with default locale, which is merged
* with parameters.
*/
public String get(Object attributeName, Object... params) {
if (attributeName == null) throw new NullPointerException("attributeName cannot be null");
return validators.get(attributeName).formatMessage(locale, params);
}
public int size() {
return validators.size();
}
public boolean isEmpty() {
return validators.isEmpty();
}
public boolean containsKey(Object key) {
return validators.containsKey(key);
}
public boolean containsValue(Object value) {
return validators.containsValue(value);
}
class NopValidator extends ValidatorAdapter {
@Override
public void validate(Model m) {}
}
public String put(String key, String value) {
NopValidator nv = new NopValidator();
nv.setMessage(value);
Validator v = validators.put(key, nv);
return v == null? null:v.formatMessage(null);
}
public String remove(Object key) {
throw new UnsupportedOperationException();
}
public void putAll(Map<? extends String, ? extends String> m) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
public Set<String> keySet() {
return validators.keySet();
}
public Collection<String> values() {
List<String> messageList = new ArrayList<String>();
- for(Object v: validators.entrySet()){
- messageList.add(((Validator)v).formatMessage(locale));
+ for(java.util.Map.Entry<String, Validator> v: validators.entrySet()){
+ messageList.add(((Validator)v.getValue()).formatMessage(locale));
}
return messageList;
}
class ErrorEntry implements Entry{
private String key, value;
ErrorEntry(String key, String value) {
this.key = key;
this.value = value;
}
public Object getKey() {
return key;
}
public Object getValue() {
return value;
}
public Object setValue(Object value) {
throw new UnsupportedOperationException();
}
}
public Set<Entry<String, String>> entrySet() {
Set<Entry<String, String>> entries = new LinkedHashSet<Entry<String, String>>();
for(Object key: validators.keySet()){
String value = validators.get(key).formatMessage(locale);
entries.add(new ErrorEntry(key.toString(), value));
}
return entries;
}
@Override
public String toString() {
String res = "{ ";
for(Object key: validators.keySet()){
res += key + "=<" +validators.get(key).formatMessage(null) + "> ";
}
res += "}";
return res;
}
}
diff --git a/activejdbc/src/test/java/activejdbc/ErrorsTest.java b/activejdbc/src/test/java/activejdbc/ErrorsTest.java
new file mode 100644
index 00000000..c7b872de
--- /dev/null
+++ b/activejdbc/src/test/java/activejdbc/ErrorsTest.java
@@ -0,0 +1,29 @@
+package activejdbc;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+import activejdbc.validation.AttributePresenceValidator;
+
+public class ErrorsTest {
+
+ Errors errors;
+
+ @Before
+ public void before() {
+ errors = new Errors();
+ errors.addValidator("name", new AttributePresenceValidator("name"));
+ errors.addValidator("description", new AttributePresenceValidator("description"));
+ }
+
+ @Test
+ public void shouldReturnCollectionsWithAllValuesOfTheErrors() {
+ Collection<String> expected = new ArrayList<String>(Arrays.asList("value is missing","value is missing"));
+ assertEquals(expected, errors.values());
+ }
+}
| false | false | null | null |
diff --git a/src/java/fedora/server/BasicServer.java b/src/java/fedora/server/BasicServer.java
index ec3a2bd18..8de72e0ec 100755
--- a/src/java/fedora/server/BasicServer.java
+++ b/src/java/fedora/server/BasicServer.java
@@ -1,41 +1,41 @@
package fedora.server;
import fedora.server.errors.ServerInitializationException;
import fedora.server.errors.ServerShutdownException;
import fedora.server.errors.ModuleInitializationException;
import fedora.server.errors.ModuleShutdownException;
import fedora.server.storage.DOManager;
import java.io.IOException;
import java.io.File;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class BasicServer
extends Server {
public BasicServer(NodeList configNodes, File fedoraHomeDir)
throws ServerInitializationException,
ModuleInitializationException {
super(configNodes, fedoraHomeDir);
}
/**
* Gets the names of the roles that are required to be fulfilled by
* modules specified in this server's configuration file.
*
* @returns String[] The roles.
*/
public String[] getRequiredModuleRoles() {
- return new String[] {Server.DOMANAGER_CLASSNAME};
+ return new String[] {Server.DOMANAGER_CLASS};
}
public DOManager getManager(String name) {
return null;
}
public String getHelp() {
return "This can be configured such and such a way...etc..";
}
}
| true | false | null | null |
diff --git a/hazelcast/src/test/java/com/hazelcast/config/TopicConfigTest.java b/hazelcast/src/test/java/com/hazelcast/config/TopicConfigTest.java
index 2c6e003570..2593e5c470 100644
--- a/hazelcast/src/test/java/com/hazelcast/config/TopicConfigTest.java
+++ b/hazelcast/src/test/java/com/hazelcast/config/TopicConfigTest.java
@@ -1,71 +1,71 @@
/*
* Copyright (c) 2008-2013, Hazelcast, 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.hazelcast.config;
import com.hazelcast.test.HazelcastJUnit4ClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
*
*/
@RunWith(HazelcastJUnit4ClassRunner.class)
@Category(ParallelTest.class)
public class TopicConfigTest {
/**
* Test method for {@link com.hazelcast.config.TopicConfig#getName()}.
*/
@Test
public void testGetName() {
TopicConfig topicConfig = new TopicConfig();
assertNull(topicConfig.getName());
}
/**
* Test method for {@link com.hazelcast.config.TopicConfig#setName(java.lang.String)}.
*/
@Test
public void testSetName() {
TopicConfig topicConfig = new TopicConfig().setName("test");
assertTrue("test".equals(topicConfig.getName()));
}
/**
* Test method for {@link com.hazelcast.config.TopicConfig#isGlobalOrderingEnabled()}.
*/
@Test
public void testIsGlobalOrderingEnabled() {
TopicConfig topicConfig = new TopicConfig();
- assertTrue(topicConfig.isGlobalOrderingEnabled());
+ assertFalse(topicConfig.isGlobalOrderingEnabled());
}
/**
* Test method for {@link com.hazelcast.config.TopicConfig#setGlobalOrderingEnabled(boolean)}.
*/
@Test
public void testSetGlobalOrderingEnabled() {
- TopicConfig topicConfig = new TopicConfig().setGlobalOrderingEnabled(false);
- assertFalse(topicConfig.isGlobalOrderingEnabled());
+ TopicConfig topicConfig = new TopicConfig().setGlobalOrderingEnabled(true);
+ assertTrue(topicConfig.isGlobalOrderingEnabled());
}
}
| false | false | null | null |
diff --git a/core/src/main/java/hudson/model/ExternalJob.java b/core/src/main/java/hudson/model/ExternalJob.java
index 4f9b1f1..1fe7092 100644
--- a/core/src/main/java/hudson/model/ExternalJob.java
+++ b/core/src/main/java/hudson/model/ExternalJob.java
@@ -1,114 +1,128 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, id:cactusman
*
* 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 hudson.model;
import hudson.model.RunMap.Constructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Job that runs outside Hudson whose result is submitted to Hudson
* (either via web interface, or simply by placing files on the file system,
* for compatibility.)
*
* @author Kohsuke Kawaguchi
*/
public class ExternalJob extends ViewJob<ExternalJob,ExternalRun> implements TopLevelItem {
public ExternalJob(String name) {
super(Hudson.getInstance(),name);
}
@Override
public Hudson getParent() {
return (Hudson)super.getParent();
}
@Override
protected void reload() {
this.runs.load(this,new Constructor<ExternalRun>() {
public ExternalRun create(File dir) throws IOException {
return new ExternalRun(ExternalJob.this,dir);
}
});
}
+ // keep track of the previous time we started a build
+ private transient long lastBuildStartTime;
+
/**
* Creates a new build of this project for immediate execution.
*
* Needs to be synchronized so that two {@link #newBuild()} invocations serialize each other.
*/
- public ExternalRun newBuild() throws IOException {
+ public synchronized ExternalRun newBuild() throws IOException {
+ // make sure we don't start two builds in the same second
+ // so the build directories will be different too
+ long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
+ if (timeSinceLast < 1000) {
+ try {
+ Thread.sleep(1000 - timeSinceLast);
+ } catch (InterruptedException e) {
+ }
+ }
+ lastBuildStartTime = System.currentTimeMillis();
+
ExternalRun run = new ExternalRun(this);
runs.put(run);
return run;
}
/**
* Used to check if this is an external job and ready to accept a build result.
*/
public void doAcceptBuildResult( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rsp.setStatus(HttpServletResponse.SC_OK);
}
/**
* Used to post the build result from a remote machine.
*/
public void doPostBuildResult( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(AbstractProject.BUILD);
ExternalRun run = newBuild();
run.acceptRemoteSubmission(req.getReader());
rsp.setStatus(HttpServletResponse.SC_OK);
}
private static final Logger logger = Logger.getLogger(ExternalJob.class.getName());
public TopLevelItemDescriptor getDescriptor() {
return DESCRIPTOR;
}
public static final TopLevelItemDescriptor DESCRIPTOR = new DescriptorImpl();
@Override
public String getPronoun() {
return Messages.ExternalJob_Pronoun();
}
public static final class DescriptorImpl extends TopLevelItemDescriptor {
public String getDisplayName() {
return Messages.ExternalJob_DisplayName();
}
public ExternalJob newInstance(String name) {
return new ExternalJob(name);
}
}
}
| false | false | null | null |
diff --git a/OsmAnd/src/net/osmand/plus/activities/LiveMonitoringHelper.java b/OsmAnd/src/net/osmand/plus/activities/LiveMonitoringHelper.java
index 88ccaa0e..51251342 100644
--- a/OsmAnd/src/net/osmand/plus/activities/LiveMonitoringHelper.java
+++ b/OsmAnd/src/net/osmand/plus/activities/LiveMonitoringHelper.java
@@ -1,125 +1,127 @@
package net.osmand.plus.activities;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import net.osmand.LogUtil;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import org.apache.commons.logging.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.content.Context;
import android.os.AsyncTask;
public class LiveMonitoringHelper {
protected Context ctx;
private OsmandSettings settings;
private long lastTimeUpdated;
private final static Log log = LogUtil.getLog(LiveMonitoringHelper.class);
public LiveMonitoringHelper(Context ctx){
this.ctx = ctx;
settings = ((OsmandApplication) ctx.getApplicationContext()).getSettings();
}
public boolean isLiveMonitoringEnabled(){
return settings.LIVE_MONITORING.get();
}
public void insertData(double lat, double lon, double alt, double speed, double hdop, long time, OsmandSettings settings){
- if (time - lastTimeUpdated > settings.LIVE_MONITORING_INTERVAL.get() * 1000) {
+ //* 1000 in next line seems to be wrong with new IntervalChooseDialog
+ //if (time - lastTimeUpdated > settings.LIVE_MONITORING_INTERVAL.get() * 1000) {
+ if (time - lastTimeUpdated > settings.LIVE_MONITORING_INTERVAL.get()) {
LiveMonitoringData data = new LiveMonitoringData((float)lat, (float)lon,(float) alt,(float) speed,(float) hdop, time );
new LiveSender().execute(data);
lastTimeUpdated = time;
}
}
private static class LiveMonitoringData {
private final float lat;
private final float lon;
private final float alt;
private final float speed;
private final float hdop;
private final long time;
public LiveMonitoringData(float lat, float lon, float alt, float speed, float hdop, long time) {
this.lat = lat;
this.lon = lon;
this.alt = alt;
this.speed = speed;
this.hdop = hdop;
this.time = time;
}
}
private class LiveSender extends AsyncTask<LiveMonitoringData, Void, Void> {
@Override
protected Void doInBackground(LiveMonitoringData... params) {
for(LiveMonitoringData d : params){
sendData(d);
}
return null;
}
}
public void sendData(LiveMonitoringData data) {
String url = MessageFormat.format(settings.LIVE_MONITORING_URL.get(), data.lat+"", data.lon+"",
data.time+"", data.hdop+"", data.alt+"", data.speed+"");
try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 15000);
DefaultHttpClient httpclient = new DefaultHttpClient(params);
HttpRequestBase method = new HttpGet(url);
log.info("Monitor " + url);
HttpResponse response = httpclient.execute(method);
if(response.getStatusLine() == null ||
response.getStatusLine().getStatusCode() != 200){
String msg;
if(response.getStatusLine() != null){
msg = ctx.getString(R.string.failed_op); //$NON-NLS-1$
} else {
msg = response.getStatusLine().getStatusCode() + " : " + //$NON-NLS-1$//$NON-NLS-2$
response.getStatusLine().getReasonPhrase();
}
log.error("Error sending monitor request request : " + msg);
} else {
InputStream is = response.getEntity().getContent();
StringBuilder responseBody = new StringBuilder();
if (is != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); //$NON-NLS-1$
String s;
while ((s = in.readLine()) != null) {
responseBody.append(s);
responseBody.append("\n"); //$NON-NLS-1$
}
is.close();
}
httpclient.getConnectionManager().shutdown();
log.info("Montior response : " + responseBody.toString());
}
} catch (Exception e) {
log.error("Failed connect to " + url, e);
}
}
}
diff --git a/OsmAnd/src/net/osmand/plus/activities/SavingTrackHelper.java b/OsmAnd/src/net/osmand/plus/activities/SavingTrackHelper.java
index 31eb1bbd..599fc806 100644
--- a/OsmAnd/src/net/osmand/plus/activities/SavingTrackHelper.java
+++ b/OsmAnd/src/net/osmand/plus/activities/SavingTrackHelper.java
@@ -1,331 +1,333 @@
package net.osmand.plus.activities;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.osmand.GPXUtilities;
import net.osmand.GPXUtilities.GPXFile;
import net.osmand.GPXUtilities.Track;
import net.osmand.GPXUtilities.TrkSegment;
import net.osmand.GPXUtilities.WptPt;
import net.osmand.LogUtil;
import net.osmand.osm.LatLon;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.ResourceManager;
import org.apache.commons.logging.Log;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.text.format.DateFormat;
public class SavingTrackHelper extends SQLiteOpenHelper {
public final static String DATABASE_NAME = "tracks"; //$NON-NLS-1$
public final static int DATABASE_VERSION = 3;
public final static String TRACK_NAME = "track"; //$NON-NLS-1$
public final static String TRACK_COL_DATE = "date"; //$NON-NLS-1$
public final static String TRACK_COL_LAT = "lat"; //$NON-NLS-1$
public final static String TRACK_COL_LON = "lon"; //$NON-NLS-1$
public final static String TRACK_COL_ALTITUDE = "altitude"; //$NON-NLS-1$
public final static String TRACK_COL_SPEED = "speed"; //$NON-NLS-1$
public final static String TRACK_COL_HDOP = "hdop"; //$NON-NLS-1$
public final static String POINT_NAME = "point"; //$NON-NLS-1$
public final static String POINT_COL_DATE = "date"; //$NON-NLS-1$
public final static String POINT_COL_LAT = "lat"; //$NON-NLS-1$
public final static String POINT_COL_LON = "lon"; //$NON-NLS-1$
public final static String POINT_COL_DESCRIPTION = "description"; //$NON-NLS-1$
public final static Log log = LogUtil.getLog(SavingTrackHelper.class);
private String updateScript;
private String updatePointsScript;
private long lastTimeUpdated = 0;
private final OsmandApplication ctx;
private LatLon lastPoint;
private float distance = 0;
public SavingTrackHelper(OsmandApplication ctx){
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.ctx = ctx;
updateScript = "INSERT INTO " + TRACK_NAME +
" (" +TRACK_COL_LAT +", " +TRACK_COL_LON+", " +TRACK_COL_ALTITUDE+", " +TRACK_COL_SPEED
+", " +TRACK_COL_HDOP+", " +TRACK_COL_DATE+ ")" +
" VALUES (?, ?, ?, ?, ?, ?)"; //$NON-NLS-1$ //$NON-NLS-2$
updatePointsScript = "INSERT INTO " + POINT_NAME + " VALUES (?, ?, ?, ?)"; //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
public void onCreate(SQLiteDatabase db) {
createTableForTrack(db);
createTableForPoints(db);
}
private void createTableForTrack(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TRACK_NAME+ " ("+TRACK_COL_LAT +" double, " + TRACK_COL_LON+" double, " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ TRACK_COL_ALTITUDE+" double, " + TRACK_COL_SPEED+" double, " //$NON-NLS-1$ //$NON-NLS-2$
+ TRACK_COL_HDOP +" double, " + TRACK_COL_DATE +" long )" ); //$NON-NLS-1$ //$NON-NLS-2$
}
private void createTableForPoints(SQLiteDatabase db){
try {
db.execSQL("CREATE TABLE " + POINT_NAME+ " ("+POINT_COL_LAT +" double, " + POINT_COL_LON+" double, " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ POINT_COL_DATE+" long, " + POINT_COL_DESCRIPTION+" text)" ); //$NON-NLS-1$ //$NON-NLS-2$
} catch (RuntimeException e) {
// ignore if already exists
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion < 2){
createTableForPoints(db);
}
if(oldVersion < 3){
db.execSQL("ALTER TABLE " + TRACK_NAME + " ADD " + TRACK_COL_HDOP + " double");
}
}
public boolean hasDataToSave() {
SQLiteDatabase db = getWritableDatabase();
if (db != null) {
Cursor q = db.query(false, TRACK_NAME, new String[0], null, null, null, null, null, null);
boolean has = q.moveToFirst();
q.close();
if (has) {
return true;
}
q = db.query(false, POINT_NAME, new String[0], null, null, null, null, null, null);
has = q.moveToFirst();
q.close();
if (has) {
return true;
}
}
return false;
}
/**
* @return warnings
*/
public List<String> saveDataToGpx() {
List<String> warnings = new ArrayList<String>();
File dir = ((OsmandApplication) ctx.getApplicationContext()).getSettings().getExternalStorageDirectory();
if (dir.canWrite()) {
dir = new File(dir, ResourceManager.GPX_PATH);
dir.mkdirs();
if (dir.exists()) {
Map<String, GPXFile> data = collectRecordedData();
// save file
for (final String f : data.keySet()) {
File fout = new File(dir, f + ".gpx"); //$NON-NLS-1$
if (!data.get(f).isEmpty()) {
WptPt pt = data.get(f).findPointToShow();
String fileName = f + "_" + new SimpleDateFormat("HH-mm_EEE").format(new Date(pt.time)); //$NON-NLS-1$
fout = new File(dir, fileName + ".gpx"); //$NON-NLS-1$
int ind = 1;
while (fout.exists()) {
fout = new File(dir, fileName + "_" + (++ind) + ".gpx"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
String warn = GPXUtilities.writeGpxFile(fout, data.get(f), ctx);
if (warn != null) {
warnings.add(warn);
return warnings;
}
}
}
}
SQLiteDatabase db = getWritableDatabase();
if (db != null && warnings.isEmpty()) {
// remove all from db
db.execSQL("DELETE FROM " + TRACK_NAME + " WHERE " + TRACK_COL_DATE + " <= ?", new Object[] { System.currentTimeMillis() }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
db.execSQL("DELETE FROM " + POINT_NAME + " WHERE " + POINT_COL_DATE + " <= ?", new Object[] { System.currentTimeMillis() }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// delete all
// db.execSQL("DELETE FROM " + TRACK_NAME + " WHERE 1 = 1", new Object[] { }); //$NON-NLS-1$ //$NON-NLS-2$
// db.execSQL("DELETE FROM " + POINT_NAME + " WHERE 1 = 1", new Object[] { }); //$NON-NLS-1$ //$NON-NLS-2$
}
return warnings;
}
public Map<String, GPXFile> collectRecordedData() {
Map<String, GPXFile> data = new LinkedHashMap<String, GPXFile>();
SQLiteDatabase db = getReadableDatabase();
if(db != null) {
collectDBPoints(db, data);
collectDBTracks(db, data);
}
return data;
}
private void collectDBPoints(SQLiteDatabase db, Map<String, GPXFile> dataTracks) {
Cursor query = db.rawQuery("SELECT " + POINT_COL_LAT + "," + POINT_COL_LON + "," + POINT_COL_DATE + "," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ POINT_COL_DESCRIPTION + " FROM " + POINT_NAME+" ORDER BY " + TRACK_COL_DATE +" ASC", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (query.moveToFirst()) {
do {
WptPt pt = new WptPt();
pt.lat = query.getDouble(0);
pt.lon = query.getDouble(1);
long time = query.getLong(2);
pt.time = time;
pt.name = query.getString(3);
String date = DateFormat.format("yyyy-MM-dd", time).toString(); //$NON-NLS-1$
GPXFile gpx;
if (dataTracks.containsKey(date)) {
gpx = dataTracks.get(date);
} else {
gpx = new GPXFile();
dataTracks.put(date, gpx);
}
gpx.points.add(pt);
} while (query.moveToNext());
}
query.close();
}
private void collectDBTracks(SQLiteDatabase db, Map<String, GPXFile> dataTracks) {
Cursor query = db.rawQuery("SELECT " + TRACK_COL_LAT + "," + TRACK_COL_LON + "," + TRACK_COL_ALTITUDE + "," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ TRACK_COL_SPEED + "," + TRACK_COL_HDOP + "," + TRACK_COL_DATE + " FROM " + TRACK_NAME +" ORDER BY " + TRACK_COL_DATE +" ASC", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
long previousTime = 0;
long previousInterval = 0;
TrkSegment segment = null;
Track track = null;
if (query.moveToFirst()) {
do {
WptPt pt = new WptPt();
pt.lat = query.getDouble(0);
pt.lon = query.getDouble(1);
pt.ele = query.getDouble(2);
pt.speed = query.getDouble(3);
pt.hdop = query.getDouble(4);
long time = query.getLong(5);
pt.time = time;
long currentInterval = Math.abs(time - previousTime);
boolean newInterval = pt.lat == 0 && pt.lon == 0;
if (track != null && !newInterval && (currentInterval < 6 * 60 * 1000 || currentInterval < 10 * previousInterval)) {
// 6 minute - same segment
segment.points.add(pt);
} else if (track != null && currentInterval < 2 * 60 * 60 * 1000) {
// 2 hour - same track
segment = new TrkSegment();
if(!newInterval) {
segment.points.add(pt);
}
track.segments.add(segment);
} else {
// check if date the same - new track otherwise new file
track = new Track();
segment = new TrkSegment();
track.segments.add(segment);
if(!newInterval) {
segment.points.add(pt);
}
String date = DateFormat.format("yyyy-MM-dd", time).toString(); //$NON-NLS-1$
if (dataTracks.containsKey(date)) {
GPXFile gpx = dataTracks.get(date);
gpx.tracks.add(track);
} else {
GPXFile file = new GPXFile();
file.tracks.add(track);
dataTracks.put(date, file);
}
}
previousInterval = currentInterval;
previousTime = time;
} while (query.moveToNext());
}
query.close();
}
public void startNewSegment() {
lastTimeUpdated = 0;
lastPoint = null;
execWithClose(updateScript, new Object[] { 0, 0, 0, 0, 0, System.currentTimeMillis()});
addTrackPoint(null, true);
}
public void insertData(double lat, double lon, double alt, double speed, double hdop, long time, OsmandSettings settings){
- if ((time - lastTimeUpdated > settings.SAVE_TRACK_INTERVAL.get() * 1000)) {
+ //* 1000 in next line seems to be wrong with new IntervalChooseDialog
+ //if (time - lastTimeUpdated > settings.SAVE_TRACK_INTERVAL.get() * 1000) {
+ if (time - lastTimeUpdated > settings.SAVE_TRACK_INTERVAL.get()) {
execWithClose(updateScript, new Object[] { lat, lon, alt, speed, hdop, time });
boolean newSegment = false;
if (lastPoint == null || (time - lastTimeUpdated) > 180 * 1000) {
lastPoint = new LatLon(lat, lon);
newSegment = true;
} else {
float[] lastInterval = new float[1];
Location.distanceBetween(lat, lon, lastPoint.getLatitude(), lastPoint.getLongitude(), lastInterval);
distance += lastInterval[0];
lastPoint = new LatLon(lat, lon);
}
lastTimeUpdated = time;
if (settings.SHOW_CURRENT_GPX_TRACK.get()) {
WptPt pt = new GPXUtilities.WptPt(lat, lon, time,
alt, speed, hdop);
addTrackPoint(pt, newSegment);
}
}
}
private void addTrackPoint(WptPt pt, boolean newSegment) {
GPXFile file = ctx.getGpxFileToDisplay();
if (file != null && ctx.getSettings().SHOW_CURRENT_GPX_TRACK.get()) {
List<List<WptPt>> points = file.processedPointsToDisplay;
if (points.size() == 0 || newSegment) {
points.add(new ArrayList<WptPt>());
}
if (pt != null) {
List<WptPt> last = points.get(points.size() - 1);
last.add(pt);
}
}
}
public void insertPointData(double lat, double lon, long time, String description) {
execWithClose(updatePointsScript, new Object[] { lat, lon, time, description });
}
private void execWithClose(String script, Object[] objects) {
SQLiteDatabase db = getWritableDatabase();
try {
if (db != null) {
db.execSQL(script, objects);
}
} finally {
if (db != null) {
db.close();
}
}
}
public float getDistance() {
return distance;
}
public long getLastTimeUpdated() {
return lastTimeUpdated;
}
}
| false | false | null | null |
diff --git a/src/test/java/ch/bind/philib/lang/ArrayUtilTest.java b/src/test/java/ch/bind/philib/lang/ArrayUtilTest.java
index a03702b..0656c41 100644
--- a/src/test/java/ch/bind/philib/lang/ArrayUtilTest.java
+++ b/src/test/java/ch/bind/philib/lang/ArrayUtilTest.java
@@ -1,447 +1,447 @@
/*
* Copyright (c) 2006-2011 Philipp Meinen <[email protected]>
*
* 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 ch.bind.philib.lang;
import static ch.bind.philib.lang.ArrayUtil.EMPTY_BYTE_ARRAY;
import static ch.bind.philib.lang.ArrayUtil.append;
import static ch.bind.philib.lang.ArrayUtil.concat;
import static ch.bind.philib.lang.ArrayUtil.contains;
import static ch.bind.philib.lang.ArrayUtil.extractBack;
import static ch.bind.philib.lang.ArrayUtil.extractFront;
import static ch.bind.philib.lang.ArrayUtil.find;
import static ch.bind.philib.lang.ArrayUtil.formatShortHex;
import static ch.bind.philib.lang.ArrayUtil.memclr;
import static ch.bind.philib.lang.ArrayUtil.pickRandom;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Random;
import org.testng.annotations.Test;
import ch.bind.philib.util.TLR;
public class ArrayUtilTest {
@Test(expectedExceptions = NullPointerException.class)
public void sourceNull() {
Object[] arr = new Object[1];
pickRandom(null, arr);
}
@Test(expectedExceptions = NullPointerException.class)
public void destinationNull() {
Object[] arr = new Object[1];
pickRandom(arr, null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
- public void sourceSmallerThenDestination() {
+ public void sourceSmallerThanDestination() {
Object[] src = new Object[1];
Object[] dst = new Object[2];
pickRandom(src, dst);
}
@Test
public void equalSize() {
final int N = 4096;
Integer[] src = new Integer[N];
Integer[] dst = new Integer[N];
boolean[] found = new boolean[N];
for (int i = 0; i < N; i++) {
src[i] = i;
}
pickRandom(src, dst);
for (int i = 0; i < N; i++) {
int v = dst[i].intValue();
assertTrue(v >= 0);
assertTrue(v < N);
assertFalse(found[v]);
found[v] = true;
}
}
@Test
public void concatNullNull() {
byte[] r = concat(null, null);
assertNotNull(r);
assertEquals(0, r.length);
}
@Test
public void concatNullEmpty() {
byte[] r = concat(null, EMPTY_BYTE_ARRAY);
assertNotNull(r);
assertEquals(0, r.length);
}
@Test
public void concatEmptyNull() {
byte[] r = concat(EMPTY_BYTE_ARRAY, null);
assertNotNull(r);
assertEquals(0, r.length);
}
@Test
public void concatEmptyEmpty() {
byte[] r = concat(EMPTY_BYTE_ARRAY, EMPTY_BYTE_ARRAY);
assertNotNull(r);
assertEquals(0, r.length);
}
@Test
public void concatNormalNull() {
byte[] a = "123".getBytes();
byte[] b = null;
byte[] c = concat(a, b);
assertNotNull(c);
assertEquals(3, c.length);
assertTrue(Arrays.equals(a, c));
}
@Test
public void concatNullNormal() {
byte[] a = null;
byte[] b = "123".getBytes();
byte[] c = concat(a, b);
assertNotNull(c);
assertEquals(3, c.length);
assertTrue(Arrays.equals(b, c));
}
@Test
public void concatNormalNormal() {
byte[] a = "123".getBytes();
byte[] b = "abc".getBytes();
byte[] c = concat(a, b);
byte[] ce = "123abc".getBytes();
assertNotNull(c);
assertEquals(6, c.length);
assertTrue(Arrays.equals(ce, c));
}
@Test
public void appendEnoughCap() {
byte[] a = "123".getBytes();
byte[] b = "abc".getBytes();
byte[] c = append(a, b, 8);
byte[] ce = "123abc".getBytes();
assertNotNull(c);
assertEquals(6, c.length);
assertTrue(Arrays.equals(ce, c));
}
@Test
public void appendCapped() {
byte[] a = "123".getBytes();
byte[] b = "abc".getBytes();
byte[] c = append(a, b, 5);
assertNotNull(c);
assertEquals(5, c.length);
assertTrue(Arrays.equals("123ab".getBytes(), c));
c = append(a, b, 4);
assertNotNull(c);
assertEquals(4, c.length);
assertTrue(Arrays.equals("123a".getBytes(), c));
c = append(a, b, 3);
assertNotNull(c);
assertEquals(3, c.length);
assertTrue(Arrays.equals("123".getBytes(), c));
c = append(a, b, 2);
assertNotNull(c);
assertEquals(2, c.length);
assertTrue(Arrays.equals("12".getBytes(), c));
c = append(a, b, 1);
assertNotNull(c);
assertEquals(1, c.length);
assertTrue(Arrays.equals("1".getBytes(), c));
c = append(a, b, 0);
assertNotNull(c);
assertEquals(0, c.length);
c = append(a, b, -1);
assertNotNull(c);
assertEquals(0, c.length);
}
@Test
public void appendNull() {
byte[] a = "123".getBytes();
byte[] b = "abc".getBytes();
byte[] c = append(null, b, 4);
assertNotNull(c);
assertEquals(3, c.length);
assertTrue(Arrays.equals(b, c));
c = append(a, null, 4);
assertNotNull(c);
assertEquals(3, c.length);
assertTrue(Arrays.equals(a, c));
}
@Test
public void testExtractBack() {
byte[] a = "abcd".getBytes();
assertEquals(extractBack(a, 0), EMPTY_BYTE_ARRAY);
assertEquals(extractBack(a, 1), "d".getBytes());
assertEquals(extractBack(a, 2), "cd".getBytes());
assertEquals(extractBack(a, 3), "bcd".getBytes());
assertEquals(extractBack(a, 4), "abcd".getBytes());
}
@Test
public void testExtractFront() {
byte[] a = "abcd".getBytes();
assertEquals(extractFront(a, 0), EMPTY_BYTE_ARRAY);
assertEquals(extractFront(a, 1), "a".getBytes());
assertEquals(extractFront(a, 2), "ab".getBytes());
assertEquals(extractFront(a, 3), "abc".getBytes());
assertEquals(extractFront(a, 4), "abcd".getBytes());
}
@Test
public void testFormatShortHexArray() {
assertEquals(formatShortHex((byte[]) null), "");
assertEquals(formatShortHex(EMPTY_BYTE_ARRAY), "");
byte[] a = "abcd".getBytes();
assertEquals(formatShortHex(a), "61626364");
}
@Test
public void testFormatShortHexArrayExtended() {
assertEquals(formatShortHex((byte[]) null, 0, 1), "");
assertEquals(formatShortHex(EMPTY_BYTE_ARRAY, 1, 2), "");
byte[] a = "abcd".getBytes();
assertEquals(formatShortHex(a, 1, 2), "6263");
assertEquals(formatShortHex(a, 1, 5555), "626364");
}
@Test
public void testFormatShortHexByteBuffer() {
assertEquals(formatShortHex((ByteBuffer) null), "");
assertEquals(formatShortHex(ByteBuffer.wrap(EMPTY_BYTE_ARRAY)), "");
byte[] a = "\u0002abcd".getBytes();
ByteBuffer arrayBb = ByteBuffer.wrap(a);
assertEquals(arrayBb.remaining(), 5);
assertEquals(formatShortHex(arrayBb), "0261626364");
assertEquals(arrayBb.remaining(), 5);
ByteBuffer directBb = ByteBuffer.allocateDirect(5);
directBb.put(a);
directBb.clear();
assertEquals(directBb.remaining(), 5);
assertEquals(formatShortHex(directBb), "0261626364");
assertEquals(directBb.remaining(), 5);
}
@Test
public void limitedFormatShortHex() {
byte[] abcd = "abcd".getBytes();
ByteBuffer bb = ByteBuffer.wrap(abcd);
String a1 = formatShortHex(bb, 8);
String b1 = formatShortHex(bb, 2);
String c1 = formatShortHex((ByteBuffer) bb.position(1), 2);
String d1 = formatShortHex((ByteBuffer) bb.position(1), 8);
String a2 = formatShortHex(abcd, 0, 8);
String b2 = formatShortHex(abcd, 0, 2);
String c2 = formatShortHex(abcd, 1, 2);
String d2 = formatShortHex(abcd, 1, 8);
assertEquals(a1, "61626364");
assertEquals(a2, "61626364");
assertEquals(b1, "6162");
assertEquals(b2, "6162");
assertEquals(c1, "6263");
assertEquals(c2, "6263");
assertEquals(d1, "626364");
assertEquals(d2, "626364");
}
@Test
public void dontCareAboutNulls() {
memclr((byte[]) null);
memclr((ByteBuffer) null);
}
@Test
public void memsetArray() {
Random rand = TLR.current();
for (int i = 0; i < 2000; i++) {
byte[] b = new byte[i];
rand.nextBytes(b);
memclr(b);
for (int j = 0; j < i; j++) {
assertTrue(b[j] == 0);
}
}
}
@Test
public void memsetArrayByteBuffer() {
Random rand = TLR.current();
for (int i = 0; i < 2000; i++) {
byte[] b = new byte[i];
rand.nextBytes(b);
ByteBuffer bb = ByteBuffer.wrap(b);
memclr(bb);
for (int j = 0; j < i; j++) {
assertTrue(b[j] == 0);
}
}
}
@Test
public void memsetDirectByteBuffer() {
Random rand = TLR.current();
for (int i = 0; i < 2000; i++) {
byte[] b = new byte[i];
rand.nextBytes(b);
ByteBuffer bb = ByteBuffer.allocateDirect(i);
bb.put(b);
bb.clear();
memclr(bb);
bb.get(b);
for (int j = 0; j < i; j++) {
assertTrue(b[j] == 0);
}
}
}
@Test
public void findAndContains() {
byte[] abc = "abc".getBytes();
byte[] xyz = "xyz".getBytes();
byte[] abcx = "abcx".getBytes();
byte[] xabc = "xabc".getBytes();
byte[] e = EMPTY_BYTE_ARRAY;
// null tests
assertEquals(find(null, null), -1);
assertEquals(find(null, abc), -1);
assertEquals(find(abc, null), -1);
assertFalse(contains(null, null));
assertFalse(contains(null, abc));
assertFalse(contains(abc, null));
// zero length tests
assertEquals(find(e, e), -1);
assertEquals(find(e, abc), -1);
assertEquals(find(abc, e), -1);
assertFalse(contains(e, e));
assertFalse(contains(e, abc));
assertFalse(contains(abc, e));
// equal length, equal content
assertEquals(find(abc, abc), 0);
assertTrue(contains(abc, abc));
// equal length, not equal content
assertEquals(find(abc, xyz), -1);
assertEquals(find(xyz, abc), -1);
assertFalse(contains(abc, xyz));
assertFalse(contains(xyz, abc));
- // search longer then data
+ // search longer than data
assertEquals(find(abc, xabc), -1);
assertFalse(contains(abc, xabc));
// different length, search ok
assertEquals(find(xabc, abc), 1);
assertEquals(find(abcx, abc), 0);
assertTrue(contains(xabc, abc));
assertTrue(contains(abcx, abc));
}
@Test
public void findMany() {
byte[] a = "abaabaaabaaaabaaaaab".getBytes();
byte[] _1 = "ab".getBytes();
byte[] _2 = "aab".getBytes();
byte[] _3 = "aaab".getBytes();
byte[] _4 = "aaaab".getBytes();
byte[] _5 = "aaaaab".getBytes();
byte[] _6 = "aaaaaab".getBytes();
assertTrue(contains(a, _1));
assertTrue(contains(a, _2));
assertTrue(contains(a, _3));
assertTrue(contains(a, _4));
assertTrue(contains(a, _5));
assertFalse(contains(a, _6));
assertEquals(find(a, _1), 0);
assertEquals(find(a, _2), 2); // +2
assertEquals(find(a, _3), 5); // +3
assertEquals(find(a, _4), 9); // +4
assertEquals(find(a, _5), 14); // +5
assertEquals(find(a, _6), -1);
assertEquals(find(a, _1, 0), 0); // ->ab
// aba->ab
assertEquals(find(a, _1, 1), 3);
assertEquals(find(a, _1, 2), 3);
assertEquals(find(a, _1, 3), 3);
// abaabaa->ab
assertEquals(find(a, _1, 4), 7);
assertEquals(find(a, _1, 5), 7);
assertEquals(find(a, _1, 6), 7);
assertEquals(find(a, _1, 7), 7);
// abaabaaabaaa->ab
assertEquals(find(a, _1, 8), 12);
assertEquals(find(a, _1, 9), 12);
assertEquals(find(a, _1, 10), 12);
assertEquals(find(a, _1, 11), 12);
assertEquals(find(a, _1, 12), 12);
// abaabaaabaaaabaaaa->ab
assertEquals(find(a, _1, 13), 18);
assertEquals(find(a, _1, 14), 18);
assertEquals(find(a, _1, 15), 18);
assertEquals(find(a, _1, 16), 18);
assertEquals(find(a, _1, 17), 18);
assertEquals(find(a, _1, 18), 18);
assertEquals(find(a, _1, 19), -1);
}
}
diff --git a/src/test/java/ch/bind/philib/lang/HashUtilTest.java b/src/test/java/ch/bind/philib/lang/HashUtilTest.java
index f359f5b..98fa991 100644
--- a/src/test/java/ch/bind/philib/lang/HashUtilTest.java
+++ b/src/test/java/ch/bind/philib/lang/HashUtilTest.java
@@ -1,264 +1,264 @@
/*
* Copyright (c) 2006-2011 Philipp Meinen <[email protected]>
*
* 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 ch.bind.philib.lang;
import static ch.bind.philib.lang.HashUtil.nextHash;
import static ch.bind.philib.lang.HashUtil.startHash;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.Test;
import ch.bind.philib.TestUtil;
public class HashUtilTest {
@Test
public void simpleByte() {
for (byte a = -128; a < 127; a++) {
for (short b = -128; b <= 127; b++) {
if (a != b) {
int h1 = nextHash(startHash(a), b);
int h2 = nextHash(startHash(b), a);
assertTrue(h1 != h2);
}
}
}
}
@Test
public void simpleChar() {
int a = nextHash(startHash('a'), 'a');
int b = nextHash(startHash('a'), 'b');
int c = nextHash(startHash('b'), 'a');
int d = nextHash(startHash('b'), 'b');
assertTrue(a != b && a != c && a != d);
assertTrue(b != c && b != d);
assertTrue(c != d);
}
@Test
public void simpleShort() {
for (short a = -500; a < 500; a++) {
for (short b = -500; b < 500; b++) {
if (a != b) {
int h1 = nextHash(startHash(a), b);
int h2 = nextHash(startHash(b), a);
assertTrue(h1 != h2);
}
}
}
}
@Test
public void simpleInt() {
for (int a = 0; a < 1000; a++) {
for (int b = 0; b < 1000; b++) {
if (a != b) {
int h1 = nextHash(startHash(a), b);
int h2 = nextHash(startHash(b), a);
assertTrue(h1 != h2);
}
}
}
}
@Test
public void simpleLong() {
for (long a = 0; a < 1000; a++) {
for (long b = 0; b < 1000; b++) {
if (a != b) {
int h1 = nextHash(startHash(a), b);
int h2 = nextHash(startHash(b), a);
assertTrue(h1 != h2);
}
}
}
}
@Test
public void floatHashes() {
float value = 0;
int expected = HashUtil.startHash(Float.floatToIntBits(value));
int hash = HashUtil.startHash(value);
assertEquals(expected, hash);
value = Float.MIN_VALUE;
hash = HashUtil.nextHash(hash, value);
expected = HashUtil.nextHash(expected, Float.floatToIntBits(value));
assertEquals(expected, hash);
value = Float.MAX_VALUE;
hash = HashUtil.nextHash(hash, value);
expected = HashUtil.nextHash(expected, Float.floatToIntBits(value));
assertEquals(expected, hash);
}
@Test
public void doubleHashes() {
double value = 0;
int expected = HashUtil.startHash(Double.doubleToLongBits(value));
int hash = HashUtil.startHash(value);
assertEquals(expected, hash);
value = Double.MIN_VALUE;
hash = HashUtil.nextHash(hash, value);
expected = HashUtil.nextHash(expected, Double.doubleToLongBits(value));
assertEquals(expected, hash);
value = Double.MAX_VALUE;
hash = HashUtil.nextHash(hash, value);
expected = HashUtil.nextHash(expected, Double.doubleToLongBits(value));
assertEquals(expected, hash);
}
@Test
public void bool() {
int a = nextHash(startHash(true), true);
int b = nextHash(startHash(true), false);
int c = nextHash(startHash(false), true);
int d = nextHash(startHash(false), false);
assertTrue(a != b && a != c && a != d);
assertTrue(b != c && b != d);
assertTrue(c != d);
}
@Test
public void nullObj() {
String s = "a";
int a = nextHash(startHash(s), null);
int b = nextHash(startHash(s), s);
int c = nextHash(startHash(null), null);
int d = nextHash(startHash(null), s);
assertTrue(a != b && a != c && a != d);
assertTrue(b != c && b != d);
assertTrue(c != d);
}
@Test
public void naiveStrings() {
List<String> wordlist = TestUtil.getWordlist();
String a = null;
for (String b : wordlist) {
if (a != null) {
naiveString(a, b);
}
a = b;
}
}
private static void naiveString(String a, String b) {
assertNotNull(a);
assertNotNull(b);
assertFalse(a.isEmpty());
assertFalse(b.isEmpty());
int h1 = nextHash(startHash(a), b);
int h2 = nextHash(startHash(b), a);
assertTrue(h1 != h2);
}
@Test(enabled = false)
public void differentHashes() {
// all permutations of a:64b, b:32b, c:16b, d:8b
// where a := [ 3 .. 300 @ step 3 ]
// where b := [ 8 .. 800 @ step 8 ]
// where c := [ 9 .. 900 @ step 9 ]
// where d := [ 1 .. 255 @ step 2]
// space: 100 * 100 * 100 * 128 = 128'000'000 * 4B = 512MiB
final int n = 100 * 100 * 100 * 128;
final int[] results = new int[n];
int idx = 0;
final long tStart = System.currentTimeMillis();
for (long a = 3; a <= 300; a += 3) {
for (int b = 8; b <= 800; b += 8) {
for (short c = 9; c <= 900; c += 9) {
for (int id = 1; id < 256; id += 2) {
byte d = (byte) (id & 0xFF);
int hc = hash(a, b, c, d);
results[idx++] = hc;
}
}
}
}
assertEquals(idx, n);
final long t0 = System.currentTimeMillis() - tStart;
Arrays.sort(results);
final long t1 = System.currentTimeMillis() - tStart - t0;
int prev = results[0];
int colls = 0;
int colCount = 0;
int highColl = 0;
for (int i = 1; i < n; i++) {
int cur = results[i];
if (cur == prev) {
colls++;
colCount++;
} else {
if (colCount > highColl) {
highColl = colCount;
}
colCount = 0;
}
prev = cur;
cur++;
}
final long t2 = System.currentTimeMillis() - tStart - t0 - t1;
double collFactor = ((double) colls) / ((double) n);
- // less then 1.5%
+ // less than 1.5%
assertTrue(collFactor < 0.015);
System.out.printf("t0=%d, t1=%d, t2=%d, collisions=%d/%d, highColl=%d\n", t0, t1, t2, colls, n, highColl);
// for (long a = 3; a <= 300; a += 3) {
// for (int b = 8; b <= 800; b += 8) {
// for (short c = 9; c <= 900; c += 9) {
// for (int id = 1; id < 256; id += 2) {
// byte d = (byte) (id & 0xFF);
// int hc = hash(a, b, c, d);
// if (Arrays.binarySearch(results, hc) >= 0) {
// System.out.printf("collision with %d,%d,%d,%d\n", a, b, c, d);
// }
// }
// }
// }
// }
// final long t3 = System.currentTimeMillis() - tStart - t0 - t1 - t2;
// System.out.printf("t0=%d, t1=%d, t2=%d,t3=%d, collisions=%d/%d\n",
// t0, t1, t2, t3, colls, n);
}
private static final int hash(long a, int b, short c, byte d) {
int h = HashUtil.startHash(a);
h = HashUtil.nextHash(h, b);
h = HashUtil.nextHash(h, c);
h = HashUtil.nextHash(h, d);
return h;
}
}
| false | false | null | null |
diff --git a/src/org/geometerplus/fbreader/library/Library.java b/src/org/geometerplus/fbreader/library/Library.java
index 279f303c..f2858c14 100644
--- a/src/org/geometerplus/fbreader/library/Library.java
+++ b/src/org/geometerplus/fbreader/library/Library.java
@@ -1,425 +1,428 @@
/*
* Copyright (C) 2007-2010 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.fbreader.library;
import java.io.File;
import java.util.*;
import org.geometerplus.zlibrary.core.filesystem.*;
import org.geometerplus.zlibrary.core.util.ZLMiscUtil;
import org.geometerplus.fbreader.Paths;
public final class Library {
public static final int STATE_NOT_INITIALIZED = 0;
public static final int STATE_FULLY_INITIALIZED = 1;
private final LinkedList<Book> myBooks = new LinkedList<Book>();
private final HashSet<Book> myExternalBooks = new HashSet<Book>();
private final LibraryTree myLibraryByAuthor = new RootTree();
private final LibraryTree myLibraryByTag = new RootTree();
private final LibraryTree myRecentBooks = new RootTree();
private final LibraryTree myFavorites = new RootTree();
- private final LibraryTree mySearchResult = new RootTree();
+ private LibraryTree mySearchResult = new RootTree();
private volatile int myState = STATE_NOT_INITIALIZED;
public Library() {
}
public boolean hasState(int state) {
return myState >= state;
}
public void waitForState(int state) {
while (myState < state) {
synchronized(this) {
if (myState < state) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
}
public static ZLResourceFile getHelpFile() {
final ZLResourceFile file = ZLResourceFile.createResourceFile(
"data/help/MiniHelp." + Locale.getDefault().getLanguage() + ".fb2"
);
if (file.exists()) {
return file;
}
return ZLResourceFile.createResourceFile("data/help/MiniHelp.en.fb2");
}
private static Book getBook(ZLFile bookFile, FileInfoSet fileInfos, Map<Long,Book> saved, boolean doReadMetaInfo) {
Book book = saved.remove(fileInfos.getId(bookFile));
if (book == null) {
doReadMetaInfo = true;
book = new Book(bookFile);
}
if (doReadMetaInfo && !book.readMetaInfo()) {
return null;
}
return book;
}
private void collectBooks(
ZLFile file,
FileInfoSet fileInfos,
Map<Long,Book> savedBooks,
boolean doReadMetaInfo
) {
Book book = getBook(file, fileInfos, savedBooks, doReadMetaInfo);
if (book != null) {
myBooks.add(book);
} else if (file.isArchive()) {
for (ZLFile entry : fileInfos.archiveEntries(file)) {
collectBooks(entry, fileInfos, savedBooks, doReadMetaInfo);
}
}
}
private void collectExternalBooks(FileInfoSet fileInfos, Map<Long,Book> savedBooks) {
final HashSet<ZLPhysicalFile> myUpdatedFiles = new HashSet<ZLPhysicalFile>();
final HashSet<Long> files = new HashSet<Long>(savedBooks.keySet());
for (Long fileId: files) {
final ZLFile bookFile = fileInfos.getFile(fileId);
if (bookFile == null) {
continue;
}
final ZLPhysicalFile physicalFile = bookFile.getPhysicalFile();
if (physicalFile == null || !physicalFile.exists()) {
continue;
}
boolean reloadMetaInfo = false;
if (myUpdatedFiles.contains(physicalFile)) {
reloadMetaInfo = true;
} else if (!fileInfos.check(physicalFile)) {
reloadMetaInfo = true;
myUpdatedFiles.add(physicalFile);
}
final Book book = getBook(bookFile, fileInfos, savedBooks, reloadMetaInfo);
if (book == null) {
continue;
}
final long bookId = book.getId();
if (bookId != -1 && BooksDatabase.Instance().checkBookList(bookId)) {
myBooks.add(book);
myExternalBooks.add(book);
}
}
}
private List<ZLPhysicalFile> collectPhysicalFiles() {
final Queue<ZLFile> dirQueue = new LinkedList<ZLFile>();
final HashSet<ZLFile> dirSet = new HashSet<ZLFile>();
final LinkedList<ZLPhysicalFile> fileList = new LinkedList<ZLPhysicalFile>();
dirQueue.offer(new ZLPhysicalFile(new File(Paths.BooksDirectoryOption().getValue())));
while (!dirQueue.isEmpty()) {
for (ZLFile file : dirQueue.poll().children()) {
if (file.isDirectory()) {
if (!dirSet.contains(file)) {
dirQueue.add(file);
dirSet.add(file);
}
} else {
file.setCached(true);
fileList.add((ZLPhysicalFile)file);
}
}
}
return fileList;
}
private void collectBooks() {
final List<ZLPhysicalFile> physicalFilesList = collectPhysicalFiles();
FileInfoSet fileInfos = new FileInfoSet();
final Map<Long,Book> savedBooks = BooksDatabase.Instance().loadBooks(fileInfos);
for (ZLPhysicalFile file : physicalFilesList) {
collectBooks(file, fileInfos, savedBooks, !fileInfos.check(file));
file.setCached(false);
}
final Book helpBook = getBook(getHelpFile(), fileInfos, savedBooks, false);
if (helpBook != null) {
myBooks.add(helpBook);
}
collectExternalBooks(fileInfos, savedBooks);
fileInfos.save();
}
private static class AuthorSeriesPair {
private final Author myAuthor;
private final String mySeries;
AuthorSeriesPair(Author author, String series) {
myAuthor = author;
mySeries = series;
}
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof AuthorSeriesPair)) {
return false;
}
AuthorSeriesPair pair = (AuthorSeriesPair)object;
return ZLMiscUtil.equals(myAuthor, pair.myAuthor) && mySeries.equals(pair.mySeries);
}
public int hashCode() {
return Author.hashCode(myAuthor) + mySeries.hashCode();
}
}
private final ArrayList myNullList = new ArrayList(1);
{
myNullList.add(null);
}
private TagTree getTagTree(Tag tag, HashMap<Tag,TagTree> tagTreeMap) {
TagTree tagTree = tagTreeMap.get(tag);
if (tagTree == null) {
LibraryTree parent =
((tag != null) && (tag.Parent != null)) ?
getTagTree(tag.Parent, tagTreeMap) : myLibraryByTag;
tagTree = parent.createTagSubTree(tag);
tagTreeMap.put(tag, tagTree);
}
return tagTree;
}
private void build() {
final HashMap<Tag,TagTree> tagTreeMap = new HashMap<Tag,TagTree>();
final HashMap<Author,AuthorTree> authorTreeMap = new HashMap<Author,AuthorTree>();
final HashMap<AuthorSeriesPair,SeriesTree> seriesTreeMap = new HashMap<AuthorSeriesPair,SeriesTree>();
final HashMap<Long,Book> bookById = new HashMap<Long,Book>();
collectBooks();
for (Book book : myBooks) {
bookById.put(book.getId(), book);
List<Author> authors = book.authors();
if (authors.isEmpty()) {
authors = (List<Author>)myNullList;
}
final SeriesInfo seriesInfo = book.getSeriesInfo();
for (Author a : authors) {
AuthorTree authorTree = authorTreeMap.get(a);
if (authorTree == null) {
authorTree = myLibraryByAuthor.createAuthorSubTree(a);
authorTreeMap.put(a, authorTree);
}
if (seriesInfo == null) {
authorTree.createBookSubTree(book, false);
} else {
final String series = seriesInfo.Name;
final AuthorSeriesPair pair = new AuthorSeriesPair(a, series);
SeriesTree seriesTree = seriesTreeMap.get(pair);
if (seriesTree == null) {
seriesTree = authorTree.createSeriesSubTree(series);
seriesTreeMap.put(pair, seriesTree);
}
seriesTree.createBookInSeriesSubTree(book);
}
}
List<Tag> tags = book.tags();
if (tags.isEmpty()) {
tags = (List<Tag>)myNullList;
}
for (Tag t : tags) {
getTagTree(t, tagTreeMap).createBookSubTree(book, true);
}
}
final BooksDatabase db = BooksDatabase.Instance();
for (long id : db.loadRecentBookIds()) {
Book book = bookById.get(id);
if (book != null) {
myRecentBooks.createBookSubTree(book, true);
}
}
for (long id : db.loadFavoritesIds()) {
Book book = bookById.get(id);
if (book != null) {
myFavorites.createBookSubTree(book, true);
}
}
myFavorites.sortAllChildren();
db.executeAsATransaction(new Runnable() {
public void run() {
for (Book book : myBooks) {
book.save();
}
}
});
}
public synchronized void synchronize() {
if (myState == STATE_NOT_INITIALIZED) {
build();
myLibraryByAuthor.sortAllChildren();
myLibraryByTag.sortAllChildren();
myState = STATE_FULLY_INITIALIZED;
notifyAll();
}
}
public LibraryTree byAuthor() {
waitForState(STATE_FULLY_INITIALIZED);
return myLibraryByAuthor;
}
public LibraryTree byTag() {
waitForState(STATE_FULLY_INITIALIZED);
return myLibraryByTag;
}
public LibraryTree recentBooks() {
waitForState(STATE_FULLY_INITIALIZED);
return myRecentBooks;
}
public static Book getRecentBook() {
List<Long> recentIds = BooksDatabase.Instance().loadRecentBookIds();
return (recentIds.size() > 0) ? Book.getById(recentIds.get(0)) : null;
}
public LibraryTree favorites() {
waitForState(STATE_FULLY_INITIALIZED);
return myFavorites;
}
public LibraryTree searchResults() {
return mySearchResult;
}
public LibraryTree searchBooks(String pattern) {
waitForState(STATE_FULLY_INITIALIZED);
- mySearchResult.clear();
+ final RootTree newSearchResults = new RootTree();
if (pattern != null) {
pattern = pattern.toLowerCase();
for (Book book : myBooks) {
if (book.matches(pattern)) {
- mySearchResult.createBookSubTree(book, true);
+ newSearchResults.createBookSubTree(book, true);
}
}
- mySearchResult.sortAllChildren();
+ newSearchResults.sortAllChildren();
+ if (newSearchResults.hasChildren()) {
+ mySearchResult = newSearchResults;
+ }
}
- return mySearchResult;
+ return newSearchResults;
}
public static void addBookToRecentList(Book book) {
final BooksDatabase db = BooksDatabase.Instance();
final List<Long> ids = db.loadRecentBookIds();
final Long bookId = book.getId();
ids.remove(bookId);
ids.add(0, bookId);
if (ids.size() > 12) {
ids.remove(12);
}
db.saveRecentBookIds(ids);
}
public boolean isBookInFavorites(Book book) {
waitForState(STATE_FULLY_INITIALIZED);
return myFavorites.containsBook(book);
}
public void addBookToFavorites(Book book) {
waitForState(STATE_FULLY_INITIALIZED);
if (!myFavorites.containsBook(book)) {
myFavorites.createBookSubTree(book, true);
myFavorites.sortAllChildren();
BooksDatabase.Instance().addToFavorites(book.getId());
}
}
public void removeBookFromFavorites(Book book) {
waitForState(STATE_FULLY_INITIALIZED);
if (myFavorites.removeBook(book)) {
BooksDatabase.Instance().removeFromFavorites(book.getId());
}
}
public static final int REMOVE_DONT_REMOVE = 0x00;
public static final int REMOVE_FROM_LIBRARY = 0x01;
public static final int REMOVE_FROM_DISK = 0x02;
public static final int REMOVE_FROM_LIBRARY_AND_DISK = REMOVE_FROM_LIBRARY | REMOVE_FROM_DISK;
public int getRemoveBookMode(Book book) {
waitForState(STATE_FULLY_INITIALIZED);
return (myExternalBooks.contains(book) ? REMOVE_FROM_LIBRARY : REMOVE_DONT_REMOVE)
| (canDeleteBookFile(book) ? REMOVE_FROM_DISK : REMOVE_DONT_REMOVE);
}
private boolean canDeleteBookFile(Book book) {
ZLFile file = book.File;
if (file.getPhysicalFile() == null) {
return false;
}
while (file instanceof ZLArchiveEntryFile) {
file = file.getParent();
if (file.children().size() != 1) {
return false;
}
}
return true;
}
public void removeBook(Book book, int removeMode) {
if (removeMode == REMOVE_DONT_REMOVE) {
return;
}
waitForState(STATE_FULLY_INITIALIZED);
myBooks.remove(book);
myLibraryByAuthor.removeBook(book);
myLibraryByTag.removeBook(book);
if (myRecentBooks.removeBook(book)) {
final BooksDatabase db = BooksDatabase.Instance();
final List<Long> ids = db.loadRecentBookIds();
ids.remove(book.getId());
db.saveRecentBookIds(ids);
}
mySearchResult.removeBook(book);
myFavorites.removeBook(book);
BooksDatabase.Instance().deleteFromBookList(book.getId());
if ((removeMode & REMOVE_FROM_DISK) != 0) {
book.File.getPhysicalFile().delete();
}
}
}
| false | false | null | null |
diff --git a/src/org/waldk33n3r/android/gnosis/games/QuestionDatabaseHandler.java b/src/org/waldk33n3r/android/gnosis/games/QuestionDatabaseHandler.java
index 237f507..5208752 100644
--- a/src/org/waldk33n3r/android/gnosis/games/QuestionDatabaseHandler.java
+++ b/src/org/waldk33n3r/android/gnosis/games/QuestionDatabaseHandler.java
@@ -1,144 +1,146 @@
package org.waldk33n3r.android.gnosis.games;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
+import android.util.Log;
public class QuestionDatabaseHandler extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "questionsManager";
//Questions table name
private static final String TABLE_QUESTIONS = "questions";
//Questions Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_BODY = "body";
private static final String KEY_ANSWER = "answer";
private static final String KEY_OPTION1 = "option1";
private static final String KEY_OPTION2 = "option2";
private static final String KEY_OPTION3 = "option3";
public QuestionDatabaseHandler(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_QUESTIONS_TABLE = "CREATE TABLE " + TABLE_QUESTIONS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_BODY + " TEXT,"
- + KEY_ANSWER + " TEXT" + KEY_OPTION1 + " TEXT" + KEY_OPTION2 +
- " TEXT" + KEY_OPTION3 + " TEXT" + ")";
+ + KEY_ANSWER + " TEXT," + KEY_OPTION1 + " TEXT," + KEY_OPTION2 +
+ " TEXT," + KEY_OPTION3 + " TEXT" + ")";
db.execSQL(CREATE_QUESTIONS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTIONS);
// Create tables again
onCreate(db);
}
// Adding new question
public void addQuestion(Question question) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_BODY, question.getBody());
values.put(KEY_ANSWER, question.getAnswer());
values.put(KEY_OPTION1, question.getOption1());
values.put(KEY_OPTION2, question.getOption2());
values.put(KEY_OPTION3, question.getOption3());
-
+ Log.e("DB","Inserting a question");
db.insert(TABLE_QUESTIONS, null, values);
db.close();
}
// Getting single question
public Question getQuestion(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_QUESTIONS, new String[] { KEY_ID,
KEY_BODY, KEY_ANSWER, KEY_OPTION1, KEY_OPTION2, KEY_OPTION3 }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor != null){
cursor.moveToFirst();
}
Question question = new Question(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3),
cursor.getString(4), cursor.getString(5));
return question;
}
// Getting All Questions as a List
public List<Question> getAllQuestions() {
List<Question> questionList = new ArrayList<Question>();
String selectQuery = "SELECT * FROM " + TABLE_QUESTIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Question question = new Question();
question.setID(Integer.parseInt(cursor.getString(0)));
question.setBody(cursor.getString(1));
question.setAnswer(cursor.getString(2));
question.setOption1(cursor.getString(3));
question.setOption2(cursor.getString(4));
question.setOption3(cursor.getString(5));
questionList.add(question);
} while (cursor.moveToNext());
}
return questionList;
}
// Getting question Count
public int getQuestionsCount() {
String questionQuery = "SELECT * FROM " + TABLE_QUESTIONS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(questionQuery, null);
+ int count = cursor.getCount();
cursor.close();
- return cursor.getCount();
+ return count;
}
// Updating single question
public int updateQuestion(Question question) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_BODY, question.getBody());
values.put(KEY_ANSWER, question.getAnswer());
values.put(KEY_OPTION1, question.getOption1());
values.put(KEY_OPTION2, question.getOption2());
values.put(KEY_OPTION3, question.getOption3());
return db.update(TABLE_QUESTIONS, values, KEY_ID + " = ?",
new String[] { String.valueOf(question.getID()) });
}
// Deleting single question
public void deleteQuestion(Question question) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_QUESTIONS, KEY_ID + " = ?",
new String[] { String.valueOf(question.getID()) });
db.close();
}
}
diff --git a/src/org/waldk33n3r/android/gnosis/games/frog/GameView.java b/src/org/waldk33n3r/android/gnosis/games/frog/GameView.java
index 8ef2440..baf8222 100644
--- a/src/org/waldk33n3r/android/gnosis/games/frog/GameView.java
+++ b/src/org/waldk33n3r/android/gnosis/games/frog/GameView.java
@@ -1,166 +1,171 @@
package org.waldk33n3r.android.gnosis.games.frog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import org.waldk33n3r.android.gnosis.R;
+import org.waldk33n3r.android.gnosis.games.Question;
+import org.waldk33n3r.android.gnosis.games.QuestionDatabaseHandler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.RectF;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class GameView extends View {
private Paint paint;
private Bitmap lilly;
private ArrayList<LillyPad> lillies;
private Random rand;
private String[] strings;
+ QuestionDatabaseHandler db;
+
public GameView(Context context) {
super(context);
paint = new Paint();
lilly = BitmapFactory.decodeResource(getResources(), R.drawable.lilypad);
rand = new Random();
-
+ db = new QuestionDatabaseHandler(getContext());
+ Log.e("Blargh",""+db.getQuestionsCount());
lillies = new ArrayList<LillyPad>();
init();
Timer timer = new Timer(100, true, new Executable() {
@Override
public void exec(Object... obj) {
((View) obj[0]).post(new Runnable() {
@Override
public void run() {
invalidate();
}
});
}
}, this);
timer.start();
}
private void init() {
strings = new String[]{"Randomly generated","sizes (weighted)","and directions.","","Click a lilly pad to","make it disappear.","","Click the place again to","make it reappear"};
int dir1 = rand.nextInt(2);
int dir2 = rand.nextInt(2);
int dir3 = rand.nextInt(2);
int dir4 = rand.nextInt(2);
for (int i = 0; i < rand.nextInt(40) + 20; i++) {
int size = rand.nextInt(3) + 1;
size = size == 3 ? 200 : 100;
float x = (rand.nextInt(10) + 1) * 50;
float y = rand.nextInt(4) * 200 + 20;
boolean intersects = false;
for (Iterator<LillyPad> it = lillies.iterator(); it.hasNext();) {
LillyPad lilly = it.next();
RectF newRect = new RectF(x, y, x + size, y + size);
intersects = RectF.intersects(lilly.getRectF(), newRect);
if (intersects)
break;
}
if (!intersects) {
int dir;
int row = (int) ((y - 20) / 200);
if (row == 1)
dir = dir1;
else if (row == 2)
dir = dir2;
else if (row == 3)
dir = dir3;
else
dir = dir4;
lillies.add(new LillyPad(dir/* rand.nextInt(2) */, x, y, size, size, lilly));
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.CYAN);
canvas.drawPaint(paint);
paint.setColor(Color.RED);
for (int i = 0; i <= canvas.getHeight(); i += 10) {
canvas.drawLine(i, 0, i, canvas.getHeight(), paint);
canvas.drawLine(0, i, canvas.getWidth(), i, paint);
}
for (Iterator<LillyPad> it = lillies.iterator(); it.hasNext();) {
LillyPad lilly = it.next();
lilly.move(this, 5);
lilly.draw(canvas);
}
paint.setColor(Color.BLACK);
paint.setTextSize(36);
paint.setTextAlign(Align.CENTER);
- for (int i = 0; i < strings.length; i++)
- canvas.drawText(strings[i], canvas.getWidth() / 2, canvas.getHeight() / 4 + 30 * i, paint);
+ //for (int i = 0; i < strings.length; i++)
+ //canvas.drawText(strings[i], canvas.getWidth() / 2, canvas.getHeight() / 4 + 30 * i, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Log.w("Touch Event", String.format("Touched at %s, %s", event.getX(), event.getY()));
for (Iterator<LillyPad> it = this.lillies.iterator(); it.hasNext();) {
LillyPad lilly = it.next();
if (new RectF(lilly.getRectF()).contains(event.getX(), event.getY())) {
Log.w("Touch Event", "Lilly pad touched");
// lilly.setCoord(event.getX(), event.getY());
lilly.setVisible(!lilly.isVisible());
this.invalidate();
}
}
}
return true;
}
interface Executable {
public void exec(Object... obj);
}
class Timer extends Thread {
Executable func;
int wait;
boolean repeat;
Object[] params;
public Timer(int wait, boolean repeat, Executable func, Object... params) {
this.wait = wait;
this.repeat = repeat;
this.func = func;
this.params = params;
}
@Override
public void run() {
do {
try {
super.sleep(this.wait);
} catch (InterruptedException e) {
e.printStackTrace();
}
func.exec(params);
} while (repeat);
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/eclipse_files/src/agent/PartsRobotAgent.java b/eclipse_files/src/agent/PartsRobotAgent.java
index bfebf883..279b7fe9 100644
--- a/eclipse_files/src/agent/PartsRobotAgent.java
+++ b/eclipse_files/src/agent/PartsRobotAgent.java
@@ -1,373 +1,388 @@
package agent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
import DeviceGraphics.DeviceGraphics;
import GraphicsInterfaces.PartsRobotGraphics;
import agent.data.Kit;
import agent.data.Part;
import agent.interfaces.Nest;
import agent.interfaces.PartsRobot;
import agent.interfaces.Stand;
import factory.KitConfig;
import factory.PartType;
/**
* Parts robot picks parts from nests and places them in kits
* @author Ross Newman, Michael Gendotti, Daniel Paje
*/
public class PartsRobotAgent extends Agent implements PartsRobot {
public PartsRobotAgent(String name) {
super();
this.name = name;
// Add arms
for (int i = 0; i < 4; i++) {
this.Arms.add(new Arm());
}
}
String name;
public class MyKit {
public Kit kit;
public MyKitStatus MKS;
public MyKit(Kit k) {
kit = k;
MKS = MyKitStatus.NotDone;
}
}
public enum MyKitStatus {
NotDone, Done
};
public class Arm {
Part part;
ArmStatus AS;
public Arm() {
part = null;
AS = ArmStatus.Empty;
}
}
private enum ArmStatus {
Empty, Full
};
private KitConfig KitConfig;
private final List<MyKit> MyKits = Collections
.synchronizedList(new ArrayList<MyKit>());
public Map<Nest, List<Part>> GoodParts = new HashMap<Nest, List<Part>>();
public List<Arm> Arms = Collections.synchronizedList(new ArrayList<Arm>());
List<Kit> KitsOnStand;
// List<Nest> nests;
Stand stand;
PartsRobotGraphics partsRobotGraphics;
public Semaphore animation = new Semaphore(0, true);
// public Semaphore accessKit = new Semaphore(0, true);
/***** MESSAGES ***************************************/
/**
* Changes the configuration for the kits From FCS
*/
@Override
public void msgHereIsKitConfiguration(KitConfig config) {
print("Received msgHereIsKitConfiguration");
KitConfig = config;
stateChanged();
}
/**
* From Camera
*/
@Override
public void msgHereAreGoodParts(Nest n, List<Part> goodParts) {
print("Received msgHereAreGoodParts");
GoodParts.put(n, goodParts);
stateChanged();
}
/**
* From Stand
*/
@Override
public void msgUseThisKit(Kit k) {
print("Received msgUseThisKit");
MyKit mk = new MyKit(k);
MyKits.add(mk);
stateChanged();
}
/**
* Releases animation semaphore after a part is picked up, so that a new
* animation may be run by graphics. From graphics
*/
@Override
public void msgPickUpPartDone() {
print("Received msgPickUpPartDone from graphics");
animation.release();
stateChanged();
}
/**
* Releases animation semaphore after a part is given to kit, so that a new
* animation may be run by graphics. From graphics
*/
@Override
public void msgGivePartToKitDone() {
print("Received msgGivePartToKitDone from graphics");
animation.release();
stateChanged();
}
/**************** SCHEDULER ***********************/
@Override
public boolean pickAndExecuteAnAction() {
// Checks if a kit is done and inspects it if it is
synchronized (MyKits) {
if (MyKits.size() > 0) {
for (MyKit mk : MyKits) {
if (mk.MKS == MyKitStatus.Done) {
RequestInspection(mk);
return true;
}
}
}
// Checks if there is an empty arm, if there is it fills it with a
// good part that the kit needs
if (IsAnyArmEmpty()) {
synchronized (GoodParts) {
for (Nest nest : GoodParts.keySet()) {
// Going through all the good parts
for (Part part : GoodParts.get(nest)) {
for (MyKit mk : MyKits) {
-
+
// Checking if the good part is needed by
// either kit
if (mk.kit.needPart(part)) {
// if(KitConfig.getConfig().containsKey(part.type))
// //Don't know why this is needed -Mike
// {
print("Found a part I need");
+ synchronized(Arms){
for (Arm arm : Arms) {
if (arm.AS == ArmStatus.Empty) {
// Find the empty arm
PickUpPart(arm, part, nest);
return true;
}
}
+ }
// }
}
}
}
}
}
}
}
// Checks if any arm is holding a part and places it if there is one
+ synchronized(Arms){
for (Arm arm : Arms) {
if (arm.AS == ArmStatus.Full) {
PlacePart(arm);
return true;
}
}
+ }
return false;
}
/********** ACTIONS **************/
private void PickUpPart(Arm arm, Part part, Nest nest) {
print("Picking up part");
arm.AS = ArmStatus.Full;
arm.part = part;
-
+ /*Getting stuck on acquire
// Tells the graphics to pickup the part
if (partsRobotGraphics != null) {
+ print("bloop");
partsRobotGraphics.pickUpPart(part.partGraphics);
try {
animation.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
-
+ */
+ print("bleep");
// Only takes 1 part from a nest at a time
nest.msgTakingPart(part);
nest.msgDoneTakingParts();
stateChanged();
}
private void PlacePart(Arm arm) {
+ synchronized(Arms){
print("Placing part");
for (MyKit mk : MyKits) {
if (mk.kit.needPart(arm.part)) {
+ /* Animation messing up
if (partsRobotGraphics != null) {
partsRobotGraphics.givePartToKit(arm.part.partGraphics,
mk.kit.kitGraphics);
try {
animation.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
+ */
// Tells the kit it has the part now
mk.kit.parts.add(arm.part);
+
+ /*Animation messing up
if (mk.kit.kitGraphics != null) {
System.out.println("receiving part");
mk.kit.kitGraphics.receivePart(arm.part.partGraphics);
}
- // mk.kit.partsExpected.remove(arm.part);
+ */
+
+ mk.kit.partsExpected.removeItem(arm.part.type);
arm.part = null;
+
arm.AS = ArmStatus.Empty;
// Checks if the kit is done
CheckMyKit(mk);
break;
}
}
stateChanged();
+ }
}
private void CheckMyKit(MyKit mk) {
int size = 1;
for (PartType type : mk.kit.partsExpected.getConfig().keySet()) {
for (int i = 0; i < mk.kit.partsExpected.getConfig().get(type); i++) {
size++;
}
}
print("Need " + (size - mk.kit.parts.size())
+ " more part(s) to finish kit.");
if (mk.kit.parts.size() == size) {
mk.MKS = MyKitStatus.Done;
}
// stateChanged();
}
private void RequestInspection(MyKit mk) {
print("Requesting inspection.");
stand.msgKitAssembled(mk.kit);
MyKits.remove(mk);
stateChanged();
}
// Helper methods
// Checks if any of the arms are empty
private boolean IsAnyArmEmpty() {
for (Arm a : Arms) {
if (a.AS == ArmStatus.Empty) {
return true;
}
}
return false;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public KitConfig getKitConfig() {
return KitConfig;
}
public void setKitConfig(KitConfig kitConfig) {
KitConfig = kitConfig;
}
public Map<Nest, List<Part>> getGoodParts() {
return GoodParts;
}
public void setGoodParts(Map<Nest, List<Part>> goodParts) {
GoodParts = goodParts;
}
public List<Arm> getArms() {
return Arms;
}
public void setArms(List<Arm> arms) {
Arms = arms;
}
public List<Kit> getKitsOnStand() {
return KitsOnStand;
}
public void setKitsOnStand(List<Kit> kitsOnStand) {
KitsOnStand = kitsOnStand;
}
/*
* public List<Nest> getNests() { return nests; } public void
* setNests(List<Nest> nests) { this.nests = nests; }
*/
public Stand getStand() {
return stand;
}
public void setStand(Stand stand) {
this.stand = stand;
}
public PartsRobotGraphics getPartsrobotGraphics() {
return partsRobotGraphics;
}
@Override
public void setGraphicalRepresentation(DeviceGraphics partsrobotGraphics) {
this.partsRobotGraphics = (PartsRobotGraphics) partsrobotGraphics;
}
public Semaphore getAnimation() {
return animation;
}
public void setAnimation(Semaphore animation) {
this.animation = animation;
}
public List<MyKit> getMyKits() {
return MyKits;
}
// Initialize Arms
public void InitializeArms() {
for (int i = 0; i < 4; i++) {
Arms.add(new Arm());
}
}
}
| false | false | null | null |
diff --git a/GAE/src/org/waterforpeople/mapping/dataexport/GraphicalSurveySummaryExporter.java b/GAE/src/org/waterforpeople/mapping/dataexport/GraphicalSurveySummaryExporter.java
index 08669ea06..6ca583fa1 100644
--- a/GAE/src/org/waterforpeople/mapping/dataexport/GraphicalSurveySummaryExporter.java
+++ b/GAE/src/org/waterforpeople/mapping/dataexport/GraphicalSurveySummaryExporter.java
@@ -1,1005 +1,1008 @@
/*
* Copyright (C) 2010-2012 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.dataexport;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.SwingUtilities;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.WorkbookUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionOptionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.TranslationDto;
import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto;
import org.waterforpeople.mapping.app.web.dto.SurveyRestRequest;
import org.waterforpeople.mapping.dataexport.service.BulkDataServiceClient;
import com.gallatinsystems.common.util.JFreechartChartUtil;
import com.gallatinsystems.common.util.StringUtil;
import com.gallatinsystems.framework.dataexport.applet.ProgressDialog;
/**
* Enhancement of the SurveySummaryExporter to support writing to Excel and
* including chart images.
*
* @author Christopher Fagiani
*
*/
public class GraphicalSurveySummaryExporter extends SurveySummaryExporter {
private static final int MAX_COL = 255;
private static final String IMAGE_PREFIX_OPT = "imgPrefix";
private static final String DO_ROLLUP_OPT = "performRollup";
private static final String LOCALE_OPT = "locale";
private static final String TYPE_OPT = "exportMode";
private static final String RAW_ONLY_TYPE = "RAW_DATA";
private static final String NO_CHART_OPT = "nocharts";
private static final String DEFAULT_IMAGE_PREFIX = "http://waterforpeople.s3.amazonaws.com/images/";
private static final String SDCARD_PREFIX = "/sdcard/";
private static final Map<String, String> REPORT_HEADER;
private static final Map<String, String> FREQ_LABEL;
private static final Map<String, String> PCT_LABEL;
private static final Map<String, String> SUMMARY_LABEL;
private static final Map<String, String> RAW_DATA_LABEL;
private static final Map<String, String> INSTANCE_LABEL;
private static final Map<String, String> SUB_DATE_LABEL;
private static final Map<String, String> SUBMITTER_LABEL;
private static final Map<String, String> MEAN_LABEL;
private static final Map<String, String> MODE_LABEL;
private static final Map<String, String> MEDIAN_LABEL;
private static final Map<String, String> MIN_LABEL;
private static final Map<String, String> MAX_LABEL;
private static final Map<String, String> VAR_LABEL;
private static final Map<String, String> STD_E_LABEL;
private static final Map<String, String> STD_D_LABEL;
private static final Map<String, String> TOTAL_LABEL;
private static final Map<String, String> RANGE_LABEL;
private static final Map<String, String> LOADING_QUESTIONS;
private static final Map<String, String> LOADING_DETAILS;
private static final Map<String, String> LOADING_INSTANCES;
private static final Map<String, String> LOADING_INSTANCE_DETAILS;
private static final Map<String, String> WRITING_SUMMARY;
private static final Map<String, String> WRITING_RAW_DATA;
private static final Map<String, String> WRITING_ROLLUPS;
private static final Map<String, String> COMPLETE;
private static final int CHART_WIDTH = 600;
private static final int CHART_HEIGHT = 400;
private static final int CHART_CELL_WIDTH = 10;
private static final int CHART_CELL_HEIGHT = 22;
private static final String DEFAULT_LOCALE = "en";
private static final String DEFAULT = "default";
private static final int FULL_STEPS = 7;
private static final int RAW_STEPS = 5;
private static final NumberFormat PCT_FMT = DecimalFormat
.getPercentInstance();
static {
// populate all translations
RANGE_LABEL = new HashMap<String, String>();
RANGE_LABEL.put("en", "Range");
RANGE_LABEL.put("es", "Distribución");
MEAN_LABEL = new HashMap<String, String>();
MEAN_LABEL.put("en", "Mean");
MEAN_LABEL.put("es", "Media");
MODE_LABEL = new HashMap<String, String>();
MODE_LABEL.put("en", "Mode");
MODE_LABEL.put("es", "Moda");
MEDIAN_LABEL = new HashMap<String, String>();
MEDIAN_LABEL.put("en", "Median");
MEDIAN_LABEL.put("es", "Número medio");
MIN_LABEL = new HashMap<String, String>();
MIN_LABEL.put("en", "Min");
MIN_LABEL.put("es", "Mínimo");
MAX_LABEL = new HashMap<String, String>();
MAX_LABEL.put("en", "Max");
MAX_LABEL.put("es", "Máximo");
VAR_LABEL = new HashMap<String, String>();
VAR_LABEL.put("en", "Variance");
VAR_LABEL.put("es", "Varianza");
STD_D_LABEL = new HashMap<String, String>();
STD_D_LABEL.put("en", "Std Deviation");
STD_D_LABEL.put("es", "Desviación Estándar");
STD_E_LABEL = new HashMap<String, String>();
STD_E_LABEL.put("en", "Std Error");
STD_E_LABEL.put("es", "Error Estándar");
TOTAL_LABEL = new HashMap<String, String>();
TOTAL_LABEL.put("en", "Total");
TOTAL_LABEL.put("es", "Suma");
REPORT_HEADER = new HashMap<String, String>();
REPORT_HEADER.put("en", "Survey Summary Report");
REPORT_HEADER.put("es", "Encuesta Informe Resumen");
FREQ_LABEL = new HashMap<String, String>();
FREQ_LABEL.put("en", "Frequency");
FREQ_LABEL.put("es", "Frecuencia");
PCT_LABEL = new HashMap<String, String>();
PCT_LABEL.put("en", "Percent");
PCT_LABEL.put("es", "Por ciento");
SUMMARY_LABEL = new HashMap<String, String>();
SUMMARY_LABEL.put("en", "Summary");
SUMMARY_LABEL.put("es", "Resumen");
RAW_DATA_LABEL = new HashMap<String, String>();
RAW_DATA_LABEL.put("en", "Raw Data");
RAW_DATA_LABEL.put("es", "Primas de Datos");
INSTANCE_LABEL = new HashMap<String, String>();
INSTANCE_LABEL.put("en", "Instance");
INSTANCE_LABEL.put("es", "Instancia");
SUB_DATE_LABEL = new HashMap<String, String>();
SUB_DATE_LABEL.put("en", "Submission Date");
SUB_DATE_LABEL.put("es", "Fecha de presentación");
SUBMITTER_LABEL = new HashMap<String, String>();
SUBMITTER_LABEL.put("en", "Submitter");
SUBMITTER_LABEL.put("es", "Peticionario");
LOADING_QUESTIONS = new HashMap<String, String>();
LOADING_QUESTIONS.put("en", "Loading Questions");
LOADING_QUESTIONS.put("es", "Cargando de preguntas");
LOADING_DETAILS = new HashMap<String, String>();
LOADING_DETAILS.put("en", "Loading Question Details");
LOADING_DETAILS.put("es", "Cargando Detalles Pregunta");
LOADING_INSTANCES = new HashMap<String, String>();
LOADING_INSTANCES.put("en", "Loading Instances");
LOADING_INSTANCES.put("es", "Cargando instancias");
LOADING_INSTANCE_DETAILS = new HashMap<String, String>();
LOADING_INSTANCE_DETAILS.put("en", "Loading Instance Details");
LOADING_INSTANCE_DETAILS.put("es", "Cargando Datos Instancia");
WRITING_SUMMARY = new HashMap<String, String>();
WRITING_SUMMARY.put("en", "Writing Summary");
WRITING_SUMMARY.put("es", "Escribiendo Resumen");
WRITING_RAW_DATA = new HashMap<String, String>();
WRITING_RAW_DATA.put("en", "Writing Raw Data");
WRITING_RAW_DATA.put("es", "Escribiendo Primas de Datos");
WRITING_ROLLUPS = new HashMap<String, String>();
WRITING_ROLLUPS.put("en", "Writing Rollups");
WRITING_ROLLUPS.put("es", "Escribiendo Resumen Municipales");
COMPLETE = new HashMap<String, String>();
COMPLETE.put("en", "Export Complete");
COMPLETE.put("es", "Exportación Completa");
}
private CellStyle headerStyle;
private String locale;
private String imagePrefix;
private String serverBase;
private ProgressDialog progressDialog;
private int currentStep;
private int maxSteps;
private boolean isFullReport;
private boolean performGeoRollup;
private ThreadPoolExecutor threadPool;
private BlockingQueue<Runnable> jobQueue;
private volatile int threadsCompleted = 0;
private Object lock = new Object();
private boolean generateCharts;
@Override
public void export(Map<String, String> criteria, File fileName,
String serverBase, Map<String, String> options) {
processOptions(options);
jobQueue = new LinkedBlockingQueue<Runnable>();
threadPool = new ThreadPoolExecutor(5, 5, 10, TimeUnit.SECONDS,
jobQueue);
progressDialog = new ProgressDialog(maxSteps, locale);
progressDialog.setVisible(true);
currentStep = 1;
this.serverBase = serverBase;
PrintWriter pw = null;
try {
SwingUtilities.invokeLater(new StatusUpdater(currentStep++,
LOADING_QUESTIONS.get(locale)));
Map<QuestionGroupDto, List<QuestionDto>> questionMap = loadAllQuestions(
criteria.get(SurveyRestRequest.SURVEY_ID_PARAM),
performGeoRollup, serverBase);
if (!DEFAULT_LOCALE.equals(locale) && questionMap.size() > 0) {
// if we are using some other locale, we need to check for
// translations
SwingUtilities.invokeLater(new StatusUpdater(currentStep++,
LOADING_DETAILS.get(locale)));
loadFullQuestions(questionMap);
} else {
currentStep++;
}
Workbook wb = null;
if (questionMap.size() > 0) {
if (questionMap.size() > MAX_COL - 3) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
}
headerStyle = wb.createCellStyle();
headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
headerStyle.setFont(headerFont);
SummaryModel model = fetchAndWriteRawData(
criteria.get(SurveyRestRequest.SURVEY_ID_PARAM),
serverBase, questionMap, wb, isFullReport, fileName);
if (isFullReport) {
SwingUtilities.invokeLater(new StatusUpdater(currentStep++,
WRITING_SUMMARY.get(locale)));
writeSummaryReport(questionMap, model, null, wb);
SwingUtilities.invokeLater(new StatusUpdater(currentStep++,
WRITING_ROLLUPS.get(locale)));
}
if (model.getSectorList() != null
&& model.getSectorList().size() > 0) {
Collections.sort(model.getSectorList(),
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1 != null && o2 != null) {
return o1.toLowerCase().compareTo(
o2.toLowerCase());
} else {
return 0;
}
}
});
for (String sector : model.getSectorList()) {
writeSummaryReport(questionMap, model, sector, wb);
}
}
FileOutputStream fileOut = new FileOutputStream(fileName);
wb.setActiveSheet(isFullReport ? 1 : 0);
wb.write(fileOut);
fileOut.close();
SwingUtilities.invokeLater(new StatusUpdater(currentStep++,
COMPLETE.get(locale)));
} else {
System.out.println("No questions for survey");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
@SuppressWarnings("unchecked")
protected SummaryModel fetchAndWriteRawData(String surveyId,
final String serverBase,
Map<QuestionGroupDto, List<QuestionDto>> questionMap, Workbook wb,
final boolean generateSummary, File outputFile) throws Exception {
final SummaryModel model = new SummaryModel();
final Sheet sheet = wb.createSheet(RAW_DATA_LABEL.get(locale));
int curRow = 1;
final Map<String, String> collapseIdMap = new HashMap<String, String>();
final Map<String, String> nameToIdMap = new HashMap<String, String>();
for (Entry<QuestionGroupDto, List<QuestionDto>> groupEntry : questionMap
.entrySet()) {
for (QuestionDto q : groupEntry.getValue()) {
if (q.getCollapseable() != null && q.getCollapseable()) {
if (collapseIdMap.get(q.getText()) == null) {
collapseIdMap.put(q.getText(), q.getKeyId().toString());
}
nameToIdMap.put(q.getKeyId().toString(), q.getText());
}
}
}
Object[] results = createRawDataHeader(wb, sheet, questionMap);
final List<String> questionIdList = (List<String>) results[0];
final List<String> unsummarizable = (List<String>) results[1];
SwingUtilities.invokeLater(new StatusUpdater(currentStep++,
LOADING_INSTANCES.get(locale)));
Map<String, String> instanceMap = BulkDataServiceClient
.fetchInstanceIds(surveyId, serverBase);
SwingUtilities.invokeLater(new StatusUpdater(currentStep++,
LOADING_INSTANCE_DETAILS.get(locale)));
final List<RowData> allData = new ArrayList<RowData>();
int started = 0;
for (Entry<String, String> instanceEntry : instanceMap.entrySet()) {
final String instanceId = instanceEntry.getKey();
final String dateString = instanceEntry.getValue();
started++;
threadPool.execute(new Runnable() {
public void run() {
int attempts = 0;
boolean done = false;
while (!done && attempts < 10) {
try {
Map<String, String> responseMap = BulkDataServiceClient
.fetchQuestionResponses(instanceId,
serverBase);
SurveyInstanceDto dto = BulkDataServiceClient
.findSurveyInstance(
Long.parseLong(instanceId.trim()),
serverBase);
if (dto != null) {
done = true;
}
synchronized (allData) {
RowData rd = new RowData();
rd.setResponseMap(responseMap);
rd.setDto(dto);
rd.setInstanceId(instanceId);
rd.setDateString(dateString);
allData.add(rd);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
synchronized (lock) {
threadsCompleted++;
}
}
attempts++;
}
}
});
}
while (!jobQueue.isEmpty() || threadPool.getActiveCount() > 0
|| started > threadsCompleted) {
try {
System.out.println("Sleeping, Queue has: " + jobQueue.size());
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
// write the data now
for (RowData rd : allData) {
Row row = getRow(curRow++, sheet);
writeRow(row, rd.getDto(), rd.getResponseMap(), rd.getDateString(),
rd.getInstanceId(), generateSummary, questionIdList,
unsummarizable, nameToIdMap, collapseIdMap, model);
}
SwingUtilities.invokeLater(new StatusUpdater(currentStep++,
WRITING_RAW_DATA.get(locale)));
return model;
}
private synchronized void writeRow(Row row, SurveyInstanceDto dto,
Map<String, String> responseMap, String dateString,
String instanceId, boolean generateSummary,
List<String> questionIdList, List<String> unsummarizable,
Map<String, String> nameToIdMap, Map<String, String> collapseIdMap,
SummaryModel model) throws Exception {
int col = 0;
MessageDigest digest = MessageDigest.getInstance("MD5");
createCell(row, col++, instanceId, null);
createCell(row, col++, dateString, null);
if (dto != null) {
String name = dto.getSubmitterName();
if (name != null) {
createCell(row, col++,
dto.getSubmitterName().replaceAll("\n", " ")
.replaceAll("\t", " ").trim(), null);
} else {
createCell(row, col++, " ", null);
}
}
for (String q : questionIdList) {
String val = null;
if (responseMap != null) {
val = responseMap.get(q);
}
if (val != null) {
if (val.contains(SDCARD_PREFIX)) {
String[] photoParts = val.split("/");
if (photoParts.length > 1) {
val = imagePrefix + photoParts[photoParts.length - 1];
} else {
val = imagePrefix
+ val.substring(val.indexOf(SDCARD_PREFIX)
+ SDCARD_PREFIX.length());
}
}
String cellVal = val.replaceAll("\n", " ").trim();
createCell(row, col++, cellVal, null);
digest.update(cellVal.getBytes());
} else {
createCell(row, col++, "", null);
}
}
// now add 1 more col that contains the digest
createCell(row, col++, StringUtil.toHexString(digest.digest()), null);
if (generateSummary && responseMap != null) {
Set<String> rollups = null;
if (rollupOrder != null && rollupOrder.size() > 0) {
rollups = formRollupStrings(responseMap);
}
for (Entry<String, String> entry : responseMap.entrySet()) {
if (!unsummarizable.contains(entry.getKey())) {
String effectiveId = entry.getKey();
if (nameToIdMap.get(effectiveId) != null) {
effectiveId = collapseIdMap.get(nameToIdMap
.get(effectiveId));
}
String[] vals = entry.getValue().split("\\|");
synchronized (model) {
for (int i = 0; i < vals.length; i++) {
if (vals[i] != null && vals[i].trim().length() > 0) {
model.tallyResponse(effectiveId, rollups,
vals[i]);
}
}
}
}
}
}
}
/**
* creates the header for the raw data tab
*
* @param row
* @param questionMap
* @return - returns a 2 element array. The first element is a List of
* String objects representing all the question Ids. The second
* element is a List of Strings representing all the non-sumarizable
* question Ids (i.e. those that aren't OPTION or NUMBER questions)
*/
protected Object[] createRawDataHeader(Workbook wb, Sheet sheet,
Map<QuestionGroupDto, List<QuestionDto>> questionMap) {
Row row = null;
row = getRow(0, sheet);
createCell(row, 0, INSTANCE_LABEL.get(locale), headerStyle);
createCell(row, 1, SUB_DATE_LABEL.get(locale), headerStyle);
createCell(row, 2, SUBMITTER_LABEL.get(locale), headerStyle);
List<String> questionIdList = new ArrayList<String>();
List<String> nonSummarizableList = new ArrayList<String>();
if (questionMap != null) {
int offset = 3;
for (QuestionGroupDto group : orderedGroupList) {
if (questionMap.get(group) != null) {
for (QuestionDto q : questionMap.get(group)) {
questionIdList.add(q.getKeyId().toString());
createCell(
row,
offset++,
q.getKeyId().toString()
+ "|"
+ getLocalizedText(q.getText(),
q.getTranslationMap())
.replaceAll("\n", "").trim(),
headerStyle);
if (!(QuestionType.NUMBER == q.getType() || QuestionType.OPTION == q
.getType())) {
nonSummarizableList.add(q.getKeyId().toString());
}
}
}
}
}
Object[] temp = new Object[2];
temp[0] = questionIdList;
temp[1] = nonSummarizableList;
return temp;
}
/**
*
* Writes the report as an XLS document
*/
private void writeSummaryReport(
Map<QuestionGroupDto, List<QuestionDto>> questionMap,
SummaryModel summaryModel, String sector, Workbook wb)
throws Exception {
String title = sector == null ? SUMMARY_LABEL.get(locale) : sector;
Sheet sheet = null;
int sheetCount = 2;
String curTitle = WorkbookUtil.createSafeSheetName(title);
while (sheet == null) {
sheet = wb.getSheet(curTitle);
if (sheet == null) {
sheet = wb.createSheet(WorkbookUtil
.createSafeSheetName(curTitle));
} else {
sheet = null;
curTitle = title + " " + sheetCount;
sheetCount++;
}
}
CreationHelper creationHelper = wb.getCreationHelper();
Drawing patriarch = sheet.createDrawingPatriarch();
int curRow = 0;
Row row = getRow(curRow++, sheet);
if (sector == null) {
createCell(row, 0, REPORT_HEADER.get(locale), headerStyle);
} else {
createCell(row, 0, sector + " " + REPORT_HEADER.get(locale),
headerStyle);
}
for (QuestionGroupDto group : orderedGroupList) {
if (questionMap.get(group) != null) {
for (QuestionDto question : questionMap.get(group)) {
if (!(QuestionType.OPTION == question.getType() || QuestionType.NUMBER == question
.getType())) {
continue;
} else {
if (summaryModel.getResponseCountsForQuestion(
question.getKeyId(), sector).size() == 0) {
// if there is no data, skip the question
continue;
}
}
// for both options and numeric, we want a pie chart and
// data table for numeric, we also want descriptive
// statistics
int tableTopRow = curRow++;
int tableBottomRow = curRow;
row = getRow(tableTopRow, sheet);
// span the question heading over the data table
sheet.addMergedRegion(new CellRangeAddress(curRow - 1,
curRow - 1, 0, 2));
createCell(
row,
0,
getLocalizedText(question.getText(),
question.getTranslationMap()), headerStyle);
DescriptiveStats stats = summaryModel
.getDescriptiveStatsForQuestion(
question.getKeyId(), sector);
if (stats != null && stats.getSampleCount() > 0) {
sheet.addMergedRegion(new CellRangeAddress(curRow - 1,
curRow - 1, 4, 5));
createCell(
row,
4,
getLocalizedText(question.getText(),
question.getTranslationMap()),
headerStyle);
}
row = getRow(curRow++, sheet);
createCell(row, 1, FREQ_LABEL.get(locale), headerStyle);
createCell(row, 2, PCT_LABEL.get(locale), headerStyle);
// now create the data table for the option count
Map<String, Long> counts = summaryModel
.getResponseCountsForQuestion(question.getKeyId(),
sector);
int sampleTotal = 0;
List<String> labels = new ArrayList<String>();
List<String> values = new ArrayList<String>();
int firstOptRow = curRow;
for (Entry<String, Long> count : counts.entrySet()) {
row = getRow(curRow++, sheet);
String labelText = count.getKey();
if (labelText == null) {
labelText = "";
}
StringBuilder builder = new StringBuilder();
if (QuestionType.OPTION == question.getType()
&& !DEFAULT_LOCALE.equals(locale)) {
String[] tokens = labelText.split("\\|");
// see if we have a translation for this option
for (int i = 0; i < tokens.length; i++) {
if (i > 0) {
builder.append("|");
}
if (question.getOptionContainerDto() != null
&& question.getOptionContainerDto()
.getOptionsList() != null) {
boolean found = false;
for (QuestionOptionDto opt : question
.getOptionContainerDto()
.getOptionsList()) {
if (opt.getText() != null
&& opt.getText()
.trim()
.equalsIgnoreCase(
tokens[i])) {
builder.append(getLocalizedText(
tokens[i],
opt.getTranslationMap()));
found = true;
break;
}
}
if (!found) {
builder.append(tokens[i]);
}
}
}
} else {
builder.append(labelText);
}
createCell(row, 0, builder.toString(), null);
createCell(row, 1, count.getValue().toString(), null);
labels.add(builder.toString());
values.add(count.getValue().toString());
sampleTotal += count.getValue();
}
row = getRow(curRow++, sheet);
createCell(row, 0, TOTAL_LABEL.get(locale), null);
createCell(row, 1, sampleTotal + "", null);
for (int i = 0; i < values.size(); i++) {
row = getRow(firstOptRow + i, sheet);
if (sampleTotal > 0) {
createCell(row, 2,
PCT_FMT.format((Double.parseDouble(values
.get(i)) / (double) sampleTotal)),
null);
} else {
createCell(row, 2, PCT_FMT.format(0), null);
}
}
tableBottomRow = curRow;
if (stats != null && stats.getSampleCount() > 0) {
int tempRow = tableTopRow + 1;
row = getRow(tempRow++, sheet);
createCell(row, 4, "N", null);
createCell(row, 5, sampleTotal + "", null);
row = getRow(tempRow++, sheet);
createCell(row, 4, MEAN_LABEL.get(locale), null);
createCell(row, 5, stats.getMean() + "", null);
row = getRow(tempRow++, sheet);
createCell(row, 4, STD_E_LABEL.get(locale), null);
createCell(row, 5, stats.getStandardError() + "", null);
row = getRow(tempRow++, sheet);
createCell(row, 4, MEDIAN_LABEL.get(locale), null);
createCell(row, 5, stats.getMedian() + "", null);
row = getRow(tempRow++, sheet);
createCell(row, 4, MODE_LABEL.get(locale), null);
createCell(row, 5, stats.getMode() + "", null);
row = getRow(tempRow++, sheet);
createCell(row, 4, STD_D_LABEL.get(locale), null);
createCell(row, 5, stats.getStandardDeviation() + "",
null);
row = getRow(tempRow++, sheet);
createCell(row, 4, VAR_LABEL.get(locale), null);
createCell(row, 5, stats.getVariance() + "", null);
row = getRow(tempRow++, sheet);
createCell(row, 4, RANGE_LABEL.get(locale), null);
createCell(row, 5, stats.getRange() + "", null);
row = getRow(tempRow++, sheet);
createCell(row, 4, MIN_LABEL.get(locale), null);
createCell(row, 5, stats.getMin() + "", null);
row = getRow(tempRow++, sheet);
createCell(row, 4, MAX_LABEL.get(locale), null);
createCell(row, 5, stats.getMax() + "", null);
if (tableBottomRow < tempRow) {
tableBottomRow = tempRow;
}
}
curRow = tableBottomRow;
if (labels.size() > 0) {
boolean hasVals = false;
if (values != null) {
for (String val : values) {
try {
if (val != null
&& new Double(val.trim()) > 0D) {
hasVals = true;
break;
}
} catch (Exception e) {
// no-op
}
}
}
// only insert the image if we have at least 1 non-zero
// value
if (hasVals && generateCharts) {
// now insert the graph
int indx = wb
.addPicture(
JFreechartChartUtil
.getPieChart(
labels,
values,
getLocalizedText(
question.getText(),
question.getTranslationMap()),
CHART_WIDTH,
CHART_HEIGHT),
Workbook.PICTURE_TYPE_PNG);
ClientAnchor anchor = creationHelper
.createClientAnchor();
anchor.setDx1(0);
anchor.setDy1(0);
anchor.setDx2(0);
anchor.setDy2(255);
anchor.setCol1(6);
anchor.setRow1(tableTopRow);
anchor.setCol2(6 + CHART_CELL_WIDTH);
anchor.setRow2(tableTopRow + CHART_CELL_HEIGHT);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, indx);
if (tableTopRow + CHART_CELL_HEIGHT > tableBottomRow) {
curRow = tableTopRow + CHART_CELL_HEIGHT;
}
}
}
// add a blank row between questions
getRow(curRow++, sheet);
}
}
}
}
/**
* creates a cell in the row passed in and sets the style and value (if
* non-null)
*
*/
protected Cell createCell(Row row, int col, String value, CellStyle style) {
Cell cell = row.createCell(col);
if (style != null) {
cell.setCellStyle(style);
}
if (value != null) {
cell.setCellValue(value);
}
return cell;
}
/**
* finds or creates the row at the given index
*
* @param index
* @param rowLocalMax
* @param sheet
* @return
*/
private synchronized Row getRow(int index, Sheet sheet) {
Row row = null;
if (index < sheet.getLastRowNum()) {
row = sheet.getRow(index);
if (row == null) {
row = sheet.createRow(index);
}
} else {
row = sheet.createRow(index);
}
return row;
}
/**
* sets instance variables to the values passed in in the Option map. If the
* option is not set, the default values are used.
*
* @param options
*/
protected void processOptions(Map<String, String> options) {
isFullReport = true;
performGeoRollup = true;
maxSteps = FULL_STEPS;
if (options != null) {
locale = options.get(LOCALE_OPT);
imagePrefix = options.get(IMAGE_PREFIX_OPT);
if (RAW_ONLY_TYPE.equalsIgnoreCase(options.get(TYPE_OPT))) {
isFullReport = false;
maxSteps = RAW_STEPS;
}
if (options.get(DO_ROLLUP_OPT) != null) {
if ("false".equalsIgnoreCase(options.get(DO_ROLLUP_OPT))) {
performGeoRollup = false;
}
}
}
if (locale != null) {
locale = locale.trim().toLowerCase();
if (DEFAULT.equalsIgnoreCase(locale)) {
locale = DEFAULT_LOCALE;
}
} else {
locale = DEFAULT_LOCALE;
}
if (imagePrefix != null) {
imagePrefix = imagePrefix.trim();
+ if (!imagePrefix.endsWith("/")) {
+ imagePrefix = imagePrefix + "/";
+ }
} else {
imagePrefix = DEFAULT_IMAGE_PREFIX;
}
if (options.get(NO_CHART_OPT) != null) {
if ("true".equalsIgnoreCase(options.get(NO_CHART_OPT))) {
generateCharts = false;
} else {
generateCharts = true;
}
}
}
/**
* call the server to augment the data already loaded in each QuestionDto in
* the map passed in.
*
* @param questionMap
*/
private void loadFullQuestions(
Map<QuestionGroupDto, List<QuestionDto>> questionMap) {
for (List<QuestionDto> questionList : questionMap.values()) {
for (int i = 0; i < questionList.size(); i++) {
try {
QuestionDto newQ = BulkDataServiceClient
.loadQuestionDetails(serverBase, questionList
.get(i).getKeyId());
if (newQ != null) {
questionList.set(i, newQ);
}
} catch (Exception e) {
System.err.println("Could not fetch question details");
e.printStackTrace(System.err);
}
}
}
}
/**
* uses the locale and the translation map passed in to determine what value
* to use for the string
*
* @param text
* @param translationMap
* @return
*/
private String getLocalizedText(String text,
Map<String, TranslationDto> translationMap) {
TranslationDto trans = null;
if (translationMap != null) {
trans = translationMap.get(locale);
}
if (trans != null && trans.getText() != null
&& trans.getText().trim().length() > 0) {
return trans.getText();
} else {
return text;
}
}
protected String getImagePrefix() {
return this.imagePrefix;
}
/**
* Private class to handle updating of the UI thread from our worker thread
*/
private class StatusUpdater implements Runnable {
private int step;
private String msg;
public StatusUpdater(int step, String message) {
msg = message;
this.step = step;
}
public void run() {
progressDialog.update(step, msg);
}
}
private class RowData {
private Map<String, String> responseMap;
private String dateString;
private String instanceId;
private SurveyInstanceDto dto;
public Map<String, String> getResponseMap() {
return responseMap;
}
public void setResponseMap(Map<String, String> responseMap) {
this.responseMap = responseMap;
}
public String getDateString() {
return dateString;
}
public void setDateString(String dateString) {
this.dateString = dateString;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public SurveyInstanceDto getDto() {
return dto;
}
public void setDto(SurveyInstanceDto dto) {
this.dto = dto;
}
}
}
diff --git a/GAE/src/org/waterforpeople/mapping/dataexport/RawDataExporter.java b/GAE/src/org/waterforpeople/mapping/dataexport/RawDataExporter.java
index f697f4aab..9d1cb80ae 100644
--- a/GAE/src/org/waterforpeople/mapping/dataexport/RawDataExporter.java
+++ b/GAE/src/org/waterforpeople/mapping/dataexport/RawDataExporter.java
@@ -1,191 +1,195 @@
/*
* Copyright (C) 2010-2012 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.dataexport;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto;
import org.waterforpeople.mapping.dataexport.service.BulkDataServiceClient;
import com.gallatinsystems.common.util.PropertyUtil;
import com.gallatinsystems.framework.dataexport.applet.AbstractDataExporter;
/**
* exports raw data based on a date
*
* @author Christopher Fagiani
*
*/
public class RawDataExporter extends AbstractDataExporter {
private static final String IMAGE_PREFIX = "http://waterforpeople.s3.amazonaws.com/images/";
private static final String SDCARD_PREFIX = "/sdcard/";
private String serverBase;
private String surveyId;
public static final String SURVEY_ID = "surveyId";
private Map<String, String> questionMap;
private List<String> keyList;
@Override
@SuppressWarnings("unchecked")
public void export(Map<String, String> criteria, File fileName,
String serverBase, Map<String, String> options) {
this.serverBase = serverBase;
surveyId = criteria.get(SURVEY_ID);
Writer pw = null;
System.out.println("In CSV exporter");
try {
Object[] results = BulkDataServiceClient.loadQuestions(surveyId,
serverBase);
if (results != null) {
keyList = (List<String>) results[0];
questionMap = (Map<String, String>) results[1];
pw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), "UTF8"));
writeHeader(pw, questionMap);
exportInstances(pw, keyList);
} else {
System.out.println("Error getting questions");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (pw != null) {
try {
pw.close();
} catch (IOException e) {
System.err.println("Could not close writer: " + e);
}
}
}
}
@SuppressWarnings("unchecked")
public void export(String serverBase, Long surveyIdentifier, Writer pw) {
try {
this.surveyId = surveyIdentifier.toString();
this.serverBase = serverBase;
Object[] results = BulkDataServiceClient.loadQuestions(surveyId,
serverBase);
if (results != null) {
keyList = (List<String>) results[0];
questionMap = (Map<String, String>) results[1];
writeHeader(pw, questionMap);
exportInstances(pw, keyList);
} else {
System.out.println("Error getting questions");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void writeHeader(Writer pw, Map<String, String> questions)
throws Exception {
pw.write("Instance\tSubmission Date\tSubmitter");
if (keyList != null) {
for (String key : keyList) {
pw.write("\t");
String questionText = questions.get(key).replaceAll("\n", " ")
.trim();
questionText = questionText.replaceAll("\r", " ").trim();
pw.write(key + "|" + questionText);
}
}
pw.write("\n");
}
private void exportInstances(Writer pw, List<String> idList)
throws Exception {
Map<String, String> instances = BulkDataServiceClient.fetchInstanceIds(
surveyId, serverBase);
if (instances != null) {
String imagePrefix = IMAGE_PREFIX;
try {
imagePrefix = PropertyUtil.getProperty("photo_url_root");
+
} catch (Exception e) {
imagePrefix = IMAGE_PREFIX;
}
+ if(imagePrefix != null && !imagePrefix.endsWith("/")){
+ imagePrefix = imagePrefix + "/";
+ }
int i = 0;
for (Entry<String, String> instanceEntry : instances.entrySet()) {
String instanceId = instanceEntry.getKey();
String dateString = instanceEntry.getValue();
if (instanceId != null && instanceId.trim().length() > 0) {
try {
Map<String, String> responses = BulkDataServiceClient
.fetchQuestionResponses(instanceId, serverBase);
if (responses != null && responses.size() > 0) {
pw.write(instanceId);
pw.write("\t");
pw.write(dateString);
pw.write("\t");
SurveyInstanceDto dto = BulkDataServiceClient
.findSurveyInstance(
Long.parseLong(instanceId.trim()),
serverBase);
if (dto != null) {
String name = dto.getSubmitterName();
if (name != null) {
pw.write(dto.getSubmitterName()
.replaceAll("\n", " ").replaceAll("\t"," ").trim());
}
}
for (String key : idList) {
String val = responses.get(key);
pw.write("\t");
if (val != null) {
if (val.contains(SDCARD_PREFIX)) {
String[] photoParts = val.split("/");
if (photoParts.length > 1) {
val = imagePrefix
+ photoParts[photoParts.length - 1];
} else {
val = imagePrefix
+ val.substring(val
.indexOf(SDCARD_PREFIX)
+ SDCARD_PREFIX
.length());
}
}
pw.write(val.replaceAll("\n", " ").trim());
}
}
pw.write("\n");
pw.flush();
i++;
System.out.println("Row: " + i);
responses = null;
}
} catch (Exception ex) {
System.out
.println("Swallow the exception for now and continue");
}
}
}
}
}
}
| false | false | null | null |
diff --git a/runtime/android/java/src/org/xwalk/core/XWalkContent.java b/runtime/android/java/src/org/xwalk/core/XWalkContent.java
index 79003184..7b8f143e 100644
--- a/runtime/android/java/src/org/xwalk/core/XWalkContent.java
+++ b/runtime/android/java/src/org/xwalk/core/XWalkContent.java
@@ -1,202 +1,204 @@
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.core;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.chromium.base.JNINamespace;
import org.chromium.content.browser.ContentVideoView;
import org.chromium.content.browser.ContentView;
import org.chromium.content.browser.ContentViewCore;
import org.chromium.content.browser.ContentViewRenderView;
import org.chromium.content.browser.LoadUrlParams;
import org.chromium.content.browser.NavigationHistory;
import org.chromium.ui.WindowAndroid;
@JNINamespace("xwalk")
/**
* This class is the implementation class for XWalkView by calling internal
* various classes.
*/
public class XWalkContent extends FrameLayout {
private ContentViewCore mContentViewCore;
private ContentView mContentView;
private ContentViewRenderView mContentViewRenderView;
private WindowAndroid mWindow;
private XWalkView mXWalkView;
private XWalkContentsClientBridge mContentsClientBridge;
private XWalkWebContentsDelegateAdapter mXWalkContentsDelegateAdapter;
private XWalkSettings mSettings;
int mXWalkContent;
int mWebContents;
boolean mReadyToLoad = false;
String mPendingUrl = null;
public XWalkContent(Context context, AttributeSet attrs, XWalkView xwView) {
super(context, attrs);
// Initialize the WebContensDelegate.
mXWalkView = xwView;
mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView);
mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter(
mContentsClientBridge);
// Initialize ContentViewRenderView
mContentViewRenderView = new ContentViewRenderView(context) {
protected void onReadyToRender() {
- if (mPendingUrl != null)
+ if (mPendingUrl != null) {
doLoadUrl(mPendingUrl);
+ mPendingUrl = null;
+ }
mReadyToLoad = true;
}
};
addView(mContentViewRenderView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mXWalkContent = nativeInit(mXWalkContentsDelegateAdapter, mContentsClientBridge);
mWebContents = nativeGetWebContents(mXWalkContent);
// Initialize mWindow which is needed by content
mWindow = new WindowAndroid(xwView.getActivity());
// Initialize ContentView.
mContentView = ContentView.newInstance(getContext(), mWebContents, mWindow);
addView(mContentView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mContentView.setContentViewClient(mContentsClientBridge);
mContentViewRenderView.setCurrentContentView(mContentView);
// For addJavascriptInterface
mContentViewCore = mContentView.getContentViewCore();
mContentsClientBridge.installWebContentsObserver(mContentViewCore);
mSettings = new XWalkSettings(getContext(), mWebContents, true);
}
void doLoadUrl(String url) {
//TODO(Xingnan): Configure appropriate parameters here.
// Handle the same url loading by parameters.
if (TextUtils.equals(url, mContentView.getUrl())) {
mContentView.reload();
} else {
mContentView.loadUrl(new LoadUrlParams(url));
}
mContentView.clearFocus();
mContentView.requestFocus();
}
public void loadUrl(String url) {
if (url == null)
return;
if (mReadyToLoad)
doLoadUrl(url);
else
mPendingUrl = url;
}
public String getUrl() {
String url = mContentView.getUrl();
if (url == null || url.trim().isEmpty()) return null;
return url;
}
public void addJavascriptInterface(Object object, String name) {
mContentViewCore.addJavascriptInterface(object, name);
}
public void setXWalkWebChromeClient(XWalkWebChromeClient client) {
mContentsClientBridge.setXWalkWebChromeClient(client);
}
public void setXWalkClient(XWalkClient client) {
mContentsClientBridge.setXWalkClient(client);
}
public void onPause() {
mContentViewCore.onActivityPause();
}
public void onResume() {
mContentViewCore.onActivityResume();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mWindow.onActivityResult(requestCode, resultCode, data);
}
public void clearCache(boolean includeDiskFiles) {
if (mXWalkContent == 0) return;
nativeClearCache(mXWalkContent, includeDiskFiles);
}
public boolean canGoBack() {
return mContentView.canGoBack();
}
public void goBack() {
mContentView.goBack();
}
public boolean canGoForward() {
return mContentView.canGoForward();
}
public void goForward() {
mContentView.goForward();
}
public void stopLoading() {
mContentView.stopLoading();
}
public String getOriginalUrl() {
NavigationHistory history = mContentViewCore.getNavigationHistory();
int currentIndex = history.getCurrentEntryIndex();
if (currentIndex >= 0 && currentIndex < history.getEntryCount()) {
return history.getEntryAtIndex(currentIndex).getOriginalUrl();
}
return null;
}
// For instrumentation test.
public ContentViewCore getContentViewCoreForTest() {
return mContentViewCore;
}
// For instrumentation test.
public void installWebContentsObserverForTest(XWalkContentsClient contentClient) {
contentClient.installWebContentsObserver(mContentViewCore);
}
public String devToolsAgentId() {
return nativeDevToolsAgentId(mXWalkContent);
}
public XWalkSettings getSettings() {
return mSettings;
}
private native int nativeInit(XWalkWebContentsDelegate webViewContentsDelegate,
XWalkContentsClientBridge bridge);
private native int nativeGetWebContents(int nativeXWalkContent);
private native void nativeClearCache(int nativeXWalkContent, boolean includeDiskFiles);
private native String nativeDevToolsAgentId(int nativeXWalkContent);
}
| false | true | public XWalkContent(Context context, AttributeSet attrs, XWalkView xwView) {
super(context, attrs);
// Initialize the WebContensDelegate.
mXWalkView = xwView;
mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView);
mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter(
mContentsClientBridge);
// Initialize ContentViewRenderView
mContentViewRenderView = new ContentViewRenderView(context) {
protected void onReadyToRender() {
if (mPendingUrl != null)
doLoadUrl(mPendingUrl);
mReadyToLoad = true;
}
};
addView(mContentViewRenderView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mXWalkContent = nativeInit(mXWalkContentsDelegateAdapter, mContentsClientBridge);
mWebContents = nativeGetWebContents(mXWalkContent);
// Initialize mWindow which is needed by content
mWindow = new WindowAndroid(xwView.getActivity());
// Initialize ContentView.
mContentView = ContentView.newInstance(getContext(), mWebContents, mWindow);
addView(mContentView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mContentView.setContentViewClient(mContentsClientBridge);
mContentViewRenderView.setCurrentContentView(mContentView);
// For addJavascriptInterface
mContentViewCore = mContentView.getContentViewCore();
mContentsClientBridge.installWebContentsObserver(mContentViewCore);
mSettings = new XWalkSettings(getContext(), mWebContents, true);
}
| public XWalkContent(Context context, AttributeSet attrs, XWalkView xwView) {
super(context, attrs);
// Initialize the WebContensDelegate.
mXWalkView = xwView;
mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView);
mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter(
mContentsClientBridge);
// Initialize ContentViewRenderView
mContentViewRenderView = new ContentViewRenderView(context) {
protected void onReadyToRender() {
if (mPendingUrl != null) {
doLoadUrl(mPendingUrl);
mPendingUrl = null;
}
mReadyToLoad = true;
}
};
addView(mContentViewRenderView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mXWalkContent = nativeInit(mXWalkContentsDelegateAdapter, mContentsClientBridge);
mWebContents = nativeGetWebContents(mXWalkContent);
// Initialize mWindow which is needed by content
mWindow = new WindowAndroid(xwView.getActivity());
// Initialize ContentView.
mContentView = ContentView.newInstance(getContext(), mWebContents, mWindow);
addView(mContentView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mContentView.setContentViewClient(mContentsClientBridge);
mContentViewRenderView.setCurrentContentView(mContentView);
// For addJavascriptInterface
mContentViewCore = mContentView.getContentViewCore();
mContentsClientBridge.installWebContentsObserver(mContentViewCore);
mSettings = new XWalkSettings(getContext(), mWebContents, true);
}
|
diff --git a/src/java/org/jamwiki/servlets/EditServlet.java b/src/java/org/jamwiki/servlets/EditServlet.java
index cd34f7c0..93211d88 100644
--- a/src/java/org/jamwiki/servlets/EditServlet.java
+++ b/src/java/org/jamwiki/servlets/EditServlet.java
@@ -1,285 +1,285 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version 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 program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.servlets;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.WikiException;
import org.jamwiki.WikiMessage;
import org.jamwiki.model.Topic;
import org.jamwiki.model.TopicVersion;
import org.jamwiki.model.WikiUser;
import org.jamwiki.parser.ParserInput;
import org.jamwiki.parser.ParserDocument;
import org.jamwiki.utils.DiffUtil;
import org.jamwiki.utils.LinkUtil;
import org.jamwiki.utils.NamespaceHandler;
import org.jamwiki.utils.Utilities;
import org.jamwiki.utils.WikiLink;
import org.jamwiki.utils.WikiLogger;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
/**
*
*/
public class EditServlet extends JAMWikiServlet {
private static WikiLogger logger = WikiLogger.getLogger(EditServlet.class.getName());
/**
*
*/
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
ModelAndView next = new ModelAndView("wiki");
WikiPageInfo pageInfo = new WikiPageInfo();
try {
ModelAndView loginRequired = loginRequired(request);
if (loginRequired != null) {
return loginRequired;
}
if (isSave(request)) {
save(request, next, pageInfo);
} else {
edit(request, next, pageInfo);
}
} catch (Exception e) {
return viewError(request, e);
}
loadDefaults(request, next, pageInfo);
return next;
}
/**
*
*/
private void edit(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = JAMWikiServlet.getTopicFromRequest(request);
String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request);
Topic topic = loadTopic(virtualWiki, topicName);
// topic name might be updated by loadTopic
topicName = topic.getName();
Integer lastTopicVersionId = retrieveLastTopicVersionId(request, topic);
next.addObject("lastTopicVersionId", lastTopicVersionId);
loadEdit(request, next, pageInfo, virtualWiki, topicName, true);
String contents = null;
if (isPreview(request)) {
preview(request, next, pageInfo);
return;
}
pageInfo.setAction(WikiPageInfo.ACTION_EDIT);
if (StringUtils.hasText(request.getParameter("topicVersionId"))) {
// editing an older version
Integer topicVersionId = new Integer(request.getParameter("topicVersionId"));
TopicVersion topicVersion = WikiBase.getHandler().lookupTopicVersion(topicName, topicVersionId.intValue());
if (topicVersion == null) {
throw new WikiException(new WikiMessage("common.exception.notopic"));
}
contents = topicVersion.getVersionContent();
- if (lastTopicVersionId != topicVersionId) {
+ if (!lastTopicVersionId.equals(topicVersionId)) {
next.addObject("topicVersionId", topicVersionId);
}
} else if (StringUtils.hasText(request.getParameter("section"))) {
// editing a section of a topic
int section = (new Integer(request.getParameter("section"))).intValue();
ParserDocument parserDocument = Utilities.parseSlice(request, virtualWiki, topicName, section);
contents = parserDocument.getContent();
} else {
// editing a full new or existing topic
contents = (topic == null) ? "" : topic.getTopicContent();
}
next.addObject("contents", contents);
}
/**
*
*/
private boolean isPreview(HttpServletRequest request) {
return StringUtils.hasText(request.getParameter("preview"));
}
/**
*
*/
private boolean isSave(HttpServletRequest request) {
return StringUtils.hasText(request.getParameter("save"));
}
/**
*
*/
private void loadEdit(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo, String virtualWiki, String topicName, boolean useSection) throws Exception {
pageInfo.setPageTitle(new WikiMessage("edit.title", topicName));
pageInfo.setTopicName(topicName);
WikiLink wikiLink = LinkUtil.parseWikiLink(topicName);
String namespace = wikiLink.getNamespace();
if (namespace != null && namespace.equals(NamespaceHandler.NAMESPACE_CATEGORY)) {
loadCategoryContent(next, virtualWiki, topicName);
}
if (request.getParameter("editComment") != null) {
next.addObject("editComment", request.getParameter("editComment"));
}
if (useSection && request.getParameter("section") != null) {
next.addObject("section", request.getParameter("section"));
}
next.addObject("minorEdit", new Boolean(request.getParameter("minorEdit") != null));
}
/**
* Initialize topic values for the topic being edited. If a topic with
* the specified name already exists then it will be initialized,
* otherwise a new topic is created.
*/
private Topic loadTopic(String virtualWiki, String topicName) throws Exception {
Topic topic = this.initializeTopic(virtualWiki, topicName);
if (topic.getReadOnly()) {
throw new WikiException(new WikiMessage("error.readonly"));
}
return topic;
}
/**
*
*/
private ModelAndView loginRequired(HttpServletRequest request) throws Exception {
String topicName = JAMWikiServlet.getTopicFromRequest(request);
String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request);
if (!StringUtils.hasText(topicName) || !StringUtils.hasText(virtualWiki)) {
return null;
}
if (Environment.getBooleanValue(Environment.PROP_TOPIC_FORCE_USERNAME) && Utilities.currentUser(request) == null) {
WikiMessage errorMessage = new WikiMessage("edit.exception.login");
return viewLogin(request, JAMWikiServlet.getTopicFromURI(request), errorMessage);
}
Topic topic = WikiBase.getHandler().lookupTopic(virtualWiki, topicName);
if (topic != null && topic.getAdminOnly() && !Utilities.isAdmin(request)) {
WikiMessage errorMessage = new WikiMessage("edit.exception.loginadmin", topicName);
return viewLogin(request, JAMWikiServlet.getTopicFromURI(request), errorMessage);
}
return null;
}
/**
*
*/
private void preview(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = JAMWikiServlet.getTopicFromRequest(request);
String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request);
String contents = (String)request.getParameter("contents");
Topic previewTopic = new Topic();
previewTopic.setName(topicName);
previewTopic.setTopicContent(contents);
previewTopic.setVirtualWiki(virtualWiki);
pageInfo.setAction(WikiPageInfo.ACTION_EDIT_PREVIEW);
next.addObject("contents", contents);
viewTopic(request, next, pageInfo, null, previewTopic, false);
}
/**
*
*/
private void resolve(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = JAMWikiServlet.getTopicFromRequest(request);
String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request);
Topic lastTopic = WikiBase.getHandler().lookupTopic(virtualWiki, topicName);
String contents1 = lastTopic.getTopicContent();
String contents2 = request.getParameter("contents");
next.addObject("lastTopicVersionId", lastTopic.getCurrentVersionId());
next.addObject("contents", contents1);
next.addObject("contentsResolve", contents2);
Vector diffs = DiffUtil.diff(contents1, contents2);
next.addObject("diffs", diffs);
loadEdit(request, next, pageInfo, virtualWiki, topicName, false);
pageInfo.setAction(WikiPageInfo.ACTION_EDIT_RESOLVE);
}
/**
*
*/
private Integer retrieveLastTopicVersionId(HttpServletRequest request, Topic topic) throws Exception {
return (request.getParameter("lastTopicVersionId") == null) ? topic.getCurrentVersionId() : new Integer(request.getParameter("lastTopicVersionId"));
}
/**
*
*/
private void save(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = JAMWikiServlet.getTopicFromRequest(request);
String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request);
Topic topic = loadTopic(virtualWiki, topicName);
Topic lastTopic = WikiBase.getHandler().lookupTopic(virtualWiki, topicName);
- if (lastTopic != null && lastTopic.getCurrentVersionId() != retrieveLastTopicVersionId(request, topic)) {
+ if (lastTopic != null && !lastTopic.getCurrentVersionId().equals(retrieveLastTopicVersionId(request, topic))) {
// someone else has edited the topic more recently
resolve(request, next, pageInfo);
return;
}
String contents = request.getParameter("contents");
String sectionName = "";
if (StringUtils.hasText(request.getParameter("section"))) {
// load section of topic
int section = (new Integer(request.getParameter("section"))).intValue();
ParserDocument parserDocument = Utilities.parseSplice(request, virtualWiki, topicName, section, contents);
contents = parserDocument.getContent();
sectionName = parserDocument.getSectionName();
}
if (contents == null) {
logger.warning("The topic " + topicName + " has no content");
throw new WikiException(new WikiMessage("edit.exception.nocontent", topicName));
}
if (lastTopic != null && lastTopic.getTopicContent().equals(contents)) {
// topic hasn't changed. redirect to prevent user from refreshing and re-submitting
this.redirect(next, virtualWiki, topic.getName());
}
// parse for signatures and other syntax that should not be saved in raw form
WikiUser user = Utilities.currentUser(request);
ParserInput parserInput = new ParserInput();
parserInput.setContext(request.getContextPath());
parserInput.setLocale(request.getLocale());
parserInput.setWikiUser(user);
parserInput.setTopicName(topicName);
parserInput.setUserIpAddress(request.getRemoteAddr());
parserInput.setVirtualWiki(virtualWiki);
ParserDocument parserDocument = Utilities.parseSave(parserInput, contents);
contents = parserDocument.getContent();
topic.setTopicContent(contents);
if (StringUtils.hasText(parserDocument.getRedirect())) {
// set up a redirect
topic.setRedirectTo(parserDocument.getRedirect());
topic.setTopicType(Topic.TYPE_REDIRECT);
} else if (topic.getTopicType() == Topic.TYPE_REDIRECT) {
// no longer a redirect
topic.setRedirectTo(null);
topic.setTopicType(Topic.TYPE_ARTICLE);
}
TopicVersion topicVersion = new TopicVersion(user, request.getRemoteAddr(), request.getParameter("editComment"), contents);
if (request.getParameter("minorEdit") != null) {
topicVersion.setEditType(TopicVersion.EDIT_MINOR);
}
WikiBase.getHandler().writeTopic(topic, topicVersion, parserDocument);
// a save request has been made
JAMWikiServlet.removeCachedContents();
// redirect to prevent user from refreshing and re-submitting
String redirect = topic.getName();
if (StringUtils.hasText(sectionName)) {
redirect += "#" + sectionName;
}
this.redirect(next, virtualWiki, redirect);
}
}
| false | false | null | null |
diff --git a/src/main/java/com/basho/riak/pbc/RiakConnectionPool.java b/src/main/java/com/basho/riak/pbc/RiakConnectionPool.java
index c751ad89..ff3cdf87 100644
--- a/src/main/java/com/basho/riak/pbc/RiakConnectionPool.java
+++ b/src/main/java/com/basho/riak/pbc/RiakConnectionPool.java
@@ -1,506 +1,514 @@
/*
* This file is provided to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.basho.riak.pbc;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import com.basho.riak.client.raw.pbc.PoolSemaphore;
import com.basho.riak.protobuf.RiakKvPB.RpbSetClientIdReq;
import com.google.protobuf.ByteString;
-import java.util.concurrent.PriorityBlockingQueue;
+import java.util.Iterator;
+import java.util.concurrent.LinkedBlockingDeque;
/**
* A bounded or boundless pool of {@link RiakConnection}s to be reused by {@link RiakClient}
*
* The pool is designed to be threadsafe, and ideally to be used as a singleton.
* Due to backwards compatibility requirements it has not been implemented as a singleton.
* This is really a host connection pool. There is a minor optimization for reusing a connection
* by client Id, but more work needs doing here.
*
* @author russell
*
*/
public class RiakConnectionPool {
/**
* Specific behaviour for the pool methods, depending on the pools current
* state.
*/
enum State {
CREATED {
@Override void releaseConnection(RiakConnection c, RiakConnectionPool pool) {
throw new IllegalStateException("Pool not yet started");
}
@Override RiakConnection getConnection(byte[] clientId, RiakConnectionPool pool) {
throw new IllegalStateException("Pool not yet started");
}
@Override void start(RiakConnectionPool pool) {
pool.doStart();
}
@Override void shutdown(RiakConnectionPool pool) {
pool.doShutdown();
}
},
RUNNING {
@Override void releaseConnection(RiakConnection c, RiakConnectionPool pool) {
pool.doRelease(c);
}
@Override RiakConnection getConnection(byte[] clientId, RiakConnectionPool pool) throws IOException {
return pool.doGetConection(clientId); // use the internal get
// connection method
}
@Override void start(RiakConnectionPool pool) {
throw new IllegalStateException("pool already started");
}
@Override void shutdown(RiakConnectionPool pool) {
pool.doShutdown();
}
},
SHUTTING_DOWN {
@Override void releaseConnection(RiakConnection c, RiakConnectionPool pool) {
pool.closeAndRemove(c);
}
@Override RiakConnection getConnection(byte[] clientId, RiakConnectionPool pool) {
throw new IllegalStateException("pool shutting down");
}
@Override void start(RiakConnectionPool pool) {
throw new IllegalStateException("pool shutting down");
}
@Override void shutdown(RiakConnectionPool pool) {
throw new IllegalStateException("pool shutting down");
}
},
SHUTDOWN {
@Override void releaseConnection(RiakConnection c, RiakConnectionPool pool) {
throw new IllegalStateException("pool shut down");
}
@Override RiakConnection getConnection(byte[] clientId, RiakConnectionPool pool) {
throw new IllegalStateException("pool shut down");
}
@Override void start(RiakConnectionPool pool) {
throw new IllegalStateException("pool shut down");
}
@Override void shutdown(RiakConnectionPool pool) {
throw new IllegalStateException("pool shut down");
}
};
abstract void releaseConnection(RiakConnection c, RiakConnectionPool pool);
abstract RiakConnection getConnection(byte[] clientId, RiakConnectionPool pool) throws IOException;
abstract void start(RiakConnectionPool pool);
abstract void shutdown(RiakConnectionPool pool);
}
/**
* Constant to use for <code>maxSize</code> when creating an unbounded pool
*/
public static final int LIMITLESS = 0;
private static final int CONNECTION_ACQUIRE_ATTEMPTS = 3;
private final InetAddress host;
private final int port;
private final Semaphore permits;
- private final PriorityBlockingQueue<RiakConnection> available;
+ private final LinkedBlockingDeque<RiakConnection> available;
private final ConcurrentLinkedQueue<RiakConnection> inUse;
private final long connectionWaitTimeoutNanos;
private final int bufferSizeKb;
private final int initialSize;
private final long idleConnectionTTLNanos;
private final int requestTimeoutMillis;
private final ScheduledExecutorService idleReaper;
private final ScheduledExecutorService shutdownExecutor;
// what state the pool is in (see enum State)
private volatile State state;
/**
* Crate a new host connection pool. NOTE: before using you must call
* start()
*
* @param initialSize
* the number of connections to create at pool creation time
* @param maxSize
* the maximum number of connections this pool will have at any
* one time, 0 means limitless (i.e. creates a new connection if
* none are available)
* @param host
* the host this pool holds connections to
* @param port
* the port on host that this pool holds connections to
* @param connectionWaitTimeoutMillis
* the connection timeout
* @param bufferSizeKb
* the size of the socket/stream read/write buffers (3 buffers,
* each of this size)
* @param idleConnectionTTLMillis
* How long for an idle connection to exist before it is reaped,
* 0 mean forever
* @param requestTimeoutMillis
* The SO_TIMEOUT flag on the socket; read/write timeout
* 0 means forever
* @throws IOException
* If the initial connection creation throws an IOException
*/
public RiakConnectionPool(int initialSize, int maxSize, InetAddress host, int port,
long connectionWaitTimeoutMillis, int bufferSizeKb, long idleConnectionTTLMillis,
int requestTimeoutMillis) throws IOException {
this(initialSize, getSemaphore(maxSize), host, port, connectionWaitTimeoutMillis, bufferSizeKb,
idleConnectionTTLMillis, requestTimeoutMillis);
if (initialSize > maxSize && (maxSize > 0)) {
state = State.SHUTTING_DOWN;
throw new IllegalArgumentException("Initial pool size is greater than maximum pools size");
}
}
/**
* Crate a new host connection pool. NOTE: before using you must call
* start()
*
* @param initialSize
* the number of connections to create at pool creation time
* @param clusterSemaphore
* a {@link Semaphore} set with the number of permits for the
* pool (and maybe cluster (see {@link PoolSemaphore}))
* @param host
* the host this pool holds connections to
* @param port
* the port on host that this pool holds connections to
* @param connectionWaitTimeoutMillis
* the connection timeout
* @param bufferSizeKb
* the size of the socket/stream read/write buffers (3 buffers,
* each of this size)
* @param idleConnectionTTLMillis
* How long for an idle connection to exist before it is reaped,
* 0 mean forever
* @param requestTimeoutMillis
* The SO_TIMEOUT flag on the socket; read/write timeout
* 0 means forever
* @throws IOException
* If the initial connection creation throws an IOException
*/
public RiakConnectionPool(int initialSize, Semaphore poolSemaphore, InetAddress host, int port,
long connectionWaitTimeoutMillis, int bufferSizeKb, long idleConnectionTTLMillis,
int requestTimeoutMillis) throws IOException {
this.permits = poolSemaphore;
- this.available = new PriorityBlockingQueue<RiakConnection>();
+ this.available = new LinkedBlockingDeque<RiakConnection>();
this.inUse = new ConcurrentLinkedQueue<RiakConnection>();
this.bufferSizeKb = bufferSizeKb;
this.host = host;
this.port = port;
this.connectionWaitTimeoutNanos = TimeUnit.NANOSECONDS.convert(connectionWaitTimeoutMillis, TimeUnit.MILLISECONDS);
this.requestTimeoutMillis = requestTimeoutMillis;
this.initialSize = initialSize;
this.idleConnectionTTLNanos = TimeUnit.NANOSECONDS.convert(idleConnectionTTLMillis, TimeUnit.MILLISECONDS);
this.idleReaper = Executors.newScheduledThreadPool(1);
this.shutdownExecutor = Executors.newScheduledThreadPool(1);
this.state = State.CREATED;
warmUp();
}
/**
* Starts the reaper thread
*/
public synchronized void start() {
state.start(this);
}
private synchronized void doStart() {
if (idleConnectionTTLNanos > 0) {
idleReaper.scheduleWithFixedDelay(new Runnable() {
public void run() {
- RiakConnection c = available.peek();
- while (c != null) {
+ // Note this will not throw a ConncurrentModificationException
+ // and if hasNext() returns true you are guaranteed that
+ // the next() will return a value (even if it has already
+ // been removed from the Deque between those calls).
+ Iterator<RiakConnection> i = available.descendingIterator();
+ while (i.hasNext()) {
+ RiakConnection c = i.next();
long connIdleStartNanos = c.getIdleStartTimeNanos();
if (connIdleStartNanos + idleConnectionTTLNanos < System.nanoTime()) {
if (c.getIdleStartTimeNanos() == connIdleStartNanos) {
// still a small window, but better than locking
// the whole pool
boolean removed = available.remove(c);
if (removed) {
c.close();
permits.release();
}
}
- c = available.peek();
- }
+ }
}
}
}, idleConnectionTTLNanos, idleConnectionTTLNanos, TimeUnit.NANOSECONDS);
}
state = State.RUNNING;
}
/**
* Create the correct type of semaphore for the
* <code>maxSize</maxSize>, zero is limitless.
*
* @param maxSize
* the number of permits to create a semaphore for
* @return a {@link Semaphore} with <code>maxSize</code> permits, or a
* {@link LimitlessSemaphore} if <code>maxSize</code> is zero or less.
*/
public static Semaphore getSemaphore(int maxSize) {
if (maxSize <= LIMITLESS) {
return new LimitlessSemaphore();
}
return new Semaphore(maxSize, true);
}
/**
* If there are any initial connections to create, do it.
* @throws IOException
*/
private void warmUp() throws IOException {
if (permits.tryAcquire(initialSize)) {
for (int i = 0; i < this.initialSize; i++) {
- available.add(new RiakConnection(this.host, this.port,
- this.bufferSizeKb, this,
- TimeUnit.MILLISECONDS.convert(connectionWaitTimeoutNanos, TimeUnit.NANOSECONDS),
- requestTimeoutMillis));
+ RiakConnection c =
+ new RiakConnection(this.host, this.port,
+ this.bufferSizeKb, this,
+ TimeUnit.MILLISECONDS.convert(connectionWaitTimeoutNanos, TimeUnit.NANOSECONDS),
+ requestTimeoutMillis);
+ c.beginIdle();
+ available.add(c);
}
} else {
throw new RuntimeException("Unable to create initial connections");
}
}
/**
* Get a connection from the pool for the given client Id. If there is a
* connection with that client id in the pool, get that, if there is a
* connection in the pool but with the wrong Id, call setClientId on it and
* return it, if there is no available connection and the pool is under
* limit create a connection, set the id on it and return it.
*
* @param clientId
* the client id of the connection requested
* @return a RiakConnection with the clientId set
* @throws IOException
* @throws AcquireConnectionTimeoutException
* if unable to acquire a permit to create a *new* connection
* within the timeout configured. This means that the pool has
* no available connections and there are no permits available to
* create new connections. Repeated incidences of this exception
* probably indicate that you have sized your pool too small.
*/
public RiakConnection getConnection(byte[] clientId) throws IOException {
return state.getConnection(clientId, this);
}
private RiakConnection doGetConection(byte[] clientId) throws IOException {
RiakConnection c = getConnection();
if (clientId != null && !Arrays.equals(clientId, c.getClientId())) {
setClientIdOnConnection(c, clientId);
}
return c;
}
/**
* Calls the Riak PB API to set the client Id on a the given connection
*
* If an exception is thrown the connection is released from the pool and
* the connection re thrown to the caller.
*
* @param c
* the connection to set the Id on
* @throws IOException
*/
private void setClientIdOnConnection(RiakConnection c, byte[] clientId) throws IOException {
RpbSetClientIdReq req = com.basho.riak.protobuf.RiakKvPB.RpbSetClientIdReq.newBuilder().setClientId(ByteString.copyFrom(clientId)).build();
try {
c.send(RiakMessageCodes.MSG_SetClientIdReq, req);
c.receive_code(RiakMessageCodes.MSG_SetClientIdResp);
c.setClientId(clientId);
} catch (IOException e) {
// can't set the clientId? Can't use the connection. Kill it and
// throw an IOException
c.close();
releaseConnection(c);
throw e;
}
}
/**
* Get a RiakConnection from the pool, or create a new one if non in the
* pool and the limit is not reached. Waits for the configured
* <code>connectionWaitTimeoutMillis</code> to acquire a connection if non
* are available, throws IOException if timeout occurs. Will re-try if
* interrupted waiting for the connection.
*
* @return a connection from the pool, or a new connection
* @throws IOException
*/
private RiakConnection getConnection() throws IOException {
RiakConnection c = available.poll();
if (c == null) {
c = createConnection(CONNECTION_ACQUIRE_ATTEMPTS);
}
inUse.offer(c);
return c;
}
/**
* @param attempts
* @return
*/
private RiakConnection createConnection(int attempts) throws IOException {
try {
if (permits.tryAcquire(connectionWaitTimeoutNanos, TimeUnit.NANOSECONDS)) {
boolean releasePermit = true;
try {
RiakConnection connection = new RiakConnection(host, port, bufferSizeKb, this, TimeUnit.MILLISECONDS.convert(connectionWaitTimeoutNanos, TimeUnit.NANOSECONDS), requestTimeoutMillis);
releasePermit = false;
return connection;
} catch (SocketTimeoutException e) {
throw new AcquireConnectionTimeoutException("timeout from socket connection " + e.getMessage(), e);
} catch (IOException e) {
throw e;
} finally {
if (releasePermit) {
permits.release();
}
}
} else {
throw new AcquireConnectionTimeoutException("timeout acquiring connection permit from pool");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
if (attempts > 0) {
return createConnection(attempts - 1);
} else {
throw new IOException("repeatedly interrupted whilst waiting to acquire connection");
}
}
}
/**
* Returns a connection to the pool (unless the connection is closed (for some
* reason))
*
* @param c
* the connection to return.
*/
public void releaseConnection(final RiakConnection c) {
state.releaseConnection(c, this);
}
/**
* internal release
* @param c
*/
private void doRelease(RiakConnection c) {
if (c == null) {
return;
}
if (inUse.remove(c)) {
if (!c.isClosed()) {
c.beginIdle();
- available.offer(c);
+ available.offerFirst(c);
} else {
// don't put a closed connection in the pool, release a permit
permits.release();
}
} else {
// not our connection?
throw new IllegalArgumentException("connection not managed by this pool");
}
}
/**
* internal close and remove from the inUse queue. Does not return to the
* available pool, does not release a permit. Used for a pool that is
* shutting/shut down.
*
* @param c
*/
private void closeAndRemove(RiakConnection c) {
c.close();
inUse.remove(c);
}
/**
* Close this pool and all its connections. The pool will throw
* {@link IllegalStateException} for calls to getConnection. While shutting
* down it will still accept calls to releaseConnection.
*/
public synchronized void shutdown() {
state.shutdown(this);
}
/**
* Shuts the pool down.
*
* Close all connections in available.
* Stop the reaper thread.
* Start a thread that checks the inUse queue is empty.
*/
private void doShutdown() {
state = State.SHUTTING_DOWN;
// drain the available pool
RiakConnection c = available.poll();
while( c != null) {
c.close();
c = available.poll();
}
shutdownExecutor.scheduleWithFixedDelay(new Runnable() {
public void run() {
// when all connections are returned, and the available pool is empty
if(inUse.isEmpty() && available.isEmpty()) {
state = State.SHUTDOWN;
shutdownExecutor.shutdown();
idleReaper.shutdown();
}
}
}, 0, 1, TimeUnit.SECONDS);
}
/**
* Convenience method to check the state of the pool.
*
* @return the name of the current {@link State} of the pool
*/
public String getPoolState() {
return state.name();
}
}
| false | false | null | null |
diff --git a/src/main/java/tconstruct/library/tools/ToolCore.java b/src/main/java/tconstruct/library/tools/ToolCore.java
index 90a3c8b25..93feca0ec 100644
--- a/src/main/java/tconstruct/library/tools/ToolCore.java
+++ b/src/main/java/tconstruct/library/tools/ToolCore.java
@@ -1,924 +1,924 @@
package tconstruct.library.tools;
import cofh.api.energy.IEnergyContainerItem;
import cofh.core.item.IEqualityOverrideItem;
import cpw.mods.fml.common.Optional;
import cpw.mods.fml.relauncher.*;
import java.util.*;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.*;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.*;
import net.minecraft.world.World;
import tconstruct.TConstruct;
import tconstruct.library.*;
import tconstruct.library.crafting.ToolBuilder;
import tconstruct.library.modifier.*;
import tconstruct.library.util.TextureHelper;
import tconstruct.tools.TinkerTools;
import tconstruct.tools.entity.FancyEntityItem;
import tconstruct.util.config.PHConstruct;
/**
* NBTTags Main tag - InfiTool
*
* @see ToolBuilder
*
* Required: Head: Base and render tag, above the handle Handle: Base and
* render tag, bottom layer
*
* Damage: Replacement for metadata MaxDamage: ItemStacks only read
* setMaxDamage() Broken: Represents whether the tool is broken (boolean)
* Attack: How much damage a mob will take MiningSpeed: The speed at which
* a tool mines
*
* Others: Accessory: Base and tag, above head. Sword guards, binding, etc
* Effects: Render tag, top layer. Fancy effects like moss or diamond edge.
* Render order: Handle > Head > Accessory > Effect1 > Effect2 > Effect3 >
* etc Unbreaking: Reinforced in-game, 10% chance to not use durability per
* level Stonebound: Mines faster as the tool takes damage, but has less
* attack Spiny: Opposite of stonebound
*
* Modifiers have their own tags.
* @see ItemModifier
*/
@Optional.InterfaceList({
@Optional.Interface(modid = "CoFHLib", iface = "cofh.api.energy.IEnergyContainerItem"),
@Optional.Interface(modid = "CoFHCore", iface = "cofh.core.item.IEqualityOverrideItem")
})
public abstract class ToolCore extends Item implements IEnergyContainerItem, IEqualityOverrideItem, IModifyable
{
protected Random random = new Random();
protected int damageVsEntity;
public static IIcon blankSprite;
public static IIcon emptyIcon;
public ToolCore(int baseDamage)
{
super();
this.maxStackSize = 1;
this.setMaxDamage(100);
this.setUnlocalizedName("InfiTool");
this.setCreativeTab(TConstructRegistry.toolTab);
damageVsEntity = baseDamage;
TConstructRegistry.addToolMapping(this);
setNoRepair();
canRepair = false;
}
@Override
public String getBaseTagName ()
{
return "InfiTool";
}
@Override
public String getModifyType ()
{
return "Tool";
}
/**
* Determines crafting behavior with regards to durability 0: None 1: Adds
* handle modifier 2: Averages part with the rest of the tool (head)
*
* @return type
*/
public int durabilityTypeHandle ()
{
return 1;
}
public int durabilityTypeAccessory ()
{
return 0;
}
public int durabilityTypeExtra ()
{
return 0;
}
public int getModifierAmount ()
{
return 3;
}
public String getToolName ()
{
return this.getClass().getSimpleName();
}
public String getLocalizedToolName ()
{
return StatCollector.translateToLocal("tool." + getToolName().toLowerCase());
}
/* Rendering */
public HashMap<Integer, IIcon> headIcons = new HashMap<Integer, IIcon>();
public HashMap<Integer, IIcon> brokenIcons = new HashMap<Integer, IIcon>();
public HashMap<Integer, IIcon> handleIcons = new HashMap<Integer, IIcon>();
public HashMap<Integer, IIcon> accessoryIcons = new HashMap<Integer, IIcon>();
public HashMap<Integer, IIcon> effectIcons = new HashMap<Integer, IIcon>();
public HashMap<Integer, IIcon> extraIcons = new HashMap<Integer, IIcon>();
//Not liking this
public HashMap<Integer, String> headStrings = new HashMap<Integer, String>();
public HashMap<Integer, String> brokenPartStrings = new HashMap<Integer, String>();
public HashMap<Integer, String> handleStrings = new HashMap<Integer, String>();
public HashMap<Integer, String> accessoryStrings = new HashMap<Integer, String>();
public HashMap<Integer, String> effectStrings = new HashMap<Integer, String>();
public HashMap<Integer, String> extraStrings = new HashMap<Integer, String>();
@SideOnly(Side.CLIENT)
@Override
public boolean requiresMultipleRenderPasses ()
{
return true;
}
@SideOnly(Side.CLIENT)
@Override
public int getRenderPasses (int metadata)
{
return 9;
}
@Override
@SideOnly(Side.CLIENT)
public boolean hasEffect (ItemStack par1ItemStack)
{
return false;
}
// Override me please!
public int getPartAmount ()
{
return 3;
}
public abstract String getIconSuffix (int partType);
public abstract String getEffectSuffix ();
public abstract String getDefaultFolder ();
/**
* Returns the COMPLETE resource path.
* Example: tinker:broadsword
*
* @return
*/
public String getDefaultTexturePath()
{
return "tinker:" + getDefaultFolder();
}
public void registerPartPaths (int index, String[] location)
{
headStrings.put(index, location[0]);
brokenPartStrings.put(index, location[1]);
handleStrings.put(index, location[2]);
if (location.length > 3)
accessoryStrings.put(index, location[3]);
if (location.length > 4)
extraStrings.put(index, location[4]);
}
public void registerAlternatePartPaths (int index, String[] location)
{
}
public void registerEffectPath (int index, String location)
{
effectStrings.put(index, location);
}
@Override
public void registerIcons (IIconRegister iconRegister)
{
boolean minimalTextures = PHConstruct.minimalTextures;
addIcons(headStrings, headIcons, iconRegister, getIconSuffix(0), minimalTextures);
addIcons(brokenPartStrings, brokenIcons, iconRegister, getIconSuffix(1), minimalTextures);
addIcons(handleStrings, handleIcons, iconRegister, getIconSuffix(2), minimalTextures);
addIcons(accessoryStrings, accessoryIcons, iconRegister, getIconSuffix(3), minimalTextures);
addIcons(extraStrings, extraIcons, iconRegister, getIconSuffix(4), minimalTextures);
addIcons(effectStrings, effectIcons, iconRegister, null, false);
emptyIcon = iconRegister.registerIcon("tinker:blankface");
}
protected void addIcons(HashMap<Integer, String> textures, HashMap<Integer, IIcon> icons, IIconRegister iconRegister, String standard, boolean defaultOnly)
{
icons.clear();
if(!defaultOnly) // compatibility mode: no specific textures
for(Map.Entry<Integer, String> entry : textures.entrySet())
{
if(TextureHelper.itemTextureExists(entry.getValue()))
icons.put(entry.getKey(), iconRegister.registerIcon(entry.getValue()));
}
if(standard != null && !standard.isEmpty()) {
standard = getDefaultTexturePath() + "/" + standard;
icons.put(-1, iconRegister.registerIcon(standard));
}
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage (int meta)
{
return blankSprite;
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon (ItemStack stack, int renderPass)
{
NBTTagCompound tags = stack.getTagCompound();
if (tags != null)
{
tags = stack.getTagCompound().getCompoundTag("InfiTool");
if (renderPass < getPartAmount())
{
// Handle
if (renderPass == 0)
return getCorrectIcon(handleIcons, tags.getInteger("RenderHandle"));
// Head
else if (renderPass == 1)
{
if (tags.getBoolean("Broken"))
return getCorrectIcon(brokenIcons, tags.getInteger("RenderHead"));
else
return getCorrectIcon(headIcons, tags.getInteger("RenderHead"));
}
// Accessory
else if (renderPass == 2)
return getCorrectIcon(accessoryIcons, tags.getInteger("RenderAccessory"));
// Extra
else if (renderPass == 3)
return getCorrectIcon(extraIcons, tags.getInteger("RenderExtra"));
}
// Effects
else if (renderPass <= 10)
{
String effect = "Effect" + (1 + renderPass - getPartAmount());
if(tags.hasKey(effect))
return effectIcons.get(tags.getInteger(effect));
}
return blankSprite;
}
return emptyIcon;
}
protected IIcon getCorrectIcon(Map<Integer, IIcon> icons, int id)
{
if(icons.containsKey(id))
return icons.get(id);
// default icon
return icons.get(-1);
}
/* Tags and information about the tool */
@Override
@SideOnly(Side.CLIENT)
public void addInformation (ItemStack stack, EntityPlayer player, List list, boolean par4)
{
if (!stack.hasTagCompound())
return;
NBTTagCompound tags = stack.getTagCompound();
if (tags.hasKey("Energy"))
{
String color = "";
int RF = tags.getInteger("Energy");
if (RF != 0)
{
if (RF <= this.getMaxEnergyStored(stack) / 3)
color = "\u00a74";
else if (RF > this.getMaxEnergyStored(stack) * 2 / 3)
color = "\u00a72";
else
color = "\u00a76";
}
String energy = new StringBuilder().append(color).append(tags.getInteger("Energy")).append("/").append(getMaxEnergyStored(stack)).append(" RF").toString();
list.add(energy);
}
if (tags.hasKey("InfiTool"))
{
boolean broken = tags.getCompoundTag("InfiTool").getBoolean("Broken");
if (broken)
list.add("\u00A7oBroken");
else
{
int head = tags.getCompoundTag("InfiTool").getInteger("Head");
int handle = tags.getCompoundTag("InfiTool").getInteger("Handle");
int binding = tags.getCompoundTag("InfiTool").getInteger("Accessory");
int extra = tags.getCompoundTag("InfiTool").getInteger("Extra");
String headName = getAbilityNameForType(head, 0);
if (!headName.equals(""))
list.add(getStyleForType(head) + headName);
String handleName = getAbilityNameForType(handle, 1);
if (!handleName.equals("") && handle != head)
list.add(getStyleForType(handle) + handleName);
if (getPartAmount() >= 3)
{
String bindingName = getAbilityNameForType(binding, 2);
if (!bindingName.equals("") && binding != head && binding != handle)
list.add(getStyleForType(binding) + bindingName);
}
if (getPartAmount() >= 4)
{
String extraName = getAbilityNameForType(extra, 3);
if (!extraName.equals("") && extra != head && extra != handle && extra != binding)
list.add(getStyleForType(extra) + extraName);
}
int unbreaking = tags.getCompoundTag("InfiTool").getInteger("Unbreaking");
String reinforced = getReinforcedName(head, handle, binding, extra, unbreaking);
if (!reinforced.equals(""))
list.add(reinforced);
boolean displayToolTips = true;
int tipNum = 0;
while (displayToolTips)
{
tipNum++;
String tooltip = "Tooltip" + tipNum;
if (tags.getCompoundTag("InfiTool").hasKey(tooltip))
{
String tipName = tags.getCompoundTag("InfiTool").getString(tooltip);
if (!tipName.equals(""))
list.add(tipName);
}
else
displayToolTips = false;
}
}
}
list.add("");
int attack = (int) (tags.getCompoundTag("InfiTool").getInteger("Attack") * this.getDamageModifier());
list.add("\u00A79+" + attack + " " + StatCollector.translateToLocalFormatted("attribute.name.generic.attackDamage"));
}
public static String getStyleForType (int type)
{
return TConstructRegistry.getMaterial(type).style();
}
/**
* Returns the localized name of the materials ability. Only use this for display purposes, not for logic.
*/
public String getAbilityNameForType (int type, int part)
{
return TConstructRegistry.getMaterial(type).ability();
}
public String getReinforcedName (int head, int handle, int accessory, int extra, int unbreaking)
{
tconstruct.library.tools.ToolMaterial headMat = TConstructRegistry.getMaterial(head);
tconstruct.library.tools.ToolMaterial handleMat = TConstructRegistry.getMaterial(handle);
tconstruct.library.tools.ToolMaterial accessoryMat = TConstructRegistry.getMaterial(accessory);
tconstruct.library.tools.ToolMaterial extraMat = TConstructRegistry.getMaterial(extra);
int reinforced = 0;
String style = "";
int current = headMat.reinforced();
if (current > 0)
{
style = headMat.style();
reinforced = current;
}
current = handleMat.reinforced();
if (current > 0 && current > reinforced)
{
style = handleMat.style();
reinforced = current;
}
if (getPartAmount() >= 3)
{
current = accessoryMat.reinforced();
if (current > 0 && current > reinforced)
{
style = accessoryMat.style();
reinforced = current;
}
}
if (getPartAmount() >= 4)
{
current = extraMat.reinforced();
if (current > 0 && current > reinforced)
{
style = extraMat.style();
reinforced = current;
}
}
reinforced += unbreaking - reinforced;
if (reinforced > 0)
{
return style + getReinforcedString(reinforced);
}
return "";
}
String getReinforcedString (int reinforced)
{
if (reinforced > 9)
return "Unbreakable";
String ret = "Reinforced ";
switch (reinforced)
{
case 1:
ret += "I";
break;
case 2:
ret += "II";
break;
case 3:
ret += "III";
break;
case 4:
ret += "IV";
break;
case 5:
ret += "V";
break;
case 6:
ret += "VI";
break;
case 7:
ret += "VII";
break;
case 8:
ret += "VIII";
break;
case 9:
ret += "IX";
break;
default:
ret += "X";
break;
}
return ret;
}
// Used for sounds and the like
public void onEntityDamaged (World world, EntityLivingBase player, Entity entity)
{
}
/* Creative mode tools */
@Override
public void getSubItems (Item id, CreativeTabs tab, List list)
{
Iterator iter = TConstructRegistry.toolMaterials.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry pairs = (Map.Entry) iter.next();
tconstruct.library.tools.ToolMaterial material = (tconstruct.library.tools.ToolMaterial) pairs.getValue();
buildTool((Integer) pairs.getKey(), ToolBuilder.defaultToolName(material, this), list);
}
}
public void buildTool (int id, String name, List list)
{
Item accessory = getAccessoryItem();
ItemStack accessoryStack = accessory != null ? new ItemStack(getAccessoryItem(), 1, id) : null;
Item extra = getExtraItem();
ItemStack extraStack = extra != null ? new ItemStack(extra, 1, id) : null;
ItemStack tool = ToolBuilder.instance.buildTool(new ItemStack(getHeadItem(), 1, id), new ItemStack(getHandleItem(), 1, id), accessoryStack, extraStack, name);
if (tool != null)
{
tool.getTagCompound().getCompoundTag("InfiTool").setBoolean("Built", true);
list.add(tool);
}
}
public abstract Item getHeadItem ();
public abstract Item getAccessoryItem ();
public Item getExtraItem ()
{
return null;
}
public Item getHandleItem ()
{
return TinkerTools.toolRod;
}
/* Updating */
@Override
public void onUpdate (ItemStack stack, World world, Entity entity, int par4, boolean par5)
{
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
mod.updateTool(this, stack, world, entity);
}
}
/* Tool uses */
// Types
public abstract String[] getTraits ();
// Mining
@Override
public boolean onBlockStartBreak (ItemStack stack, int x, int y, int z, EntityPlayer player)
{
if(!stack.hasTagCompound())
return false;
boolean cancelHarvest = false;
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
{
if (mod.beforeBlockBreak(this, stack, x, y, z, player))
cancelHarvest = true;
}
return cancelHarvest;
}
@Override
public boolean onBlockDestroyed (ItemStack itemstack, World world, Block block, int x, int y, int z, EntityLivingBase player)
{
if(!itemstack.hasTagCompound())
return false;
// callbacks!
for (ActiveToolMod mod : TConstructRegistry.activeModifiers)
mod.afterBlockBreak(this, itemstack, block, x, y, z, player);
if (block != null && (double) block.getBlockHardness(world, x, y, z) != 0.0D)
{
return AbilityHelper.onBlockChanged(itemstack, world, block, x, y, z, player, random);
}
return true;
}
@Override
public float getDigSpeed (ItemStack stack, Block block, int meta)
{
NBTTagCompound tags = stack.getTagCompound();
if (tags.getCompoundTag("InfiTool").getBoolean("Broken"))
return 0.1f;
return 1f;
}
// Attacking
@Override
public boolean onLeftClickEntity (ItemStack stack, EntityPlayer player, Entity entity)
{
return AbilityHelper.onLeftClickEntity(stack, player, entity, this, 0);
}
@Override
public boolean hitEntity (ItemStack stack, EntityLivingBase mob, EntityLivingBase player)
{
return true;
}
public boolean pierceArmor ()
{
return false;
}
public float chargeAttack ()
{
return 1f;
}
public int getDamageVsEntity (Entity par1Entity)
{
return this.damageVsEntity;
}
// Changes how much durability the base tool has
public float getDurabilityModifier ()
{
return 1f;
}
public float getRepairCost ()
{
return getDurabilityModifier();
}
public float getDamageModifier ()
{
return 1.0f;
}
@Override
public int getColorFromItemStack(ItemStack stack, int renderPass) {
NBTTagCompound tags = stack.getTagCompound();
if (tags != null)
{
tags = stack.getTagCompound().getCompoundTag("InfiTool");
if (renderPass < getPartAmount())
{
switch(renderPass)
{
case 0: return getCorrectColor(stack, renderPass, tags, "Handle", handleIcons);
- case 1: return getCorrectColor(stack, renderPass, tags, "Head", headIcons);
+ case 1: return tags.getBoolean("Broken") ? getCorrectColor(stack, renderPass, tags, "Head", brokenIcons) : getCorrectColor(stack, renderPass, tags, "Head", headIcons);
case 2: return getCorrectColor(stack, renderPass, tags, "Accessory", accessoryIcons);
case 3: return getCorrectColor(stack, renderPass, tags, "Extra", extraIcons);
}
}
}
return super.getColorFromItemStack(stack, renderPass);
}
protected int getCorrectColor(ItemStack stack, int renderPass, NBTTagCompound tags, String key, Map<Integer, IIcon> map)
{
// custom coloring
if(tags.hasKey(key + "Color"))
return tags.getInteger(key + "Color");
// custom texture?
Integer matId = tags.getInteger("Render" + key);
if(map.containsKey(matId))
return super.getColorFromItemStack(stack, renderPass);
// color default texture with material color
return getDefaultColor(renderPass, matId);
}
protected int getDefaultColor(int renderPass, int materialID)
{
return TConstructRegistry.getMaterial(materialID).primaryColor();
}
@Override
public ItemStack onItemRightClick (ItemStack stack, World world, EntityPlayer player)
{
boolean used = false;
int hotbarSlot = player.inventory.currentItem;
int itemSlot = hotbarSlot == 0 ? 8 : hotbarSlot + 1;
ItemStack nearbyStack = null;
if (hotbarSlot < 8)
{
nearbyStack = player.inventory.getStackInSlot(itemSlot);
if (nearbyStack != null)
{
Item item = nearbyStack.getItem();
if (item instanceof ItemPotion && ((ItemPotion) item).isSplash(nearbyStack.getItemDamage()))
{
nearbyStack = item.onItemRightClick(nearbyStack, world, player);
if (nearbyStack.stackSize < 1)
{
nearbyStack = null;
player.inventory.setInventorySlotContents(itemSlot, null);
}
}
}
}
return stack;
}
/* Vanilla overrides */
@Override
public boolean isItemTool (ItemStack par1ItemStack)
{
return false;
}
@Override
public boolean getIsRepairable (ItemStack par1ItemStack, ItemStack par2ItemStack)
{
return false;
}
@Override
public boolean isRepairable ()
{
return false;
}
@Override
public int getItemEnchantability ()
{
return 0;
}
@Override
public boolean isFull3D ()
{
return true;
}
@Override
@SideOnly(Side.CLIENT)
public boolean hasEffect (ItemStack par1ItemStack, int pass)
{
return false;
}
/* Proper stack damage */
@Override
public boolean showDurabilityBar(ItemStack stack) {
if(!stack.hasTagCompound())
return false;
NBTTagCompound tags = stack.getTagCompound().getCompoundTag("InfiTool");
return !tags.getBoolean("Broken") && getDamage(stack) > 0;
}
@Override
public int getMaxDamage (ItemStack stack)
{
return 100;
}
@Override
public int getDamage(ItemStack stack) {
NBTTagCompound tags = stack.getTagCompound();
if (tags == null)
{
return 0;
}
if (tags.hasKey("Energy"))
{
int energy = tags.getInteger("Energy");
int max = getMaxEnergyStored(stack);
if(energy > 0) {
int damage = ((max - energy) * 100) / max;
if(damage == 0 && max-energy > 0)
damage = 1;
super.setDamage(stack, damage);
return damage;
}
}
int dur = tags.getCompoundTag("InfiTool").getInteger("Damage");
int max = tags.getCompoundTag("InfiTool").getInteger("TotalDurability");
int damage = 0;
if(max > 0)
damage = (dur*100)/max;
// rounding.
if(damage == 0 && dur > 0)
damage = 1;
// synchronize values with stack..
super.setDamage(stack, damage);
return damage;
}
@Override
public int getDisplayDamage(ItemStack stack) {
return getDamage(stack);
}
@Override
public void setDamage(ItemStack stack, int damage) {
AbilityHelper.damageTool(stack, damage - stack.getItemDamage(), null, false);
getDamage(stack); // called to synchronize with itemstack value
}
/* Prevent tools from dying */
public boolean hasCustomEntity (ItemStack stack)
{
return true;
}
public Entity createEntity (World world, Entity location, ItemStack itemstack)
{
return new FancyEntityItem(world, location, itemstack);
}
// TE support section -- from COFH core API reference section
// TE power constants. These are only for backup if the lookup of the real value somehow fails!
protected int capacity = 400000;
protected int maxReceive = 400000;
protected int maxExtract = 80;
/* IEnergyContainerItem */
@Override
@Optional.Method(modid = "CoFHLib")
public int receiveEnergy (ItemStack container, int maxReceive, boolean simulate)
{
NBTTagCompound tags = container.getTagCompound();
if (tags == null || !tags.hasKey("Energy"))
return 0;
int energy = tags.getInteger("Energy");
int energyReceived = tags.hasKey("EnergyReceiveRate") ? tags.getInteger("EnergyReceiveRate") : this.maxReceive; // backup value
int maxEnergy = tags.hasKey("EnergyMax") ? tags.getInteger("EnergyMax") : this.capacity; // backup value
// calculate how much we can receive
energyReceived = Math.min(maxEnergy - energy, Math.min(energyReceived, maxReceive));
if (!simulate)
{
energy += energyReceived;
tags.setInteger("Energy", energy);
//container.setItemDamage(1 + (getMaxEnergyStored(container) - energy) * (container.getMaxDamage() - 2) / getMaxEnergyStored(container));
}
return energyReceived;
}
@Override
@Optional.Method(modid = "CoFHLib")
public int extractEnergy (ItemStack container, int maxExtract, boolean simulate)
{
NBTTagCompound tags = container.getTagCompound();
if (tags == null || !tags.hasKey("Energy"))
{
return 0;
}
int energy = tags.getInteger("Energy");
int energyExtracted = tags.hasKey("EnergyExtractionRate") ? tags.getInteger("EnergyExtractionRate") : this.maxExtract; // backup value
// calculate how much we can extract
energyExtracted = Math.min(energy, Math.min(energyExtracted, maxExtract));
if (!simulate)
{
energy -= energyExtracted;
tags.setInteger("Energy", energy);
//container.setItemDamage(1 + (getMaxEnergyStored(container) - energy) * (container.getMaxDamage() - 1) / getMaxEnergyStored(container));
}
return energyExtracted;
}
@Override
@Optional.Method(modid = "CoFHLib")
public int getEnergyStored (ItemStack container)
{
NBTTagCompound tags = container.getTagCompound();
if (tags == null || !tags.hasKey("Energy"))
{
return 0;
}
return tags.getInteger("Energy");
}
@Override
@Optional.Method(modid = "CoFHLib")
public int getMaxEnergyStored (ItemStack container)
{
NBTTagCompound tags = container.getTagCompound();
if (tags == null || !tags.hasKey("Energy"))
return 0;
if (tags.hasKey("EnergyMax"))
return tags.getInteger("EnergyMax");
// backup
return capacity;
}
@Override
@Optional.Method(modid = "CoFHCore")
public boolean isLastHeldItemEqual(ItemStack current, ItemStack previous) {
if(!current.hasTagCompound() || !previous.hasTagCompound())
return false;
NBTTagCompound curTags = current.getTagCompound();
NBTTagCompound prevTags = previous.getTagCompound();
if(curTags == prevTags)
return true;
if(!curTags.hasKey("InfiTool") || !prevTags.hasKey("InfiTool"))
return false;
// create copies so we don't modify the original
curTags = (NBTTagCompound) curTags.copy();
prevTags = (NBTTagCompound) prevTags.copy();
curTags.removeTag("Energy");
prevTags.removeTag("Energy");
curTags.getCompoundTag("InfiTool").removeTag("Damage");
prevTags.getCompoundTag("InfiTool").removeTag("Damage");
return curTags.equals(prevTags);
}
// end of TE support section
}
| true | false | null | null |
diff --git a/src/org/mollyproject/android/controller/MollyModule.java b/src/org/mollyproject/android/controller/MollyModule.java
index 0f7273c..0fe8e86 100644
--- a/src/org/mollyproject/android/controller/MollyModule.java
+++ b/src/org/mollyproject/android/controller/MollyModule.java
@@ -1,105 +1,107 @@
package org.mollyproject.android.controller;
import java.util.HashMap;
import java.util.Map;
import org.mollyproject.android.R;
import org.mollyproject.android.Splash;
import org.mollyproject.android.view.apps.*;
import org.mollyproject.android.view.apps.contact.ContactPage;
import org.mollyproject.android.view.apps.contact.ContactResultsPage;
import org.mollyproject.android.view.apps.features.FeatureVotePage;
import org.mollyproject.android.view.apps.feedback.FeedbackPage;
import org.mollyproject.android.view.apps.home.HomePage;
import org.mollyproject.android.view.apps.library.LibraryPage;
import org.mollyproject.android.view.apps.library.LibraryResultsPage;
import org.mollyproject.android.view.apps.map.PlacesPage;
import org.mollyproject.android.view.apps.results_release.ResultsReleasePage;
import org.mollyproject.android.view.apps.search.SearchPage;
import org.mollyproject.android.view.apps.weather.WeatherPage;
import com.google.common.collect.HashBiMap;
import com.google.inject.AbstractModule;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
public class MollyModule extends AbstractModule {
//I don't want a simple list of Strings because that makes it more difficult
//to query from, and Java won't take : as part of the name if that variable
//is not a String, thus the complication introduced by the getStringLocator()
//public static enum ViewNames { places_index, home_index, result_index };
//ClassPathResource res = new ClassPathResource("spring-beans.xml");
//BeanFactory factory = new XmlBeanFactory(res);
public static String HOME_PAGE = "home:index";
public static String RESULTS_PAGE = "results:index";
public static String PLACES_PAGE = "places:index";
public static String CONTACT_PAGE = "contact:index";
public static String FEATURE_VOTE = "feature_vote:index";
public static String FEEDBACK_PAGE = "feedback:index";
public static String LIBRARY_PAGE = "library:index";
public static String LIBRARY_RESULTS_PAGE = "library:search";
public static String CONTACT_RESULTS_PAGE = "contact:result_list";
public static String SEARCH_PAGE = "search:index";
+ public static String WEATHER_PAGE = "weather:index";
//The following hash table allows for easier future change in implementation
//of new pages
protected static HashBiMap<String,Class<? extends Page>> pages
= HashBiMap.create();
static {
pages.put(HOME_PAGE, HomePage.class);
pages.put(RESULTS_PAGE, ResultsReleasePage.class);
pages.put(PLACES_PAGE, PlacesPage.class);
pages.put(CONTACT_PAGE, ContactPage.class);
pages.put(FEATURE_VOTE, FeatureVotePage.class);
pages.put(FEEDBACK_PAGE, FeedbackPage.class);
pages.put(LIBRARY_PAGE, LibraryPage.class);
pages.put(SEARCH_PAGE, SearchPage.class);
pages.put(LIBRARY_RESULTS_PAGE, LibraryResultsPage.class);
pages.put(CONTACT_RESULTS_PAGE, ContactResultsPage.class);
+ pages.put(WEATHER_PAGE, WeatherPage.class);
}
protected static Map<String,Integer> bcImg
= new HashMap<String,Integer>();
@Override
protected void configure() {
//views and drawables for contact page
bind(Page.class).annotatedWith(Names.named(CONTACT_PAGE)).to(ContactPage.class);
bind(Integer.class).annotatedWith(Names.named(CONTACT_PAGE+"_img")).toInstance(R.drawable.contact);
bind(Integer.class).annotatedWith(Names.named(CONTACT_PAGE+"_bc")).toInstance(R.drawable.contact_bc);
//views and drawables for library page
bind(Page.class).annotatedWith(Names.named(LIBRARY_PAGE)).to(LibraryPage.class);
bind(Integer.class).annotatedWith(Names.named(LIBRARY_PAGE+"_img")).toInstance(R.drawable.library);
bind(Integer.class).annotatedWith(Names.named(LIBRARY_PAGE+"_bc")).toInstance(R.drawable.library_bc);
bind(Page.class).annotatedWith(Names.named(LIBRARY_RESULTS_PAGE)).to(LibraryResultsPage.class);
bind(Page.class).annotatedWith(Names.named("places:index")).to(PlacesPage.class);
bind(Integer.class).annotatedWith(Names.named("places:index_img")).toInstance(R.drawable.places);
bind(Integer.class).annotatedWith(Names.named("places:index_bc")).toInstance(R.drawable.places_bc);
//views and drawables for weather page
bind(Page.class).annotatedWith(Names.named("weather:index")).to(WeatherPage.class);
bind(Integer.class).annotatedWith(Names.named("weather:index_img")).toInstance(R.drawable.weather);
bind(Integer.class).annotatedWith(Names.named("weather:index_bc")).toInstance(R.drawable.weather_bc);
bind(Page.class).annotatedWith(Names.named("search:index")).to(SearchPage.class);
bind(Page.class).annotatedWith(Names.named("results:index")).to(ResultsReleasePage.class);
bind(Page.class).annotatedWith(Names.named("splash")).to(Splash.class);
bind(Page.class).annotatedWith(Names.named("home:index")).to(HomePage.class);
//Unimplemented pages and default images
bind(Page.class).annotatedWith(Named.class).to(UnimplementedPage.class);
bind(Integer.class).annotatedWith(Named.class).toInstance(R.drawable.android_button);
}
public static String getName(Class <? extends Page> pageClass)
{
return (pages.inverse().get(pageClass));
}
public static Class<? extends Page> getPageClass(String s)
{
return pages.get(s);
}
}
diff --git a/src/org/mollyproject/android/view/apps/search/SearchPage.java b/src/org/mollyproject/android/view/apps/search/SearchPage.java
new file mode 100644
index 0000000..c1bfe09
--- /dev/null
+++ b/src/org/mollyproject/android/view/apps/search/SearchPage.java
@@ -0,0 +1,30 @@
+package org.mollyproject.android.view.apps.search;
+
+import org.mollyproject.android.R;
+import org.mollyproject.android.view.apps.ContentPage;
+import org.mollyproject.android.view.apps.Page;
+
+import android.os.Bundle;
+import android.widget.EditText;
+import android.widget.RelativeLayout;
+
+public class SearchPage extends ContentPage {
+
+ @Override
+ public void onCreate(Bundle savedInstanceState)
+ {
+ super.onCreate(savedInstanceState);
+ RelativeLayout searchBar = (RelativeLayout)
+ layoutInflater.inflate(R.layout.search_bar,contentLayout, false);
+ contentLayout.addView(searchBar);
+ final EditText searchField = (EditText) findViewById(R.id.searchField);
+ setEnterKeySearch(searchField, this);
+ contentLayout.setBackgroundColor(R.color.white);
+ new SearchTask(this,true).execute("query="+myApp.getGeneralQuery());
+ }
+ @Override
+ public Page getInstance() {
+ return this;
+ }
+
+}
| false | false | null | null |
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/format/Visitor.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/format/Visitor.java
index c82aa6b4..bbf01242 100644
--- a/javafx.editor/src/org/netbeans/modules/javafx/editor/format/Visitor.java
+++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/format/Visitor.java
@@ -1,1148 +1,1153 @@
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
*/
package org.netbeans.modules.javafx.editor.format;
import com.sun.javafx.api.tree.*;
import com.sun.source.tree.*;
import com.sun.source.util.SourcePositions;
import org.netbeans.api.java.source.CodeStyle;
import static org.netbeans.api.java.source.CodeStyle.BracePlacement;
import org.netbeans.api.javafx.lexer.JFXTokenId;
import org.netbeans.api.javafx.source.CompilationInfo;
import org.netbeans.api.javafx.source.TreeUtilities;
import org.netbeans.api.lexer.Token;
import org.netbeans.api.lexer.TokenId;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.api.project.Project;
import org.netbeans.modules.editor.indent.spi.Context;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.Position;
import java.util.List;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* Implementation of tree path scanner to work with actual AST to provide formating.
*
* @author Rastislav Komara (<a href="mailto:[email protected]">RKo</a>)
*/
class Visitor extends JavaFXTreePathScanner<Queue<Adjustment>, Queue<Adjustment>> {
private static Logger log = Logger.getLogger(Visitor.class.getName());
private final TreeUtilities tu;
private final CompilationInfo info;
private final Context ctx;
private int indentOffset = 0;
private final CodeStyle cs;
private static final String NEW_LINE_STRING = "\n";
// private static final String NEW_LINE_STRING = System.getProperty("line.separator", "\n");
protected final DocumentLinesIterator li;
private static final String STRING_EMPTY_LENGTH_ONE = " ";
protected static final String ONE_SPACE = STRING_EMPTY_LENGTH_ONE;
private TokenSequence<TokenId> ts;
private static final String STRING_ZERO_LENGTH = "";
Visitor(CompilationInfo info, Context ctx, int startOffset, Project project) {
this(info, ctx, project);
indentOffset = startOffset;
}
Visitor(CompilationInfo info, Context ctx, Project project) {
this.info = info;
this.ctx = ctx;
tu = new TreeUtilities(info);
cs = CodeStyle.getDefault(project);
li = new DocumentLinesIterator(ctx);
}
private int getIndentStepLevel() {
return cs.getIndentSize();
}
@Override
public Queue<Adjustment> visitInitDefinition(InitDefinitionTree node, Queue<Adjustment> adjustments) {
try {
processStandaloneNode(node, adjustments);
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
super.visitInitDefinition(node, adjustments);
return adjustments;
}
@Override
public Queue<Adjustment> visitVariable(JavaFXVariableTree node, Queue<Adjustment> adjustments) {
try {
final int start = getStartPos(node);
// if (isFirstOnLine(start)) {
// indentLine(start, adjustments);
// }
- processStandaloneNode(node, adjustments);
+ if (!holdOnLine(getCurrentPath().getParentPath().getLeaf())) {
+ processStandaloneNode(node, adjustments);
+ }
if (isMultiline(node)) {
if (node.getOnReplaceTree() != null) {
indentEndLine(node.getOnReplaceTree(), adjustments);
} else {
li.moveTo(start);
if (li.hasNext()) {
indentMultiline(li, getEndPos(node), adjustments);
}
}
}
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
super.visitVariable(node, adjustments);
return adjustments;
}
private void indentLine(Element line, Queue<Adjustment> adjustments) throws BadLocationException {
final int ls = ctx.lineStartOffset(line.getStartOffset());
indentLine(ls, adjustments);
}
private void indentLine(int ls, Queue<Adjustment> adjustments) throws BadLocationException {
indentLine(ls, adjustments, indentOffset);
}
private void indentLine(int ls, Queue<Adjustment> adjustments, int indent) throws BadLocationException {
if (ctx.lineIndent(ctx.lineStartOffset(ls)) != indent) {
adjustments.offer(Adjustment.indent(ctx.document().createPosition(ls), indent));
}
}
@Override
public Queue<Adjustment> visitExpressionStatement(ExpressionStatementTree node, Queue<Adjustment> adjustments) {
try {
processStandaloneNode(node, adjustments);
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return super.visitExpressionStatement(node, adjustments);
}
private void processStandaloneNode(Tree node, Queue<Adjustment> adjustments) throws BadLocationException {
final int position = getStartPos(node);
if (isFirstOnLine(position)) {
indentLine(position, adjustments);
} else {
adjustments.offer(Adjustment.add(ctx.document().createPosition(position), NEW_LINE_STRING));
adjustments.offer(Adjustment.indent(ctx.document().createPosition(position + 1), indentOffset));
}
if (isMultiline(node)) {
indentLine(getEndPos(node), adjustments);
}
}
@Override
public Queue<Adjustment> visitIdentifier(IdentifierTree node, Queue<Adjustment> adjustments) {
try {
if (isWidow(node)) {
final int position = getStartPos(node);
indentLine(position, adjustments);
}
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return super.visitIdentifier(node, adjustments);
}
private boolean isWidow(Tree node) throws BadLocationException {
final int endPos = getEndPos(node);
boolean probablyWidow = false;
final TokenSequence<JFXTokenId> ts = ts();
ts.move(endPos);
while (ts.moveNext()) {
if (JFXTokenId.WS == ts.token().id()) {
if (NEW_LINE_STRING.equals(ts.token().text().toString())) {
probablyWidow = true;
break;
}
continue;
}
break;
}
return probablyWidow && isFirstOnLine(getStartPos(node));
}
@Override
public Queue<Adjustment> visitUnary(UnaryTree node, Queue<Adjustment> adjustments) {
return super.visitUnary(node, adjustments);
}
@Override
public Queue<Adjustment> visitBinary(BinaryTree node, Queue<Adjustment> adjustments) {
final Tree tree = getCurrentPath().getParentPath().getLeaf();
if (tree instanceof BinaryTree) {
super.visitBinary((BinaryTree) tree, adjustments);
return adjustments;
}
try {
final int offset = getStartPos(node);
final int end = getEndPos(node);
if (isMultiline(node)) {
li.moveTo(offset);
if (isFirstOnLine(offset)) {
indentLine(li.get(), adjustments);
}
indentMultiline(li, end, adjustments);
}
final TokenSequence<JFXTokenId> ts = ts(node);
ts.move(offset);
while (ts.moveNext() && ts.offset() <= end) {
if ("operator".equals(ts.token().id().primaryCategory())) {
if (cs.spaceAroundBinaryOps()) {
int operatorOffset = ts.offset();
if (ts.movePrevious() && ts.token().id() != JFXTokenId.WS) {
adjustments.offer(Adjustment.add(ctx.document().createPosition(operatorOffset), ONE_SPACE));
}
if (!ts.moveNext())
throw new BadLocationException("Concurent modification has occured on document.", ts.offset());
if (ts.moveNext() && ts.token().id() != JFXTokenId.WS) {
adjustments.offer(Adjustment.add(ctx.document().createPosition(ts.offset()), ONE_SPACE));
}
}
}
}
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return super.visitBinary(node, adjustments);
}
private TokenSequence<JFXTokenId> ts(Tree node) {
return tu.tokensFor(node);
}
@Override
public Queue<Adjustment> visitObjectLiteralPart(ObjectLiteralPartTree node, Queue<Adjustment> adjustments) {
if (log.isLoggable(Level.INFO)) log.info("entering: visitObjectLiteralPart " + node);
try {
final int offset = getStartPos(node);
if (isFirstOnLine(offset)) {
indentLine(offset, adjustments);
}
boolean hasContinuosIndent = isMultiline(node) && !isOnSameLine(node, node.getExpression());
if (hasContinuosIndent) {
indentOffset = indentOffset + getCi();
}
super.visitObjectLiteralPart(node, adjustments);
if (hasContinuosIndent) {
indentOffset = indentOffset - getCi();
}
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
if (log.isLoggable(Level.INFO)) log.info("leaving: visitObjectLiteralPart " + node);
return adjustments;
}
private boolean isOnSameLine(Tree node, Tree tree) throws BadLocationException {
return ctx.lineStartOffset(getStartPos(node)) == ctx.lineStartOffset(getStartPos(tree));
}
@Override
public Queue<Adjustment> visitSequenceDelete(SequenceDeleteTree node, Queue<Adjustment> adjustments) {
try {
indentSimpleStructure(node, adjustments);
incIndent();
super.visitSequenceDelete(node, adjustments);
decIndent();
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
private void decIndent() {
indentOffset = indentOffset - getIndentStepLevel();
}
private void incIndent() {
indentOffset = indentOffset + getIndentStepLevel();
}
private void indentSimpleStructure(Tree node, Queue<Adjustment> adjustments) throws BadLocationException {
int start = getStartPos(node);
if (isFirstOnLine(start)) {
indentLine(start, adjustments);
}
if (isMultiline(node)) {
indentLine(getEndPos(node), adjustments);
}
}
@Override
public Queue<Adjustment> visitSequenceEmpty(SequenceEmptyTree node, Queue<Adjustment> adjustments) {
try {
indentSimpleStructure(node, adjustments);
incIndent();
super.visitSequenceEmpty(node, adjustments);
decIndent();
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
@Override
public Queue<Adjustment> visitSequenceExplicit(SequenceExplicitTree node, Queue<Adjustment> adjustments) {
try {
indentSimpleStructure(node, adjustments);
incIndent();
super.visitSequenceExplicit(node, adjustments);
decIndent();
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
/*
@Override
public Queue<Adjustment> visitSequenceIndexed(SequenceIndexedTree node, Queue<Adjustment> adjustments) {
try {
indentSimpleStructure(node, adjustments);
incIndent();
super.visitSequenceIndexed(node, adjustments);
decIndent();
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
*/
@Override
public Queue<Adjustment> visitSequenceSlice(SequenceSliceTree node, Queue<Adjustment> adjustments) {
try {
indentSimpleStructure(node, adjustments);
incIndent();
super.visitSequenceSlice(node, adjustments);
decIndent();
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
// @Override
// public Queue<Adjustment> visitSequenceInsert(SequenceInsertTree node, Queue<Adjustment> adjustments) {
// try {
// indentSimpleStructure(node, adjustments);
// incIndent();
// super.visitSequenceInsert(node, adjustments);
// decIndent();
// } catch (BadLocationException e) {
// if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
// }
// return adjustments;
// }
@Override
public Queue<Adjustment> visitSequenceRange(SequenceRangeTree node, Queue<Adjustment> adjustments) {
try {
indentSimpleStructure(node, adjustments);
incIndent();
super.visitSequenceRange(node, adjustments);
decIndent();
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
private void indentMultiline(LineIterator<Element> li, int endOffset, Queue<Adjustment> adjustments) throws BadLocationException {
// final int ci = getCi();
// if (li.hasNext()) {
// indentOffset = indentOffset + ci;
// while (li.hasNext()) {
// final Element element = li.next();
// if (element.getStartOffset() > endOffset) {
// break;
// }
// indentLine(element, adjustments);
// }
// indentOffset = indentOffset - ci;
// }
}
private boolean isMultiline(Tree tree) throws BadLocationException {
return ctx.lineStartOffset(getStartPos(tree)) != ctx.lineStartOffset(getEndPos(tree));
}
@Override
public Queue<Adjustment> visitFunctionValue(FunctionValueTree node, Queue<Adjustment> adjustments) {
final Tree tree = getCurrentPath().getParentPath().getLeaf();
if (tree instanceof FunctionDefinitionTree) {
super.visitFunctionValue(node, adjustments);
} else {
try {
if (isFirstOnLine(getStartPos(node))) {
indentLine(getStartPos(node), adjustments);
}
verifyFunctionSpaces(ts(node), node, adjustments);
super.visitFunctionValue(node, adjustments);
indentLine(getEndPos(node), adjustments);
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
}
return adjustments;
}
@Override
public Queue<Adjustment> visitMethodInvocation(MethodInvocationTree node, Queue<Adjustment> adjustments) {
try {
indentSimpleStructure(node, adjustments);
incIndent();
super.visitMethodInvocation(node, adjustments);
decIndent();
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
@Override
public Queue<Adjustment> visitFunctionDefinition(FunctionDefinitionTree node, Queue<Adjustment> adjustments) {
final TokenSequence<JFXTokenId> ts = ts();
try {
processStandaloneNode(node, adjustments);
verifyFunctionSpaces(ts, node, adjustments);
// ts.move(getStartPos(node));
// while (ts.moveNext()) {
// final JFXTokenId id = ts.token().id();
// switch (id) {
// case PUBLIC:
// case PRIVATE:
// case STATIC:
// case WS:
// continue;
// case FUNCTION:
// verifyFunctionSpaces(ts, node, adjustments);
// break;
// default:
// break;
// }
// break;
// }
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
super.visitFunctionDefinition(node, adjustments);
return adjustments;
}
private void verifyFunctionSpaces(TokenSequence<JFXTokenId> ts, Tree node, Queue<Adjustment> adjustments) throws BadLocationException {
if (ts.moveNext() && ts.token().id() == JFXTokenId.IDENTIFIER) {
if (cs.spaceBeforeMethodDeclLeftBrace()) {
if (ts.moveNext() && ts.token().id() != JFXTokenId.WS) {
adjustments.offer(Adjustment.add(ctx.document().createPosition(ts.offset()), ONE_SPACE));
} else {
verifyNextIs(JFXTokenId.LPAREN, ts, adjustments, true);
}
} else {
verifyNextIs(JFXTokenId.LPAREN, ts, adjustments, true);
}
}
verifyBraces(node, adjustments, cs.getMethodDeclBracePlacement(), cs.spaceBeforeMethodDeclLeftBrace());
processStandaloneNode(node, adjustments);
}
private void verifyNextIs(JFXTokenId id, TokenSequence<JFXTokenId> ts, Queue<Adjustment> adjustments, boolean moveNext) throws BadLocationException {
if ((moveNext ? ts.moveNext() : ts.movePrevious()) && ts.token().id() != id) {
int startOffset = ts.offset() + (moveNext ? 0 : ts.token().length());
while (moveNext ? ts.moveNext() : ts.movePrevious()) {
if (ts.token().id() == id) {
adjustments.offer(
Adjustment.delete(ctx.document().createPosition(startOffset),
ctx.document().createPosition(ts.offset() + (moveNext ? 0 : ts.token().length()))));
}
}
}
}
@SuppressWarnings({"OverlyComplexMethod"})
private void verifyBraces(Tree node, Queue<Adjustment> adjustments, BracePlacement bp, boolean spaceBeforeLeftBrace) throws BadLocationException {
final TokenSequence<JFXTokenId> ts = tu.tokensFor(node);
Token<JFXTokenId> obrace = moveTo(ts, JFXTokenId.LBRACE);
if (obrace != null) {
int obraceTokenStart = ts.offset();
boolean nlFound = false;
while (ts.movePrevious()) {
if (ts.token().id() != JFXTokenId.WS) {
break;
} else {
final CharSequence cs = ts.token().text();
if ("\n".equals(cs.toString())) {
nlFound = true;
}
}
}
final Document doc = ctx.document();
int oldIndent = indentOffset;
switch (bp) {
case SAME_LINE:
if (nlFound || (obraceTokenStart - (ts.offset() + ts.token().length()) > 1)) {
adjustments.offer(Adjustment.replace(doc.createPosition(ts.offset() + ts.token().length()),
doc.createPosition(obraceTokenStart),
spaceBeforeLeftBrace ? ONE_SPACE : STRING_ZERO_LENGTH));
}
break;
case NEW_LINE:
verifyNL(adjustments, ts, obraceTokenStart, nlFound);
break;
case NEW_LINE_HALF_INDENTED:
verifyNL(adjustments, ts, obraceTokenStart, nlFound);
indentOffset = indentOffset + (getIndentStepLevel() / 2);
adjustments.offer(Adjustment.indent(doc.createPosition(obraceTokenStart), indentOffset));
break;
case NEW_LINE_INDENTED:
verifyNL(adjustments, ts, obraceTokenStart, nlFound);
incIndent();
adjustments.offer(Adjustment.indent(doc.createPosition(obraceTokenStart), indentOffset));
break;
}
checkEndBrace(node, adjustments, ts);
indentOffset = oldIndent;
}
}
private void checkEndBrace(Tree node, Queue<Adjustment> adjustments, TokenSequence<JFXTokenId> ts) throws BadLocationException {
Document doc = ctx.document();
final int end = getEndPos(node);
ts.move(end); //getting into last token...
if (ts.movePrevious() && ts.token().id() != JFXTokenId.RBRACE) {
return;
}
while (ts.movePrevious()) {
final JFXTokenId id = ts.token().id();
switch (id) {
case WS: {
final CharSequence cs = ts.token().text();
if (cs != null && "\n".equals(cs.toString())) {
indentEndLine(node, adjustments);
return;
}
continue;
}
default: {
adjustments.offer(Adjustment.add(doc.createPosition(end - 1), NEW_LINE_STRING));
adjustments.offer(Adjustment.indent(doc.createPosition(end), indentOffset));
return;
}
}
}
}
private SourcePositions sp() {
return info.getTrees().getSourcePositions();
}
private void verifyNL(Queue<Adjustment> adjustments, TokenSequence<JFXTokenId> ts, int originTokenStart, boolean nlFound) throws BadLocationException {
if (!nlFound || (originTokenStart - (ts.offset() + ts.token().length()) > 1)) {
adjustments.offer(Adjustment.replace(ctx.document().createPosition(ts.offset() + ts.token().length()),
ctx.document().createPosition(originTokenStart), NEW_LINE_STRING));
}
}
private Token<JFXTokenId> moveTo(TokenSequence<JFXTokenId> ts, JFXTokenId id) {
while (ts.moveNext()) {
if (ts.token().id() == id) {
return ts.token();
}
}
return null;
}
private CompilationUnitTree cu() {
return info.getCompilationUnit();
}
@SuppressWarnings({"unchecked"})
private <T extends TokenId> TokenSequence<T> ts() {
if (ts != null && ts.isValid()) {
return (TokenSequence<T>) ts;
}
this.ts = info.getTokenHierarchy().tokenSequence(JFXTokenId.language());
return (TokenSequence<T>) this.ts;
}
@Override
public Queue<Adjustment> visitAssignment(AssignmentTree node, Queue<Adjustment> adjustments) {
try {
processStandaloneNode(node, adjustments);
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
super.visitAssignment(node, adjustments);
return adjustments;
}
@Override
public Queue<Adjustment> visitInstantiate(InstantiateTree node, Queue<Adjustment> adjustments) {
try {
final int offset = getStartPos(node);
final Tree tree = getCurrentPath().getParentPath().getLeaf();
if (!holdOnLine(tree) || isFirstOnLine(offset)) {
processStandaloneNode(node, adjustments);
}
incIndent();
super.visitInstantiate(node, adjustments);
decIndent();
if (isMultiline(node)) {
indentEndLine(node, adjustments);
}
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
private boolean holdOnLine(Tree tree) {
return tree instanceof ReturnTree
|| tree instanceof JavaFXVariableTree
|| tree instanceof AssignmentTree
|| tree instanceof UnaryTree
|| tree instanceof BinaryTree
- || tree instanceof BindExpressionTree;
+ || tree instanceof BindExpressionTree
+ || tree instanceof CatchTree
+ || tree instanceof ConditionalExpressionTree
+ || tree instanceof ForExpressionInClauseTree;
}
private void indentEndLine(Tree node, Queue<Adjustment> adjustments) throws BadLocationException {
final int endPos = getEndPos(node);
final TokenSequence<JFXTokenId> ts = ts(node);
ts.move(endPos);
boolean shouldIndent = false;
while (ts.movePrevious()) {
final JFXTokenId id = ts.token().id();
switch (id) {
case RBRACE:
case RPAREN: {
shouldIndent = true;
continue;
}
case WS: {
final CharSequence cs = ts.token().text();
if (cs != null && "\n".equals(cs.toString()) && shouldIndent) {
indentLine(endPos, adjustments);
return;
}
continue;
}
default:
return;
}
}
}
private int getEndPos(Tree node) {
return (int) sp().getEndPosition(cu(), node);
}
private int getStartPos(Tree node) {
int nodeStart = (int) sp().getStartPosition(cu(), node);
int modifiersStart = getModifiersStart(node);
return Math.min(nodeStart, modifiersStart);
}
private int getModifiersStart(Tree node) {
if (node instanceof ClassDeclarationTree) {
ClassDeclarationTree tree = (ClassDeclarationTree) node;
return includeModifiers(tree.getModifiers());
} else if (node instanceof FunctionDefinitionTree) {
FunctionDefinitionTree tree = (FunctionDefinitionTree) node;
return includeModifiers(tree.getModifiers());
} else if (node instanceof JavaFXVariableTree) {
JavaFXVariableTree tree = (JavaFXVariableTree) node;
return includeModifiers(tree.getModifiers());
}
return Integer.MAX_VALUE;
}
private int includeModifiers(ModifiersTree modifiers) {
final int startPos = getStartPos(modifiers);
if (startPos < 0) return Integer.MAX_VALUE;
return startPos;
}
@Override
public Queue<Adjustment> visitClassDeclaration(ClassDeclarationTree node, Queue<Adjustment> adjustments) {
if (tu.isSynthetic(getCurrentPath())) {
return super.visitClassDeclaration(node, adjustments);
}
final Document doc = ctx.document();
try {
final int sp = getStartPos(node);
int elc = cs.getBlankLinesBeforeClass();
processStandaloneNode(node, adjustments);
if (!isFirstOnLine(sp) && !holdOnLine(getCurrentPath().getParentPath().getLeaf())) {
adjustments.offer(Adjustment.add(ctx.document().createPosition(sp), buildString(elc, NEW_LINE_STRING).toString()));
adjustments.offer(Adjustment.indent(ctx.document().createPosition(sp + elc + 1), indentOffset));
} else {
int pos = ctx.lineStartOffset(sp);
indentLine(pos, adjustments);
final Tree tree = getCurrentPath().getParentPath().getLeaf();
if (tree instanceof CompilationUnitTree || tree instanceof ClassDeclarationTree) {
pos = skipPreviousComment(pos);
int emptyLines = getEmptyLinesBefore(li, pos);
elc = elc - emptyLines;
if (elc < 0) {
Element nth = getNthElement(Math.abs(elc), li);
if (nth != null) {
adjustments.offer(Adjustment.delete(doc.createPosition(nth.getStartOffset()), doc.createPosition(pos)));
}
} else if (elc > 0) {
StringBuilder sb = buildString(elc, NEW_LINE_STRING);
adjustments.offer(Adjustment.add(doc.createPosition(pos), sb.toString()));
}
}
}
incIndent();
super.visitClassDeclaration(node, adjustments);
decIndent();
verifyBraces(node, adjustments, cs.getClassDeclBracePlacement(), cs.spaceBeforeClassDeclLeftBrace());
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
private Tree firstImport;
private Tree lastImport;
@Override
public Queue<Adjustment> visitImport(ImportTree importTree, Queue<Adjustment> adjustments) {
if (log.isLoggable(Level.FINE)) log.fine("Visiting import" + importTree);
try {
final int ls = ctx.lineStartOffset(getStartPos(importTree));
processStandaloneNode(importTree, adjustments);
if (firstImport == null) {
firstImport = getFirstImport();
}
if (lastImport == null) {
lastImport = getLastImport();
}
if (importTree.equals(firstImport)) {
li.moveTo(ls);
final int lines = getEmptyLinesBefore(li, ls);
final int linesBeforeImports = cs.getBlankLinesBeforeImports();
if (linesBeforeImports != lines) {
adjustLinesBefore(lines, linesBeforeImports, adjustments, li, ls);
}
}
if (importTree.equals(lastImport)) {
}
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return super.visitImport(importTree, adjustments);
}
private Tree getLastImport() {
final List<? extends ImportTree> trees = getCurrentPath().getCompilationUnit().getImports();
if (!trees.isEmpty()) {
return trees.get(trees.size() - 1);
}
return null;
}
private Tree getFirstImport() {
final List<? extends ImportTree> trees = getCurrentPath().getCompilationUnit().getImports();
if (!trees.isEmpty()) {
return trees.get(0);
}
return null;
}
private void adjustLinesBefore(int realLines, int linesRequired, Queue<Adjustment> list, LineIterator<Element> li, int pos) throws BadLocationException {
linesRequired = linesRequired - realLines;
if (linesRequired < 0) {
Element nth = getNthElement(Math.abs(linesRequired), li);
if (nth != null) {
list.add(Adjustment.delete(ctx.document().createPosition(nth.getStartOffset()), ctx.document().createPosition(pos)));
}
} else if (linesRequired > 0) {
StringBuilder sb = buildString(linesRequired, NEW_LINE_STRING);
list.add(Adjustment.add(ctx.document().createPosition(pos), sb.toString()));
}
}
private boolean isFirstOnLine(int offset) throws BadLocationException {
final int ls = ctx.lineStartOffset(offset);
final Document doc = ctx.document();
final String s = doc.getText(ls, offset - ls);
return isEmpty(s);
}
@Override
public Queue<Adjustment> visitCompoundAssignment(CompoundAssignmentTree node, Queue<Adjustment> adjustments) {
if (getCurrentPath().getParentPath().getLeaf() instanceof ExpressionStatementTree) {
return adjustments;
}
try {
processStandaloneNode(node, adjustments);
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
super.visitCompoundAssignment(node, adjustments);
return adjustments;
}
@Override
public Queue<Adjustment> visitReturn(ReturnTree returnTree, Queue<Adjustment> adjustments) {
try {
processStandaloneNode(returnTree, adjustments);
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return super.visitReturn(returnTree, adjustments);
}
@Override
public Queue<Adjustment> visitLiteral(LiteralTree literalTree, Queue<Adjustment> adjustments) {
try {
final int offset = getStartPos(literalTree);
if (isFirstOnLine(offset)) {
indentLine(offset, adjustments, isWidow(literalTree) ? indentOffset : (indentOffset + getCi()));
}
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
@Override
public Queue<Adjustment> visitBlock(BlockTree blockTree, Queue<Adjustment> adjustments) {
if (!tu.isSynthetic(getCurrentPath())) {
try {
final int start = ctx.lineStartOffset(getStartPos(blockTree));
indentLine(start, adjustments);
incIndent();
super.visitBlock(blockTree, adjustments);
decIndent();
verifyBraces(blockTree, adjustments, cs.getOtherBracePlacement(), false);
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
}
return adjustments;
}
@Override
public Queue<Adjustment> visitWhileLoop(WhileLoopTree node, Queue<Adjustment> adjustments) {
try {
verifySpaceBefore(node, adjustments, cs.spaceBeforeWhile());
verifyBraces(node, adjustments, cs.getOtherBracePlacement(), cs.spaceBeforeWhileLeftBrace());
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
super.visitWhileLoop(node, adjustments);
return adjustments;
}
private void verifySpaceBefore(Tree node, Queue<Adjustment> adjustments, boolean spaceBefore) throws BadLocationException {
final int start = getStartPos(node);
if (!isFirstOnLine(start) && spaceBefore) {
final TokenSequence<JFXTokenId> ts = ts();
ts.move(start);
if (ts.movePrevious() && ts.token().id() != JFXTokenId.WS) {
adjustments.offer(Adjustment.add(toPos(start), STRING_EMPTY_LENGTH_ONE));
}
}
}
@Override
public Queue<Adjustment> visitForExpression(ForExpressionTree node, Queue<Adjustment> adjustments) {
try {
processStandaloneNode(node, adjustments);
verifyBraces(node, adjustments, cs.getOtherBracePlacement(), cs.spaceBeforeWhileLeftBrace());
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return super.visitForExpression(node, adjustments);
}
@Override
public Queue<Adjustment> visitIf(IfTree node, Queue<Adjustment> adjustments) {
try {
processStandaloneNode(node, adjustments);
verifyBraces(node.getThenStatement(), adjustments, cs.getOtherBracePlacement(), cs.spaceBeforeIfLeftBrace());
verifySpaceBefore(node.getElseStatement(), adjustments, cs.spaceBeforeElse());
verifyBraces(node.getElseStatement(), adjustments, cs.getOtherBracePlacement(), cs.spaceBeforeElseLeftBrace());
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return super.visitIf(node, adjustments);
}
private Position toPos(int index) throws BadLocationException {
return ctx.document().createPosition(index);
}
@Override
public Queue<Adjustment> visitTry(TryTree node, Queue<Adjustment> adjustments) {
try {
processStandaloneNode(node, adjustments);
verifyBraces(node, adjustments, cs.getOtherBracePlacement(), cs.spaceBeforeTryLeftBrace());
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
super.visitTry(node, adjustments);
return adjustments;
}
@Override
public Queue<Adjustment> visitCatch(CatchTree node, Queue<Adjustment> adjustments) {
try {
final int start = getStartPos(node);
if (cs.placeCatchOnNewLine() && !isFirstOnLine(start)) {
adjustments.offer(Adjustment.add(toPos(start), NEW_LINE_STRING));
adjustments.offer(Adjustment.indent(toPos(start + 1), indentOffset));
verifyBraces(node, adjustments, cs.getOtherBracePlacement(), cs.spaceBeforeCatchLeftBrace());
verifyParens(node, adjustments, cs.spaceBeforeCatchParen(), false);
} else if (!cs.placeCatchOnNewLine() && isFirstOnLine(start)) {
final TokenSequence<JFXTokenId> ts = ts();
ts.move(start);
while (ts.movePrevious()) {
if (ts.token().id() == JFXTokenId.RBRACE) {
adjustments.offer(Adjustment.replace(toPos(ts.offset() + ts.token().length()),
toPos(start), cs.spaceBeforeCatch() ? STRING_EMPTY_LENGTH_ONE : STRING_ZERO_LENGTH));
verifyBraces(node, adjustments, cs.getOtherBracePlacement(), cs.spaceBeforeCatchLeftBrace());
verifyParens(node, adjustments, cs.spaceBeforeCatchParen(), false);
break;
}
}
} else {
verifySpaceBefore(node, adjustments, cs.spaceBeforeCatch() && !cs.placeCatchOnNewLine());
verifyBraces(node, adjustments, cs.getOtherBracePlacement(), cs.spaceBeforeCatchLeftBrace());
verifyParens(node, adjustments, cs.spaceBeforeCatchParen(), cs.spaceWithinCatchParens());
}
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
super.visitCatch(node, adjustments);
return adjustments;
}
@SuppressWarnings({"MethodWithMultipleLoops"})
private void verifyParens(Tree node, Queue<Adjustment> adjustments, boolean spaceBeforParen, boolean spaceWithin) throws BadLocationException {
final TokenSequence<JFXTokenId> ts = ts(node);
ts.move(getStartPos(node));
final int endPos = getEndPos(node);
while (ts.moveNext() && ts.offset() < endPos) {
JFXTokenId id = ts.token().id();
if (id == JFXTokenId.LPAREN) {
int lps = ts.offset();
int tl = ts.token().length();
spaceWithin(adjustments, spaceWithin, ts, endPos, lps + tl);
ts.move(lps);
while (ts.movePrevious()) {
id = ts.token().id();
if (id != JFXTokenId.WS) {
adjustments.offer(Adjustment.replace(toPos(ts.offset() + ts.token().length()),
toPos(lps), spaceBeforParen ? STRING_EMPTY_LENGTH_ONE : STRING_ZERO_LENGTH));
return;
}
}
}
}
}
private void spaceWithin(Queue<Adjustment> adjustments, boolean spaceWithin, TokenSequence<JFXTokenId> ts, int endPos, int parenEndIndex) throws BadLocationException {
if (spaceWithin) {
if (ts.moveNext() && ts.token().id() != JFXTokenId.WS) {
adjustments.offer(Adjustment.add(toPos(ts.offset()), STRING_EMPTY_LENGTH_ONE));
}
} else {
if (ts.moveNext() && ts.token().id() == JFXTokenId.WS) {
while (ts.moveNext() && ts.offset() < endPos) {
if (ts.token().id() != JFXTokenId.WS) {
adjustments.offer(Adjustment.delete(toPos(parenEndIndex), toPos(ts.offset())));
break;
}
}
}
}
}
// @Override
// public Queue<Adjustment> visitStringExpression(StringExpressionTree stringExpressionTree, Queue<Adjustment> adjustments) {
// SourcePositions sps = sp();
// try {
// final int offset = (int) sps.getStartPosition(cu(), getCurrentPath().getLeaf());
// final int endOffset = (int) sps.getEndPosition(cu(), getCurrentPath().getLeaf());
// final int start = ctx.lineStartOffset(offset);
// indentLine(start, adjustments);
// if (start != ctx.lineStartOffset(endOffset)) {
// li.moveTo(offset);
// indentMultiline(li, endOffset, adjustments);
//
// }
//
// } catch (BadLocationException e) {
// if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
// }
// return super.visitStringExpression(stringExpressionTree, adjustments);
// }
/**
* Gets continuation indent adjustment. This is sum of spaces to be added to current indet to achieve required
* continuation offset.
*
* @return size of continuation indent adjustment.
*/
private int getCi() {
return cs.getContinuationIndentSize() - getIndentStepLevel();
}
@Override
public Queue<Adjustment> visitBlockExpression(BlockExpressionTree node, Queue<Adjustment> adjustments) {
try {
final int start = ctx.lineStartOffset(getStartPos(node));
indentLine(start, adjustments);
incIndent();
super.visitBlockExpression(node, adjustments);
decIndent();
final int end = ctx.lineStartOffset(getEndPos(node));
indentLine(end, adjustments);
} catch (BadLocationException e) {
if (log.isLoggable(Level.SEVERE)) log.severe("Reformat failed. " + e);
}
return adjustments;
}
private int getEmptyLinesBefore(LineIterator<Element> iterator, int pos) throws BadLocationException {
iterator.moveTo(pos);
int res = 0;
while (iterator.hasPrevious()) {
final Element line = iterator.previous();
if (!isEmpty(line)) {
break;
}
res++;
}
return res;
}
private boolean isEmpty(Element line) throws BadLocationException {
final Document d = line.getDocument();
final String s = d.getText(line.getStartOffset(), line.getEndOffset() - line.getStartOffset());
return isEmpty(s);
}
private int skipPreviousComment(int pos) {
final TokenSequence<JFXTokenId> ts = ts();
ts.move(pos);
while (ts.movePrevious()) {
final Token<JFXTokenId> t = ts.token();
switch (t.id()) {
case COMMENT:
return ts.offset();
case WS:
continue;
default:
break;
}
}
return pos;
}
private Element getNthElement(int n, LineIterator<Element> iterator) {
Element nth = null;
while (iterator.hasNext() && n != 0) {
nth = iterator.next();
n--;
}
return nth;
}
private StringBuilder buildString(int elc, String str) {
StringBuilder sb = new StringBuilder(elc);
while (elc != 0) {
sb.append(str);
elc--;
}
return sb;
}
private static final Pattern EMPTY_LINE_PTRN = Pattern.compile("\\s+");
private boolean isEmpty(String text) {
return text == null || text.length() == 0 || EMPTY_LINE_PTRN.matcher(text).matches();
}
}
| false | false | null | null |
diff --git a/cli/src/main/java/com/vmware/bdd/cli/commands/NetworkCommands.java b/cli/src/main/java/com/vmware/bdd/cli/commands/NetworkCommands.java
index 218472b6..e2d321d1 100644
--- a/cli/src/main/java/com/vmware/bdd/cli/commands/NetworkCommands.java
+++ b/cli/src/main/java/com/vmware/bdd/cli/commands/NetworkCommands.java
@@ -1,506 +1,506 @@
/*****************************************************************************
* Copyright (c) 2012-2013 VMware, 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.vmware.bdd.cli.commands;
/**
* <p>This class is the realization of Network command.</p>
*/
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;
import com.vmware.bdd.apitypes.IpAllocEntryRead;
import com.vmware.bdd.apitypes.IpBlock;
import com.vmware.bdd.apitypes.NetworkAdd;
import com.vmware.bdd.apitypes.NetworkRead;
import com.vmware.bdd.cli.rest.CliRestException;
import com.vmware.bdd.cli.rest.NetworkRestClient;
@Component
public class NetworkCommands implements CommandMarker {
@Autowired
private NetworkRestClient networkRestClient;
private String networkName;
// Define network type
private enum NetworkType {
DHCP, IP
}
// Define the pattern type.
private interface PatternType {
// Match a single IP format,eg. 192.168.0.2 .
final String IP =
"\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
// Match a IP section format,eg. 192.168.0.2-100 .
final String IPSEG =
"\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\-((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
}
@CliAvailabilityIndicator({ "network help" })
public boolean isCommandAvailable() {
return true;
}
/**
* <p>
* Add function of network command.
* </p>
*
* @param name
* Customize the network's name.
* @param portGroup
* The port group name.
* @param dhcp
* The dhcp flag.
* @param dns
* The frist dns information.
* @param sedDNS
* The second dns information.
* @param ip
* The ip range information.
* @param gateway
* The gateway information.
* @param mask
* The network mask information.
*/
@CliCommand(value = "network add", help = "Add a network to Serengeti")
public void addNetwork(
@CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name,
@CliOption(key = { "portGroup" }, mandatory = true, help = "The port group name") final String portGroup,
@CliOption(key = { "dhcp" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "The dhcp information") final boolean dhcp,
@CliOption(key = { "dns" }, mandatory = false, help = "The first dns information") final String dns,
@CliOption(key = { "secondDNS" }, mandatory = false, help = "The second dns information") final String sedDNS,
@CliOption(key = { "ip" }, mandatory = false, help = "The ip information") final String ip,
@CliOption(key = { "gateway" }, mandatory = false, help = "The gateway information") final String gateway,
@CliOption(key = { "mask" }, mandatory = false, help = "The mask information") final String mask) {
NetworkType operType = null;
if (!CommandsUtils.isBlank(ip) && dhcp) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_EXCLUSION_PAIR_NETWORK_ADD_IP_DHCP
+ Constants.PARAMS_EXCLUSION);
return;
} else if (dhcp) {
operType = NetworkType.DHCP;
} else if (!CommandsUtils.isBlank(ip)) {
operType = NetworkType.IP;
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_IP_DHCP_NOT_NULL);
return;
}
addNetwork(operType, name, portGroup, ip, dhcp, dns, sedDNS, gateway,
mask);
}
/**
* <p>
* Delete a network from Serengeti by name
* </p>
*
* @param name
* Customize the network's name
*/
@CliCommand(value = "network delete", help = "Delete a network from Serengeti by name")
public void deleteNetwork(
@CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name) {
//rest invocation
try {
networkRestClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_DELETE);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
/**
* <p>
* get network information from Serengeti
* </p>
*
* @param name
* Customize the network's name
* @param detail
* The detail flag
*
*/
@CliCommand(value = "network list", help = "Get network information from Serengeti")
public void getNetwork(
@CliOption(key = { "name" }, mandatory = false, help = "Customize the network's name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
NetworkRead[] networks = networkRestClient.getAll(detail);
prettyOutputNetworksInfo(networks, detail);
} else {
NetworkRead network = networkRestClient.get(name, detail);
prettyOutputNetworkInfo(network, detail);
}
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private void addNetwork(NetworkType operType, final String name,
final String portGroup, final String ip, final boolean dhcp,
final String dns, final String sedDNS, final String gateway,
final String mask) {
switch (operType) {
case IP:
try {
addNetworkByIPModel(operType, name, portGroup, ip, dns, sedDNS,
gateway, mask);
} catch (UnknownHostException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.OUTPUT_UNKNOWN_HOST);
}
break;
case DHCP:
addNetworkByDHCPModel(operType, name, portGroup, dhcp);
}
}
private void addNetworkByDHCPModel(NetworkType operType, final String name,
final String portGroup, final boolean dhcp) {
NetworkAdd networkAdd = new NetworkAdd();
networkAdd.setName(name);
networkAdd.setPortGroup(portGroup);
networkAdd.setDhcp(true);
//rest invocation
try {
networkRestClient.add(networkAdd);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_ADD);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private void addNetworkByIPModel(NetworkType operType, final String name,
final String portGroup, final String ip, final String dns,
final String sedDNS, final String gateway, final String mask)
throws UnknownHostException {
// validate the network add command option.
networkName = name;
if (validateAddNetworkOptionByIP(ip, dns, sedDNS, gateway, mask)) {
NetworkAdd networkAdd = new NetworkAdd();
networkAdd.setName(name);
networkAdd.setPortGroup(portGroup);
networkAdd.setIp(transferIpInfo(ip));
networkAdd.setDns1(dns);
networkAdd.setDns2(sedDNS);
networkAdd.setGateway(gateway);
networkAdd.setNetmask(mask);
//rest invocation
try {
networkRestClient.add(networkAdd);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_ADD);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
}
private List<IpBlock> transferIpInfo(final String ip)
throws UnknownHostException {
List<IpBlock> ipBlockList = new ArrayList<IpBlock>();
List<String> ipList = CommandsUtils.inputsConvert(ip);
Pattern ipPattern = Pattern.compile(PatternType.IP);
Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG);
if (ipList == null) {
throw new RuntimeException(
"[NetworkCommands:transferIpInfo]ipList is null .");
} else if (ipList.size() == 0) {
return ipBlockList;
} else {
IpBlock ipBlock = null;
for (Iterator<String> iterator = ipList.iterator(); iterator.hasNext();) {
String ipRangeStr = (String) iterator.next();
if (ipPattern.matcher(ipRangeStr).matches()) {
ipBlock = new IpBlock();
ipBlock.setBeginIp(ipRangeStr);
ipBlock.setEndIp(ipRangeStr);
ipBlockList.add(ipBlock);
} else if (ipSegPattern.matcher(ipRangeStr).matches()) {
ipBlock = new IpBlock();
String[] ips = ipRangeStr.split("-");
ipBlock.setBeginIp(ips[0]);
ipBlock.setEndIp(new StringBuilder()
.append(ips[0].substring(0, ips[0].lastIndexOf(".") + 1))
.append(ips[1]).toString());
ipBlockList.add(ipBlock);
}
}
}
return ipBlockList;
}
private boolean validateAddNetworkOptionByIP(final String ip,
final String dns, final String sedDNS, final String gateway,
final String mask) {
if (!validateIP(ip)) {
return false;
}
if (!validateDNS(dns)) {
return false;
}
if (!validateDNS(sedDNS)) {
return false;
}
if (!validateGateway(gateway)) {
return false;
}
if (!validateMask(mask)) {
return false;
}
return true;
}
private boolean validateIP(final String ip) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG);
List<String> ipPrarams = CommandsUtils.inputsConvert(ip);
if (ipPrarams.size() == 0) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString());
return false;
}
for (Iterator<String> iterator = ipPrarams.iterator(); iterator.hasNext();) {
String ipParam = (String) iterator.next();
if (!ipPattern.matcher(ipParam).matches()
&& !ipSegPattern.matcher(ipParam).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString());
return false;
}
}
return true;
}
private boolean validateDNS(final String dns) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (!CommandsUtils.isBlank(dns) && !ipPattern.matcher(dns).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "dns=" + dns + errorMessage.toString());
return false;
} else
return true;
}
private boolean validateGateway(final String gateway) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (CommandsUtils.isBlank(gateway)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_GATEWAY + Constants.MULTI_INPUTS_CHECK);
return false;
} else if (!ipPattern.matcher(gateway).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "gateway=" + gateway + errorMessage.toString());
return false;
} else
return true;
}
private boolean validateMask(final String mask) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (CommandsUtils.isBlank(mask)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_MASK + Constants.MULTI_INPUTS_CHECK);
return false;
} else if (!ipPattern.matcher(mask).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
- Constants.INVALID_VALUE + " " + "maks=" + mask + errorMessage.toString());
+ Constants.INVALID_VALUE + " " + "mask=" + mask + errorMessage.toString());
return false;
} else
return true;
}
private void prettyOutputNetworksInfo(NetworkRead[] networks, boolean detail) {
if (networks != null) {
LinkedHashMap<String, List<String>> networkIpColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_PORT_GROUP,
Arrays.asList("getPortGroup"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("findDhcpOrIp"));
if (detail) {
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_FREE_IPS,
Arrays.asList("getFreeIpBlocks"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ASSIGNED_IPS,
Arrays.asList("getAssignedIpBlocks"));
} else {
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP_RANGES,
Arrays.asList("getAllIpBlocks"));
}
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_DNS1, Arrays.asList("getDns1"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_DNS2, Arrays.asList("getDns2"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GATEWAY,
Arrays.asList("getGateway"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_MASK, Arrays.asList("getNetmask"));
try {
if (detail) {
LinkedHashMap<String, List<String>> networkDhcpColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME,
Arrays.asList("getName"));
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_PORT_GROUP,
Arrays.asList("getPortGroup"));
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("findDhcpOrIp"));
for (NetworkRead network : networks) {
if (network.isDhcp())
CommandsUtils.printInTableFormat(
networkDhcpColumnNamesWithGetMethodNames,
new NetworkRead[] { network },
Constants.OUTPUT_INDENT);
else
CommandsUtils.printInTableFormat(
networkIpColumnNamesWithGetMethodNames,
new NetworkRead[] { network },
Constants.OUTPUT_INDENT);
System.out.println();
prettyOutputNetworkDetailInfo(network);
System.out.println();
}
} else {
CommandsUtils.printInTableFormat(
networkIpColumnNamesWithGetMethodNames, networks,
Constants.OUTPUT_INDENT);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
private void prettyOutputNetworkInfo(NetworkRead network, boolean detail) {
if (network != null)
prettyOutputNetworksInfo(new NetworkRead[] {network}, detail);
}
private void prettyOutputNetworkDetailInfo(NetworkRead network)
throws Exception {
List<IpAllocEntryRead> ipAllocEntrys = network.getIpAllocEntries();
LinkedHashMap<String, List<String>> networkDetailColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIpAddress"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE,
Arrays.asList("getNodeName"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE_GROUP_NAME,
Arrays.asList("getNodeGroupName"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_CLUSTER_NAME,
Arrays.asList("getClusterName"));
CommandsUtils.printInTableFormat(
networkDetailColumnNamesWithGetMethodNames,
ipAllocEntrys.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
}
| true | true | public void addNetwork(
@CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name,
@CliOption(key = { "portGroup" }, mandatory = true, help = "The port group name") final String portGroup,
@CliOption(key = { "dhcp" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "The dhcp information") final boolean dhcp,
@CliOption(key = { "dns" }, mandatory = false, help = "The first dns information") final String dns,
@CliOption(key = { "secondDNS" }, mandatory = false, help = "The second dns information") final String sedDNS,
@CliOption(key = { "ip" }, mandatory = false, help = "The ip information") final String ip,
@CliOption(key = { "gateway" }, mandatory = false, help = "The gateway information") final String gateway,
@CliOption(key = { "mask" }, mandatory = false, help = "The mask information") final String mask) {
NetworkType operType = null;
if (!CommandsUtils.isBlank(ip) && dhcp) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_EXCLUSION_PAIR_NETWORK_ADD_IP_DHCP
+ Constants.PARAMS_EXCLUSION);
return;
} else if (dhcp) {
operType = NetworkType.DHCP;
} else if (!CommandsUtils.isBlank(ip)) {
operType = NetworkType.IP;
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_IP_DHCP_NOT_NULL);
return;
}
addNetwork(operType, name, portGroup, ip, dhcp, dns, sedDNS, gateway,
mask);
}
/**
* <p>
* Delete a network from Serengeti by name
* </p>
*
* @param name
* Customize the network's name
*/
@CliCommand(value = "network delete", help = "Delete a network from Serengeti by name")
public void deleteNetwork(
@CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name) {
//rest invocation
try {
networkRestClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_DELETE);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
/**
* <p>
* get network information from Serengeti
* </p>
*
* @param name
* Customize the network's name
* @param detail
* The detail flag
*
*/
@CliCommand(value = "network list", help = "Get network information from Serengeti")
public void getNetwork(
@CliOption(key = { "name" }, mandatory = false, help = "Customize the network's name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
NetworkRead[] networks = networkRestClient.getAll(detail);
prettyOutputNetworksInfo(networks, detail);
} else {
NetworkRead network = networkRestClient.get(name, detail);
prettyOutputNetworkInfo(network, detail);
}
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private void addNetwork(NetworkType operType, final String name,
final String portGroup, final String ip, final boolean dhcp,
final String dns, final String sedDNS, final String gateway,
final String mask) {
switch (operType) {
case IP:
try {
addNetworkByIPModel(operType, name, portGroup, ip, dns, sedDNS,
gateway, mask);
} catch (UnknownHostException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.OUTPUT_UNKNOWN_HOST);
}
break;
case DHCP:
addNetworkByDHCPModel(operType, name, portGroup, dhcp);
}
}
private void addNetworkByDHCPModel(NetworkType operType, final String name,
final String portGroup, final boolean dhcp) {
NetworkAdd networkAdd = new NetworkAdd();
networkAdd.setName(name);
networkAdd.setPortGroup(portGroup);
networkAdd.setDhcp(true);
//rest invocation
try {
networkRestClient.add(networkAdd);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_ADD);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private void addNetworkByIPModel(NetworkType operType, final String name,
final String portGroup, final String ip, final String dns,
final String sedDNS, final String gateway, final String mask)
throws UnknownHostException {
// validate the network add command option.
networkName = name;
if (validateAddNetworkOptionByIP(ip, dns, sedDNS, gateway, mask)) {
NetworkAdd networkAdd = new NetworkAdd();
networkAdd.setName(name);
networkAdd.setPortGroup(portGroup);
networkAdd.setIp(transferIpInfo(ip));
networkAdd.setDns1(dns);
networkAdd.setDns2(sedDNS);
networkAdd.setGateway(gateway);
networkAdd.setNetmask(mask);
//rest invocation
try {
networkRestClient.add(networkAdd);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_ADD);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
}
private List<IpBlock> transferIpInfo(final String ip)
throws UnknownHostException {
List<IpBlock> ipBlockList = new ArrayList<IpBlock>();
List<String> ipList = CommandsUtils.inputsConvert(ip);
Pattern ipPattern = Pattern.compile(PatternType.IP);
Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG);
if (ipList == null) {
throw new RuntimeException(
"[NetworkCommands:transferIpInfo]ipList is null .");
} else if (ipList.size() == 0) {
return ipBlockList;
} else {
IpBlock ipBlock = null;
for (Iterator<String> iterator = ipList.iterator(); iterator.hasNext();) {
String ipRangeStr = (String) iterator.next();
if (ipPattern.matcher(ipRangeStr).matches()) {
ipBlock = new IpBlock();
ipBlock.setBeginIp(ipRangeStr);
ipBlock.setEndIp(ipRangeStr);
ipBlockList.add(ipBlock);
} else if (ipSegPattern.matcher(ipRangeStr).matches()) {
ipBlock = new IpBlock();
String[] ips = ipRangeStr.split("-");
ipBlock.setBeginIp(ips[0]);
ipBlock.setEndIp(new StringBuilder()
.append(ips[0].substring(0, ips[0].lastIndexOf(".") + 1))
.append(ips[1]).toString());
ipBlockList.add(ipBlock);
}
}
}
return ipBlockList;
}
private boolean validateAddNetworkOptionByIP(final String ip,
final String dns, final String sedDNS, final String gateway,
final String mask) {
if (!validateIP(ip)) {
return false;
}
if (!validateDNS(dns)) {
return false;
}
if (!validateDNS(sedDNS)) {
return false;
}
if (!validateGateway(gateway)) {
return false;
}
if (!validateMask(mask)) {
return false;
}
return true;
}
private boolean validateIP(final String ip) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG);
List<String> ipPrarams = CommandsUtils.inputsConvert(ip);
if (ipPrarams.size() == 0) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString());
return false;
}
for (Iterator<String> iterator = ipPrarams.iterator(); iterator.hasNext();) {
String ipParam = (String) iterator.next();
if (!ipPattern.matcher(ipParam).matches()
&& !ipSegPattern.matcher(ipParam).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString());
return false;
}
}
return true;
}
private boolean validateDNS(final String dns) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (!CommandsUtils.isBlank(dns) && !ipPattern.matcher(dns).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "dns=" + dns + errorMessage.toString());
return false;
} else
return true;
}
private boolean validateGateway(final String gateway) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (CommandsUtils.isBlank(gateway)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_GATEWAY + Constants.MULTI_INPUTS_CHECK);
return false;
} else if (!ipPattern.matcher(gateway).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "gateway=" + gateway + errorMessage.toString());
return false;
} else
return true;
}
private boolean validateMask(final String mask) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (CommandsUtils.isBlank(mask)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_MASK + Constants.MULTI_INPUTS_CHECK);
return false;
} else if (!ipPattern.matcher(mask).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "maks=" + mask + errorMessage.toString());
return false;
} else
return true;
}
private void prettyOutputNetworksInfo(NetworkRead[] networks, boolean detail) {
if (networks != null) {
LinkedHashMap<String, List<String>> networkIpColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_PORT_GROUP,
Arrays.asList("getPortGroup"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("findDhcpOrIp"));
if (detail) {
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_FREE_IPS,
Arrays.asList("getFreeIpBlocks"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ASSIGNED_IPS,
Arrays.asList("getAssignedIpBlocks"));
} else {
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP_RANGES,
Arrays.asList("getAllIpBlocks"));
}
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_DNS1, Arrays.asList("getDns1"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_DNS2, Arrays.asList("getDns2"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GATEWAY,
Arrays.asList("getGateway"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_MASK, Arrays.asList("getNetmask"));
try {
if (detail) {
LinkedHashMap<String, List<String>> networkDhcpColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME,
Arrays.asList("getName"));
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_PORT_GROUP,
Arrays.asList("getPortGroup"));
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("findDhcpOrIp"));
for (NetworkRead network : networks) {
if (network.isDhcp())
CommandsUtils.printInTableFormat(
networkDhcpColumnNamesWithGetMethodNames,
new NetworkRead[] { network },
Constants.OUTPUT_INDENT);
else
CommandsUtils.printInTableFormat(
networkIpColumnNamesWithGetMethodNames,
new NetworkRead[] { network },
Constants.OUTPUT_INDENT);
System.out.println();
prettyOutputNetworkDetailInfo(network);
System.out.println();
}
} else {
CommandsUtils.printInTableFormat(
networkIpColumnNamesWithGetMethodNames, networks,
Constants.OUTPUT_INDENT);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
private void prettyOutputNetworkInfo(NetworkRead network, boolean detail) {
if (network != null)
prettyOutputNetworksInfo(new NetworkRead[] {network}, detail);
}
private void prettyOutputNetworkDetailInfo(NetworkRead network)
throws Exception {
List<IpAllocEntryRead> ipAllocEntrys = network.getIpAllocEntries();
LinkedHashMap<String, List<String>> networkDetailColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIpAddress"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE,
Arrays.asList("getNodeName"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE_GROUP_NAME,
Arrays.asList("getNodeGroupName"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_CLUSTER_NAME,
Arrays.asList("getClusterName"));
CommandsUtils.printInTableFormat(
networkDetailColumnNamesWithGetMethodNames,
ipAllocEntrys.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
}
| public void addNetwork(
@CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name,
@CliOption(key = { "portGroup" }, mandatory = true, help = "The port group name") final String portGroup,
@CliOption(key = { "dhcp" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "The dhcp information") final boolean dhcp,
@CliOption(key = { "dns" }, mandatory = false, help = "The first dns information") final String dns,
@CliOption(key = { "secondDNS" }, mandatory = false, help = "The second dns information") final String sedDNS,
@CliOption(key = { "ip" }, mandatory = false, help = "The ip information") final String ip,
@CliOption(key = { "gateway" }, mandatory = false, help = "The gateway information") final String gateway,
@CliOption(key = { "mask" }, mandatory = false, help = "The mask information") final String mask) {
NetworkType operType = null;
if (!CommandsUtils.isBlank(ip) && dhcp) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_EXCLUSION_PAIR_NETWORK_ADD_IP_DHCP
+ Constants.PARAMS_EXCLUSION);
return;
} else if (dhcp) {
operType = NetworkType.DHCP;
} else if (!CommandsUtils.isBlank(ip)) {
operType = NetworkType.IP;
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_IP_DHCP_NOT_NULL);
return;
}
addNetwork(operType, name, portGroup, ip, dhcp, dns, sedDNS, gateway,
mask);
}
/**
* <p>
* Delete a network from Serengeti by name
* </p>
*
* @param name
* Customize the network's name
*/
@CliCommand(value = "network delete", help = "Delete a network from Serengeti by name")
public void deleteNetwork(
@CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name) {
//rest invocation
try {
networkRestClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_DELETE);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
/**
* <p>
* get network information from Serengeti
* </p>
*
* @param name
* Customize the network's name
* @param detail
* The detail flag
*
*/
@CliCommand(value = "network list", help = "Get network information from Serengeti")
public void getNetwork(
@CliOption(key = { "name" }, mandatory = false, help = "Customize the network's name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
NetworkRead[] networks = networkRestClient.getAll(detail);
prettyOutputNetworksInfo(networks, detail);
} else {
NetworkRead network = networkRestClient.get(name, detail);
prettyOutputNetworkInfo(network, detail);
}
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private void addNetwork(NetworkType operType, final String name,
final String portGroup, final String ip, final boolean dhcp,
final String dns, final String sedDNS, final String gateway,
final String mask) {
switch (operType) {
case IP:
try {
addNetworkByIPModel(operType, name, portGroup, ip, dns, sedDNS,
gateway, mask);
} catch (UnknownHostException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.OUTPUT_UNKNOWN_HOST);
}
break;
case DHCP:
addNetworkByDHCPModel(operType, name, portGroup, dhcp);
}
}
private void addNetworkByDHCPModel(NetworkType operType, final String name,
final String portGroup, final boolean dhcp) {
NetworkAdd networkAdd = new NetworkAdd();
networkAdd.setName(name);
networkAdd.setPortGroup(portGroup);
networkAdd.setDhcp(true);
//rest invocation
try {
networkRestClient.add(networkAdd);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_ADD);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private void addNetworkByIPModel(NetworkType operType, final String name,
final String portGroup, final String ip, final String dns,
final String sedDNS, final String gateway, final String mask)
throws UnknownHostException {
// validate the network add command option.
networkName = name;
if (validateAddNetworkOptionByIP(ip, dns, sedDNS, gateway, mask)) {
NetworkAdd networkAdd = new NetworkAdd();
networkAdd.setName(name);
networkAdd.setPortGroup(portGroup);
networkAdd.setIp(transferIpInfo(ip));
networkAdd.setDns1(dns);
networkAdd.setDns2(sedDNS);
networkAdd.setGateway(gateway);
networkAdd.setNetmask(mask);
//rest invocation
try {
networkRestClient.add(networkAdd);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_RESULT_ADD);
}catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name,
Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
}
private List<IpBlock> transferIpInfo(final String ip)
throws UnknownHostException {
List<IpBlock> ipBlockList = new ArrayList<IpBlock>();
List<String> ipList = CommandsUtils.inputsConvert(ip);
Pattern ipPattern = Pattern.compile(PatternType.IP);
Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG);
if (ipList == null) {
throw new RuntimeException(
"[NetworkCommands:transferIpInfo]ipList is null .");
} else if (ipList.size() == 0) {
return ipBlockList;
} else {
IpBlock ipBlock = null;
for (Iterator<String> iterator = ipList.iterator(); iterator.hasNext();) {
String ipRangeStr = (String) iterator.next();
if (ipPattern.matcher(ipRangeStr).matches()) {
ipBlock = new IpBlock();
ipBlock.setBeginIp(ipRangeStr);
ipBlock.setEndIp(ipRangeStr);
ipBlockList.add(ipBlock);
} else if (ipSegPattern.matcher(ipRangeStr).matches()) {
ipBlock = new IpBlock();
String[] ips = ipRangeStr.split("-");
ipBlock.setBeginIp(ips[0]);
ipBlock.setEndIp(new StringBuilder()
.append(ips[0].substring(0, ips[0].lastIndexOf(".") + 1))
.append(ips[1]).toString());
ipBlockList.add(ipBlock);
}
}
}
return ipBlockList;
}
private boolean validateAddNetworkOptionByIP(final String ip,
final String dns, final String sedDNS, final String gateway,
final String mask) {
if (!validateIP(ip)) {
return false;
}
if (!validateDNS(dns)) {
return false;
}
if (!validateDNS(sedDNS)) {
return false;
}
if (!validateGateway(gateway)) {
return false;
}
if (!validateMask(mask)) {
return false;
}
return true;
}
private boolean validateIP(final String ip) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG);
List<String> ipPrarams = CommandsUtils.inputsConvert(ip);
if (ipPrarams.size() == 0) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString());
return false;
}
for (Iterator<String> iterator = ipPrarams.iterator(); iterator.hasNext();) {
String ipParam = (String) iterator.next();
if (!ipPattern.matcher(ipParam).matches()
&& !ipSegPattern.matcher(ipParam).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString());
return false;
}
}
return true;
}
private boolean validateDNS(final String dns) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (!CommandsUtils.isBlank(dns) && !ipPattern.matcher(dns).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "dns=" + dns + errorMessage.toString());
return false;
} else
return true;
}
private boolean validateGateway(final String gateway) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (CommandsUtils.isBlank(gateway)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_GATEWAY + Constants.MULTI_INPUTS_CHECK);
return false;
} else if (!ipPattern.matcher(gateway).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "gateway=" + gateway + errorMessage.toString());
return false;
} else
return true;
}
private boolean validateMask(final String mask) {
Pattern ipPattern = Pattern.compile(PatternType.IP);
if (CommandsUtils.isBlank(mask)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAMS_NETWORK_ADD_MASK + Constants.MULTI_INPUTS_CHECK);
return false;
} else if (!ipPattern.matcher(mask).matches()) {
StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK,
networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INVALID_VALUE + " " + "mask=" + mask + errorMessage.toString());
return false;
} else
return true;
}
private void prettyOutputNetworksInfo(NetworkRead[] networks, boolean detail) {
if (networks != null) {
LinkedHashMap<String, List<String>> networkIpColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_PORT_GROUP,
Arrays.asList("getPortGroup"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("findDhcpOrIp"));
if (detail) {
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_FREE_IPS,
Arrays.asList("getFreeIpBlocks"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ASSIGNED_IPS,
Arrays.asList("getAssignedIpBlocks"));
} else {
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP_RANGES,
Arrays.asList("getAllIpBlocks"));
}
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_DNS1, Arrays.asList("getDns1"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_DNS2, Arrays.asList("getDns2"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GATEWAY,
Arrays.asList("getGateway"));
networkIpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_MASK, Arrays.asList("getNetmask"));
try {
if (detail) {
LinkedHashMap<String, List<String>> networkDhcpColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NAME,
Arrays.asList("getName"));
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_PORT_GROUP,
Arrays.asList("getPortGroup"));
networkDhcpColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("findDhcpOrIp"));
for (NetworkRead network : networks) {
if (network.isDhcp())
CommandsUtils.printInTableFormat(
networkDhcpColumnNamesWithGetMethodNames,
new NetworkRead[] { network },
Constants.OUTPUT_INDENT);
else
CommandsUtils.printInTableFormat(
networkIpColumnNamesWithGetMethodNames,
new NetworkRead[] { network },
Constants.OUTPUT_INDENT);
System.out.println();
prettyOutputNetworkDetailInfo(network);
System.out.println();
}
} else {
CommandsUtils.printInTableFormat(
networkIpColumnNamesWithGetMethodNames, networks,
Constants.OUTPUT_INDENT);
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
private void prettyOutputNetworkInfo(NetworkRead network, boolean detail) {
if (network != null)
prettyOutputNetworksInfo(new NetworkRead[] {network}, detail);
}
private void prettyOutputNetworkDetailInfo(NetworkRead network)
throws Exception {
List<IpAllocEntryRead> ipAllocEntrys = network.getIpAllocEntries();
LinkedHashMap<String, List<String>> networkDetailColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIpAddress"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE,
Arrays.asList("getNodeName"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE_GROUP_NAME,
Arrays.asList("getNodeGroupName"));
networkDetailColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_CLUSTER_NAME,
Arrays.asList("getClusterName"));
CommandsUtils.printInTableFormat(
networkDetailColumnNamesWithGetMethodNames,
ipAllocEntrys.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
}
|
diff --git a/src/org/apache/html/dom/ObjectFactory.java b/src/org/apache/html/dom/ObjectFactory.java
index 3ffe3463e..7a04cbea9 100644
--- a/src/org/apache/html/dom/ObjectFactory.java
+++ b/src/org/apache/html/dom/ObjectFactory.java
@@ -1,545 +1,545 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.html.dom;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
* <p>
* This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to run on JDK version 1.1 and
* later, and to compile on JDK 1.2 and onward.
* The code also runs both as part of an unbundled jar file and
* when bundled as part of the JDK.
* <p>
*
* @xerces.internal
*
* @version $Id$
*/
final class ObjectFactory {
//
// Constants
//
// name of default properties file to look for in JDK's jre/lib directory
private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";
/** Set to true for debugging */
private static final boolean DEBUG = isDebugEnabled();
/**
* Default columns per line.
*/
private static final int DEFAULT_LINE_LENGTH = 80;
/** cache the contents of the xerces.properties file.
* Until an attempt has been made to read this file, this will
* be null; if the file does not exist or we encounter some other error
* during the read, this will be empty.
*/
private static Properties fXercesProperties = null;
/***
* Cache the time stamp of the xerces.properties file so
* that we know if it's been modified and can invalidate
* the cache when necessary.
*/
private static long fLastModified = -1;
//
// static methods
//
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId, String fallbackClassName)
throws ConfigurationError {
return createObject(factoryId, null, fallbackClassName);
} // createObject(String,String):Object
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param propertiesFilename The filename in the $java.home/lib directory
* of the properties file. If none specified,
* ${java.home}/lib/xerces.properties will be used.
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId,
String propertiesFilename,
String fallbackClassName)
throws ConfigurationError
{
if (DEBUG) debugPrintln("debug is on");
ClassLoader cl = findClassLoader();
// Use the system property first
try {
String systemProp = SecuritySupport.getSystemProperty(factoryId);
if (systemProp != null && systemProp.length() > 0) {
if (DEBUG) debugPrintln("found system property, value=" + systemProp);
return newInstance(systemProp, cl, true);
}
} catch (SecurityException se) {
// Ignore and continue w/ next location
}
// Try to read from propertiesFilename, or $java.home/lib/xerces.properties
String factoryClassName = null;
// no properties file name specified; use $JAVA_HOME/lib/xerces.properties:
if (propertiesFilename == null) {
File propertiesFile = null;
boolean propertiesFileExists = false;
try {
String javah = SecuritySupport.getSystemProperty("java.home");
propertiesFilename = javah + File.separator +
"lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
propertiesFile = new File(propertiesFilename);
propertiesFileExists = SecuritySupport.getFileExists(propertiesFile);
} catch (SecurityException e) {
// try again...
fLastModified = -1;
fXercesProperties = null;
}
synchronized (ObjectFactory.class) {
boolean loadProperties = false;
FileInputStream fis = null;
try {
// file existed last time
if(fLastModified >= 0) {
if(propertiesFileExists &&
(fLastModified < (fLastModified = SecuritySupport.getLastModified(propertiesFile)))) {
loadProperties = true;
} else {
// file has stopped existing...
if(!propertiesFileExists) {
fLastModified = -1;
fXercesProperties = null;
} // else, file wasn't modified!
}
} else {
// file has started to exist:
if(propertiesFileExists) {
loadProperties = true;
fLastModified = SecuritySupport.getLastModified(propertiesFile);
} // else, nothing's changed
}
if(loadProperties) {
// must never have attempted to read xerces.properties before (or it's outdeated)
fXercesProperties = new Properties();
fis = SecuritySupport.getFileInputStream(propertiesFile);
fXercesProperties.load(fis);
}
} catch (Exception x) {
fXercesProperties = null;
fLastModified = -1;
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if(fXercesProperties != null) {
factoryClassName = fXercesProperties.getProperty(factoryId);
}
} else {
FileInputStream fis = null;
try {
fis = SecuritySupport.getFileInputStream(new File(propertiesFilename));
Properties props = new Properties();
props.load(fis);
factoryClassName = props.getProperty(factoryId);
} catch (Exception x) {
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if (factoryClassName != null) {
if (DEBUG) debugPrintln("found in " + propertiesFilename + ", value=" + factoryClassName);
return newInstance(factoryClassName, cl, true);
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
return newInstance(fallbackClassName, cl, true);
} // createObject(String,String,String):Object
//
// Private static methods
//
/** Returns true if debug has been enabled. */
private static boolean isDebugEnabled() {
try {
String val = SecuritySupport.getSystemProperty("xerces.debug");
// Allow simply setting the prop to turn on debug
return (val != null && (!"false".equals(val)));
}
catch (SecurityException se) {}
return false;
} // isDebugEnabled()
/** Prints a message to standard error if debugging is enabled. */
private static void debugPrintln(String msg) {
if (DEBUG) {
System.err.println("XERCES: " + msg);
}
} // debugPrintln(String)
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use
* the context ClassLoader.
*/
static ClassLoader findClassLoader()
throws ConfigurationError
{
// Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
ClassLoader context = SecuritySupport.getContextClassLoader();
ClassLoader system = SecuritySupport.getSystemClassLoader();
ClassLoader chain = system;
while (true) {
if (context == chain) {
// Assert: we are on JDK 1.1 or we have no Context ClassLoader
// or any Context ClassLoader in chain of system classloader
// (including extension ClassLoader) so extend to widest
// ClassLoader (always look in system ClassLoader if Xerces
// is in boot/extension/system classpath and in current
// ClassLoader otherwise); normal classloaders delegate
// back to system ClassLoader first so this widening doesn't
// change the fact that context ClassLoader will be consulted
ClassLoader current = ObjectFactory.class.getClassLoader();
chain = system;
while (true) {
if (current == chain) {
// Assert: Current ClassLoader in chain of
// boot/extension/system ClassLoaders
return system;
}
if (chain == null) {
break;
}
chain = SecuritySupport.getParentClassLoader(chain);
}
// Assert: Current ClassLoader not in chain of
// boot/extension/system ClassLoaders
return current;
}
if (chain == null) {
// boot ClassLoader reached
break;
}
// Check for any extension ClassLoaders in chain up to
// boot ClassLoader
chain = SecuritySupport.getParentClassLoader(chain);
};
// Assert: Context ClassLoader not in chain of
// boot/extension/system ClassLoaders
return context;
} // findClassLoader():ClassLoader
/**
* Create an instance of a class using the specified ClassLoader
*/
static Object newInstance(String className, ClassLoader cl,
boolean doFallback)
throws ConfigurationError
{
// assert(className != null);
try{
Class providerClass = findProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (DEBUG) debugPrintln("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) {
throw new ConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Find a Class using the specified ClassLoader
*/
static Class findProviderClass(String className, ClassLoader cl,
boolean doFallback)
throws ClassNotFoundException, ConfigurationError
{
//throw security exception if the calling thread is not allowed to access the package
- //restrict the access to package as speicified in java.security policy
+ //restrict the access to package as specified in java.security policy
SecurityManager security = System.getSecurityManager();
if (security != null) {
final int lastDot = className.lastIndexOf('.');
String packageName = className;
if (lastDot != -1) packageName = className.substring(0, lastDot);
security.checkPackageAccess(packageName);
}
Class providerClass;
if (cl == null) {
// XXX Use the bootstrap ClassLoader. There is no way to
// load a class using the bootstrap ClassLoader that works
// in both JDK 1.1 and Java 2. However, this should still
// work b/c the following should be true:
//
// (cl == null) iff current ClassLoader == null
//
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else {
try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
ClassLoader current = ObjectFactory.class.getClassLoader();
if (current == null) {
providerClass = Class.forName(className);
} else if (cl != current) {
cl = current;
providerClass = cl.loadClass(className);
} else {
throw x;
}
} else {
throw x;
}
}
}
return providerClass;
}
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider(String factoryId)
throws ConfigurationError
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = findClassLoader();
is = SecuritySupport.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
ClassLoader current = ObjectFactory.class.getClassLoader();
if (cl != current) {
cl = current;
is = SecuritySupport.getResourceAsStream(cl, serviceId);
}
}
if (is == null) {
// No provider found
return null;
}
if (DEBUG) debugPrintln("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
}
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine();
} catch (IOException x) {
// No provider found
return null;
}
finally {
try {
// try to close the reader.
rd.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
if (DEBUG) debugPrintln("found in resource, value="
+ factoryClassName);
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance(factoryClassName, cl, false);
}
// No provider found
return null;
}
//
// Classes
//
/**
* A configuration error.
*/
static final class ConfigurationError
extends Error {
/** Serialization version. */
static final long serialVersionUID = 2646822752226280048L;
//
// Data
//
/** Exception. */
private Exception exception;
//
// Constructors
//
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
} // <init>(String,Exception)
//
// methods
//
/** Returns the exception associated to this error. */
Exception getException() {
return exception;
} // getException():Exception
} // class ConfigurationError
} // class ObjectFactory
diff --git a/src/org/apache/xerces/dom/ObjectFactory.java b/src/org/apache/xerces/dom/ObjectFactory.java
index a2ba0cfed..11eebe258 100644
--- a/src/org/apache/xerces/dom/ObjectFactory.java
+++ b/src/org/apache/xerces/dom/ObjectFactory.java
@@ -1,545 +1,545 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.dom;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
* <p>
* This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to run on JDK version 1.1 and
* later, and to compile on JDK 1.2 and onward.
* The code also runs both as part of an unbundled jar file and
* when bundled as part of the JDK.
* <p>
*
* @xerces.internal
*
* @version $Id$
*/
final class ObjectFactory {
//
// Constants
//
// name of default properties file to look for in JDK's jre/lib directory
private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";
/** Set to true for debugging */
private static final boolean DEBUG = isDebugEnabled();
/**
* Default columns per line.
*/
private static final int DEFAULT_LINE_LENGTH = 80;
/** cache the contents of the xerces.properties file.
* Until an attempt has been made to read this file, this will
* be null; if the file does not exist or we encounter some other error
* during the read, this will be empty.
*/
private static Properties fXercesProperties = null;
/***
* Cache the time stamp of the xerces.properties file so
* that we know if it's been modified and can invalidate
* the cache when necessary.
*/
private static long fLastModified = -1;
//
// static methods
//
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId, String fallbackClassName)
throws ConfigurationError {
return createObject(factoryId, null, fallbackClassName);
} // createObject(String,String):Object
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param propertiesFilename The filename in the $java.home/lib directory
* of the properties file. If none specified,
* ${java.home}/lib/xerces.properties will be used.
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId,
String propertiesFilename,
String fallbackClassName)
throws ConfigurationError
{
if (DEBUG) debugPrintln("debug is on");
ClassLoader cl = findClassLoader();
// Use the system property first
try {
String systemProp = SecuritySupport.getSystemProperty(factoryId);
if (systemProp != null && systemProp.length() > 0) {
if (DEBUG) debugPrintln("found system property, value=" + systemProp);
return newInstance(systemProp, cl, true);
}
} catch (SecurityException se) {
// Ignore and continue w/ next location
}
// Try to read from propertiesFilename, or $java.home/lib/xerces.properties
String factoryClassName = null;
// no properties file name specified; use $JAVA_HOME/lib/xerces.properties:
if (propertiesFilename == null) {
File propertiesFile = null;
boolean propertiesFileExists = false;
try {
String javah = SecuritySupport.getSystemProperty("java.home");
propertiesFilename = javah + File.separator +
"lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
propertiesFile = new File(propertiesFilename);
propertiesFileExists = SecuritySupport.getFileExists(propertiesFile);
} catch (SecurityException e) {
// try again...
fLastModified = -1;
fXercesProperties = null;
}
synchronized (ObjectFactory.class) {
boolean loadProperties = false;
FileInputStream fis = null;
try {
// file existed last time
if(fLastModified >= 0) {
if(propertiesFileExists &&
(fLastModified < (fLastModified = SecuritySupport.getLastModified(propertiesFile)))) {
loadProperties = true;
} else {
// file has stopped existing...
if(!propertiesFileExists) {
fLastModified = -1;
fXercesProperties = null;
} // else, file wasn't modified!
}
} else {
// file has started to exist:
if(propertiesFileExists) {
loadProperties = true;
fLastModified = SecuritySupport.getLastModified(propertiesFile);
} // else, nothing's changed
}
if(loadProperties) {
// must never have attempted to read xerces.properties before (or it's outdeated)
fXercesProperties = new Properties();
fis = SecuritySupport.getFileInputStream(propertiesFile);
fXercesProperties.load(fis);
}
} catch (Exception x) {
fXercesProperties = null;
fLastModified = -1;
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if(fXercesProperties != null) {
factoryClassName = fXercesProperties.getProperty(factoryId);
}
} else {
FileInputStream fis = null;
try {
fis = SecuritySupport.getFileInputStream(new File(propertiesFilename));
Properties props = new Properties();
props.load(fis);
factoryClassName = props.getProperty(factoryId);
} catch (Exception x) {
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if (factoryClassName != null) {
if (DEBUG) debugPrintln("found in " + propertiesFilename + ", value=" + factoryClassName);
return newInstance(factoryClassName, cl, true);
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
return newInstance(fallbackClassName, cl, true);
} // createObject(String,String,String):Object
//
// Private static methods
//
/** Returns true if debug has been enabled. */
private static boolean isDebugEnabled() {
try {
String val = SecuritySupport.getSystemProperty("xerces.debug");
// Allow simply setting the prop to turn on debug
return (val != null && (!"false".equals(val)));
}
catch (SecurityException se) {}
return false;
} // isDebugEnabled()
/** Prints a message to standard error if debugging is enabled. */
private static void debugPrintln(String msg) {
if (DEBUG) {
System.err.println("XERCES: " + msg);
}
} // debugPrintln(String)
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use
* the context ClassLoader.
*/
static ClassLoader findClassLoader()
throws ConfigurationError
{
// Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
ClassLoader context = SecuritySupport.getContextClassLoader();
ClassLoader system = SecuritySupport.getSystemClassLoader();
ClassLoader chain = system;
while (true) {
if (context == chain) {
// Assert: we are on JDK 1.1 or we have no Context ClassLoader
// or any Context ClassLoader in chain of system classloader
// (including extension ClassLoader) so extend to widest
// ClassLoader (always look in system ClassLoader if Xerces
// is in boot/extension/system classpath and in current
// ClassLoader otherwise); normal classloaders delegate
// back to system ClassLoader first so this widening doesn't
// change the fact that context ClassLoader will be consulted
ClassLoader current = ObjectFactory.class.getClassLoader();
chain = system;
while (true) {
if (current == chain) {
// Assert: Current ClassLoader in chain of
// boot/extension/system ClassLoaders
return system;
}
if (chain == null) {
break;
}
chain = SecuritySupport.getParentClassLoader(chain);
}
// Assert: Current ClassLoader not in chain of
// boot/extension/system ClassLoaders
return current;
}
if (chain == null) {
// boot ClassLoader reached
break;
}
// Check for any extension ClassLoaders in chain up to
// boot ClassLoader
chain = SecuritySupport.getParentClassLoader(chain);
};
// Assert: Context ClassLoader not in chain of
// boot/extension/system ClassLoaders
return context;
} // findClassLoader():ClassLoader
/**
* Create an instance of a class using the specified ClassLoader
*/
static Object newInstance(String className, ClassLoader cl,
boolean doFallback)
throws ConfigurationError
{
// assert(className != null);
try{
Class providerClass = findProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (DEBUG) debugPrintln("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) {
throw new ConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Find a Class using the specified ClassLoader
*/
static Class findProviderClass(String className, ClassLoader cl,
boolean doFallback)
throws ClassNotFoundException, ConfigurationError
{
//throw security exception if the calling thread is not allowed to access the package
- //restrict the access to package as speicified in java.security policy
+ //restrict the access to package as specified in java.security policy
SecurityManager security = System.getSecurityManager();
if (security != null) {
final int lastDot = className.lastIndexOf('.');
String packageName = className;
if (lastDot != -1) packageName = className.substring(0, lastDot);
security.checkPackageAccess(packageName);
}
Class providerClass;
if (cl == null) {
// XXX Use the bootstrap ClassLoader. There is no way to
// load a class using the bootstrap ClassLoader that works
// in both JDK 1.1 and Java 2. However, this should still
// work b/c the following should be true:
//
// (cl == null) iff current ClassLoader == null
//
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else {
try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
ClassLoader current = ObjectFactory.class.getClassLoader();
if (current == null) {
providerClass = Class.forName(className);
} else if (cl != current) {
cl = current;
providerClass = cl.loadClass(className);
} else {
throw x;
}
} else {
throw x;
}
}
}
return providerClass;
}
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider(String factoryId)
throws ConfigurationError
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = findClassLoader();
is = SecuritySupport.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
ClassLoader current = ObjectFactory.class.getClassLoader();
if (cl != current) {
cl = current;
is = SecuritySupport.getResourceAsStream(cl, serviceId);
}
}
if (is == null) {
// No provider found
return null;
}
if (DEBUG) debugPrintln("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
}
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine();
} catch (IOException x) {
// No provider found
return null;
}
finally {
try {
// try to close the reader.
rd.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
if (DEBUG) debugPrintln("found in resource, value="
+ factoryClassName);
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance(factoryClassName, cl, false);
}
// No provider found
return null;
}
//
// Classes
//
/**
* A configuration error.
*/
static final class ConfigurationError
extends Error {
/** Serialization version. */
static final long serialVersionUID = 1914065341994951202L;
//
// Data
//
/** Exception. */
private Exception exception;
//
// Constructors
//
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
} // <init>(String,Exception)
//
// methods
//
/** Returns the exception associated to this error. */
Exception getException() {
return exception;
} // getException():Exception
} // class ConfigurationError
} // class ObjectFactory
diff --git a/src/org/apache/xerces/impl/dv/ObjectFactory.java b/src/org/apache/xerces/impl/dv/ObjectFactory.java
index f80cc2efe..07a6aed5c 100644
--- a/src/org/apache/xerces/impl/dv/ObjectFactory.java
+++ b/src/org/apache/xerces/impl/dv/ObjectFactory.java
@@ -1,545 +1,545 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.impl.dv;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
* <p>
* This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to run on JDK version 1.1 and
* later, and to compile on JDK 1.2 and onward.
* The code also runs both as part of an unbundled jar file and
* when bundled as part of the JDK.
* <p>
*
* @xerces.internal
*
* @version $Id$
*/
final class ObjectFactory {
//
// Constants
//
// name of default properties file to look for in JDK's jre/lib directory
private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";
/** Set to true for debugging */
private static final boolean DEBUG = isDebugEnabled();
/**
* Default columns per line.
*/
private static final int DEFAULT_LINE_LENGTH = 80;
/** cache the contents of the xerces.properties file.
* Until an attempt has been made to read this file, this will
* be null; if the file does not exist or we encounter some other error
* during the read, this will be empty.
*/
private static Properties fXercesProperties = null;
/***
* Cache the time stamp of the xerces.properties file so
* that we know if it's been modified and can invalidate
* the cache when necessary.
*/
private static long fLastModified = -1;
//
// static methods
//
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId, String fallbackClassName)
throws ConfigurationError {
return createObject(factoryId, null, fallbackClassName);
} // createObject(String,String):Object
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param propertiesFilename The filename in the $java.home/lib directory
* of the properties file. If none specified,
* ${java.home}/lib/xerces.properties will be used.
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId,
String propertiesFilename,
String fallbackClassName)
throws ConfigurationError
{
if (DEBUG) debugPrintln("debug is on");
ClassLoader cl = findClassLoader();
// Use the system property first
try {
String systemProp = SecuritySupport.getSystemProperty(factoryId);
if (systemProp != null && systemProp.length() > 0) {
if (DEBUG) debugPrintln("found system property, value=" + systemProp);
return newInstance(systemProp, cl, true);
}
} catch (SecurityException se) {
// Ignore and continue w/ next location
}
// Try to read from propertiesFilename, or $java.home/lib/xerces.properties
String factoryClassName = null;
// no properties file name specified; use $JAVA_HOME/lib/xerces.properties:
if (propertiesFilename == null) {
File propertiesFile = null;
boolean propertiesFileExists = false;
try {
String javah = SecuritySupport.getSystemProperty("java.home");
propertiesFilename = javah + File.separator +
"lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
propertiesFile = new File(propertiesFilename);
propertiesFileExists = SecuritySupport.getFileExists(propertiesFile);
} catch (SecurityException e) {
// try again...
fLastModified = -1;
fXercesProperties = null;
}
synchronized (ObjectFactory.class) {
boolean loadProperties = false;
FileInputStream fis = null;
try {
// file existed last time
if(fLastModified >= 0) {
if(propertiesFileExists &&
(fLastModified < (fLastModified = SecuritySupport.getLastModified(propertiesFile)))) {
loadProperties = true;
} else {
// file has stopped existing...
if(!propertiesFileExists) {
fLastModified = -1;
fXercesProperties = null;
} // else, file wasn't modified!
}
} else {
// file has started to exist:
if(propertiesFileExists) {
loadProperties = true;
fLastModified = SecuritySupport.getLastModified(propertiesFile);
} // else, nothing's changed
}
if(loadProperties) {
// must never have attempted to read xerces.properties before (or it's outdeated)
fXercesProperties = new Properties();
fis = SecuritySupport.getFileInputStream(propertiesFile);
fXercesProperties.load(fis);
}
} catch (Exception x) {
fXercesProperties = null;
fLastModified = -1;
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if(fXercesProperties != null) {
factoryClassName = fXercesProperties.getProperty(factoryId);
}
} else {
FileInputStream fis = null;
try {
fis = SecuritySupport.getFileInputStream(new File(propertiesFilename));
Properties props = new Properties();
props.load(fis);
factoryClassName = props.getProperty(factoryId);
} catch (Exception x) {
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if (factoryClassName != null) {
if (DEBUG) debugPrintln("found in " + propertiesFilename + ", value=" + factoryClassName);
return newInstance(factoryClassName, cl, true);
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
return newInstance(fallbackClassName, cl, true);
} // createObject(String,String,String):Object
//
// Private static methods
//
/** Returns true if debug has been enabled. */
private static boolean isDebugEnabled() {
try {
String val = SecuritySupport.getSystemProperty("xerces.debug");
// Allow simply setting the prop to turn on debug
return (val != null && (!"false".equals(val)));
}
catch (SecurityException se) {}
return false;
} // isDebugEnabled()
/** Prints a message to standard error if debugging is enabled. */
private static void debugPrintln(String msg) {
if (DEBUG) {
System.err.println("XERCES: " + msg);
}
} // debugPrintln(String)
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use
* the context ClassLoader.
*/
static ClassLoader findClassLoader()
throws ConfigurationError
{
// Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
ClassLoader context = SecuritySupport.getContextClassLoader();
ClassLoader system = SecuritySupport.getSystemClassLoader();
ClassLoader chain = system;
while (true) {
if (context == chain) {
// Assert: we are on JDK 1.1 or we have no Context ClassLoader
// or any Context ClassLoader in chain of system classloader
// (including extension ClassLoader) so extend to widest
// ClassLoader (always look in system ClassLoader if Xerces
// is in boot/extension/system classpath and in current
// ClassLoader otherwise); normal classloaders delegate
// back to system ClassLoader first so this widening doesn't
// change the fact that context ClassLoader will be consulted
ClassLoader current = ObjectFactory.class.getClassLoader();
chain = system;
while (true) {
if (current == chain) {
// Assert: Current ClassLoader in chain of
// boot/extension/system ClassLoaders
return system;
}
if (chain == null) {
break;
}
chain = SecuritySupport.getParentClassLoader(chain);
}
// Assert: Current ClassLoader not in chain of
// boot/extension/system ClassLoaders
return current;
}
if (chain == null) {
// boot ClassLoader reached
break;
}
// Check for any extension ClassLoaders in chain up to
// boot ClassLoader
chain = SecuritySupport.getParentClassLoader(chain);
};
// Assert: Context ClassLoader not in chain of
// boot/extension/system ClassLoaders
return context;
} // findClassLoader():ClassLoader
/**
* Create an instance of a class using the specified ClassLoader
*/
static Object newInstance(String className, ClassLoader cl,
boolean doFallback)
throws ConfigurationError
{
// assert(className != null);
try{
Class providerClass = findProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (DEBUG) debugPrintln("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) {
throw new ConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Find a Class using the specified ClassLoader
*/
static Class findProviderClass(String className, ClassLoader cl,
boolean doFallback)
throws ClassNotFoundException, ConfigurationError
{
//throw security exception if the calling thread is not allowed to access the package
- //restrict the access to package as speicified in java.security policy
+ //restrict the access to package as specified in java.security policy
SecurityManager security = System.getSecurityManager();
if (security != null) {
final int lastDot = className.lastIndexOf('.');
String packageName = className;
if (lastDot != -1) packageName = className.substring(0, lastDot);
security.checkPackageAccess(packageName);
}
Class providerClass;
if (cl == null) {
// XXX Use the bootstrap ClassLoader. There is no way to
// load a class using the bootstrap ClassLoader that works
// in both JDK 1.1 and Java 2. However, this should still
// work b/c the following should be true:
//
// (cl == null) iff current ClassLoader == null
//
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else {
try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
ClassLoader current = ObjectFactory.class.getClassLoader();
if (current == null) {
providerClass = Class.forName(className);
} else if (cl != current) {
cl = current;
providerClass = cl.loadClass(className);
} else {
throw x;
}
} else {
throw x;
}
}
}
return providerClass;
}
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider(String factoryId)
throws ConfigurationError
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = findClassLoader();
is = SecuritySupport.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
ClassLoader current = ObjectFactory.class.getClassLoader();
if (cl != current) {
cl = current;
is = SecuritySupport.getResourceAsStream(cl, serviceId);
}
}
if (is == null) {
// No provider found
return null;
}
if (DEBUG) debugPrintln("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
}
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine();
} catch (IOException x) {
// No provider found
return null;
}
finally {
try {
// try to close the reader.
rd.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
if (DEBUG) debugPrintln("found in resource, value="
+ factoryClassName);
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance(factoryClassName, cl, false);
}
// No provider found
return null;
}
//
// Classes
//
/**
* A configuration error.
*/
static final class ConfigurationError
extends Error {
/** Serialization version. */
static final long serialVersionUID = 8521878292694272124L;
//
// Data
//
/** Exception. */
private Exception exception;
//
// Constructors
//
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
} // <init>(String,Exception)
//
// methods
//
/** Returns the exception associated to this error. */
Exception getException() {
return exception;
} // getException():Exception
} // class ConfigurationError
} // class ObjectFactory
diff --git a/src/org/apache/xerces/parsers/ObjectFactory.java b/src/org/apache/xerces/parsers/ObjectFactory.java
index 50de22491..3dfd23519 100644
--- a/src/org/apache/xerces/parsers/ObjectFactory.java
+++ b/src/org/apache/xerces/parsers/ObjectFactory.java
@@ -1,543 +1,543 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
* <p>
* This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to run on JDK version 1.1 and
* later, and to compile on JDK 1.2 and onward.
* The code also runs both as part of an unbundled jar file and
* when bundled as part of the JDK.
* <p>
*
* @version $Id$
*/
final class ObjectFactory {
//
// Constants
//
// name of default properties file to look for in JDK's jre/lib directory
private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";
/** Set to true for debugging */
private static final boolean DEBUG = isDebugEnabled();
/**
* Default columns per line.
*/
private static final int DEFAULT_LINE_LENGTH = 80;
/** cache the contents of the xerces.properties file.
* Until an attempt has been made to read this file, this will
* be null; if the file does not exist or we encounter some other error
* during the read, this will be empty.
*/
private static Properties fXercesProperties = null;
/***
* Cache the time stamp of the xerces.properties file so
* that we know if it's been modified and can invalidate
* the cache when necessary.
*/
private static long fLastModified = -1;
//
// static methods
//
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId, String fallbackClassName)
throws ConfigurationError {
return createObject(factoryId, null, fallbackClassName);
} // createObject(String,String):Object
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param propertiesFilename The filename in the $java.home/lib directory
* of the properties file. If none specified,
* ${java.home}/lib/xerces.properties will be used.
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId,
String propertiesFilename,
String fallbackClassName)
throws ConfigurationError
{
if (DEBUG) debugPrintln("debug is on");
ClassLoader cl = findClassLoader();
// Use the system property first
try {
String systemProp = SecuritySupport.getSystemProperty(factoryId);
if (systemProp != null && systemProp.length() > 0) {
if (DEBUG) debugPrintln("found system property, value=" + systemProp);
return newInstance(systemProp, cl, true);
}
} catch (SecurityException se) {
// Ignore and continue w/ next location
}
// Try to read from propertiesFilename, or $java.home/lib/xerces.properties
String factoryClassName = null;
// no properties file name specified; use $JAVA_HOME/lib/xerces.properties:
if (propertiesFilename == null) {
File propertiesFile = null;
boolean propertiesFileExists = false;
try {
String javah = SecuritySupport.getSystemProperty("java.home");
propertiesFilename = javah + File.separator +
"lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
propertiesFile = new File(propertiesFilename);
propertiesFileExists = SecuritySupport.getFileExists(propertiesFile);
} catch (SecurityException e) {
// try again...
fLastModified = -1;
fXercesProperties = null;
}
synchronized (ObjectFactory.class) {
boolean loadProperties = false;
FileInputStream fis = null;
try {
// file existed last time
if(fLastModified >= 0) {
if(propertiesFileExists &&
(fLastModified < (fLastModified = SecuritySupport.getLastModified(propertiesFile)))) {
loadProperties = true;
} else {
// file has stopped existing...
if(!propertiesFileExists) {
fLastModified = -1;
fXercesProperties = null;
} // else, file wasn't modified!
}
} else {
// file has started to exist:
if(propertiesFileExists) {
loadProperties = true;
fLastModified = SecuritySupport.getLastModified(propertiesFile);
} // else, nothing's changed
}
if(loadProperties) {
// must never have attempted to read xerces.properties before (or it's outdeated)
fXercesProperties = new Properties();
fis = SecuritySupport.getFileInputStream(propertiesFile);
fXercesProperties.load(fis);
}
} catch (Exception x) {
fXercesProperties = null;
fLastModified = -1;
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if(fXercesProperties != null) {
factoryClassName = fXercesProperties.getProperty(factoryId);
}
} else {
FileInputStream fis = null;
try {
fis = SecuritySupport.getFileInputStream(new File(propertiesFilename));
Properties props = new Properties();
props.load(fis);
factoryClassName = props.getProperty(factoryId);
} catch (Exception x) {
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if (factoryClassName != null) {
if (DEBUG) debugPrintln("found in " + propertiesFilename + ", value=" + factoryClassName);
return newInstance(factoryClassName, cl, true);
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
return newInstance(fallbackClassName, cl, true);
} // createObject(String,String,String):Object
//
// Private static methods
//
/** Returns true if debug has been enabled. */
private static boolean isDebugEnabled() {
try {
String val = SecuritySupport.getSystemProperty("xerces.debug");
// Allow simply setting the prop to turn on debug
return (val != null && (!"false".equals(val)));
}
catch (SecurityException se) {}
return false;
} // isDebugEnabled()
/** Prints a message to standard error if debugging is enabled. */
private static void debugPrintln(String msg) {
if (DEBUG) {
System.err.println("XERCES: " + msg);
}
} // debugPrintln(String)
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use
* the context ClassLoader.
*/
static ClassLoader findClassLoader()
throws ConfigurationError
{
// Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
ClassLoader context = SecuritySupport.getContextClassLoader();
ClassLoader system = SecuritySupport.getSystemClassLoader();
ClassLoader chain = system;
while (true) {
if (context == chain) {
// Assert: we are on JDK 1.1 or we have no Context ClassLoader
// or any Context ClassLoader in chain of system classloader
// (including extension ClassLoader) so extend to widest
// ClassLoader (always look in system ClassLoader if Xerces
// is in boot/extension/system classpath and in current
// ClassLoader otherwise); normal classloaders delegate
// back to system ClassLoader first so this widening doesn't
// change the fact that context ClassLoader will be consulted
ClassLoader current = ObjectFactory.class.getClassLoader();
chain = system;
while (true) {
if (current == chain) {
// Assert: Current ClassLoader in chain of
// boot/extension/system ClassLoaders
return system;
}
if (chain == null) {
break;
}
chain = SecuritySupport.getParentClassLoader(chain);
}
// Assert: Current ClassLoader not in chain of
// boot/extension/system ClassLoaders
return current;
}
if (chain == null) {
// boot ClassLoader reached
break;
}
// Check for any extension ClassLoaders in chain up to
// boot ClassLoader
chain = SecuritySupport.getParentClassLoader(chain);
};
// Assert: Context ClassLoader not in chain of
// boot/extension/system ClassLoaders
return context;
} // findClassLoader():ClassLoader
/**
* Create an instance of a class using the specified ClassLoader
*/
static Object newInstance(String className, ClassLoader cl,
boolean doFallback)
throws ConfigurationError
{
// assert(className != null);
try{
Class providerClass = findProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (DEBUG) debugPrintln("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) {
throw new ConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Find a Class using the specified ClassLoader
*/
static Class findProviderClass(String className, ClassLoader cl,
boolean doFallback)
throws ClassNotFoundException, ConfigurationError
{
//throw security exception if the calling thread is not allowed to access the package
- //restrict the access to package as speicified in java.security policy
+ //restrict the access to package as specified in java.security policy
SecurityManager security = System.getSecurityManager();
if (security != null) {
final int lastDot = className.lastIndexOf('.');
String packageName = className;
if (lastDot != -1) packageName = className.substring(0, lastDot);
security.checkPackageAccess(packageName);
}
Class providerClass;
if (cl == null) {
// XXX Use the bootstrap ClassLoader. There is no way to
// load a class using the bootstrap ClassLoader that works
// in both JDK 1.1 and Java 2. However, this should still
// work b/c the following should be true:
//
// (cl == null) iff current ClassLoader == null
//
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else {
try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
ClassLoader current = ObjectFactory.class.getClassLoader();
if (current == null) {
providerClass = Class.forName(className);
} else if (cl != current) {
cl = current;
providerClass = cl.loadClass(className);
} else {
throw x;
}
} else {
throw x;
}
}
}
return providerClass;
}
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider(String factoryId)
throws ConfigurationError
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = findClassLoader();
is = SecuritySupport.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
ClassLoader current = ObjectFactory.class.getClassLoader();
if (cl != current) {
cl = current;
is = SecuritySupport.getResourceAsStream(cl, serviceId);
}
}
if (is == null) {
// No provider found
return null;
}
if (DEBUG) debugPrintln("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
}
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine();
} catch (IOException x) {
// No provider found
return null;
}
finally {
try {
// try to close the reader.
rd.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
if (DEBUG) debugPrintln("found in resource, value="
+ factoryClassName);
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance(factoryClassName, cl, false);
}
// No provider found
return null;
}
//
// Classes
//
/**
* A configuration error.
*/
static final class ConfigurationError
extends Error {
/** Serialization version. */
static final long serialVersionUID = -7285495612271660427L;
//
// Data
//
/** Exception. */
private Exception exception;
//
// Constructors
//
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
} // <init>(String,Exception)
//
// methods
//
/** Returns the exception associated to this error. */
Exception getException() {
return exception;
} // getException():Exception
} // class ConfigurationError
} // class ObjectFactory
diff --git a/src/org/apache/xerces/xinclude/ObjectFactory.java b/src/org/apache/xerces/xinclude/ObjectFactory.java
index 469ec8e19..2c82e1d31 100644
--- a/src/org/apache/xerces/xinclude/ObjectFactory.java
+++ b/src/org/apache/xerces/xinclude/ObjectFactory.java
@@ -1,543 +1,543 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.xinclude;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
* <p>
* This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to run on JDK version 1.1 and
* later, and to compile on JDK 1.2 and onward.
* The code also runs both as part of an unbundled jar file and
* when bundled as part of the JDK.
* <p>
*
* @version $Id$
*/
final class ObjectFactory {
//
// Constants
//
// name of default properties file to look for in JDK's jre/lib directory
private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";
/** Set to true for debugging */
private static final boolean DEBUG = isDebugEnabled();
/**
* Default columns per line.
*/
private static final int DEFAULT_LINE_LENGTH = 80;
/** cache the contents of the xerces.properties file.
* Until an attempt has been made to read this file, this will
* be null; if the file does not exist or we encounter some other error
* during the read, this will be empty.
*/
private static Properties fXercesProperties = null;
/***
* Cache the time stamp of the xerces.properties file so
* that we know if it's been modified and can invalidate
* the cache when necessary.
*/
private static long fLastModified = -1;
//
// static methods
//
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId, String fallbackClassName)
throws ConfigurationError {
return createObject(factoryId, null, fallbackClassName);
} // createObject(String,String):Object
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param propertiesFilename The filename in the $java.home/lib directory
* of the properties file. If none specified,
* ${java.home}/lib/xerces.properties will be used.
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId,
String propertiesFilename,
String fallbackClassName)
throws ConfigurationError
{
if (DEBUG) debugPrintln("debug is on");
ClassLoader cl = findClassLoader();
// Use the system property first
try {
String systemProp = SecuritySupport.getSystemProperty(factoryId);
if (systemProp != null && systemProp.length() > 0) {
if (DEBUG) debugPrintln("found system property, value=" + systemProp);
return newInstance(systemProp, cl, true);
}
} catch (SecurityException se) {
// Ignore and continue w/ next location
}
// Try to read from propertiesFilename, or $java.home/lib/xerces.properties
String factoryClassName = null;
// no properties file name specified; use $JAVA_HOME/lib/xerces.properties:
if (propertiesFilename == null) {
File propertiesFile = null;
boolean propertiesFileExists = false;
try {
String javah = SecuritySupport.getSystemProperty("java.home");
propertiesFilename = javah + File.separator +
"lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
propertiesFile = new File(propertiesFilename);
propertiesFileExists = SecuritySupport.getFileExists(propertiesFile);
} catch (SecurityException e) {
// try again...
fLastModified = -1;
fXercesProperties = null;
}
synchronized (ObjectFactory.class) {
boolean loadProperties = false;
FileInputStream fis = null;
try {
// file existed last time
if(fLastModified >= 0) {
if(propertiesFileExists &&
(fLastModified < (fLastModified = SecuritySupport.getLastModified(propertiesFile)))) {
loadProperties = true;
} else {
// file has stopped existing...
if(!propertiesFileExists) {
fLastModified = -1;
fXercesProperties = null;
} // else, file wasn't modified!
}
} else {
// file has started to exist:
if(propertiesFileExists) {
loadProperties = true;
fLastModified = SecuritySupport.getLastModified(propertiesFile);
} // else, nothing's changed
}
if(loadProperties) {
// must never have attempted to read xerces.properties before (or it's outdeated)
fXercesProperties = new Properties();
fis = SecuritySupport.getFileInputStream(propertiesFile);
fXercesProperties.load(fis);
}
} catch (Exception x) {
fXercesProperties = null;
fLastModified = -1;
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if(fXercesProperties != null) {
factoryClassName = fXercesProperties.getProperty(factoryId);
}
} else {
FileInputStream fis = null;
try {
fis = SecuritySupport.getFileInputStream(new File(propertiesFilename));
Properties props = new Properties();
props.load(fis);
factoryClassName = props.getProperty(factoryId);
} catch (Exception x) {
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if (factoryClassName != null) {
if (DEBUG) debugPrintln("found in " + propertiesFilename + ", value=" + factoryClassName);
return newInstance(factoryClassName, cl, true);
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
return newInstance(fallbackClassName, cl, true);
} // createObject(String,String,String):Object
//
// Private static methods
//
/** Returns true if debug has been enabled. */
private static boolean isDebugEnabled() {
try {
String val = SecuritySupport.getSystemProperty("xerces.debug");
// Allow simply setting the prop to turn on debug
return (val != null && (!"false".equals(val)));
}
catch (SecurityException se) {}
return false;
} // isDebugEnabled()
/** Prints a message to standard error if debugging is enabled. */
private static void debugPrintln(String msg) {
if (DEBUG) {
System.err.println("XERCES: " + msg);
}
} // debugPrintln(String)
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use
* the context ClassLoader.
*/
static ClassLoader findClassLoader()
throws ConfigurationError
{
// Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
ClassLoader context = SecuritySupport.getContextClassLoader();
ClassLoader system = SecuritySupport.getSystemClassLoader();
ClassLoader chain = system;
while (true) {
if (context == chain) {
// Assert: we are on JDK 1.1 or we have no Context ClassLoader
// or any Context ClassLoader in chain of system classloader
// (including extension ClassLoader) so extend to widest
// ClassLoader (always look in system ClassLoader if Xerces
// is in boot/extension/system classpath and in current
// ClassLoader otherwise); normal classloaders delegate
// back to system ClassLoader first so this widening doesn't
// change the fact that context ClassLoader will be consulted
ClassLoader current = ObjectFactory.class.getClassLoader();
chain = system;
while (true) {
if (current == chain) {
// Assert: Current ClassLoader in chain of
// boot/extension/system ClassLoaders
return system;
}
if (chain == null) {
break;
}
chain = SecuritySupport.getParentClassLoader(chain);
}
// Assert: Current ClassLoader not in chain of
// boot/extension/system ClassLoaders
return current;
}
if (chain == null) {
// boot ClassLoader reached
break;
}
// Check for any extension ClassLoaders in chain up to
// boot ClassLoader
chain = SecuritySupport.getParentClassLoader(chain);
};
// Assert: Context ClassLoader not in chain of
// boot/extension/system ClassLoaders
return context;
} // findClassLoader():ClassLoader
/**
* Create an instance of a class using the specified ClassLoader
*/
static Object newInstance(String className, ClassLoader cl,
boolean doFallback)
throws ConfigurationError
{
// assert(className != null);
try{
Class providerClass = findProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (DEBUG) debugPrintln("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) {
throw new ConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Find a Class using the specified ClassLoader
*/
static Class findProviderClass(String className, ClassLoader cl,
boolean doFallback)
throws ClassNotFoundException, ConfigurationError
{
//throw security exception if the calling thread is not allowed to access the package
- //restrict the access to package as speicified in java.security policy
+ //restrict the access to package as specified in java.security policy
SecurityManager security = System.getSecurityManager();
if (security != null) {
final int lastDot = className.lastIndexOf('.');
String packageName = className;
if (lastDot != -1) packageName = className.substring(0, lastDot);
security.checkPackageAccess(packageName);
}
Class providerClass;
if (cl == null) {
// XXX Use the bootstrap ClassLoader. There is no way to
// load a class using the bootstrap ClassLoader that works
// in both JDK 1.1 and Java 2. However, this should still
// work b/c the following should be true:
//
// (cl == null) iff current ClassLoader == null
//
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else {
try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
ClassLoader current = ObjectFactory.class.getClassLoader();
if (current == null) {
providerClass = Class.forName(className);
} else if (cl != current) {
cl = current;
providerClass = cl.loadClass(className);
} else {
throw x;
}
} else {
throw x;
}
}
}
return providerClass;
}
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider(String factoryId)
throws ConfigurationError
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = findClassLoader();
is = SecuritySupport.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
ClassLoader current = ObjectFactory.class.getClassLoader();
if (cl != current) {
cl = current;
is = SecuritySupport.getResourceAsStream(cl, serviceId);
}
}
if (is == null) {
// No provider found
return null;
}
if (DEBUG) debugPrintln("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
}
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine();
} catch (IOException x) {
// No provider found
return null;
}
finally {
try {
// try to close the reader.
rd.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
if (DEBUG) debugPrintln("found in resource, value="
+ factoryClassName);
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance(factoryClassName, cl, false);
}
// No provider found
return null;
}
//
// Classes
//
/**
* A configuration error.
*/
static final class ConfigurationError
extends Error {
/** Serialization version. */
static final long serialVersionUID = 5061904944269807898L;
//
// Data
//
/** Exception. */
private Exception exception;
//
// Constructors
//
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
} // <init>(String,Exception)
//
// methods
//
/** Returns the exception associated to this error. */
Exception getException() {
return exception;
} // getException():Exception
} // class ConfigurationError
} // class ObjectFactory
diff --git a/src/org/apache/xml/serialize/ObjectFactory.java b/src/org/apache/xml/serialize/ObjectFactory.java
index 8441501e0..1373231b0 100644
--- a/src/org/apache/xml/serialize/ObjectFactory.java
+++ b/src/org/apache/xml/serialize/ObjectFactory.java
@@ -1,543 +1,543 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xml.serialize;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
* <p>
* This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to run on JDK version 1.1 and
* later, and to compile on JDK 1.2 and onward.
* The code also runs both as part of an unbundled jar file and
* when bundled as part of the JDK.
* <p>
*
* @version $Id$
*/
final class ObjectFactory {
//
// Constants
//
// name of default properties file to look for in JDK's jre/lib directory
private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";
/** Set to true for debugging */
private static final boolean DEBUG = isDebugEnabled();
/**
* Default columns per line.
*/
private static final int DEFAULT_LINE_LENGTH = 80;
/** cache the contents of the xerces.properties file.
* Until an attempt has been made to read this file, this will
* be null; if the file does not exist or we encounter some other error
* during the read, this will be empty.
*/
private static Properties fXercesProperties = null;
/***
* Cache the time stamp of the xerces.properties file so
* that we know if it's been modified and can invalidate
* the cache when necessary.
*/
private static long fLastModified = -1;
//
// static methods
//
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId, String fallbackClassName)
throws ConfigurationError {
return createObject(factoryId, null, fallbackClassName);
} // createObject(String,String):Object
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param propertiesFilename The filename in the $java.home/lib directory
* of the properties file. If none specified,
* ${java.home}/lib/xerces.properties will be used.
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId,
String propertiesFilename,
String fallbackClassName)
throws ConfigurationError
{
if (DEBUG) debugPrintln("debug is on");
ClassLoader cl = findClassLoader();
// Use the system property first
try {
String systemProp = SecuritySupport.getSystemProperty(factoryId);
if (systemProp != null && systemProp.length() > 0) {
if (DEBUG) debugPrintln("found system property, value=" + systemProp);
return newInstance(systemProp, cl, true);
}
} catch (SecurityException se) {
// Ignore and continue w/ next location
}
// Try to read from propertiesFilename, or $java.home/lib/xerces.properties
String factoryClassName = null;
// no properties file name specified; use $JAVA_HOME/lib/xerces.properties:
if (propertiesFilename == null) {
File propertiesFile = null;
boolean propertiesFileExists = false;
try {
String javah = SecuritySupport.getSystemProperty("java.home");
propertiesFilename = javah + File.separator +
"lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
propertiesFile = new File(propertiesFilename);
propertiesFileExists = SecuritySupport.getFileExists(propertiesFile);
} catch (SecurityException e) {
// try again...
fLastModified = -1;
fXercesProperties = null;
}
synchronized (ObjectFactory.class) {
boolean loadProperties = false;
FileInputStream fis = null;
try {
// file existed last time
if(fLastModified >= 0) {
if(propertiesFileExists &&
(fLastModified < (fLastModified = SecuritySupport.getLastModified(propertiesFile)))) {
loadProperties = true;
} else {
// file has stopped existing...
if(!propertiesFileExists) {
fLastModified = -1;
fXercesProperties = null;
} // else, file wasn't modified!
}
} else {
// file has started to exist:
if(propertiesFileExists) {
loadProperties = true;
fLastModified = SecuritySupport.getLastModified(propertiesFile);
} // else, nothing's changed
}
if(loadProperties) {
// must never have attempted to read xerces.properties before (or it's outdeated)
fXercesProperties = new Properties();
fis = SecuritySupport.getFileInputStream(propertiesFile);
fXercesProperties.load(fis);
}
} catch (Exception x) {
fXercesProperties = null;
fLastModified = -1;
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if(fXercesProperties != null) {
factoryClassName = fXercesProperties.getProperty(factoryId);
}
} else {
FileInputStream fis = null;
try {
fis = SecuritySupport.getFileInputStream(new File(propertiesFilename));
Properties props = new Properties();
props.load(fis);
factoryClassName = props.getProperty(factoryId);
} catch (Exception x) {
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
finally {
// try to close the input stream if one was opened.
if (fis != null) {
try {
fis.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
}
}
if (factoryClassName != null) {
if (DEBUG) debugPrintln("found in " + propertiesFilename + ", value=" + factoryClassName);
return newInstance(factoryClassName, cl, true);
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
return newInstance(fallbackClassName, cl, true);
} // createObject(String,String,String):Object
//
// Private static methods
//
/** Returns true if debug has been enabled. */
private static boolean isDebugEnabled() {
try {
String val = SecuritySupport.getSystemProperty("xerces.debug");
// Allow simply setting the prop to turn on debug
return (val != null && (!"false".equals(val)));
}
catch (SecurityException se) {}
return false;
} // isDebugEnabled()
/** Prints a message to standard error if debugging is enabled. */
private static void debugPrintln(String msg) {
if (DEBUG) {
System.err.println("XERCES: " + msg);
}
} // debugPrintln(String)
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use
* the context ClassLoader.
*/
static ClassLoader findClassLoader()
throws ConfigurationError
{
// Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
ClassLoader context = SecuritySupport.getContextClassLoader();
ClassLoader system = SecuritySupport.getSystemClassLoader();
ClassLoader chain = system;
while (true) {
if (context == chain) {
// Assert: we are on JDK 1.1 or we have no Context ClassLoader
// or any Context ClassLoader in chain of system classloader
// (including extension ClassLoader) so extend to widest
// ClassLoader (always look in system ClassLoader if Xerces
// is in boot/extension/system classpath and in current
// ClassLoader otherwise); normal classloaders delegate
// back to system ClassLoader first so this widening doesn't
// change the fact that context ClassLoader will be consulted
ClassLoader current = ObjectFactory.class.getClassLoader();
chain = system;
while (true) {
if (current == chain) {
// Assert: Current ClassLoader in chain of
// boot/extension/system ClassLoaders
return system;
}
if (chain == null) {
break;
}
chain = SecuritySupport.getParentClassLoader(chain);
}
// Assert: Current ClassLoader not in chain of
// boot/extension/system ClassLoaders
return current;
}
if (chain == null) {
// boot ClassLoader reached
break;
}
// Check for any extension ClassLoaders in chain up to
// boot ClassLoader
chain = SecuritySupport.getParentClassLoader(chain);
};
// Assert: Context ClassLoader not in chain of
// boot/extension/system ClassLoaders
return context;
} // findClassLoader():ClassLoader
/**
* Create an instance of a class using the specified ClassLoader
*/
static Object newInstance(String className, ClassLoader cl,
boolean doFallback)
throws ConfigurationError
{
// assert(className != null);
try{
Class providerClass = findProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (DEBUG) debugPrintln("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) {
throw new ConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Find a Class using the specified ClassLoader
*/
static Class findProviderClass(String className, ClassLoader cl,
boolean doFallback)
throws ClassNotFoundException, ConfigurationError
{
//throw security exception if the calling thread is not allowed to access the package
- //restrict the access to package as speicified in java.security policy
+ //restrict the access to package as specified in java.security policy
SecurityManager security = System.getSecurityManager();
if (security != null) {
final int lastDot = className.lastIndexOf('.');
String packageName = className;
if (lastDot != -1) packageName = className.substring(0, lastDot);
security.checkPackageAccess(packageName);
}
Class providerClass;
if (cl == null) {
// XXX Use the bootstrap ClassLoader. There is no way to
// load a class using the bootstrap ClassLoader that works
// in both JDK 1.1 and Java 2. However, this should still
// work b/c the following should be true:
//
// (cl == null) iff current ClassLoader == null
//
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else {
try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
ClassLoader current = ObjectFactory.class.getClassLoader();
if (current == null) {
providerClass = Class.forName(className);
} else if (cl != current) {
cl = current;
providerClass = cl.loadClass(className);
} else {
throw x;
}
} else {
throw x;
}
}
}
return providerClass;
}
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider(String factoryId)
throws ConfigurationError
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = findClassLoader();
is = SecuritySupport.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
ClassLoader current = ObjectFactory.class.getClassLoader();
if (cl != current) {
cl = current;
is = SecuritySupport.getResourceAsStream(cl, serviceId);
}
}
if (is == null) {
// No provider found
return null;
}
if (DEBUG) debugPrintln("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
}
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine();
} catch (IOException x) {
// No provider found
return null;
}
finally {
try {
// try to close the reader.
rd.close();
}
// Ignore the exception.
catch (IOException exc) {}
}
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
if (DEBUG) debugPrintln("found in resource, value="
+ factoryClassName);
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance(factoryClassName, cl, false);
}
// No provider found
return null;
}
//
// Classes
//
/**
* A configuration error.
*/
static final class ConfigurationError
extends Error {
/** Serialization version. */
static final long serialVersionUID = 937647395548533254L;
//
// Data
//
/** Exception. */
private Exception exception;
//
// Constructors
//
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
} // <init>(String,Exception)
//
// methods
//
/** Returns the exception associated to this error. */
Exception getException() {
return exception;
} // getException():Exception
} // class ConfigurationError
} // class ObjectFactory
| false | false | null | null |
diff --git a/java/com/adaptionsoft/games/trivia/runner/GameRunnerTest.java b/java/com/adaptionsoft/games/trivia/runner/GameRunnerTest.java
index 11c3a89..6b9ca60 100644
--- a/java/com/adaptionsoft/games/trivia/runner/GameRunnerTest.java
+++ b/java/com/adaptionsoft/games/trivia/runner/GameRunnerTest.java
@@ -1,56 +1,56 @@
package com.adaptionsoft.games.trivia.runner;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Random;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import org.junit.Before;
import org.junit.Test;
import com.adaptionsoft.games.uglytrivia.Game;
public class GameRunnerTest {
Checker checker;
Random rand;
Game game;
class Checker extends OutputStream {
Checksum checksum = new CRC32();
public void write(int b) throws IOException {
checksum.update(b);
}
}
@Before
public void setUp() {
checker = new Checker();
System.setOut(new PrintStream(checker));
rand = new Random(0L);
game = new Game();
game.add("Chet");
game.add("Pat");
game.add("Sue");
}
@Test
public void testMain() {
GameRunner.run(game, rand);
- assertEquals(1763398543L, checker.checksum.getValue());
+ assertEquals(590124755L, checker.checksum.getValue());
GameRunner.run(game, rand);
- assertEquals(2961284199L, checker.checksum.getValue());
+ assertEquals(220049483L, checker.checksum.getValue());
GameRunner.run(game, rand);
- assertEquals(3062906570L, checker.checksum.getValue());
+ assertEquals(2318374383L, checker.checksum.getValue());
}
}
diff --git a/java/com/adaptionsoft/games/uglytrivia/Game.java b/java/com/adaptionsoft/games/uglytrivia/Game.java
index 9ce4623..cf27efb 100644
--- a/java/com/adaptionsoft/games/uglytrivia/Game.java
+++ b/java/com/adaptionsoft/games/uglytrivia/Game.java
@@ -1,174 +1,174 @@
package com.adaptionsoft.games.uglytrivia;
import java.util.ArrayList;
import java.util.LinkedList;
public class Game {
ArrayList players = new ArrayList();
int[] places = new int[6];
int[] purses = new int[6];
boolean[] inPenaltyBox = new boolean[6];
int[] highscores= new int[6];
LinkedList popQuestions = new LinkedList();
LinkedList scienceQuestions = new LinkedList();
LinkedList sportsQuestions = new LinkedList();
LinkedList rockQuestions = new LinkedList();
int currentPlayer = 0;
boolean isGettingOutOfPenaltyBox;
public Game(){
for (int i = 0; i < 50; i++) {
popQuestions.addLast("Pop Question " + i);
scienceQuestions.addLast(("Science Question " + i));
sportsQuestions.addLast(("Sports Question " + i));
rockQuestions.addLast(createRockQuestion(i));
}
}
public String createRockQuestion(int index){
return "Rock Question " + index;
}
public boolean add(String playerName) {
players.add(playerName);
places[howManyPlayers()] = 0;
purses[howManyPlayers()] = 0;
inPenaltyBox[howManyPlayers()] = false;
System.out.println(playerName + " was added");
System.out.println("They are player number " + players.size());
return true;
}
public boolean remove(String playerName) {
players.remove(howManyPlayers());
return true;
}
public int howManyPlayers() {
return players.size();
}
public void roll(int roll) {
System.out.println(players.get(currentPlayer) + " is the current player");
System.out.println("They have rolled a " + roll);
if (inPenaltyBox[currentPlayer]) {
if (roll % 2 != 0) {
isGettingOutOfPenaltyBox = true;
System.out.println(players.get(currentPlayer) + " is getting out of the penalty box");
places[currentPlayer] = places[currentPlayer] + roll;
if (places[currentPlayer] > 11) places[currentPlayer] = places[currentPlayer] - 12;
System.out.println(players.get(currentPlayer)
+ "'s new location is "
+ places[currentPlayer]);
System.out.println("The category is " + currentCategory());
askQuestion();
} else {
System.out.println(players.get(currentPlayer) + " is not getting out of the penalty box");
isGettingOutOfPenaltyBox = false;
}
} else {
places[currentPlayer] = places[currentPlayer] + roll;
if (places[currentPlayer] > 11) places[currentPlayer] = places[currentPlayer] - 12;
System.out.println(players.get(currentPlayer)
+ "'s new location is "
+ places[currentPlayer]);
System.out.println("The category is " + currentCategory());
askQuestion();
}
}
private void askQuestion() {
if (currentCategory() == "Pop")
System.out.println(popQuestions.removeFirst());
if (currentCategory() == "Science")
System.out.println(scienceQuestions.removeFirst());
if (currentCategory() == "Sports")
System.out.println(sportsQuestions.removeFirst());
if (currentCategory() == "Rock")
System.out.println(rockQuestions.removeFirst());
}
// randomly return a category
private String currentCategory() {
if (places[currentPlayer] == 0) return "Pop";
if (places[currentPlayer] == 4) return "Pop";
if (places[currentPlayer] == 8) return "Pop";
if (places[currentPlayer] == 1) return "Science";
if (places[currentPlayer] == 5) return "Science";
if (places[currentPlayer] == 9) return "Science";
if (places[currentPlayer] == 2) return "Sports";
if (places[currentPlayer] == 6) return "Sports";
if (places[currentPlayer] == 10) return "Sports";
return "Rock";
}
public boolean wasCorrectlyAnswered() {
if (inPenaltyBox[currentPlayer]){
if (isGettingOutOfPenaltyBox) {
System.out.println("Answer was correct!!!!");
purses[currentPlayer]++;
System.out.println(players.get(currentPlayer)
+ " now has "
+ purses[currentPlayer]
+ " Gold Coins.");
boolean winner = didPlayerWin();
nextPlayer();
return winner;
} else {
nextPlayer();
return true;
}
} else {
- System.out.println("Answer was corrent!!!!");
+ System.out.println("Answer was correct!!!!");
purses[currentPlayer]++;
System.out.println(players.get(currentPlayer)
+ " now has "
+ purses[currentPlayer]
+ " Gold Coins.");
boolean winner = didPlayerWin();
nextPlayer();
return winner;
}
}
private void nextPlayer() {
currentPlayer++;
if (currentPlayer == players.size()) currentPlayer = 0;
}
public boolean wrongAnswer(){
System.out.println("Question was incorrectly answered");
System.out.println(players.get(currentPlayer)+ " was sent to the penalty box");
inPenaltyBox[currentPlayer] = true;
nextPlayer();
return true;
}
/**
* Tells if the last player won.
*/
private boolean didPlayerWin() {
return !(purses[currentPlayer] == 6);
}
}
| false | false | null | null |
diff --git a/ext/java/base32/Base32Encoder.java b/ext/java/base32/Base32Encoder.java
index 159afd1..e94d7e5 100644
--- a/ext/java/base32/Base32Encoder.java
+++ b/ext/java/base32/Base32Encoder.java
@@ -1,90 +1,89 @@
/*
Copyright (c) 2011 The Skunkworx
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 base32;
/**
* Static class to perform base32 encoding
*
* @author Chris Umbel
*/
public class Base32Encoder {
private static final String charTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
public static int getDigit(byte[] buff, int i) {
return buff[i] >= 0 ? buff[i] : buff[i] + 256;
}
public static String encode(String plainText) {
return encode(plainText.getBytes());
}
public static int quintetCount(byte[] buff) {
int quintets = buff.length / 5;
return buff.length % 5 == 0 ? quintets: quintets + 1;
}
public static String encode(byte[] buff) {
int next;
int current;
int iBase = 0;
int digit = 0;
int i = 0;
int outputLength = quintetCount(buff) * 8;
StringBuilder builder = new StringBuilder(outputLength);
while(i < buff.length) {
current = getDigit(buff, i);
if(iBase > 3) {
if((i + 1) < buff.length)
next = getDigit(buff, i + 1);
else
next = 0;
digit = current & (0xff >> iBase);
iBase = (iBase + 5) % 8;
digit <<= iBase;
digit |= next >> (8 - iBase);
i++;
} else {
digit = (current >> (8 - (iBase + 5))) & 0x1f;
iBase = (iBase + 5) % 8;
if(iBase == 0)
i++;
}
builder.append(charTable.charAt(digit));
}
int padding = builder.capacity() - builder.length();
- for(i = 0; i < padding; i++) {
+ for(i = 0; i < padding; i++)
builder.append("=");
- }
return builder.toString();
}
}
| false | true | public static String encode(byte[] buff) {
int next;
int current;
int iBase = 0;
int digit = 0;
int i = 0;
int outputLength = quintetCount(buff) * 8;
StringBuilder builder = new StringBuilder(outputLength);
while(i < buff.length) {
current = getDigit(buff, i);
if(iBase > 3) {
if((i + 1) < buff.length)
next = getDigit(buff, i + 1);
else
next = 0;
digit = current & (0xff >> iBase);
iBase = (iBase + 5) % 8;
digit <<= iBase;
digit |= next >> (8 - iBase);
i++;
} else {
digit = (current >> (8 - (iBase + 5))) & 0x1f;
iBase = (iBase + 5) % 8;
if(iBase == 0)
i++;
}
builder.append(charTable.charAt(digit));
}
int padding = builder.capacity() - builder.length();
for(i = 0; i < padding; i++) {
builder.append("=");
}
return builder.toString();
}
| public static String encode(byte[] buff) {
int next;
int current;
int iBase = 0;
int digit = 0;
int i = 0;
int outputLength = quintetCount(buff) * 8;
StringBuilder builder = new StringBuilder(outputLength);
while(i < buff.length) {
current = getDigit(buff, i);
if(iBase > 3) {
if((i + 1) < buff.length)
next = getDigit(buff, i + 1);
else
next = 0;
digit = current & (0xff >> iBase);
iBase = (iBase + 5) % 8;
digit <<= iBase;
digit |= next >> (8 - iBase);
i++;
} else {
digit = (current >> (8 - (iBase + 5))) & 0x1f;
iBase = (iBase + 5) % 8;
if(iBase == 0)
i++;
}
builder.append(charTable.charAt(digit));
}
int padding = builder.capacity() - builder.length();
for(i = 0; i < padding; i++)
builder.append("=");
return builder.toString();
}
|
diff --git a/src/example/BrainFuck/Main.java b/src/example/BrainFuck/Main.java
index f6ddfd5..e4c1803 100644
--- a/src/example/BrainFuck/Main.java
+++ b/src/example/BrainFuck/Main.java
@@ -1,43 +1,43 @@
package example.BrainFuck;
import java.io.IOException;
import firm.Backend;
import firm.Firm;
/* Test libFirm bindings */
public class Main {
public static void main(String[] args) throws IOException {
Firm.init();
Firm.finish();
Firm.init();
System.out.printf("Initialized Firm Version: %1s.%2s\n",
- Firm.getMinorVersion(), Firm.getMajorVersion());
+ Firm.getMajorVersion(), Firm.getMinorVersion());
/* what is our input file? */
String input = "bf_examples/bockbeer.bf";
if (args.length > 0) {
input = args[0];
}
/* transform brainfuck program to firm graphs */
BrainFuck fuck = new BrainFuck();
fuck.compile(input);
/* dump all firm graphs to disk */
/*
* for(Graph g : Program.getGraphs()) { Dump.dumpBlockGraph(g,
* "-finished"); }
*/
/* transform to x86 assembler */
Backend.createAssembler("test.s", "<builtin>");
/* assembler */
Runtime.getRuntime().exec("gcc test.s -o a.out");
Firm.finish();
Firm.init();
Firm.finish();
}
}
diff --git a/src/example/SimpleIf.java b/src/example/SimpleIf.java
index cf0242d..3398433 100644
--- a/src/example/SimpleIf.java
+++ b/src/example/SimpleIf.java
@@ -1,146 +1,146 @@
package example;
import firm.ClassType;
import firm.Construction;
import firm.Dump;
import firm.Entity;
import firm.Firm;
import firm.Graph;
import firm.MethodType;
import firm.Mode;
import firm.PointerType;
import firm.PrimitiveType;
import firm.Program;
import firm.Relation;
import firm.Type;
import firm.nodes.Block;
import firm.nodes.Cond;
import firm.nodes.Node;
/**
* Simple example. Creating a firm equivalent to:
*
* public class A { public int calc(int x, int y) { int sum;
*
* if (x > y) { sum = x + y; } else { sum = x * y; }
*
* return sum; } }
*/
public class SimpleIf {
public static void main(String[] main_args) {
final int varNumThis = 0;
final int varNumX = 1;
final int varNumY = 2;
final int varNumSum = 3;
final int numLocalVars = 3 + 1; /* 3 parameters + 1 local variable */
// Initialize firm
Firm.init();
- System.out.printf("Firm Version: %1s.%2s\n", Firm.getMinorVersion(),
- Firm.getMajorVersion());
+ System.out.printf("Firm Version: %1s.%2s\n",
+ Firm.getMajorVersion(), Firm.getMinorVersion());
// decide which modes represent int and references
final Mode modeInt = Mode.getIs();
final Mode modeRef = Mode.getP();
// Create type and unique entity for class A
ClassType class_A = new ClassType("A");
// Create method type for calc (first parameter is this-pointer)
Type intType = new PrimitiveType(modeInt);
Type reference_to_A = new PointerType(class_A);
Type calcMethodType = new MethodType(new Type[] { reference_to_A,
intType, intType }, new Type[] { intType });
// Create entity for calc method
Entity calcEnt = new Entity(class_A, "calc(II)I", calcMethodType);
// Start actual code creation
Graph graph = new Graph(calcEnt, numLocalVars);
Construction cons = new Construction(graph);
// Initialize parameter "variables"
Node args = graph.getArgs();
Node projThis = cons.newProj(args, modeRef, 0); /*
* this is parameter
* number 0
*/
cons.setVariable(varNumThis, projThis);
Node projX = cons.newProj(args, modeInt, 1); /* x is parameter number 1 */
cons.setVariable(varNumX, projX);
Node projY = cons.newProj(args, modeInt, 2); /* y is parameter number 2 */
cons.setVariable(varNumY, projY);
// Code for Condition expression
// Get value of x
Node xVal = cons.getVariable(varNumX, modeInt);
// Get value of y
Node yVal = cons.getVariable(varNumY, modeInt);
// Compare x,y with <
Node cmp = cons.newCmp(xVal, yVal, Relation.Less);
// Conditional Jump Node with the True+False Proj
Node cond = cons.newCond(cmp);
Node projTrue = cons.newProj(cond, Mode.getX(), Cond.pnTrue);
Node projFalse = cons.newProj(cond, Mode.getX(), Cond.pnFalse);
// If-Block (the true part)
Block bTrue = cons.newBlock();
bTrue.addPred(projTrue);
cons.setCurrentBlock(bTrue); /* we create nodes in the new block now */
// Code for if-part
// Compute value of right part of the assignment
Node xVal2 = cons.getVariable(varNumX, modeInt);
Node yVal2 = cons.getVariable(varNumY, modeInt);
Node add = cons.newAdd(xVal2, yVal2, modeInt);
// Set value to local var sum
cons.setVariable(varNumSum, add);
// Jump out of if-block
Node endIf = cons.newJmp();
// Else-Block
Block bFalse = cons.newBlock();
bFalse.addPred(projFalse);
cons.setCurrentBlock(bFalse);
// Code for else-part
Node xVal3 = cons.getVariable(varNumX, modeInt);
Node yVal3 = cons.getVariable(varNumY, modeInt);
Node mul = cons.newMul(xVal3, yVal3, Mode.getIs());
// Set value to local var sum
cons.setVariable(varNumSum, mul);
// Jump out of else-block
Node endElse = cons.newJmp();
// Follow-up block connect with the jumps out of if- and else-block
Block bAfter = cons.newBlock();
bAfter.addPred(endIf);
bAfter.addPred(endElse);
cons.setCurrentBlock(bAfter);
// Get value of sum variable
Node sumVal = cons.getVariable(varNumSum, Mode.getIs());
// Create Return statement
Node curMem = cons.getCurrentMem();
Node retn = cons.newReturn(curMem, new Node[] { sumVal });
graph.getEndBlock().addPred(retn);
// No code should follow a return statement.
cons.setCurrentBlockBad();
// Done.
cons.finish();
// Check and dump created graphs - can be viewed with ycomp
for (Graph g : Program.getGraphs()) {
g.check();
// Should produce a file calc(II)I.vcg
Dump.dumpGraph(g, "");
}
}
}
| false | false | null | null |
diff --git a/android/src/ch/fixme/cowsay/Cow.java b/android/src/ch/fixme/cowsay/Cow.java
index 35bcc25..93b1e64 100644
--- a/android/src/ch/fixme/cowsay/Cow.java
+++ b/android/src/ch/fixme/cowsay/Cow.java
@@ -1,214 +1,209 @@
package ch.fixme.cowsay;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
-import android.view.WindowManager;
-import android.util.DisplayMetrics;
import android.util.Log;
import android.content.Context;
import android.content.res.AssetManager;
public class Cow
{
public String style = "default";
private String eyes;
private String tongue;
public String thoughts = "";
public String message;
private int think = 0;
public int face = -1;
public static final int FACE_BORG = 1;
public static final int FACE_DEAD = 2;
public static final int FACE_GREEDY = 3;
public static final int FACE_PARANOID = 4;
public static final int FACE_STONED = 5;
public static final int FACE_TIRED = 6;
public static final int FACE_WIRED = 7;
public static final int FACE_YOUNG = 8;
private final int WRAPLEN = 30;
final Context context;
public Cow(Context context) {
this.context = context;
construct_face();
- DisplayMetrics dm = new DisplayMetrics();
- ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
- Log.e("Cow", "x="+dm.widthPixels);
}
public String asString() {
try {
AssetManager mngr = context.getAssets();
InputStream is = mngr.open("cows/" + style + ".cow");
return getBalloon() + parse_cowfile(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "No cow today";
}
}
private String parse_cowfile(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
try {
String line;
// Jump to cow start
while (true) {
line = br.readLine();
Log.d("Cow", "Line: " + line);
if (line == null) {
return "Cow parsing failure";
};
if (line.contains("$the_cow =")) {
break;
};
}
Log.d("Cow", "Got the cow!");
while ((line = br.readLine()) != null) {
Log.d("Cow", "Line: " + line);
if ((line.contains("EOC") || line.contains("EOF"))) {
Log.d("Cow", "End of cow found");
break;
}
sb.append(line + "\n");
}
String text = sb.toString();
Log.d("Cow", "Before replacment: '" + text + "'");
text = text.replace("$eyes", eyes);
text = text.replace("${eyes}", eyes);
text = text.replace("$tongue", tongue);
text = text.replace("${tongue}", tongue);
text = text.replace("$thoughts", thoughts);
text = text.replace("${thoughts}", thoughts);
text = text.replace("\\@", "@");
text = text.replace("\\\\", "\\");
Log.d("Cow", "Returns:\n'" + text + "'");
return text;
} catch (IOException e) {
e.printStackTrace();
return "No cow available due to some parser crash, too bad!";
}
}
public String[] getCowTypes() {
ArrayList res = new ArrayList();
try {
String[] cows = context.getAssets().list("cows");
for (int i = 0; i < cows.length; i++) {
String string = cows[i];
res.add(string.substring(0, string.length() - 4));
}
} catch (IOException e) {
e.printStackTrace();
}
String[] array = new String[res.size()];
return (String[]) res.toArray(array);
}
private String getBalloon() {
String balloon = "";
int msglen = message.length();
int maxlen = (msglen > WRAPLEN) ? WRAPLEN : msglen;
int max2 = maxlen + 2;
// Balloon borders
// up-left, up-right, down-left, down-right, left, right
final char[] border;
if(think==1) {
thoughts = "o";
border = new char[] { '(',')','(',')','(',')' };
} else if(msglen > WRAPLEN) {
thoughts = "\\";
border = new char[] { '/', '\\', '\\', '/', '|', '|' };
} else {
thoughts = "\\";
border = new char[] { '<','>' };
}
// Draw balloon content
balloon += " " + new String(new char[max2]).replace("\0", "_") + " \n";
if (msglen > WRAPLEN) {
for (int i = 0; i < msglen; i += WRAPLEN){
// First line
if(i < WRAPLEN){
balloon += border[0] + " " + message.substring(0, WRAPLEN) + " " + border[1] + " \n";
} else {
// Last line
int sublen = message.substring(i, msglen-1).length();
if(sublen < WRAPLEN) {
int padlen = WRAPLEN - sublen;
String padding = new String(new char[padlen]).replace("\0", " ");
balloon += border[2] + " " + message.substring(i, msglen) + padding + border[3] + " \n";
// Middle line
} else {
balloon += border[4] + " " + message.substring(i, i+WRAPLEN) + " " + border[5] + " \n";
}
}
}
} else {
balloon += border[0] + " " + message + " " + border[1] + " \n";
}
balloon += " " + new String(new char[max2]).replace("\0", "-") + " \n";
return balloon;
}
private void construct_face() {
eyes = "oo";
tongue = " ";
switch(face){
case FACE_BORG:
eyes = "==";
tongue = " ";
break;
case FACE_DEAD:
eyes = "xx";
tongue = "U ";
break;
case FACE_GREEDY:
eyes = "$$";
tongue = " ";
break;
case FACE_PARANOID:
eyes = "@@";
tongue = " ";
break;
case FACE_STONED:
eyes = "**";
tongue = "U ";
break;
case FACE_WIRED:
eyes = "00";
tongue = " ";
break;
case FACE_YOUNG:
case FACE_TIRED:
eyes = "..";
tongue = " ";
break;
}
}
}
diff --git a/android/src/ch/fixme/cowsay/Main.java b/android/src/ch/fixme/cowsay/Main.java
index 1a88b2e..dd1a572 100644
--- a/android/src/ch/fixme/cowsay/Main.java
+++ b/android/src/ch/fixme/cowsay/Main.java
@@ -1,167 +1,174 @@
package ch.fixme.cowsay;
+import android.util.TypedValue;
+import java.lang.Math;
+import android.view.WindowManager;
+import android.util.DisplayMetrics;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Main extends Activity
{
private Cow cow;
private EditText messageView;
private TextView outputView;
// Menu
public static final int MENU_SHARE_TEXT = Menu.FIRST;
public static final int MENU_SHARE_HTML = Menu.FIRST + 1;
public static final int MENU_SHARE_IMAGE = Menu.FIRST + 2;
/* Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_SHARE_TEXT, 0, "Share as text");
menu.add(0, MENU_SHARE_HTML, 0, "Share as HTML");
menu.add(0, MENU_SHARE_IMAGE, 0, "Share as image");
return true;
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(Intent.ACTION_SEND);
switch (item.getItemId()) {
case MENU_SHARE_TEXT:
Log.d("Main Menu", "Share as text");
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Cowsay");
intent.putExtra(Intent.EXTRA_TEXT, cow.asString());
startActivity(Intent.createChooser(intent, "Share with"));
case MENU_SHARE_HTML:
Log.d("Main Menu", "Share as HTML");
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_SUBJECT, "Cowsay");
intent.putExtra(Intent.EXTRA_TEXT, "<html><pre>" + cow.asString() + "</pre></html>");
startActivity(Intent.createChooser(intent, "Share with"));
case MENU_SHARE_IMAGE:
Log.d("Main Menu", "Share as image");
View thecow = findViewById(R.id.thecow);
Bitmap screenshot = Bitmap.createBitmap(thecow.getWidth(), thecow.getHeight(), Bitmap.Config.RGB_565);
thecow.draw(new Canvas(screenshot));
String path = Images.Media.insertImage(getContentResolver(), screenshot, "title", null);
Uri screenshotUri = Uri.parse(path);
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
emailIntent.setType("image/png");
startActivity(Intent.createChooser(emailIntent, "Send email using"));
}
return false;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
final Context ctxt = getApplicationContext();
messageView = (EditText) findViewById(R.id.message);
outputView = (TextView) findViewById(R.id.thecow);
cow = new Cow(ctxt);
TextWatcher myTextWatcher = new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
cowRefresh();
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
}
};
messageView.addTextChangedListener(myTextWatcher);
messageView.setText("Moo");
populateCowTypes();
}
private void populateCowTypes() {
// Populate the cow type Spinner widget
final String[] items = cow.getCowTypes();
for (int i = 0; i < items.length; i++) {
String item = items[i];
Log.d("Main", "item: " + item);
}
final Spinner spinner = (Spinner) findViewById(R.id.type);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapter, View v, int position, long id) {
cow.style = items[position];
cowRefresh();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void cowRefresh() {
Log.d("Main", "Let's refresh the cow");
final EditText txt = (EditText) findViewById(R.id.message);
cow.message = txt.getText().toString();
-
String text = cow.asString();
- cow.message = text;
- outputView.setText(cow.asString());
+ outputView.setText(text);
String[] lines = text.split("\n");
Integer width = 0;
Integer height = lines.length;
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
if (line.length() > width) {
width = line.length();
}
}
+
+ //View container = findViewById(R.id.container);
+ //int textHeight = (container.getHeight()) / height;
+ //int textWidth = (container.getWidth()) / width;
+ //outputView.setTextSize(TypedValue.COMPLEX_UNIT_DP, Math.min(textHeight, textWidth));
}
}
| false | false | null | null |
diff --git a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/timer/SingleActionTimerData.java b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/timer/SingleActionTimerData.java
index a9444ee9c..b56c4dba4 100644
--- a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/timer/SingleActionTimerData.java
+++ b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/timer/SingleActionTimerData.java
@@ -1,64 +1,61 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openejb.core.timer;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.util.Date;
import javax.ejb.TimerConfig;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
/**
* @version $Rev$ $Date$
*/
public class SingleActionTimerData extends TimerData {
private final Date expiration;
public SingleActionTimerData(long id, EjbTimerServiceImpl timerService, String deploymentId, Object primaryKey, Method timeoutMethod, TimerConfig timerConfig, Date expiration) {
super(id, timerService, deploymentId, primaryKey, timeoutMethod, timerConfig);
this.expiration = expiration;
}
@Override
public TimerType getType() {
return TimerType.SingleAction;
}
public Date getExpiration() {
return expiration;
}
@Override
public Trigger initializeTrigger() {
- SimpleTrigger simpleTrigger = new SimpleTrigger();
- Date startTime = new Date();
- simpleTrigger.setStartTime(startTime);
- simpleTrigger.setRepeatInterval(expiration.getTime() - startTime.getTime());
- simpleTrigger.setRepeatCount(1);
+ final SimpleTrigger simpleTrigger = new SimpleTrigger();
+ simpleTrigger.setStartTime(expiration);
return simpleTrigger;
}
@Override
public String toString() {
return TimerType.SingleAction.name() + " expiration = [" + DateFormat.getDateTimeInstance().format(expiration) + "]";
}
}
| true | true | public Trigger initializeTrigger() {
SimpleTrigger simpleTrigger = new SimpleTrigger();
Date startTime = new Date();
simpleTrigger.setStartTime(startTime);
simpleTrigger.setRepeatInterval(expiration.getTime() - startTime.getTime());
simpleTrigger.setRepeatCount(1);
return simpleTrigger;
}
| public Trigger initializeTrigger() {
final SimpleTrigger simpleTrigger = new SimpleTrigger();
simpleTrigger.setStartTime(expiration);
return simpleTrigger;
}
|
diff --git a/gcm-client/src/com/google/android/gcm/GCMConstants.java b/gcm-client/src/com/google/android/gcm/GCMConstants.java
index e64af7c..f39ff07 100644
--- a/gcm-client/src/com/google/android/gcm/GCMConstants.java
+++ b/gcm-client/src/com/google/android/gcm/GCMConstants.java
@@ -1,167 +1,167 @@
/*
* Copyright 2012 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.android.gcm;
/**
* Constants used by the GCM library.
*/
public final class GCMConstants {
/**
* Intent sent to GCM to register the application.
*/
public static final String INTENT_TO_GCM_REGISTRATION =
"com.google.android.c2dm.intent.REGISTER";
/**
* Intent sent to GCM to unregister the application.
*/
public static final String INTENT_TO_GCM_UNREGISTRATION =
"com.google.android.c2dm.intent.UNREGISTER";
/**
* Intent sent by GCM indicating with the result of a registration request.
*/
public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK =
"com.google.android.c2dm.intent.REGISTRATION";
/**
* Intent used by the GCM library to indicate that the registration call
* should be retried.
*/
public static final String INTENT_FROM_GCM_LIBRARY_RETRY =
"com.google.android.gcm.intent.RETRY";
/**
* Intent sent by GCM containing a message.
*/
public static final String INTENT_FROM_GCM_MESSAGE =
"com.google.android.c2dm.intent.RECEIVE";
/**
* Extra used on {@value #INTENT_TO_GCM_REGISTRATION} to indicate which
* senders (Google API project ids) can send messages to the application.
*/
public static final String EXTRA_SENDER = "sender";
/**
* Extra used on {@value #INTENT_TO_GCM_REGISTRATION} to get the
* application info.
*/
public static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
/**
* Extra used on {@value #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate
* that the application has been unregistered.
*/
public static final String EXTRA_UNREGISTERED = "unregistered";
/**
* Extra used on {@value #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate
* an error when the registration fails. See constants starting with ERROR_
* for possible values.
*/
public static final String EXTRA_ERROR = "error";
/**
* Extra used on {@value #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate
* the registration id when the registration succeeds.
*/
public static final String EXTRA_REGISTRATION_ID = "registration_id";
/**
- * Type of message present in the {@link #INTENT_FROM_GCM_MESSAGE} intent.
+ * Type of message present in the {@value #INTENT_FROM_GCM_MESSAGE} intent.
* This extra is only set for special messages sent from GCM, not for
* messages originated from the application.
*/
public static final String EXTRA_SPECIAL_MESSAGE = "message_type";
/**
* Special message indicating the server deleted the pending messages.
*/
public static final String VALUE_DELETED_MESSAGES = "deleted_messages";
/**
* Number of messages deleted by the server because the device was idle.
* Present only on messages of special type
- * {@link #VALUE_DELETED_MESSAGES}
+ * {@value #VALUE_DELETED_MESSAGES}
*/
public static final String EXTRA_TOTAL_DELETED = "total_deleted";
/**
* Extra used on {@value #INTENT_FROM_GCM_MESSAGE} to indicate which
* sender (Google API project id) sent the message.
*/
public static final String EXTRA_FROM = "from";
/**
* Permission necessary to receive GCM intents.
*/
public static final String PERMISSION_GCM_INTENTS =
"com.google.android.c2dm.permission.SEND";
/**
* @see GCMBroadcastReceiver
*/
public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME =
".GCMIntentService";
/**
* The device can't read the response, or there was a 500/503 from the
* server that can be retried later. The application should use exponential
* back off and retry.
*/
public static final String ERROR_SERVICE_NOT_AVAILABLE =
"SERVICE_NOT_AVAILABLE";
/**
* There is no Google account on the phone. The application should ask the
* user to open the account manager and add a Google account.
*/
public static final String ERROR_ACCOUNT_MISSING =
"ACCOUNT_MISSING";
/**
* Bad password. The application should ask the user to enter his/her
* password, and let user retry manually later. Fix on the device side.
*/
public static final String ERROR_AUTHENTICATION_FAILED =
"AUTHENTICATION_FAILED";
/**
* The request sent by the phone does not contain the expected parameters.
* This phone doesn't currently support GCM.
*/
public static final String ERROR_INVALID_PARAMETERS =
"INVALID_PARAMETERS";
/**
* The sender account is not recognized. Fix on the device side.
*/
public static final String ERROR_INVALID_SENDER =
"INVALID_SENDER";
/**
* Incorrect phone registration with Google. This phone doesn't currently
* support GCM.
*/
public static final String ERROR_PHONE_REGISTRATION_ERROR =
"PHONE_REGISTRATION_ERROR";
private GCMConstants() {
throw new UnsupportedOperationException();
}
}
diff --git a/gcm-client/src/com/google/android/gcm/GCMRegistrar.java b/gcm-client/src/com/google/android/gcm/GCMRegistrar.java
index 6f5a92d..0e026f9 100644
--- a/gcm-client/src/com/google/android/gcm/GCMRegistrar.java
+++ b/gcm-client/src/com/google/android/gcm/GCMRegistrar.java
@@ -1,507 +1,509 @@
/*
* Copyright 2012 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.android.gcm;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Utilities for device registration.
* <p>
* <strong>Note:</strong> this class uses a private {@link SharedPreferences}
* object to keep track of the registration token.
*/
public final class GCMRegistrar {
/**
* Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)}
* flag until it is considered expired.
*/
// NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8
public static final long DEFAULT_ON_SERVER_LIFESPAN_MS =
1000 * 3600 * 24 * 7;
private static final String TAG = "GCMRegistrar";
private static final String BACKOFF_MS = "backoff_ms";
private static final String GSF_PACKAGE = "com.google.android.gsf";
private static final String PREFERENCES = "com.google.android.gcm";
private static final int DEFAULT_BACKOFF_MS = 3000;
private static final String PROPERTY_REG_ID = "regId";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String PROPERTY_ON_SERVER = "onServer";
private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME =
"onServerExpirationTime";
private static final String PROPERTY_ON_SERVER_LIFESPAN =
"onServerLifeSpan";
/**
* {@link GCMBroadcastReceiver} instance used to handle the retry intent.
*
* <p>
* This instance cannot be the same as the one defined in the manifest
* because it needs a different permission.
*/
private static GCMBroadcastReceiver sRetryReceiver;
private static String sRetryReceiverClassName;
/**
* Checks if the device has the proper dependencies installed.
* <p>
* This method should be called when the application starts to verify that
* the device supports GCM.
*
* @param context application context.
* @throws UnsupportedOperationException if the device does not support GCM.
*/
public static void checkDevice(Context context) {
int version = Build.VERSION.SDK_INT;
if (version < 8) {
throw new UnsupportedOperationException("Device must be at least " +
"API Level 8 (instead of " + version + ")");
}
PackageManager packageManager = context.getPackageManager();
try {
packageManager.getPackageInfo(GSF_PACKAGE, 0);
} catch (NameNotFoundException e) {
throw new UnsupportedOperationException(
"Device does not have package " + GSF_PACKAGE);
}
}
/**
* Checks that the application manifest is properly configured.
* <p>
* A proper configuration means:
* <ol>
* <li>It creates a custom permission called
* {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
* <li>It defines at least one {@link BroadcastReceiver} with category
* {@code PACKAGE_NAME}.
* <li>The {@link BroadcastReceiver}(s) uses the
- * {@value GCMConstants#PERMISSION_GCM_INTENTS} permission.
+ * {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS}
+ * permission.
* <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents
- * ({@value GCMConstants#INTENT_FROM_GCM_MESSAGE} and
- * {@value GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}).
+ * ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
+ * and
+ * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}).
* </ol>
* ...where {@code PACKAGE_NAME} is the application package.
* <p>
* This method should be used during development time to verify that the
* manifest is properly set up, but it doesn't need to be called once the
* application is deployed to the users' devices.
*
* @param context application context.
* @throws IllegalStateException if any of the conditions above is not met.
*/
public static void checkManifest(Context context) {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
String permissionName = packageName + ".permission.C2D_MESSAGE";
// check permission
try {
packageManager.getPermissionInfo(permissionName,
PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Application does not define permission " + permissionName);
}
// check receivers
PackageInfo receiversInfo;
try {
receiversInfo = packageManager.getPackageInfo(
packageName, PackageManager.GET_RECEIVERS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Could not get receivers for package " + packageName);
}
ActivityInfo[] receivers = receiversInfo.receivers;
if (receivers == null || receivers.length == 0) {
throw new IllegalStateException("No receiver for package " +
packageName);
}
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "number of receivers for " + packageName + ": " +
receivers.length);
}
Set<String> allowedReceivers = new HashSet<String>();
for (ActivityInfo receiver : receivers) {
if (GCMConstants.PERMISSION_GCM_INTENTS.equals(
receiver.permission)) {
allowedReceivers.add(receiver.name);
}
}
if (allowedReceivers.isEmpty()) {
throw new IllegalStateException("No receiver allowed to receive " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_MESSAGE);
}
private static void checkReceiver(Context context,
Set<String> allowedReceivers, String action) {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
Intent intent = new Intent(action);
intent.setPackage(packageName);
List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent,
PackageManager.GET_INTENT_FILTERS);
if (receivers.isEmpty()) {
throw new IllegalStateException("No receivers for action " +
action);
}
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Found " + receivers.size() + " receivers for action " +
action);
}
// make sure receivers match
for (ResolveInfo receiver : receivers) {
String name = receiver.activityInfo.name;
if (!allowedReceivers.contains(name)) {
throw new IllegalStateException("Receiver " + name +
" is not set with permission " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
}
}
/**
* Initiate messaging registration for the current application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with
* either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or
* {@link GCMConstants#EXTRA_ERROR}.
*
* @param context application context.
* @param senderIds Google Project ID of the accounts authorized to send
* messages to this application.
* @throws IllegalStateException if device does not have all GCM
* dependencies installed.
*/
public static void register(Context context, String... senderIds) {
GCMRegistrar.resetBackoff(context);
internalRegister(context, senderIds);
}
static void internalRegister(Context context, String... senderIds) {
String flatSenderIds = getFlatSenderIds(senderIds);
Log.v(TAG, "Registering app " + context.getPackageName() +
" of senders " + flatSenderIds);
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.setPackage(GSF_PACKAGE);
intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
PendingIntent.getBroadcast(context, 0, new Intent(), 0));
intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds);
context.startService(intent);
}
static String getFlatSenderIds(String... senderIds) {
if (senderIds == null || senderIds.length == 0) {
throw new IllegalArgumentException("No senderIds");
}
StringBuilder builder = new StringBuilder(senderIds[0]);
for (int i = 1; i < senderIds.length; i++) {
builder.append(',').append(senderIds[i]);
}
return builder.toString();
}
/**
* Unregister the application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an
* {@link GCMConstants#EXTRA_UNREGISTERED} extra.
*/
public static void unregister(Context context) {
GCMRegistrar.resetBackoff(context);
internalUnregister(context);
}
/**
* Clear internal resources.
*
* <p>
* This method should be called by the main activity's {@code onDestroy()}
* method.
*/
public static synchronized void onDestroy(Context context) {
if (sRetryReceiver != null) {
Log.v(TAG, "Unregistering receiver");
context.unregisterReceiver(sRetryReceiver);
sRetryReceiver = null;
}
}
static void internalUnregister(Context context) {
Log.v(TAG, "Unregistering app " + context.getPackageName());
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION);
intent.setPackage(GSF_PACKAGE);
intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
PendingIntent.getBroadcast(context, 0, new Intent(), 0));
context.startService(intent);
}
/**
* Lazy initializes the {@link GCMBroadcastReceiver} instance.
*/
static synchronized void setRetryBroadcastReceiver(Context context) {
if (sRetryReceiver == null) {
if (sRetryReceiverClassName == null) {
// should never happen
Log.e(TAG, "internal error: retry receiver class not set yet");
sRetryReceiver = new GCMBroadcastReceiver();
} else {
Class<?> clazz;
try {
clazz = Class.forName(sRetryReceiverClassName);
sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance();
} catch (Exception e) {
Log.e(TAG, "Could not create instance of " +
sRetryReceiverClassName + ". Using " +
GCMBroadcastReceiver.class.getName() +
" directly.");
sRetryReceiver = new GCMBroadcastReceiver();
}
}
String category = context.getPackageName();
IntentFilter filter = new IntentFilter(
GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
filter.addCategory(category);
// must use a permission that is defined on manifest for sure
String permission = category + ".permission.C2D_MESSAGE";
Log.v(TAG, "Registering receiver");
context.registerReceiver(sRetryReceiver, filter, permission, null);
}
}
/**
* Sets the name of the retry receiver class.
*/
static void setRetryReceiverClassName(String className) {
Log.v(TAG, "Setting the name of retry receiver class to " + className);
sRetryReceiverClassName = className;
}
/**
* Gets the current registration id for application on GCM service.
* <p>
* If result is empty, the registration has failed.
*
* @return registration id, or empty string if the registration is not
* complete.
*/
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int newVersion = getAppVersion(context);
if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
Log.v(TAG, "App version changed from " + oldVersion + " to " +
newVersion + "; resetting registration id");
clearRegistrationId(context);
registrationId = "";
}
return registrationId;
}
/**
* Checks whether the application was successfully registered on GCM
* service.
*/
public static boolean isRegistered(Context context) {
return getRegistrationId(context).length() > 0;
}
/**
* Clears the registration id in the persistence store.
*
* @param context application's context.
* @return old registration id.
*/
static String clearRegistrationId(Context context) {
return setRegistrationId(context, "");
}
/**
* Sets the registration id in the persistence store.
*
* @param context application's context.
* @param regId registration id
*/
static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
Log.v(TAG, "Saving regId on app version " + appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
}
/**
* Sets whether the device was successfully registered in the server side.
*/
public static void setRegisteredOnServer(Context context, boolean flag) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putBoolean(PROPERTY_ON_SERVER, flag);
// set the flag's expiration date
long lifespan = getRegisterOnServerLifespan(context);
long expirationTime = System.currentTimeMillis() + lifespan;
Log.v(TAG, "Setting registeredOnServer status as " + flag + " until " +
new Timestamp(expirationTime));
editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
editor.commit();
}
/**
* Checks whether the device was successfully registered in the server side,
* as set by {@link #setRegisteredOnServer(Context, boolean)}.
*
* <p>To avoid the scenario where the device sends the registration to the
* server but the server loses it, this flag has an expiration date, which
* is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed
* by {@link #setRegisterOnServerLifespan(Context, long)}).
*/
public static boolean isRegisteredOnServer(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false);
Log.v(TAG, "Is registered on server: " + isRegistered);
if (isRegistered) {
// checks if the information is not stale
long expirationTime =
prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
if (System.currentTimeMillis() > expirationTime) {
Log.v(TAG, "flag expired on: " + new Timestamp(expirationTime));
return false;
}
}
return isRegistered;
}
/**
* Gets how long (in milliseconds) the {@link #isRegistered(Context)}
* property is valid.
*
* @return value set by {@link #setRegisteredOnServer(Context, boolean)} or
* {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set.
*/
public static long getRegisterOnServerLifespan(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN,
DEFAULT_ON_SERVER_LIFESPAN_MS);
return lifespan;
}
/**
* Sets how long (in milliseconds) the {@link #isRegistered(Context)}
* flag is valid.
*/
public static void setRegisterOnServerLifespan(Context context,
long lifespan) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan);
editor.commit();
}
/**
* Gets the application version.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
}
}
/**
* Resets the backoff counter.
* <p>
* This method should be called after a GCM call succeeds.
*
* @param context application's context.
*/
static void resetBackoff(Context context) {
Log.d(TAG, "resetting backoff for " + context.getPackageName());
setBackoff(context, DEFAULT_BACKOFF_MS);
}
/**
* Gets the current backoff counter.
*
* @param context application's context.
* @return current backoff counter, in milliseconds.
*/
static int getBackoff(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
}
/**
* Sets the backoff counter.
* <p>
* This method should be called after a GCM call fails, passing an
* exponential value.
*
* @param context application's context.
* @param backoff new backoff counter, in milliseconds.
*/
static void setBackoff(Context context, int backoff) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putInt(BACKOFF_MS, backoff);
editor.commit();
}
private static SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
}
private GCMRegistrar() {
throw new UnsupportedOperationException();
}
}
| false | false | null | null |
diff --git a/project/Server/ChatServerChatRoom.java b/project/Server/ChatServerChatRoom.java
index 5d207b3..9915a66 100644
--- a/project/Server/ChatServerChatRoom.java
+++ b/project/Server/ChatServerChatRoom.java
@@ -1,97 +1,109 @@
package Server;
import java.util.ArrayList;
public class ChatServerChatRoom {
//the name of this chat room
private String name;
//the greeting message displayed when a user enters
//private String greeting;
//Is this chat room in tinfoil hat mode?
//private boolean encrypted; Never mind, it always will be.
//unique ID
private int id;
//ChatServerThread threads stored here:
private ArrayList<ChatServerThread> threads;
public ChatServerChatRoom(String n, int i){
name = n;
//greeting = g;
id = i;
threads = new ArrayList<ChatServerThread>();
}
public void addThread(ChatServerThread thread){ //replaces the first dead thread with this one, taking its id
int count = threads.size(); boolean found = false;
for (int i = 0; i<count; i++){
ChatServerThread thread2 = threads.get(i);
if (thread2==null || !thread2.isAlive()){
thread.setID(i);
// thread.setUserName(""+i);
threads.remove(i);
threads.add(i, thread);
System.out.println("New thread added and ID set to "+i+".");
found = true;
break;
}
}
if (!found){
threads.add(thread);
thread.setID(count);
//thread.setUserName(""+count);
System.out.println("New thread added and ID set to "+count+".");
}
//thread.tell("Server Message", "You've joined the chat room "+name+".");
//tellEveryone( "Server Message", ""+thread.getUserName()+" joined the room."); //id -1 reserved for server messages
}
public void removeThread(ChatServerThread thread){
int id = thread.getID();
threads.remove(id);
threads.add(id, null); //to fill the space in the "hash set"
}
public String getName(){ return name; }
public int getID(){ return id; }
public void tellEveryone(String name, String message){ //general chat
if (message==null || message.length()==0) return;
for (ChatServerThread thread : threads){
if (thread!=null && thread.isLoggedIn()) thread.tell(name, message);
}
}
+ public void tellEveryoneNotAdmins(String name, String message){ //general chat
+ if (message==null || message.length()==0) return;
+ for (ChatServerThread thread : threads){
+ if (thread!=null && thread.isLoggedIn() && !thread.getIsAdmin()) thread.tell(name, message);
+ }
+ }
+ public void tellAdmins(String name, String message){ //general chat
+ if (message==null || message.length()==0) return;
+ for (ChatServerThread thread : threads){
+ if (thread!=null && thread.isLoggedIn() && thread.getIsAdmin()) thread.tell(name, message);
+ }
+ }
/*
public void shutDown(){ //called when server is stopping, should kick all the users
for (ChatServerThread thread : threads){
thread.disconnect("Server is shutting down.");
}
}
*/
public void close(){ //called when room is closing, should kick all users
for (ChatServerThread thread : threads){
thread.disconnect("Room is closing.");
}
}
public String getUsers(){
StringBuffer ret = new StringBuffer(threads.size()*10+12);
ret.append("Users in room: [");
for (ChatServerThread thread : threads){
- if (thread!=null && thread.getUserName()!=null && thread.isAlive())
+ if (thread!=null && thread.isLoggedIn() && thread.isAlive())
ret.append(""+thread.getUserName()+", ");
}
ret.delete(ret.length()-2, ret.length());
ret.append("]");
return ret.toString();
}
/* public boolean changeUserName(String name, int id){
for (ChatServerThread thread : threads){
if (thread.getUserName().equalsIgnoreCase(name)) return false;
}
threads.get(id).setUserName(name);
return true;
} */
}
diff --git a/project/Server/ChatServerThread.java b/project/Server/ChatServerThread.java
index 24fce36..bfc1036 100644
--- a/project/Server/ChatServerThread.java
+++ b/project/Server/ChatServerThread.java
@@ -1,288 +1,299 @@
package Server;
import java.net.*;
import java.util.Scanner;
import java.io.*;
import Common.Encryptor;
public class ChatServerThread extends Thread {
/* The client socket and IO we are going to handle in this thread */
protected Socket socket;
protected PrintWriter out;
protected BufferedReader in;
//the user this thread corresponds to
private UserAccount user;
//chat room this belongs to
private ChatServerChatRoom chatRoom;
//server this belongs to
private ChatServerMain chatServer;
private String pendingAudioChat; //if there is a pending request
//id specific to room
private int id;
public static final boolean ENCRYPTED = true; //encryption enabled? false for server debug
public boolean isLoggedIn(){ return (user!=null); }
public int getID(){ return id; }
public void setID(int a){ id = a; }
+
+ public boolean getIsAdmin(){ return user.getIsAdmin(); }
public String getUserName(){ if (user!=null) return user.getName(); return null; }
public void setUserName(String n){ user.setName(n); }
public ChatServerChatRoom getRoom(){ return chatRoom; }
public void setRoom(ChatServerChatRoom room){ chatRoom = room; }
public ChatServerThread(Socket socket, UserAccount account, ChatServerChatRoom chatRoom, ChatServerMain chatServer){
user = account;
this.chatRoom = chatRoom;
this.chatServer = chatServer;
/* Create the I/O variables */
try {
this.out = new PrintWriter(socket.getOutputStream(), true);
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
/* Debug */
System.out.println("Client handler thread created.");
} catch (IOException e) {
System.out.println("IOException: " + e);
}
}
public void send(String a){
if (ENCRYPTED) a = Encryptor.encrypt(a, 5); //encrypt it 5 times
this.out.println(a);
}
public String receive(){
try{
if (ENCRYPTED) return Encryptor.decrypt(this.in.readLine(), 5); //decrypt it 5 times
else return this.in.readLine();
} catch (Exception e) {}
return null;
}
@Override
public void run() {
//ask for login credentials
send("Enter username (will be created if doesn't exist).");
String name = receive();
send("Enter your password (or desired password for new account).");
String password = receive();
System.out.println("Handling login for "+name+", password is "+password+".");
user = chatServer.handleLogin(name, password);
if (user==null){ send("Invalid password or username, disconnecting!"); System.out.println("Disconnecting user because of bad login."); forceDisconnect(); return; }
user.setThread(this);
this.tell("Server Message", "You've joined the chat room "+chatRoom.getName()+".");
chatRoom.tellEveryone("Server Message", ""+user.getName()+" joined the room.");
//else{ System.out.println("Unknown error run ChatServerThread run from handling login!!!"); this.out.println("Technical difficulties, disconnecting."); forceDisconnect(); }
Scanner scanner; //for analyzing text
while (true) {
try {
if (user==null) return; //check if thread should be killed off
/* Get string from client */
String fromClient = receive();
if (user==null) return; //check if thread should be killed off
/* If null, connection is closed, so just finish */
if (fromClient == null) {
disconnect(null);
}
/* Handle the text. */
if (fromClient.length()>0){
if (fromClient.charAt(0)=='/'){ //if it's a command
scanner = new Scanner(fromClient);
String firstWord = scanner.next();
if (firstWord.equalsIgnoreCase("/whisper")){ //to tell a user a private message
if (!scanner.hasNext()) send("You must specify the target's name.");
String target = scanner.next();
if (!scanner.hasNext()) send("You must specify a message.");
String message = scanner.next();
System.out.println("User "+user.getName()+" saying (privately) "+message+" to target "+target+".");
if (!chatServer.tellUser(user.getName()+" (privately)", target, message)) send("User not found online.");
}
+ else if (firstWord.equalsIgnoreCase("/anonymous")){
+ String message = "";
+ message = fromClient.substring(10, fromClient.length()); //10 is the length of /anonymous
+ if (!user.getIsAdmin()){
+ chatRoom.tellEveryoneNotAdmins("Anonymous User", message);
+ chatRoom.tellAdmins(""+user.getName()+" (anonymously)", message); //users not anonymous to admins
+ }
+ else chatRoom.tellEveryone("Anonymous User", message); //admins are anonymous to admins
+ }
else if (firstWord.equalsIgnoreCase("/nick")){ //to change a user's name
if (!scanner.hasNext()) send("You must specify a name.");
String oldName = user.getName();
if (!chatServer.changeUserName(user.getName(), scanner.next())){ send("Name already taken or invalid."); return; }
if (chatRoom!=null) chatRoom.tellEveryone("Server Message", "User "+oldName+" is now known as "+user.getName()+"."); //server message
}
else if (firstWord.equalsIgnoreCase("/disconnect")){ //to disconnect gracefully
String message = null;
if (scanner.hasNext()) message = scanner.next();
disconnect(message);
}
else if (firstWord.equalsIgnoreCase("/stop")){ //to close the server, ADMIN ONLY
if (user.getIsAdmin()) chatServer.quit();
else send("You do not have permission to use this command.");
}
else if (firstWord.equalsIgnoreCase("/audio")){ //to start an audio chat with someone
if (!scanner.hasNext()) send("You must specify the target's name.");
String target = scanner.next();
System.out.println("User "+user.getName()+" starting audio chat with "+target+".");
if (!chatServer.audioChat(user.getName(), target)) send("Unable to start audio chat with user.");
else{
send("Sent audio chat request. You can end it at any time with /decline.");
send("/accept"); //client interprets this and makes a chat thread in this case
}
}
else if (firstWord.equalsIgnoreCase("/accept")){
if (pendingAudioChat==null || pendingAudioChat.length()==0){ send("No pending audio chat request to accept."); }
else{
Scanner tempScanner = new Scanner(pendingAudioChat); String sender = tempScanner.next(); String target = tempScanner.next();
System.out.println("User "+target+" accepted audio chat with "+sender+".");
if (chatServer.audioChat(sender, target)){ send("/accept"); System.out.println("User "+user.getName()+" accepted audio chat."); }
else send("No pending audio chat request to accept.");
}
}
else if (firstWord.equalsIgnoreCase("/decline")){
chatServer.endAudioChat(pendingAudioChat); pendingAudioChat = null;
}
else if (firstWord.equalsIgnoreCase("/changeroom")){
if (!scanner.hasNext()) send("You must specify a room name.");
else if (!chatServer.changeRoom(user.getName(), scanner.next())) send("Invalid room name specified. ");
else{
this.tell("Server Message", "You've joined the chat room "+chatRoom.getName()+".");
chatRoom.tellEveryone("Server Message", ""+user.getName()+" joined the room.");
}
}
else if (firstWord.equalsIgnoreCase("/rooms")){
send(chatServer.getRoomNames());
}
else if (firstWord.equalsIgnoreCase("/users")){
send(chatRoom.getUsers());
}
else if (firstWord.equalsIgnoreCase("/addroom")){
if (!user.getIsAdmin()) send("You do not have permission to use this command.");
else{
if (!scanner.hasNext()) send("You must specify a room name.");
else if (!chatServer.addRoom(scanner.next())) send("Invalid room name specified. ");
else send("New room created.");
}
}
else if (firstWord.equalsIgnoreCase("/removeroom")){
if (!user.getIsAdmin()) send("You do not have permission to use this command.");
else{
if (!scanner.hasNext()) send("You must specify a room name.");
else if (!chatServer.removeRoom(scanner.next())) send("Invalid room name specified. ");
else send("Room removed.");
}
}
else if (firstWord.equalsIgnoreCase("/ban")){
if (!user.getIsAdmin()) send("You do not have permission to use this command.");
else{
if (!scanner.hasNext()) send("You must specify a user.");
else{
String target = scanner.next();
if (chatServer.banUser(target)) send("Banned user "+target);
else send("Could not ban user "+target);
}
}
}
else if (firstWord.equalsIgnoreCase("/unban")){
if (!user.getIsAdmin()) send("You do not have permission to use this command.");
else{
if (!scanner.hasNext()) send("You must specify a user.");
else{
String target = scanner.next();
if (chatServer.unbanUser(target)) send("Unbanned user "+target);
else send("Could not unban user "+target);
}
}
}
else if (firstWord.equalsIgnoreCase("/op")){
if (!user.getIsAdmin()) send("You do not have permission to use this command.");
else{
if (!scanner.hasNext()) send("You must specify a user.");
else{
String target = scanner.next();
if (chatServer.promoteUser(target)) send("Opped user "+target);
else send("Could not op user "+target);
}
}
}
else if (firstWord.equalsIgnoreCase("/deop")){
if (!user.getIsAdmin()) send("You do not have permission to use this command.");
else{
if (!scanner.hasNext()) send("You must specify a user.");
else{
String target = scanner.next();
if (chatServer.demoteUser(target)) send("Deopped user "+target);
else send("Could not deop user "+target);
}
}
}
else send("Invalid command.");
scanner.close();
}
else chatRoom.tellEveryone(user.getName(), fromClient);
}
} catch (Exception e) {
/* On exception, stop the thread */
return;
}
}
}
public void disconnect(String message){ //called when disconnecting from server
if (message == null) message = "No message given.";
System.out.println("Client "+user.getName()+ " disconnected");
if (message!=null && chatRoom!=null) chatRoom.tellEveryone(user.getName()+" (disconnecting)", message);
if (chatRoom!=null) chatRoom.tellEveryone("Server Message", ""+user.getName()+" disconnected"); //server message
tell("Server Message", "You have been disconnected: "+message);
this.user = null; //causes the thread to stop
try{
this.socket.close();
this.in.close();
this.out.close();
} catch (Exception e) { System.out.println("Caught non-problematic exception: "+e); }
}
public void forceDisconnect(){ //just disconnect, sending no messages
System.out.println("Client disconnected forcibly");
tell("Server Message", "You have been disconnected forcibly.");
this.user = null; //causes the thread to stop
//this.user = null;
}
public void tell(String user, String message){
if (message==null || message.length()<=0) return;
send(user+": "+message);
}
public boolean audioChat(String user){
if (pendingAudioChat!=null) return false;
tell(user, "I've invited you to an audio chat. Type /accept to accept or /decline to decline.");
pendingAudioChat = (""+user+" "+this.user.getName());
return true;
}
}
| false | false | null | null |
diff --git a/framework/src/com/phonegap/CameraLauncher.java b/framework/src/com/phonegap/CameraLauncher.java
index 0fdb08a4..9dd5d0c1 100755
--- a/framework/src/com/phonegap/CameraLauncher.java
+++ b/framework/src/com/phonegap/CameraLauncher.java
@@ -1,500 +1,502 @@
/*
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 com.phonegap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.LOG;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore;
/**
* This class launches the camera view, allows the user to take a picture, closes the camera view,
* and returns the captured image. When the camera view is closed, the screen displayed before
* the camera view was shown is redisplayed.
*/
public class CameraLauncher extends Plugin {
private static final int DATA_URL = 0; // Return base64 encoded string
private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)
private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
private static final int CAMERA = 1; // Take picture from camera
private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android)
private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL
private static final int ALLMEDIA = 2; // allow selection from all media types
private static final int JPEG = 0; // Take a picture of type JPEG
private static final int PNG = 1; // Take a picture of type PNG
private static final String GET_PICTURE = "Get Picture";
private static final String GET_VIDEO = "Get Video";
private static final String GET_All = "Get All";
private static final String LOG_TAG = "CameraLauncher";
private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
private int targetWidth; // desired width of the image
private int targetHeight; // desired height of the image
private Uri imageUri; // Uri of captured image
private int encodingType; // Type of encoding to use
private int mediaType; // What type of media to retrieve
public String callbackId;
private int numPics;
/**
* Constructor.
*/
public CameraLauncher() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
this.callbackId = callbackId;
try {
if (action.equals("takePicture")) {
int srcType = CAMERA;
int destType = DATA_URL;
this.targetHeight = 0;
this.targetWidth = 0;
this.encodingType = JPEG;
this.mediaType = PICTURE;
this.mQuality = 80;
JSONObject options = args.optJSONObject(0);
if (options != null) {
srcType = options.getInt("sourceType");
destType = options.getInt("destinationType");
this.targetHeight = options.getInt("targetHeight");
this.targetWidth = options.getInt("targetWidth");
this.encodingType = options.getInt("encodingType");
this.mediaType = options.getInt("mediaType");
this.mQuality = options.getInt("quality");
}
if (srcType == CAMERA) {
this.takePicture(destType, encodingType);
}
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
this.getImage(srcType, destType);
}
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
return new PluginResult(status, result);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Take a picture with the camera.
* When an image is captured or the camera view is cancelled, the result is returned
* in PhonegapActivity.onActivityResult, which forwards the result to this.onActivityResult.
*
* The image can either be returned as a base64 string or a URI that points to the file.
* To display base64 string in an img tag, set the source to:
* img.src="data:image/jpeg;base64,"+result;
* or to display URI in an img tag
* img.src=result;
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param returnType Set the type of image to return.
*/
public void takePicture(int returnType, int encodingType) {
// Save the number of images currently on disk for later
this.numPics = queryImgDB().getCount();
// Display camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// Specify file so that large image is captured and returned
// TODO: What if there isn't any external storage?
File photo = createCaptureFile(encodingType);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
this.imageUri = Uri.fromFile(photo);
this.ctx.startActivityForResult((Plugin) this, intent, (CAMERA+1)*16 + returnType+1);
}
/**
* Create a file in the applications temporary directory based upon the supplied encoding.
*
* @param encodingType of the image to be taken
* @return a File object pointing to the temporary picture
*/
private File createCaptureFile(int encodingType) {
File photo = null;
if (encodingType == JPEG) {
photo = new File(DirectoryManager.getTempDirectoryPath(ctx), "Pic.jpg");
} else {
photo = new File(DirectoryManager.getTempDirectoryPath(ctx), "Pic.png");
}
return photo;
}
/**
* Get image from photo library.
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param srcType The album to get image from.
* @param returnType Set the type of image to return.
*/
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
public void getImage(int srcType, int returnType) {
Intent intent = new Intent();
String title = GET_PICTURE;
if (this.mediaType == PICTURE) {
intent.setType("image/*");
}
else if (this.mediaType == VIDEO) {
intent.setType("video/*");
title = GET_VIDEO;
}
else if (this.mediaType == ALLMEDIA) {
// I wanted to make the type 'image/*, video/*' but this does not work on all versions
// of android so I had to go with the wildcard search.
intent.setType("*/*");
title = GET_All;
}
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent,
new String(title)), (srcType+1)*16 + returnType + 1);
}
/**
* Scales the bitmap according to the requested size.
*
* @param bitmap The bitmap to scale.
* @return Bitmap A new Bitmap object of the same bitmap after scaling.
*/
public Bitmap scaleBitmap(Bitmap bitmap) {
int newWidth = this.targetWidth;
int newHeight = this.targetHeight;
int origWidth = bitmap.getWidth();
int origHeight = bitmap.getHeight();
// If no new width or height were specified return the original bitmap
if (newWidth <= 0 && newHeight <= 0) {
return bitmap;
}
// Only the width was specified
else if (newWidth > 0 && newHeight <= 0) {
newHeight = (newWidth * origHeight) / origWidth;
}
// only the height was specified
else if (newWidth <= 0 && newHeight > 0) {
newWidth = (newHeight * origWidth) / origHeight;
}
// If the user specified both a positive width and height
// (potentially different aspect ratio) then the width or height is
// scaled so that the image fits while maintaining aspect ratio.
// Alternatively, the specified width and height could have been
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
// would result in whitespace in the new image.
else {
double newRatio = newWidth / (double)newHeight;
double origRatio = origWidth / (double)origHeight;
if (origRatio > newRatio) {
newHeight = (newWidth * origHeight) / origWidth;
} else if (origRatio < newRatio) {
newWidth = (newHeight * origWidth) / origHeight;
}
}
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
/**
* Called when the camera view exits.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode/16) - 1;
int destType = (requestCode % 16) - 1;
// If CAMERA
if (srcType == CAMERA) {
// If image available
if (resultCode == Activity.RESULT_OK) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
if (this.encodingType == JPEG) {
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Pic.jpg");
exif.readExifData();
}
// Read in bitmap of captured image
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
}
bitmap = scaleBitmap(bitmap);
// If sending base64 image back
if (destType == DATA_URL) {
this.processPicture(bitmap);
checkForDuplicateImage(DATA_URL);
}
// If sending filename back
else if (destType == FILE_URI){
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = null;
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.failPicture("Error capturing image - no media storage found.");
return;
}
}
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
exif.writeExifData();
}
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
bitmap.recycle();
bitmap = null;
System.gc();
checkForDuplicateImage(FILE_URI);
} catch (IOException e) {
e.printStackTrace();
this.failPicture("Error capturing image.");
}
}
// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
// If retrieving photo from library
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
// If you ask for video or all media type you will automatically get back a file URI
// and there will be no attempt to resize any returned data
if (this.mediaType != PICTURE) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
else {
// If sending base64 image back
if (destType == DATA_URL) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
this.processPicture(bitmap);
bitmap.recycle();
bitmap = null;
System.gc();
} catch (FileNotFoundException e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
// If sending filename back
else if (destType == FILE_URI) {
// Do we need to scale the returned file
if (this.targetHeight > 0 && this.targetWidth > 0) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
String fileName = DirectoryManager.getTempDirectoryPath(ctx) + "/resize.jpg";
OutputStream os = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
bitmap.recycle();
bitmap = null;
- this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName)), this.callbackId);
+ // The resized image is cached by the app in order to get around this and not have to delete you
+ // application cache I'm adding the current system time to the end of the file url.
+ this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName + "?" + System.currentTimeMillis())), this.callbackId);
System.gc();
} catch (Exception e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
else {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Selection cancelled.");
}
else {
this.failPicture("Selection did not complete!");
}
}
}
/**
* Creates a cursor that can be used to determine how many images we have.
*
* @return a cursor
*/
private Cursor queryImgDB() {
return this.ctx.getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
null,
null,
null);
}
/**
* Used to find out if we are in a situation where the Camera Intent adds to images
* to the content store. If we are using a FILE_URI and the number of images in the DB
* increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
*
* @param type FILE_URI or DATA_URL
*/
private void checkForDuplicateImage(int type) {
int diff = 1;
Cursor cursor = queryImgDB();
int currentNumOfImages = cursor.getCount();
if (type == FILE_URI) {
diff = 2;
}
// delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
if ((currentNumOfImages - numPics) == diff) {
cursor.moveToLast();
int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
this.ctx.getContentResolver().delete(uri, null, null);
}
}
/**
* Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript.
*
* @param bitmap
*/
public void processPicture(Bitmap bitmap) {
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
try {
if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encodeBase64(code);
String js_out = new String(output);
this.success(new PluginResult(PluginResult.Status.OK, js_out), this.callbackId);
js_out = null;
output = null;
code = null;
}
}
catch(Exception e) {
this.failPicture("Error compressing image.");
}
jpeg_data = null;
}
/**
* Send error message to JavaScript.
*
* @param err
*/
public void failPicture(String err) {
this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId);
}
}
| true | true | public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode/16) - 1;
int destType = (requestCode % 16) - 1;
// If CAMERA
if (srcType == CAMERA) {
// If image available
if (resultCode == Activity.RESULT_OK) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
if (this.encodingType == JPEG) {
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Pic.jpg");
exif.readExifData();
}
// Read in bitmap of captured image
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
}
bitmap = scaleBitmap(bitmap);
// If sending base64 image back
if (destType == DATA_URL) {
this.processPicture(bitmap);
checkForDuplicateImage(DATA_URL);
}
// If sending filename back
else if (destType == FILE_URI){
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = null;
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.failPicture("Error capturing image - no media storage found.");
return;
}
}
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
exif.writeExifData();
}
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
bitmap.recycle();
bitmap = null;
System.gc();
checkForDuplicateImage(FILE_URI);
} catch (IOException e) {
e.printStackTrace();
this.failPicture("Error capturing image.");
}
}
// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
// If retrieving photo from library
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
// If you ask for video or all media type you will automatically get back a file URI
// and there will be no attempt to resize any returned data
if (this.mediaType != PICTURE) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
else {
// If sending base64 image back
if (destType == DATA_URL) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
this.processPicture(bitmap);
bitmap.recycle();
bitmap = null;
System.gc();
} catch (FileNotFoundException e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
// If sending filename back
else if (destType == FILE_URI) {
// Do we need to scale the returned file
if (this.targetHeight > 0 && this.targetWidth > 0) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
String fileName = DirectoryManager.getTempDirectoryPath(ctx) + "/resize.jpg";
OutputStream os = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
bitmap.recycle();
bitmap = null;
this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName)), this.callbackId);
System.gc();
} catch (Exception e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
else {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Selection cancelled.");
}
else {
this.failPicture("Selection did not complete!");
}
}
}
| public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode/16) - 1;
int destType = (requestCode % 16) - 1;
// If CAMERA
if (srcType == CAMERA) {
// If image available
if (resultCode == Activity.RESULT_OK) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
if (this.encodingType == JPEG) {
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Pic.jpg");
exif.readExifData();
}
// Read in bitmap of captured image
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
}
bitmap = scaleBitmap(bitmap);
// If sending base64 image back
if (destType == DATA_URL) {
this.processPicture(bitmap);
checkForDuplicateImage(DATA_URL);
}
// If sending filename back
else if (destType == FILE_URI){
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = null;
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.failPicture("Error capturing image - no media storage found.");
return;
}
}
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
exif.writeExifData();
}
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
bitmap.recycle();
bitmap = null;
System.gc();
checkForDuplicateImage(FILE_URI);
} catch (IOException e) {
e.printStackTrace();
this.failPicture("Error capturing image.");
}
}
// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
// If retrieving photo from library
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
// If you ask for video or all media type you will automatically get back a file URI
// and there will be no attempt to resize any returned data
if (this.mediaType != PICTURE) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
else {
// If sending base64 image back
if (destType == DATA_URL) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
this.processPicture(bitmap);
bitmap.recycle();
bitmap = null;
System.gc();
} catch (FileNotFoundException e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
// If sending filename back
else if (destType == FILE_URI) {
// Do we need to scale the returned file
if (this.targetHeight > 0 && this.targetWidth > 0) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
String fileName = DirectoryManager.getTempDirectoryPath(ctx) + "/resize.jpg";
OutputStream os = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
bitmap.recycle();
bitmap = null;
// The resized image is cached by the app in order to get around this and not have to delete you
// application cache I'm adding the current system time to the end of the file url.
this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName + "?" + System.currentTimeMillis())), this.callbackId);
System.gc();
} catch (Exception e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
else {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Selection cancelled.");
}
else {
this.failPicture("Selection did not complete!");
}
}
}
|
diff --git a/jackson/src/main/java/com/cedarsoft/serialization/jackson/AbstractJacksonSerializer.java b/jackson/src/main/java/com/cedarsoft/serialization/jackson/AbstractJacksonSerializer.java
index a07ce7e8..33261cfb 100644
--- a/jackson/src/main/java/com/cedarsoft/serialization/jackson/AbstractJacksonSerializer.java
+++ b/jackson/src/main/java/com/cedarsoft/serialization/jackson/AbstractJacksonSerializer.java
@@ -1,402 +1,402 @@
/**
* Copyright (C) cedarsoft GmbH.
*
* Licensed under the GNU General Public License version 3 (the "License")
* with Classpath Exception; you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cedarsoft.org/gpl3ce
* (GPL 3 with Classpath Exception)
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3 only, as
* published by the Free Software Foundation. cedarsoft GmbH designates this
* particular file as subject to the "Classpath" exception as provided
* by cedarsoft GmbH in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 3 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 3 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
* or visit www.cedarsoft.com if you need additional information or
* have any questions.
*/
package com.cedarsoft.serialization.jackson;
import com.cedarsoft.version.Version;
import com.cedarsoft.version.VersionException;
import com.cedarsoft.version.VersionRange;
import com.cedarsoft.serialization.AbstractSerializer;
import com.cedarsoft.serialization.jackson.test.compatible.JacksonParserWrapper;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.WillNotClose;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @param <T> the type
* @author Johannes Schneider (<a href="mailto:[email protected]">[email protected]</a>)
*/
public abstract class AbstractJacksonSerializer<T> extends AbstractSerializer<T, JsonGenerator, JsonParser, JsonProcessingException> implements JacksonSerializer<T> {
public static final String FIELD_NAME_DEFAULT_TEXT = "$";
public static final String PROPERTY_TYPE = "@type";
public static final String PROPERTY_VERSION = "@version";
public static final String PROPERTY_SUB_TYPE = "@subtype";
@Nonnull
private final String type; //$NON-NLS-1$
protected AbstractJacksonSerializer( @Nonnull String type, @Nonnull VersionRange formatVersionRange ) {
super( formatVersionRange );
this.type = type;
}
@Nonnull
@Override
public String getType() {
return type;
}
@Override
public void verifyType( @Nullable String type ) throws InvalidTypeException {
if ( !this.type.equals( type ) ) {//$NON-NLS-1$
throw new InvalidTypeException( type, this.type );
}
}
@Override
public void serialize( @Nonnull T object, @WillNotClose @Nonnull OutputStream out ) throws IOException {
JsonFactory jsonFactory = JacksonSupport.getJsonFactory();
JsonGenerator generator = jsonFactory.createJsonGenerator( out, JsonEncoding.UTF8 );
serialize( object, generator );
generator.flush();
}
/**
* Serializes the object to the given serializeTo.
* <p/>
* The serializer is responsible for writing start/close object/array brackets if necessary.
* This method also writes the @type property.
*
* @param object the object that is serialized
* @param generator the serialize to object
* @throws IOException
*/
@Override
public void serialize( @Nonnull T object, @Nonnull JsonGenerator generator ) throws IOException {
if ( isObjectType() ) {
generator.writeStartObject();
beforeTypeAndVersion( object, generator );
generator.writeStringField( PROPERTY_TYPE, type );
generator.writeStringField( PROPERTY_VERSION, getFormatVersion().format() );
}
serialize( generator, object, getFormatVersion() );
if ( isObjectType() ) {
generator.writeEndObject();
}
}
protected void beforeTypeAndVersion( @Nonnull T object, @Nonnull JsonGenerator serializeTo ) throws IOException {
}
@Nonnull
@Override
public T deserialize( @Nonnull InputStream in ) throws IOException, VersionException {
return deserialize( in, null );
}
@Override
@Nonnull
public T deserialize( @Nonnull JsonParser parser ) throws IOException, JsonProcessingException, InvalidTypeException {
- return deserialize( parser, null );
+ return deserializeInternal( parser, null );
}
@Nonnull
public T deserialize( @Nonnull InputStream in, @Nullable Version version ) throws IOException, VersionException {
try {
JsonFactory jsonFactory = JacksonSupport.getJsonFactory();
JsonParser parser = jsonFactory.createJsonParser( in );
T deserialized = deserializeInternal( parser, version );
ensureParserClosed( parser );
return deserialized;
} catch ( InvalidTypeException e ) {
throw new IOException( "Could not parse due to " + e.getMessage(), e );
}
}
/**
* If the format version override is not null, the type and version field are skipped
* @param parser the parser
* @param formatVersionOverride the format version override (usually "null")
* @return the deserialized object
* @throws IOException
* @throws JsonProcessingException
* @throws InvalidTypeException
*/
@Nonnull
protected T deserializeInternal( @Nonnull JsonParser parser, @Nullable Version formatVersionOverride ) throws IOException, JsonProcessingException, InvalidTypeException {
JacksonParserWrapper wrapper = new JacksonParserWrapper( parser );
Version version = prepareDeserialization( wrapper, formatVersionOverride );
T deserialized = deserialize( parser, version );
if ( isObjectType() ) {
ensureObjectClosed( parser );
}
return deserialized;
}
/**
* Prepares the deserialization.
*
* If the format version is set - the type and version properties are *not* read!
* This can be useful for cases where this information is not available...
*
* @param wrapper the wrapper
* @param formatVersionOverride the format version
* @return the format version
* @throws IOException
* @throws InvalidTypeException
*/
@Nonnull
private Version prepareDeserialization( @Nonnull JacksonParserWrapper wrapper, @Nullable Version formatVersionOverride ) throws IOException, InvalidTypeException {
if ( isObjectType() ) {
wrapper.nextToken( JsonToken.START_OBJECT );
beforeTypeAndVersion( wrapper );
if ( formatVersionOverride == null ) {
wrapper.nextFieldValue( PROPERTY_TYPE );
String readType = wrapper.getText();
verifyType( readType );
wrapper.nextFieldValue( PROPERTY_VERSION );
Version version = Version.parse( wrapper.getText() );
verifyVersionReadable( version );
return version;
} else {
verifyVersionReadable( formatVersionOverride );
return formatVersionOverride;
}
} else {
wrapper.nextToken();
return getFormatVersion();
}
}
/**
* Callback method that is called before the type and version are parsed
*
* @param wrapper the wrapper
*/
protected void beforeTypeAndVersion( @Nonnull JacksonParserWrapper wrapper ) throws IOException, JsonProcessingException, InvalidTypeException {
}
@Deprecated
public static void ensureParserClosedObject( @Nonnull JsonParser parser ) throws IOException {
ensureObjectClosed( parser );
ensureParserClosed( parser );
}
@Deprecated
public static void ensureObjectClosed( @Nonnull JsonParser parser ) throws JsonParseException {
if ( parser.getCurrentToken() != JsonToken.END_OBJECT ) {
throw new JsonParseException( "No consumed everything " + parser.getCurrentToken(), parser.getCurrentLocation() );
}
}
@Deprecated
public static void ensureParserClosed( @Nonnull JsonParser parser ) throws IOException {
if ( parser.nextToken() != null ) {
throw new JsonParseException( "No consumed everything " + parser.getCurrentToken(), parser.getCurrentLocation() );
}
parser.close();
}
/**
* Verifies the next field has the given name and prepares for read (by calling parser.nextToken).
*
* @param parser the parser
* @param fieldName the field name
* @throws IOException
*/
@Deprecated
public static void nextFieldValue( @Nonnull JsonParser parser, @Nonnull String fieldName ) throws IOException {
nextField( parser, fieldName );
parser.nextToken();
}
/**
* Verifies that the next field starts.
* When the content of the field shall be accessed, it is necessary to call parser.nextToken() afterwards.
*
* @param parser the parser
* @param fieldName the field name
* @throws IOException
*/
@Deprecated
public static void nextField( @Nonnull JsonParser parser, @Nonnull String fieldName ) throws IOException {
nextToken( parser, JsonToken.FIELD_NAME );
String currentName = parser.getCurrentName();
if ( !fieldName.equals( currentName ) ) {
throw new JsonParseException( "Invalid field. Expected <" + fieldName + "> but was <" + currentName + ">", parser.getCurrentLocation() );
}
}
@Deprecated
public static void nextToken( @Nonnull JsonParser parser, @Nonnull JsonToken expected ) throws IOException {
parser.nextToken();
verifyCurrentToken( parser, expected );
}
@Deprecated
public static void verifyCurrentToken( @Nonnull JsonParser parser, @Nonnull JsonToken expected ) throws JsonParseException {
JsonToken current = parser.getCurrentToken();
if ( current != expected ) {
throw new JsonParseException( "Invalid token. Expected <" + expected + "> but got <" + current + ">", parser.getCurrentLocation() );
}
}
@Deprecated
public static void closeObject( @Nonnull JsonParser deserializeFrom ) throws IOException {
nextToken( deserializeFrom, JsonToken.END_OBJECT );
}
protected <T> void serializeArray( @Nonnull Iterable<? extends T> elements, @Nonnull Class<T> type, @Nonnull JsonGenerator serializeTo, @Nonnull Version formatVersion ) throws IOException {
serializeArray( elements, type, null, serializeTo, formatVersion );
}
protected <T> void serializeArray( @Nonnull Iterable<? extends T> elements, @Nonnull Class<T> type, @Nullable String propertyName, @Nonnull JsonGenerator serializeTo, @Nonnull Version formatVersion ) throws IOException {
JacksonSerializer<? super T> serializer = getSerializer( type );
Version delegateVersion = delegatesMappings.getVersionMappings().resolveVersion( type, formatVersion );
if ( propertyName == null ) {
serializeTo.writeStartArray();
} else {
serializeTo.writeArrayFieldStart( propertyName );
}
for ( T element : elements ) {
if ( serializer.isObjectType() ) {
serializeTo.writeStartObject();
}
serializer.serialize( serializeTo, element, delegateVersion );
if ( serializer.isObjectType() ) {
serializeTo.writeEndObject();
}
}
serializeTo.writeEndArray();
}
@Nonnull
protected <T> List<? extends T> deserializeArray( @Nonnull Class<T> type, @Nonnull JsonParser deserializeFrom, @Nonnull Version formatVersion ) throws IOException {
return deserializeArray( type, null, deserializeFrom, formatVersion );
}
@Nonnull
protected <T> List<? extends T> deserializeArray( @Nonnull Class<T> type, @Nullable String propertyName, @Nonnull JsonParser deserializeFrom, @Nonnull Version formatVersion ) throws IOException {
if ( propertyName == null ) {
assert deserializeFrom.getCurrentToken() == JsonToken.START_ARRAY;
} else {
nextFieldValue( deserializeFrom, propertyName );
}
List<T> deserialized = new ArrayList<T>();
while ( deserializeFrom.nextToken() != JsonToken.END_ARRAY ) {
deserialized.add( deserialize( type, formatVersion, deserializeFrom ) );
}
return deserialized;
}
public <T> void serialize( @Nullable T object, @Nonnull Class<T> type, @Nonnull String propertyName, @Nonnull JsonGenerator serializeTo, @Nonnull Version formatVersion ) throws JsonProcessingException, IOException {
serializeTo.writeFieldName( propertyName );
//Fast exit if the value is null
if ( object == null ) {
serializeTo.writeNull();
return;
}
JacksonSerializer<? super T> serializer = getSerializer( type );
Version delegateVersion = delegatesMappings.getVersionMappings().resolveVersion( type, formatVersion );
if ( serializer.isObjectType() ) {
serializeTo.writeStartObject();
}
serializer.serialize( serializeTo, object, delegateVersion );
if ( serializer.isObjectType() ) {
serializeTo.writeEndObject();
}
}
@Nullable
protected <T> T deserializeNullable( @Nonnull Class<T> type, @Nonnull String propertyName, @Nonnull Version formatVersion, @Nonnull JsonParser deserializeFrom ) throws IOException, JsonProcessingException {
nextFieldValue( deserializeFrom, propertyName );
if ( deserializeFrom.getCurrentToken() == JsonToken.VALUE_NULL ) {
return null;
}
return deserialize( type, formatVersion, deserializeFrom );
}
@Nonnull
protected <T> T deserialize( @Nonnull Class<T> type, @Nonnull String propertyName, @Nonnull Version formatVersion, @Nonnull JsonParser deserializeFrom ) throws IOException, JsonProcessingException {
nextFieldValue( deserializeFrom, propertyName );
return deserialize( type, formatVersion, deserializeFrom );
}
@Nonnull
@Override
public <T> JacksonSerializer<? super T> getSerializer( @Nonnull Class<T> type ) {
return ( JacksonSerializer<? super T> ) super.getSerializer( type );
}
@Override
public boolean isObjectType() {
return true;
}
public void serializeEnum( @Nonnull Enum<?> enumValue, @Nonnull String propertyName, @Nonnull JsonGenerator serializeTo ) throws IOException {
serializeTo.writeStringField( propertyName, enumValue.name() );
}
@Nonnull
public <T extends Enum<T>> T deserializeEnum( @Nonnull Class<T> enumClass, @Nonnull String propertyName, @Nonnull JacksonParserWrapper parser ) throws IOException {
parser.nextFieldValue( propertyName );
return Enum.valueOf( enumClass, parser.getText() );
}
}
| true | false | null | null |
diff --git a/lib/stackConfiguration/src/main/java/org/sagebionetworks/S3PropertyFileLoader.java b/lib/stackConfiguration/src/main/java/org/sagebionetworks/S3PropertyFileLoader.java
index 86c7a3d4..3d1b8e79 100644
--- a/lib/stackConfiguration/src/main/java/org/sagebionetworks/S3PropertyFileLoader.java
+++ b/lib/stackConfiguration/src/main/java/org/sagebionetworks/S3PropertyFileLoader.java
@@ -1,81 +1,86 @@
package org.sagebionetworks;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
/**
* A helper to load properties files from S3
*
* @author jmhill
*
*/
public class S3PropertyFileLoader {
private static final Logger log = Logger.getLogger(S3PropertyFileLoader.class
.getName());
/**
*
* @param propertyFileUrl
* @param AMIid
* @param AMIkey
* @return
* @throws IOException
*/
public static void loadPropertiesFromS3(String propertyFileUrl, String IAMId, String IAMKey, Properties properties) throws IOException {
log.info("propertyFileUrl="+propertyFileUrl);
log.info("IAMId= "+IAMId);
if (propertyFileUrl == null)throw new IllegalArgumentException("The file URL cannot be null");
if (IAMId == null) throw new IllegalArgumentException("IAM id cannot be null");
if (IAMKey == null) throw new IllegalArgumentException("IAM key cannot be null");
if(properties == null) throw new IllegalArgumentException("Properties cannot be null");
AWSCredentials creds = new BasicAWSCredentials(IAMId, IAMKey);
AmazonS3Client client = new AmazonS3Client(creds);
// Create a temp file to store the properties file.
File temp = null;
FileInputStream in = null;
try {
temp = File.createTempFile("propertyFileUrl", ".tmp");
GetObjectRequest request = createObjectRequestForUrl(propertyFileUrl);
client.getObject(request, temp);
// Read the file
in = new FileInputStream(temp);
properties.load(in);
} finally {
if(in != null) in.close();
if(temp != null) temp.delete();
}
}
/**
*
* @param url
* @return
* @throws MalformedURLException
*/
public static GetObjectRequest createObjectRequestForUrl(
String propertyFileUrl) throws MalformedURLException {
URL url = new URL(propertyFileUrl);
String path = url.getPath();
if (path == null)
throw new IllegalArgumentException(
"Cannot read URL. URL.getPath() was null");
String[] split = path.split("/");
- if (split.length != 3)
+ if (split.length < 3)
throw new IllegalArgumentException(
"Could not get the bucket and object ID from the URL: "+propertyFileUrl);
String bucket = split[1];
String key = split[2];
+ if(split.length > 3) {
+ for(int i = 3; i < split.length; i++) {
+ key += "/" + split[i];
+ }
+ }
return new GetObjectRequest(bucket, key);
}
}
diff --git a/lib/stackConfiguration/src/test/java/org/sagebionetworks/S3PropertyFileLoaderTest.java b/lib/stackConfiguration/src/test/java/org/sagebionetworks/S3PropertyFileLoaderTest.java
index f07dc5c4..a795b82f 100644
--- a/lib/stackConfiguration/src/test/java/org/sagebionetworks/S3PropertyFileLoaderTest.java
+++ b/lib/stackConfiguration/src/test/java/org/sagebionetworks/S3PropertyFileLoaderTest.java
@@ -1,57 +1,71 @@
package org.sagebionetworks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Properties;
import org.junit.Ignore;
import org.junit.Test;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.model.GetObjectRequest;
public class S3PropertyFileLoaderTest {
/**
* This test is ignored because it requires a real url, id, and key.
* It was tested once with with real data.
* @throws IOException
*/
@Test (expected=AmazonServiceException.class)
public void testLoadFails() throws IOException{
String url = "https://s3.amazonaws.com/fake-bucket/fake-file.properties";
String id = "fake-id";
String key = "fake-key";
Properties props = new Properties();
S3PropertyFileLoader.loadPropertiesFromS3(url, id, key, props);
}
/**
* This test is ignored because it requires a real url, id, and key.
* It was tested once with with real data.
* @throws IOException
*/
+ @Test (expected=AmazonServiceException.class)
+ public void testS3FolderUrl() throws IOException{
+ String url = "https://s3.amazonaws.com/fake-bucket/fake-folder/fake-yet-another-folder/fake-file.properties";
+ String id = "fake-id";
+ String key = "fake-key";
+ Properties props = new Properties();
+ S3PropertyFileLoader.loadPropertiesFromS3(url, id, key, props);
+ }
+
+ /**
+ * This test is ignored because it requires a real url, id, and key.
+ * It was tested once with with real data.
+ * @throws IOException
+ */
@Ignore
@Test
public void testLoad() throws IOException{
String url = "Set a real URL to test";
String id = "Set a real ID to test";
String key = "Set a real key to test.";
Properties props = new Properties();
S3PropertyFileLoader.loadPropertiesFromS3(url, id, key, props);
assertNotNull(props.getProperty("org.sagebionetworks.repository.database.connection.url"));
}
@Test
public void testcreateObjectRequestForUrl() throws MalformedURLException{
String propertyFileUrl = "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-325565585839/my-local.properties";
GetObjectRequest request = S3PropertyFileLoader.createObjectRequestForUrl(propertyFileUrl);
assertNotNull(request);
assertEquals("elasticbeanstalk-us-east-1-325565585839", request.getBucketName());
assertEquals("my-local.properties", request.getKey());
}
}
| false | false | null | null |
diff --git a/railo-java/railo-core/src/railo/runtime/CFMLFactoryImpl.java b/railo-java/railo-core/src/railo/runtime/CFMLFactoryImpl.java
index 02d3b7dc6..64320b780 100644
--- a/railo-java/railo-core/src/railo/runtime/CFMLFactoryImpl.java
+++ b/railo-java/railo-core/src/railo/runtime/CFMLFactoryImpl.java
@@ -1,439 +1,448 @@
package railo.runtime;
import java.net.URL;
import java.util.Iterator;
import java.util.Stack;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspEngineInfo;
import railo.commons.io.SystemUtil;
import railo.commons.io.log.Log;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.SizeOf;
import railo.commons.lang.SystemOut;
import railo.runtime.config.ConfigWeb;
import railo.runtime.config.ConfigWebImpl;
import railo.runtime.engine.CFMLEngineImpl;
import railo.runtime.engine.ThreadLocalPageContext;
import railo.runtime.exp.Abort;
import railo.runtime.exp.PageException;
import railo.runtime.exp.PageExceptionImpl;
import railo.runtime.exp.RequestTimeoutException;
import railo.runtime.functions.string.Hash;
import railo.runtime.lock.LockManager;
import railo.runtime.op.Caster;
import railo.runtime.query.QueryCache;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.List;
import railo.runtime.type.Struct;
import railo.runtime.type.StructImpl;
import railo.runtime.type.dt.DateTimeImpl;
import railo.runtime.type.scope.ArgumentIntKey;
import railo.runtime.type.scope.LocalNotSupportedScope;
import railo.runtime.type.scope.ScopeContext;
import railo.runtime.type.util.ArrayUtil;
import railo.runtime.type.util.KeyConstants;
/**
* implements a JSP Factory, this class produce JSP Compatible PageContext Object
* this object holds also the must interfaces to coldfusion specified functionlity
*/
public final class CFMLFactoryImpl extends CFMLFactory {
private static JspEngineInfo info=new JspEngineInfoImpl("1.0");
private ConfigWebImpl config;
Stack<PageContext> pcs=new Stack<PageContext>();
private Struct runningPcs=new StructImpl();
int idCounter=1;
private QueryCache queryCache;
private ScopeContext scopeContext=new ScopeContext(this);
private HttpServlet servlet;
private URL url=null;
private CFMLEngineImpl engine;
/**
* constructor of the JspFactory
* @param config Railo specified Configuration
* @param compiler CFML compiler
* @param engine
*/
public CFMLFactoryImpl(CFMLEngineImpl engine,QueryCache queryCache) {
this.engine=engine;
this.queryCache=queryCache;
}
/**
* reset the PageContexes
*/
public void resetPageContext() {
SystemOut.printDate(config.getOutWriter(),"Reset "+pcs.size()+" Unused PageContexts");
synchronized(pcs) {
pcs.clear();
}
+
+ if(runningPcs!=null) {
+ synchronized(runningPcs) {
+ Iterator<Object> it = runningPcs.valueIterator();
+ while(it.hasNext()){
+ ((PageContextImpl)it.next()).reset();
+ }
+ }
+ }
}
/**
* @see javax.servlet.jsp.JspFactory#getPageContext(javax.servlet.Servlet, javax.servlet.ServletRequest, javax.servlet.ServletResponse, java.lang.String, boolean, int, boolean)
*/
public javax.servlet.jsp.PageContext getPageContext(
Servlet servlet,
ServletRequest req,
ServletResponse rsp,
String errorPageURL,
boolean needsSession,
int bufferSize,
boolean autoflush) {
return getPageContextImpl((HttpServlet)servlet,(HttpServletRequest)req,(HttpServletResponse)rsp,errorPageURL,needsSession,bufferSize,autoflush,true,false);
}
/**
* similar to getPageContext Method but return the concrete implementation of the railo PageCOntext
* and take the HTTP Version of the Servlet Objects
* @param servlet
* @param req
* @param rsp
* @param errorPageURL
* @param needsSession
* @param bufferSize
* @param autoflush
* @return return the page<context
*/
public PageContext getRailoPageContext(
HttpServlet servlet,
HttpServletRequest req,
HttpServletResponse rsp,
String errorPageURL,
boolean needsSession,
int bufferSize,
boolean autoflush) {
//runningCount++;
return getPageContextImpl(servlet, req, rsp, errorPageURL, needsSession, bufferSize, autoflush,true,false);
}
public PageContextImpl getPageContextImpl(
HttpServlet servlet,
HttpServletRequest req,
HttpServletResponse rsp,
String errorPageURL,
boolean needsSession,
int bufferSize,
boolean autoflush,boolean registerPageContext2Thread,boolean isChild) {
//runningCount++;
PageContextImpl pc;
synchronized (pcs) {
if(pcs.isEmpty()) pc=new PageContextImpl(scopeContext,config,queryCache,idCounter++,servlet);
else pc=((PageContextImpl)pcs.pop());
runningPcs.setEL(ArgumentIntKey.init(pc.getId()),pc);
this.servlet=servlet;
if(registerPageContext2Thread)ThreadLocalPageContext.register(pc);
}
pc.initialize(servlet,req,rsp,errorPageURL,needsSession,bufferSize,autoflush,isChild);
return pc;
}
/**
* @see javax.servlet.jsp.JspFactory#releasePageContext(javax.servlet.jsp.PageContext)
*/
public void releasePageContext(javax.servlet.jsp.PageContext pc) {
releaseRailoPageContext((PageContext)pc);
}
/**
* Similar to the releasePageContext Method, but take railo PageContext as entry
* @param pc
*/
public void releaseRailoPageContext(PageContext pc) {
if(pc.getId()<0)return;
pc.release();
ThreadLocalPageContext.release();
//if(!pc.hasFamily()){
synchronized (runningPcs) {
runningPcs.removeEL(ArgumentIntKey.init(pc.getId()));
if(pcs.size()<100)// not more than 100 PCs
pcs.push(pc);
//SystemOut.printDate(config.getOutWriter(),"Release: (id:"+pc.getId()+";running-requests:"+config.getThreadQueue().size()+";)");
}
/*}
else {
SystemOut.printDate(config.getOutWriter(),"Unlink: ("+pc.getId()+")");
}*/
}
/**
* check timeout of all running threads, downgrade also priority from all thread run longer than 10 seconds
*/
public void checkTimeout() {
if(!engine.allowRequestTimeout())return;
synchronized (runningPcs) {
//int len=runningPcs.size();
Iterator it = runningPcs.keyIterator();
PageContext pc;
Collection.Key key;
while(it.hasNext()) {
key=KeyImpl.toKey(it.next(),null);
//print.out("key:"+key);
pc=(PageContext) runningPcs.get(key,null);
if(pc==null) {
runningPcs.removeEL(key);
continue;
}
long timeout=pc.getRequestTimeout();
if(pc.getStartTime()+timeout<System.currentTimeMillis()) {
terminate(pc);
}
// after 10 seconds downgrade priority of the thread
else if(pc.getStartTime()+10000<System.currentTimeMillis() && pc.getThread().getPriority()!=Thread.MIN_PRIORITY) {
Log log = config.getRequestTimeoutLogger();
if(log!=null)log.warn("controler","downgrade priority of the a thread at "+getPath(pc));
try {
pc.getThread().setPriority(Thread.MIN_PRIORITY);
}
catch(Throwable t) {}
}
}
}
}
public static void terminate(PageContext pc) {
Log log = pc.getConfig().getRequestTimeoutLogger();
String strLocks="";
try{
LockManager manager = pc.getConfig().getLockManager();
String[] locks = manager.getOpenLockNames();
if(!ArrayUtil.isEmpty(locks))
strLocks=" open locks at this time ("+List.arrayToList(locks, ", ")+").";
//LockManagerImpl.unlockAll(pc.getId());
}
catch(Throwable t){}
if(log!=null)log.error("controler",
"stop thread ("+pc.getId()+") because run into a timeout "+getPath(pc)+"."+strLocks);
pc.getThread().stop(new RequestTimeoutException(pc,"request ("+getPath(pc)+":"+pc.getId()+") is run into a timeout ("+(pc.getRequestTimeout()/1000)+" seconds) and has been stopped."+strLocks));
}
private static String getPath(PageContext pc) {
try {
String base=ResourceUtil.getResource(pc, pc.getBasePageSource()).getAbsolutePath();
String current=ResourceUtil.getResource(pc, pc.getCurrentPageSource()).getAbsolutePath();
if(base.equals(current)) return "path: "+base;
return "path: "+base+" ("+current+")";
}
catch(Throwable t) {
return "";
}
}
/**
* @see javax.servlet.jsp.JspFactory#getEngineInfo()
*/
public JspEngineInfo getEngineInfo() {
return info;
}
/**
* @return returns count of pagecontext in use
*/
public int getUsedPageContextLength() {
int length=0;
try{
Iterator it = runningPcs.values().iterator();
while(it.hasNext()){
PageContextImpl pc=(PageContextImpl) it.next();
if(!pc.isGatewayContext()) length++;
}
}
catch(Throwable t){
return length;
}
return length;
}
/**
* @return Returns the config.
*/
public ConfigWeb getConfig() {
return config;
}
public ConfigWebImpl getConfigWebImpl() {
return config;
}
/**
* @return Returns the scopeContext.
*/
public ScopeContext getScopeContext() {
return scopeContext;
}
/**
* @return label of the factory
*/
public Object getLabel() {
return ((ConfigWebImpl)getConfig()).getLabel();
}
/**
* @param label
*/
public void setLabel(String label) {
// deprecated
}
/**
* @return the hostName
*/
public URL getURL() {
return url;
}
public void setURL(URL url) {
this.url=url;
}
/**
* @return the servlet
*/
public HttpServlet getServlet() {
return servlet;
}
public void setConfig(ConfigWebImpl config) {
this.config=config;
}
public Struct getRunningPageContextes() {
return runningPcs;
}
public long getPageContextesSize() {
return SizeOf.size(pcs);
}
public Array getInfo() {
Array info=new ArrayImpl();
synchronized (runningPcs) {
//int len=runningPcs.size();
Iterator<Key> it = runningPcs.keyIterator();
PageContextImpl pc;
Struct data,sctThread,scopes;
Collection.Key key;
Thread thread;
while(it.hasNext()) {
data=new StructImpl();
sctThread=new StructImpl();
scopes=new StructImpl();
data.setEL("thread", sctThread);
data.setEL("scopes", scopes);
key=KeyImpl.toKey(it.next(),null);
//print.out("key:"+key);
pc=(PageContextImpl) runningPcs.get(key,null);
if(pc==null || pc.isGatewayContext()) continue;
thread=pc.getThread();
if(thread==Thread.currentThread()) continue;
thread=pc.getThread();
if(thread==Thread.currentThread()) continue;
data.setEL("startTime", new DateTimeImpl(pc.getStartTime(),false));
data.setEL("endTime", new DateTimeImpl(pc.getStartTime()+pc.getRequestTimeout(),false));
data.setEL(KeyConstants._timeout,new Double(pc.getRequestTimeout()));
// thread
sctThread.setEL(KeyConstants._name,thread.getName());
sctThread.setEL("priority",Caster.toDouble(thread.getPriority()));
data.setEL("TagContext",PageExceptionImpl.getTagContext(pc.getConfig(),thread.getStackTrace() ));
data.setEL("urlToken", pc.getURLToken());
try {
data.setEL("debugger", pc.getDebugger().getDebuggingData(pc));
} catch (PageException e2) {}
try {
data.setEL("id", Hash.call(pc, pc.getId()+":"+pc.getStartTime()));
} catch (PageException e1) {}
data.setEL("requestid", pc.getId());
// Scopes
scopes.setEL(KeyConstants._name, pc.getApplicationContext().getName());
try {
scopes.setEL(KeyConstants._application, pc.applicationScope());
} catch (PageException e) {}
try {
scopes.setEL(KeyConstants._session, pc.sessionScope());
} catch (PageException e) {}
try {
scopes.setEL(KeyConstants._client, pc.clientScope());
} catch (PageException e) {}
scopes.setEL(KeyConstants._cookie, pc.cookieScope());
scopes.setEL(KeyConstants._variables, pc.variablesScope());
if(!(pc.localScope() instanceof LocalNotSupportedScope)){
scopes.setEL(KeyConstants._local, pc.localScope());
scopes.setEL(KeyConstants._arguments, pc.argumentsScope());
}
scopes.setEL(KeyConstants._cgi, pc.cgiScope());
scopes.setEL(KeyConstants._form, pc.formScope());
scopes.setEL(KeyConstants._url, pc.urlScope());
scopes.setEL(KeyConstants._request, pc.requestScope());
info.appendEL(data);
}
return info;
}
}
public void stopThread(String threadId, String stopType) {
synchronized (runningPcs) {
//int len=runningPcs.size();
Iterator it = runningPcs.keyIterator();
PageContext pc;
while(it.hasNext()) {
pc=(PageContext) runningPcs.get(KeyImpl.toKey(it.next(),null),null);
if(pc==null) continue;
try {
String id = Hash.call(pc, pc.getId()+":"+pc.getStartTime());
if(id.equals(threadId)){
stopType=stopType.trim();
Throwable t;
if("abort".equalsIgnoreCase(stopType) || "cfabort".equalsIgnoreCase(stopType))
t=new Abort(Abort.SCOPE_REQUEST);
else
t=new RequestTimeoutException(pc,"request has been forced to stop.");
pc.getThread().stop(t);
SystemUtil.sleep(10);
break;
}
} catch (PageException e1) {}
}
}
}
@Override
public QueryCache getDefaultQueryCache() {
return queryCache;
}
}
\ No newline at end of file
diff --git a/railo-java/railo-core/src/railo/runtime/PageContextImpl.java b/railo-java/railo-core/src/railo/runtime/PageContextImpl.java
index 8aa040168..28ba6dbbf 100755
--- a/railo-java/railo-core/src/railo/runtime/PageContextImpl.java
+++ b/railo-java/railo-core/src/railo/runtime/PageContextImpl.java
@@ -1,3281 +1,3285 @@
package railo.runtime;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TryCatchFinally;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import railo.commons.io.BodyContentStack;
import railo.commons.io.IOUtil;
import railo.commons.io.res.Resource;
import railo.commons.io.res.util.ResourceClassLoader;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.PhysicalClassLoader;
import railo.commons.lang.SizeOf;
import railo.commons.lang.StringUtil;
import railo.commons.lang.SystemOut;
import railo.commons.lang.mimetype.MimeType;
import railo.commons.lang.types.RefBoolean;
import railo.commons.lang.types.RefBooleanImpl;
import railo.commons.lock.KeyLock;
import railo.commons.lock.Lock;
import railo.commons.net.HTTPUtil;
import railo.intergral.fusiondebug.server.FDSignal;
import railo.runtime.component.ComponentLoader;
import railo.runtime.config.Config;
import railo.runtime.config.ConfigImpl;
import railo.runtime.config.ConfigWeb;
import railo.runtime.config.ConfigWebImpl;
import railo.runtime.config.Constants;
import railo.runtime.db.DataSource;
import railo.runtime.db.DataSourceManager;
import railo.runtime.db.DatasourceConnection;
import railo.runtime.db.DatasourceConnectionPool;
import railo.runtime.db.DatasourceManagerImpl;
import railo.runtime.db.debug.DebugQuery;
import railo.runtime.debug.DebugEntryTemplate;
import railo.runtime.debug.Debugger;
import railo.runtime.debug.DebuggerImpl;
import railo.runtime.dump.DumpUtil;
import railo.runtime.dump.DumpWriter;
import railo.runtime.engine.ExecutionLog;
import railo.runtime.engine.ThreadLocalPageContext;
import railo.runtime.err.ErrorPage;
import railo.runtime.err.ErrorPageImpl;
import railo.runtime.err.ErrorPagePool;
import railo.runtime.exp.Abort;
import railo.runtime.exp.ApplicationException;
import railo.runtime.exp.CasterException;
import railo.runtime.exp.ExceptionHandler;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.MissingIncludeException;
import railo.runtime.exp.PageException;
import railo.runtime.exp.PageExceptionBox;
import railo.runtime.exp.PageServletException;
import railo.runtime.functions.dynamicEvaluation.Serialize;
import railo.runtime.interpreter.CFMLExpressionInterpreter;
import railo.runtime.interpreter.VariableInterpreter;
import railo.runtime.listener.AppListenerSupport;
import railo.runtime.listener.ApplicationContext;
import railo.runtime.listener.ApplicationListener;
import railo.runtime.listener.ClassicApplicationContext;
import railo.runtime.listener.JavaSettings;
import railo.runtime.listener.JavaSettingsImpl;
import railo.runtime.listener.ModernAppListenerException;
import railo.runtime.monitor.RequestMonitor;
import railo.runtime.net.ftp.FTPPool;
import railo.runtime.net.ftp.FTPPoolImpl;
import railo.runtime.net.http.HTTPServletRequestWrap;
import railo.runtime.net.http.ReqRspUtil;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.orm.ORMConfiguration;
import railo.runtime.orm.ORMEngine;
import railo.runtime.orm.ORMSession;
import railo.runtime.query.QueryCache;
import railo.runtime.rest.RestRequestListener;
import railo.runtime.rest.RestUtil;
import railo.runtime.security.Credential;
import railo.runtime.security.CredentialImpl;
import railo.runtime.tag.Login;
import railo.runtime.tag.TagHandlerPool;
import railo.runtime.type.Array;
import railo.runtime.type.Collection;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.Iterator;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.Query;
import railo.runtime.type.SVArray;
import railo.runtime.type.Sizeable;
import railo.runtime.type.Struct;
import railo.runtime.type.StructImpl;
import railo.runtime.type.UDF;
import railo.runtime.type.it.ItAsEnum;
import railo.runtime.type.ref.Reference;
import railo.runtime.type.ref.VariableReference;
import railo.runtime.type.scope.Application;
import railo.runtime.type.scope.Argument;
import railo.runtime.type.scope.ArgumentImpl;
import railo.runtime.type.scope.CGI;
import railo.runtime.type.scope.CGIImpl;
import railo.runtime.type.scope.Client;
import railo.runtime.type.scope.Cluster;
import railo.runtime.type.scope.Cookie;
import railo.runtime.type.scope.CookieImpl;
import railo.runtime.type.scope.Form;
import railo.runtime.type.scope.FormImpl;
import railo.runtime.type.scope.Local;
import railo.runtime.type.scope.LocalNotSupportedScope;
import railo.runtime.type.scope.Request;
import railo.runtime.type.scope.RequestImpl;
import railo.runtime.type.scope.Scope;
import railo.runtime.type.scope.ScopeContext;
import railo.runtime.type.scope.ScopeFactory;
import railo.runtime.type.scope.ScopeSupport;
import railo.runtime.type.scope.Server;
import railo.runtime.type.scope.Session;
import railo.runtime.type.scope.Threads;
import railo.runtime.type.scope.URL;
import railo.runtime.type.scope.URLForm;
import railo.runtime.type.scope.URLImpl;
import railo.runtime.type.scope.Undefined;
import railo.runtime.type.scope.UndefinedImpl;
import railo.runtime.type.scope.UrlFormImpl;
import railo.runtime.type.scope.Variables;
import railo.runtime.type.scope.VariablesImpl;
import railo.runtime.type.util.KeyConstants;
import railo.runtime.util.VariableUtil;
import railo.runtime.util.VariableUtilImpl;
import railo.runtime.writer.CFMLWriter;
import railo.runtime.writer.DevNullBodyContent;
/**
* page context for every page object.
* the PageContext is a jsp page context expanded by CFML functionality.
* for example you have the method getSession to get jsp combatible session object (HTTPSession)
* and with sessionScope() you get CFML combatible session object (Struct,Scope).
*/
public final class PageContextImpl extends PageContext implements Sizeable {
private static final RefBoolean DUMMY_BOOL = new RefBooleanImpl(false);
private static int counter=0;
/**
* Field <code>pathList</code>
*/
private LinkedList<UDF> udfs=new LinkedList<UDF>();
private LinkedList<PageSource> pathList=new LinkedList<PageSource>();
private LinkedList<PageSource> includePathList=new LinkedList<PageSource>();
private Set<PageSource> includeOnce=new HashSet<PageSource>();
/**
* Field <code>executionTime</code>
*/
protected int executionTime=0;
private HTTPServletRequestWrap req;
private HttpServletResponse rsp;
private HttpServlet servlet;
private JspWriter writer;
private JspWriter forceWriter;
private BodyContentStack bodyContentStack;
private DevNullBodyContent devNull;
private ConfigWebImpl config;
//private DataSourceManager manager;
//private CFMLCompilerImpl compiler;
// Scopes
private ScopeContext scopeContext;
private Variables variablesRoot=new VariablesImpl();//ScopeSupport(false,"variables",Scope.SCOPE_VARIABLES);
private Variables variables=variablesRoot;//new ScopeSupport("variables",Scope.SCOPE_VARIABLES);
private Undefined undefined;
private URLImpl _url=new URLImpl();
private FormImpl _form=new FormImpl();
private URLForm urlForm=new UrlFormImpl(_form,_url);
private URL url;
private Form form;
private RequestImpl request=new RequestImpl();
private CGIImpl cgi=new CGIImpl();
private Argument argument=new ArgumentImpl();
private static LocalNotSupportedScope localUnsupportedScope=LocalNotSupportedScope.getInstance();
private Local local=localUnsupportedScope;
private Session session;
private Server server;
private Cluster cluster;
private CookieImpl cookie=new CookieImpl();
private Client client;
private Application application;
private DebuggerImpl debugger=new DebuggerImpl();
private long requestTimeout=-1;
private short enablecfoutputonly=0;
private int outputState;
private String cfid;
private String cftoken;
private int id;
private int requestId;
private boolean psq;
private Locale locale;
private TimeZone timeZone;
// Pools
private ErrorPagePool errorPagePool=new ErrorPagePool();
private TagHandlerPool tagHandlerPool;
private FTPPool ftpPool=new FTPPoolImpl();
private final QueryCache queryCache;
private Component activeComponent;
private UDF activeUDF;
//private ComponentScope componentScope=new ComponentScope(this);
private Credential remoteUser;
protected VariableUtilImpl variableUtil=new VariableUtilImpl();
private PageException exception;
private PageSource base;
ApplicationContext applicationContext;
ApplicationContext defaultApplicationContext;
private ScopeFactory scopeFactory=new ScopeFactory();
private Tag parentTag=null;
private Tag currentTag=null;
private Thread thread;
private long startTime;
private boolean isCFCRequest;
private DatasourceManagerImpl manager;
private Struct threads;
private boolean hasFamily=false;
//private CFMLFactoryImpl factory;
private PageContextImpl parent;
private Map<String,DatasourceConnection> conns=new HashMap<String,DatasourceConnection>();
private boolean fdEnabled;
private ExecutionLog execLog;
private boolean useSpecialMappings;
private ORMSession ormSession;
private boolean isChild;
private boolean gatewayContext;
private String serverPassword;
public long sizeOf() {
return
SizeOf.size(pathList)+
SizeOf.size(includePathList)+
SizeOf.size(executionTime)+
SizeOf.size(writer)+
SizeOf.size(forceWriter)+
SizeOf.size(bodyContentStack)+
SizeOf.size(variables)+
SizeOf.size(url)+
SizeOf.size(form)+
SizeOf.size(_url)+
SizeOf.size(_form)+
SizeOf.size(request)+
SizeOf.size(argument)+
SizeOf.size(local)+
SizeOf.size(cookie)+
SizeOf.size(debugger)+
SizeOf.size(requestTimeout)+
SizeOf.size(enablecfoutputonly)+
SizeOf.size(outputState)+
SizeOf.size(cfid)+
SizeOf.size(cftoken)+
SizeOf.size(id)+
SizeOf.size(psq)+
SizeOf.size(locale)+
SizeOf.size(errorPagePool)+
SizeOf.size(tagHandlerPool)+
SizeOf.size(ftpPool)+
SizeOf.size(activeComponent)+
SizeOf.size(activeUDF)+
SizeOf.size(remoteUser)+
SizeOf.size(exception)+
SizeOf.size(base)+
SizeOf.size(applicationContext)+
SizeOf.size(defaultApplicationContext)+
SizeOf.size(parentTag)+
SizeOf.size(currentTag)+
SizeOf.size(startTime)+
SizeOf.size(isCFCRequest)+
SizeOf.size(conns)+
SizeOf.size(serverPassword)+
SizeOf.size(ormSession);
}
/**
* default Constructor
* @param factoryImpl
* @param scopeContext
* @param config Configuration of the CFML Container
* @param compiler CFML Compiler
* @param queryCache Query Cache Object
* @param id identity of the pageContext
*/
public PageContextImpl(ScopeContext scopeContext, ConfigWebImpl config, QueryCache queryCache,int id,HttpServlet servlet) {
// must be first because is used after
tagHandlerPool=config.getTagHandlerPool();
this.servlet=servlet;
this.id=id;
//this.factory=factory;
bodyContentStack=new BodyContentStack();
devNull=bodyContentStack.getDevNullBodyContent();
this.config=config;
manager=new DatasourceManagerImpl(config);
this.scopeContext=scopeContext;
undefined=
new UndefinedImpl(this,config.getScopeCascadingType());
//this.compiler=compiler;
//tagHandlerPool=config.getTagHandlerPool();
this.queryCache=queryCache;
server=ScopeContext.getServerScope(this);
defaultApplicationContext=new ClassicApplicationContext(config,"",true,null);
}
/**
* @see javax.servlet.jsp.PageContext#initialize(javax.servlet.Servlet, javax.servlet.ServletRequest, javax.servlet.ServletResponse, java.lang.String, boolean, int, boolean)
*/
public void initialize(
Servlet servlet,
ServletRequest req,
ServletResponse rsp,
String errorPageURL,
boolean needsSession,
int bufferSize,
boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException {
initialize(
(HttpServlet)servlet,
(HttpServletRequest)req,
(HttpServletResponse)rsp,
errorPageURL,
needsSession,
bufferSize,
autoFlush,false);
}
/**
* initialize a existing page context
* @param servlet
* @param req
* @param rsp
* @param errorPageURL
* @param needsSession
* @param bufferSize
* @param autoFlush
*/
public PageContextImpl initialize(
HttpServlet servlet,
HttpServletRequest req,
HttpServletResponse rsp,
String errorPageURL,
boolean needsSession,
int bufferSize,
boolean autoFlush,
boolean isChild) {
requestId=counter++;
rsp.setContentType("text/html; charset=UTF-8");
this.isChild=isChild;
//rsp.setHeader("Connection", "close");
applicationContext=defaultApplicationContext;
startTime=System.currentTimeMillis();
thread=Thread.currentThread();
isCFCRequest = StringUtil.endsWithIgnoreCase(req.getServletPath(),"."+config.getCFCExtension());
this.req=new HTTPServletRequestWrap(req);
this.rsp=rsp;
this.servlet=servlet;
// Writers
bodyContentStack.init(req,rsp,config.isSuppressWhitespace(),config.closeConnection(),config.isShowVersion(),config.contentLength(),config.allowCompression());
writer=bodyContentStack.getWriter();
forceWriter=writer;
// Scopes
server=ScopeContext.getServerScope(this);
if(hasFamily) {
variablesRoot=new VariablesImpl();
variables=variablesRoot;
request=new RequestImpl();
_url=new URLImpl();
_form=new FormImpl();
urlForm=new UrlFormImpl(_form,_url);
undefined=
new UndefinedImpl(this,config.getScopeCascadingType());
hasFamily=false;
}
else if(variables==null) {
variablesRoot=new VariablesImpl();
variables=variablesRoot;
}
request.initialize(this);
if(config.mergeFormAndURL()) {
url=urlForm;
form=urlForm;
}
else {
url=_url;
form=_form;
}
//url.initialize(this);
//form.initialize(this);
//undefined.initialize(this);
psq=config.getPSQL();
fdEnabled=!config.allowRequestTimeout();
if(config.getExecutionLogEnabled())
this.execLog=config.getExecutionLogFactory().getInstance(this);
if(config.debug())
debugger.init(config);
return this;
}
/**
* @see javax.servlet.jsp.PageContext#release()
*/
public void release() {
if(config.debug()) {
if(!gatewayContext)config.getDebuggerPool().store(this, debugger);
debugger.reset();
}
this.serverPassword=null;
boolean isChild=parent!=null;
parent=null;
// Attention have to be before close
if(client!=null){
client.touchAfterRequest(this);
client=null;
}
if(session!=null){
session.touchAfterRequest(this);
session=null;
}
// ORM
if(ormSession!=null){
// flush orm session
try {
ORMEngine engine=ormSession.getEngine();
ORMConfiguration config=engine.getConfiguration(this);
if(config==null || (config.flushAtRequestEnd() && config.autoManageSession())){
ormSession.flush(this);
//ormSession.close(this);
//print.err("2orm flush:"+Thread.currentThread().getId());
}
ormSession.close(this);
}
catch (Throwable t) {
//print.printST(t);
}
// release connection
DatasourceConnectionPool pool = this.config.getDatasourceConnectionPool();
DatasourceConnection dc=ormSession.getDatasourceConnection();
if(dc!=null)pool.releaseDatasourceConnection(dc);
ormSession=null;
}
close();
thread=null;
base=null;
//RequestImpl r = request;
// Scopes
if(hasFamily) {
if(!isChild){
req.disconnect();
}
request=null;
_url=null;
_form=null;
urlForm=null;
undefined=null;
variables=null;
variablesRoot=null;
if(threads!=null && threads.size()>0) threads.clear();
}
else {
if(variables.isBind()) {
variables=null;
variablesRoot=null;
}
else {
variables=variablesRoot;
variables.release();
}
undefined.release();
urlForm.release();
request.release();
}
cgi.release();
argument.release();
local=localUnsupportedScope;
cookie.release();
//if(cluster!=null)cluster.release();
//client=null;
//session=null;
application=null;// not needed at the moment -> application.releaseAfterRequest();
applicationContext=null;
// Properties
requestTimeout=-1;
outputState=0;
cfid=null;
cftoken=null;
locale=null;
timeZone=null;
url=null;
form=null;
// Pools
errorPagePool.clear();
// transaction connection
if(!conns.isEmpty()){
java.util.Iterator<Entry<String, DatasourceConnection>> it = conns.entrySet().iterator();
DatasourceConnectionPool pool = config.getDatasourceConnectionPool();
while(it.hasNext()) {
pool.releaseDatasourceConnection((it.next().getValue()));
}
conns.clear();
}
pathList.clear();
includePathList.clear();
executionTime=0;
bodyContentStack.release();
//activeComponent=null;
remoteUser=null;
exception=null;
ftpPool.clear();
parentTag=null;
currentTag=null;
// Req/Rsp
//if(req!=null)
req.clear();
req=null;
rsp=null;
servlet=null;
// Writer
writer=null;
forceWriter=null;
if(pagesUsed.size()>0)pagesUsed.clear();
activeComponent=null;
activeUDF=null;
if(config.getExecutionLogEnabled()){
execLog.release();
execLog=null;
}
gatewayContext=false;
manager.release();
includeOnce.clear();
}
/**
* @see railo.runtime.PageContext#write(java.lang.String)
*/
public void write(String str) throws IOException {
writer.write(str);
}
/**
* @see railo.runtime.PageContext#forceWrite(java.lang.String)
*/
public void forceWrite(String str) throws IOException {
forceWriter.write(str);
}
/**
* @see railo.runtime.PageContext#writePSQ(java.lang.Object)
*/
public void writePSQ(Object o) throws IOException, PageException {
if(o instanceof Date || Decision.isDate(o, false)) {
writer.write(Caster.toString(o));
}
else {
writer.write(psq?Caster.toString(o):StringUtil.replace(Caster.toString(o),"'","''",false));
}
}
/**
* @see railo.runtime.PageContext#flush()
*/
public void flush() {
try {
getOut().flush();
} catch (IOException e) {}
}
/**
* @see railo.runtime.PageContext#close()
*/
public void close() {
IOUtil.closeEL(getOut());
}
/**
* @see railo.runtime.PageContext#getRelativePageSource(java.lang.String)
*/
public PageSource getRelativePageSource(String realPath) {
SystemOut.print(config.getOutWriter(),"method getRelativePageSource is deprecated");
if(StringUtil.startsWith(realPath,'/')) return PageSourceImpl.best(getPageSources(realPath));
if(pathList.size()==0) return null;
return pathList.getLast().getRealPage(realPath);
}
public PageSource getRelativePageSourceExisting(String realPath) {
if(StringUtil.startsWith(realPath,'/')) return getPageSourceExisting(realPath);
if(pathList.size()==0) return null;
PageSource ps = pathList.getLast().getRealPage(realPath);
if(PageSourceImpl.pageExist(ps)) return ps;
return null;
}
public PageSource[] getRelativePageSources(String realPath) {
if(StringUtil.startsWith(realPath,'/')) return getPageSources(realPath);
if(pathList.size()==0) return null;
return new PageSource[]{ pathList.getLast().getRealPage(realPath)};
}
public PageSource getPageSource(String realPath) {
SystemOut.print(config.getOutWriter(),"method getPageSource is deprecated");
return PageSourceImpl.best(config.getPageSources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true));
}
public PageSource[] getPageSources(String realPath) {
return config.getPageSources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true);
}
public PageSource getPageSourceExisting(String realPath) {
return config.getPageSourceExisting(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true,false);
}
public boolean useSpecialMappings(boolean useTagMappings) {
boolean b=this.useSpecialMappings;
this.useSpecialMappings=useTagMappings;
return b;
}
public boolean useSpecialMappings() {
return useSpecialMappings;
}
public Resource getPhysical(String realPath, boolean alsoDefaultMapping){
return config.getPhysical(applicationContext.getMappings(),realPath, alsoDefaultMapping);
}
public PageSource toPageSource(Resource res, PageSource defaultValue){
return config.toPageSource(applicationContext.getMappings(),res, defaultValue);
}
@Override
public void doInclude(String realPath) throws PageException {
doInclude(getRelativePageSources(realPath),false);
}
@Override
public void doInclude(String realPath, boolean runOnce) throws PageException {
doInclude(getRelativePageSources(realPath),runOnce);
}
@Override
public void doInclude(PageSource source) throws PageException {
doInclude(new PageSource[]{source},false);
}
@Override
public void doInclude(PageSource[] sources, boolean runOnce) throws PageException {
// debug
if(!gatewayContext && config.debug()) {
int currTime=executionTime;
long exeTime=0;
long time=System.nanoTime();
Page currentPage = PageSourceImpl.loadPage(this, sources);
if(runOnce && includeOnce.contains(currentPage.getPageSource())) return;
DebugEntryTemplate debugEntry=debugger.getEntry(this,currentPage.getPageSource());
try {
addPageSource(currentPage.getPageSource(),true);
debugEntry.updateFileLoadTime((int)(System.nanoTime()-time));
exeTime=System.nanoTime();
currentPage.call(this);
}
catch(Throwable t){
PageException pe = Caster.toPageException(t);
if(Abort.isAbort(pe)) {
if(Abort.isAbort(pe,Abort.SCOPE_REQUEST))throw pe;
}
else {
if(fdEnabled){
FDSignal.signal(pe, false);
}
pe.addContext(currentPage.getPageSource(),-187,-187, null);// TODO was soll das 187
throw pe;
}
}
finally {
includeOnce.add(currentPage.getPageSource());
int diff= ((int)(System.nanoTime()-exeTime)-(executionTime-currTime));
executionTime+=(int)(System.nanoTime()-time);
debugEntry.updateExeTime(diff);
removeLastPageSource(true);
}
}
// no debug
else {
Page currentPage = PageSourceImpl.loadPage(this, sources);
if(runOnce && includeOnce.contains(currentPage.getPageSource())) return;
try {
addPageSource(currentPage.getPageSource(),true);
currentPage.call(this);
}
catch(Throwable t){
PageException pe = Caster.toPageException(t);
if(Abort.isAbort(pe)) {
if(Abort.isAbort(pe,Abort.SCOPE_REQUEST))throw pe;
}
else {
pe.addContext(currentPage.getPageSource(),-187,-187, null);
throw pe;
}
}
finally {
includeOnce.add(currentPage.getPageSource());
removeLastPageSource(true);
}
}
}
/**
* @see railo.runtime.PageContext#getTemplatePath()
*/
public Array getTemplatePath() throws PageException {
int len=includePathList.size();
SVArray sva = new SVArray();
PageSource ps;
for(int i=0;i<len;i++) {
ps=includePathList.get(i);
if(i==0) {
if(!ps.equals(getBasePageSource()))
sva.append(ResourceUtil.getResource(this,getBasePageSource()).getAbsolutePath());
}
sva.append(ResourceUtil.getResource(this, ps).getAbsolutePath());
}
//sva.setPosition(sva.size());
return sva;
}
public List<PageSource> getPageSourceList() {
return (List<PageSource>) pathList.clone();
}
protected PageSource getPageSource(int index) {
return includePathList.get(index-1);
}
public synchronized void copyStateTo(PageContextImpl other) {
// private Debugger debugger=new DebuggerImpl();
other.requestTimeout=requestTimeout;
other.locale=locale;
other.timeZone=timeZone;
other.fdEnabled=fdEnabled;
other.useSpecialMappings=useSpecialMappings;
other.serverPassword=serverPassword;
hasFamily=true;
other.hasFamily=true;
other.parent=this;
other.applicationContext=applicationContext;
other.thread=Thread.currentThread();
other.startTime=System.currentTimeMillis();
other.isCFCRequest = isCFCRequest;
// path
other.base=base;
java.util.Iterator<PageSource> it = includePathList.iterator();
while(it.hasNext()) {
other.includePathList.add(it.next());
}
it = pathList.iterator();
while(it.hasNext()) {
other.pathList.add(it.next());
}
// scopes
//other.req.setAttributes(request);
/*HttpServletRequest org = other.req.getOriginalRequest();
if(org instanceof HttpServletRequestDummy) {
((HttpServletRequestDummy)org).setAttributes(request);
}*/
other.req=req;
other.request=request;
other.form=form;
other.url=url;
other.urlForm=urlForm;
other._url=_url;
other._form=_form;
other.variables=variables;
other.undefined=new UndefinedImpl(other,(short)other.undefined.getType());
// writers
other.bodyContentStack.init(other.req,other.rsp,other.config.isSuppressWhitespace(),other.config.closeConnection(),
other.config.isShowVersion(),config.contentLength(),config.allowCompression());
other.writer=other.bodyContentStack.getWriter();
other.forceWriter=other.writer;
other.psq=psq;
other.gatewayContext=gatewayContext;
// thread
if(threads!=null){
synchronized (threads) {
java.util.Iterator<Entry<Key, Object>> it2 = threads.entryIterator();
Entry<Key, Object> entry;
while(it2.hasNext()) {
entry = it2.next();
other.setThreadScope(entry.getKey(), (Threads)entry.getValue());
}
}
}
}
/*public static void setState(PageContextImpl other,ApplicationContext applicationContext, boolean isCFCRequest) {
other.hasFamily=true;
other.applicationContext=applicationContext;
other.thread=Thread.currentThread();
other.startTime=System.currentTimeMillis();
other.isCFCRequest = isCFCRequest;
// path
other.base=base;
java.util.Iterator it = includePathList.iterator();
while(it.hasNext()) {
other.includePathList.add(it.next());
}
// scopes
other.request=request;
other.form=form;
other.url=url;
other.urlForm=urlForm;
other._url=_url;
other._form=_form;
other.variables=variables;
other.undefined=new UndefinedImpl(other,(short)other.undefined.getType());
// writers
other.bodyContentStack.init(other.rsp,other.config.isSuppressWhitespace(),other.config.closeConnection(),other.config.isShowVersion());
other.writer=other.bodyContentStack.getWriter();
other.forceWriter=other.writer;
other.psq=psq;
}*/
public int getCurrentLevel() {
return includePathList.size()+1;
}
/**
* @return the current template SourceFile
*/
public PageSource getCurrentPageSource() {
return pathList.getLast();
}
/**
* @return the current template SourceFile
*/
public PageSource getCurrentTemplatePageSource() {
return includePathList.getLast();
}
/**
* @return base template file
*/
public PageSource getBasePageSource() {
return base;
}
/**
* @see railo.runtime.PageContext#getRootTemplateDirectory()
*/
public Resource getRootTemplateDirectory() {
return config.getResource(ReqRspUtil.getRootPath(servlet.getServletContext()));
}
/**
* @see PageContext#scope(int)
* @deprecated use instead <code>VariableInterpreter.scope(...)</code>
*/
public Scope scope(int type) throws PageException {
switch(type) {
case Scope.SCOPE_UNDEFINED: return undefinedScope();
case Scope.SCOPE_URL: return urlScope();
case Scope.SCOPE_FORM: return formScope();
case Scope.SCOPE_VARIABLES: return variablesScope();
case Scope.SCOPE_REQUEST: return requestScope();
case Scope.SCOPE_CGI: return cgiScope();
case Scope.SCOPE_APPLICATION: return applicationScope();
case Scope.SCOPE_ARGUMENTS: return argumentsScope();
case Scope.SCOPE_SESSION: return sessionScope();
case Scope.SCOPE_SERVER: return serverScope();
case Scope.SCOPE_COOKIE: return cookieScope();
case Scope.SCOPE_CLIENT: return clientScope();
case Scope.SCOPE_LOCAL:
case ScopeSupport.SCOPE_VAR: return localScope();
case Scope.SCOPE_CLUSTER:return clusterScope();
}
return variables;
}
public Scope scope(String strScope,Scope defaultValue) throws PageException {
if(strScope==null)return defaultValue;
strScope=strScope.toLowerCase().trim();
if("variables".equals(strScope)) return variablesScope();
if("url".equals(strScope)) return urlScope();
if("form".equals(strScope)) return formScope();
if("request".equals(strScope)) return requestScope();
if("cgi".equals(strScope)) return cgiScope();
if("application".equals(strScope)) return applicationScope();
if("arguments".equals(strScope)) return argumentsScope();
if("session".equals(strScope)) return sessionScope();
if("server".equals(strScope)) return serverScope();
if("cookie".equals(strScope)) return cookieScope();
if("client".equals(strScope)) return clientScope();
if("local".equals(strScope)) return localScope();
if("cluster".equals(strScope)) return clusterScope();
return defaultValue;
}
/**
* @see PageContext#undefinedScope()
*/
public Undefined undefinedScope() {
if(!undefined.isInitalized()) undefined.initialize(this);
return undefined;
}
/**
* @return undefined scope, undefined scope is a placeholder for the scopecascading
*/
public Undefined us() {
if(!undefined.isInitalized()) undefined.initialize(this);
return undefined;
}
/**
* @see PageContext#variablesScope()
*/
public Variables variablesScope() { return variables; }
/**
* @see PageContext#urlScope()
*/
public URL urlScope() {
if(!url.isInitalized())url.initialize(this);
return url;
}
/**
* @see PageContext#formScope()
*/
public Form formScope() {
if(!form.isInitalized())form.initialize(this);
return form;
}
/**
* @see railo.runtime.PageContext#urlFormScope()
*/
public URLForm urlFormScope() {
if(!urlForm.isInitalized())urlForm.initialize(this);
return urlForm;
}
/**
* @see PageContext#requestScope()
*/
public Request requestScope() { return request; }
/**
* @see PageContext#cgiScope()
*/
public CGI cgiScope() {
if(!cgi.isInitalized())cgi.initialize(this);
return cgi;
}
/**
* @see PageContext#applicationScope()
*/
public Application applicationScope() throws PageException {
if(application==null) {
if(!applicationContext.hasName())
throw new ExpressionException("there is no application context defined for this application","you can define a application context with the tag "+railo.runtime.config.Constants.CFAPP_NAME+"/"+railo.runtime.config.Constants.APP_CFC);
application=scopeContext.getApplicationScope(this,DUMMY_BOOL);
}
return application;
}
/**
* @see PageContext#argumentsScope()
*/
public Argument argumentsScope() { return argument; }
/**
* @see PageContext#argumentsScope(boolean)
*/
public Argument argumentsScope(boolean bind) {
//Argument a=argumentsScope();
if(bind)argument.setBind(true);
return argument;
}
/**
* @see railo.runtime.PageContext#localScope()
*/
public Local localScope() {
//if(local==localUnsupportedScope)
// throw new PageRuntimeException(new ExpressionException("Unsupported Context for Local Scope"));
return local;
}
/**
* @see railo.runtime.PageContext#localScope(boolean)
*/
public Local localScope(boolean bind) {
if(bind)local.setBind(true);
//if(local==localUnsupportedScope)
// throw new PageRuntimeException(new ExpressionException("Unsupported Context for Local Scope"));
return local;
}
public Object localGet() throws PageException {
return localGet(false);
}
public Object localGet(boolean bind) throws PageException {
// inside a local supported block
if(undefined.getCheckArguments()){
return localScope(bind);
}
return undefinedScope().get(KeyConstants._local);
}
public Object localTouch() throws PageException {
return localTouch(false);
}
public Object localTouch(boolean bind) throws PageException {
// inside a local supported block
if(undefined.getCheckArguments()){
return localScope(bind);
}
return touch(undefinedScope(), KeyConstants._local);
//return undefinedScope().get(LOCAL);
}
/**
* @param local sets the current local scope
* @param argument sets the current argument scope
*/
public void setFunctionScopes(Local local,Argument argument) {
this.argument=argument;
this.local=local;
undefined.setFunctionScopes(local,argument);
}
/**
* @see PageContext#sessionScope()
*/
public Session sessionScope() throws PageException {
return sessionScope(true);
}
public Session sessionScope(boolean checkExpires) throws PageException {
if(session==null) {
checkSessionContext();
session=scopeContext.getSessionScope(this,DUMMY_BOOL);
}
return session;
}
public void invalidateUserScopes(boolean migrateSessionData,boolean migrateClientData) throws PageException {
scopeContext.invalidateUserScope(this, migrateSessionData, migrateClientData);
}
private void checkSessionContext() throws ExpressionException {
if(!applicationContext.hasName())
throw new ExpressionException("there is no session context defined for this application","you can define a session context with the tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC);
if(!applicationContext.isSetSessionManagement())
throw new ExpressionException("session scope is not enabled","you can enable session scope with tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC);
}
/**
* @see PageContext#serverScope()
*/
public Server serverScope() {
//if(!server.isInitalized()) server.initialize(this);
return server;
}
+ public void reset() {
+ server=ScopeContext.getServerScope(this);
+ }
+
/**
* @see railo.runtime.PageContext#clusterScope()
*/
public Cluster clusterScope() throws PageException {
return clusterScope(true);
}
public Cluster clusterScope(boolean create) throws PageException {
if(cluster==null && create) {
cluster=ScopeContext.getClusterScope(config,create);
//cluster.initialize(this);
}
//else if(!cluster.isInitalized()) cluster.initialize(this);
return cluster;
}
/**
* @see PageContext#cookieScope()
*/
public Cookie cookieScope() {
if(!cookie.isInitalized()) cookie.initialize(this);
return cookie;
}
/**
* @see PageContext#clientScope()
*/
public Client clientScope() throws PageException {
if(client==null) {
if(!applicationContext.hasName())
throw new ExpressionException("there is no client context defined for this application",
"you can define a client context with the tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC);
if(!applicationContext.isSetClientManagement())
throw new ExpressionException("client scope is not enabled",
"you can enable client scope with tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC);
client= scopeContext.getClientScope(this);
}
return client;
}
public Client clientScopeEL() {
if(client==null) {
if(applicationContext==null || !applicationContext.hasName()) return null;
if(!applicationContext.isSetClientManagement()) return null;
client= scopeContext.getClientScopeEL(this);
}
return client;
}
/**
* @see PageContext#set(java.lang.Object, java.lang.String, java.lang.Object)
*/
public Object set(Object coll, String key, Object value) throws PageException {
return variableUtil.set(this,coll,key,value);
}
public Object set(Object coll, Collection.Key key, Object value) throws PageException {
return variableUtil.set(this,coll,key,value);
}
/**
* @see PageContext#touch(java.lang.Object, java.lang.String)
*/
public Object touch(Object coll, String key) throws PageException {
Object o=getCollection(coll,key,null);
if(o!=null) return o;
return set(coll,key,new StructImpl());
}
/**
*
* @see railo.runtime.PageContext#touch(java.lang.Object, railo.runtime.type.Collection.Key)
*/
public Object touch(Object coll, Collection.Key key) throws PageException {
Object o=getCollection(coll,key,null);
if(o!=null) return o;
return set(coll,key,new StructImpl());
}
/*private Object _touch(Scope scope, String key) throws PageException {
Object o=scope.get(key,null);
if(o!=null) return o;
return scope.set(key, new StructImpl());
}*/
/**
* @see PageContext#getCollection(java.lang.Object, java.lang.String)
*/
public Object getCollection(Object coll, String key) throws PageException {
return variableUtil.getCollection(this,coll,key);
}
/**
* @see railo.runtime.PageContext#getCollection(java.lang.Object, railo.runtime.type.Collection.Key)
*/
public Object getCollection(Object coll, Collection.Key key) throws PageException {
return variableUtil.getCollection(this,coll,key);
}
/**
*
* @see railo.runtime.PageContext#getCollection(java.lang.Object, java.lang.String, java.lang.Object)
*/
public Object getCollection(Object coll, String key, Object defaultValue) {
return variableUtil.getCollection(this,coll,key,defaultValue);
}
/**
* @see railo.runtime.PageContext#getCollection(java.lang.Object, railo.runtime.type.Collection.Key, java.lang.Object)
*/
public Object getCollection(Object coll, Collection.Key key, Object defaultValue) {
return variableUtil.getCollection(this,coll,key,defaultValue);
}
/**
* @see PageContext#get(java.lang.Object, java.lang.String)
*/
public Object get(Object coll, String key) throws PageException {
return variableUtil.get(this,coll,key);
}
/**
*
* @see railo.runtime.PageContext#get(java.lang.Object, railo.runtime.type.Collection.Key)
*/
public Object get(Object coll, Collection.Key key) throws PageException {
return variableUtil.get(this,coll,key);
}
/**
*
* @see railo.runtime.PageContext#getReference(java.lang.Object, java.lang.String)
*/
public Reference getReference(Object coll, String key) throws PageException {
return new VariableReference(coll,key);
}
public Reference getReference(Object coll, Collection.Key key) throws PageException {
return new VariableReference(coll,key);
}
/**
* @see railo.runtime.PageContext#get(java.lang.Object, java.lang.String, java.lang.Object)
*/
public Object get(Object coll, String key, Object defaultValue) {
return variableUtil.get(this,coll,key, defaultValue);
}
/**
* @see railo.runtime.PageContext#get(java.lang.Object, railo.runtime.type.Collection.Key, java.lang.Object)
*/
public Object get(Object coll, Collection.Key key, Object defaultValue) {
return variableUtil.get(this,coll,key, defaultValue);
}
/**
* @see PageContext#setVariable(java.lang.String, java.lang.Object)
*/
public Object setVariable(String var, Object value) throws PageException {
//return new CFMLExprInterpreter().interpretReference(this,new ParserString(var)).set(value);
return VariableInterpreter.setVariable(this,var,value);
}
/**
* @see PageContext#getVariable(java.lang.String)
*/
public Object getVariable(String var) throws PageException {
return VariableInterpreter.getVariable(this,var);
}
public void param(String type, String name, Object defaultValue,String regex) throws PageException {
param(type, name, defaultValue,Double.NaN,Double.NaN,regex,-1);
}
public void param(String type, String name, Object defaultValue,double min, double max) throws PageException {
param(type, name, defaultValue,min,max,null,-1);
}
public void param(String type, String name, Object defaultValue,int maxLength) throws PageException {
param(type, name, defaultValue,Double.NaN,Double.NaN,null,maxLength);
}
public void param(String type, String name, Object defaultValue) throws PageException {
param(type, name, defaultValue,Double.NaN,Double.NaN,null,-1);
}
private void param(String type, String name, Object defaultValue, double min,double max, String strPattern, int maxLength) throws PageException {
// check attributes type
if(type==null)type="any";
else type=type.trim().toLowerCase();
// check attributes name
if(StringUtil.isEmpty(name))
throw new ExpressionException("The attribute name is required");
Object value=null;
boolean isNew=false;
// get value
value=VariableInterpreter.getVariableEL(this,name,null);// NULL Support
if(value==null) {
if(defaultValue==null)
throw new ExpressionException("The required parameter ["+name+"] was not provided.");
value=defaultValue;
isNew=true;
}
// cast and set value
if(!"any".equals(type)) {
// range
if("range".equals(type)) {
double number = Caster.toDoubleValue(value);
if(!Decision.isValid(min)) throw new ExpressionException("Missing attribute [min]");
if(!Decision.isValid(max)) throw new ExpressionException("Missing attribute [max]");
if(number<min || number>max)
throw new ExpressionException("The number ["+Caster.toString(number)+"] is out of range [min:"+Caster.toString(min)+";max:"+Caster.toString(max)+"]");
setVariable(name,Caster.toDouble(number));
}
// regex
else if("regex".equals(type) || "regular_expression".equals(type)) {
String str=Caster.toString(value);
if(strPattern==null) throw new ExpressionException("Missing attribute [pattern]");
try {
Pattern pattern = new Perl5Compiler().compile(strPattern, Perl5Compiler.DEFAULT_MASK);
PatternMatcherInput input = new PatternMatcherInput(str);
if( !new Perl5Matcher().matches(input, pattern))
throw new ExpressionException("The value ["+str+"] doesn't match the provided pattern ["+strPattern+"]");
} catch (MalformedPatternException e) {
throw new ExpressionException("The provided pattern ["+strPattern+"] is invalid",e.getMessage());
}
setVariable(name,str);
}
else {
if(!Decision.isCastableTo(type,value,true,true,maxLength)) {
if(maxLength>-1 && ("email".equalsIgnoreCase(type) || "url".equalsIgnoreCase(type) || "string".equalsIgnoreCase(type))) {
StringBuilder msg=new StringBuilder(CasterException.createMessage(value, type));
msg.append(" with a maximal length of "+maxLength+" characters");
throw new CasterException(msg.toString());
}
throw new CasterException(value,type);
}
setVariable(name,value);
//REALCAST setVariable(name,Caster.castTo(this,type,value,true));
}
}
else if(isNew) setVariable(name,value);
}
/**
* @see PageContext#removeVariable(java.lang.String)
*/
public Object removeVariable(String var) throws PageException {
return VariableInterpreter.removeVariable(this,var);
}
/**
*
* a variable reference, references to variable, to modifed it, with global effect.
* @param var variable name to get
* @return return a variable reference by string syntax ("scopename.key.key" -> "url.name")
* @throws PageException
*/
public VariableReference getVariableReference(String var) throws PageException {
return VariableInterpreter.getVariableReference(this,var);
}
/**
* @see railo.runtime.PageContext#getFunction(java.lang.Object, java.lang.String, java.lang.Object[])
*/
public Object getFunction(Object coll, String key, Object[] args) throws PageException {
return variableUtil.callFunctionWithoutNamedValues(this,coll,key,args);
}
/**
* @see railo.runtime.PageContext#getFunction(java.lang.Object, railo.runtime.type.Collection.Key, java.lang.Object[])
*/
public Object getFunction(Object coll, Key key, Object[] args) throws PageException {
return variableUtil.callFunctionWithoutNamedValues(this,coll,key,args);
}
/**
* @see railo.runtime.PageContext#getFunctionWithNamedValues(java.lang.Object, java.lang.String, java.lang.Object[])
*/
public Object getFunctionWithNamedValues(Object coll, String key, Object[] args) throws PageException {
return variableUtil.callFunctionWithNamedValues(this,coll,key,args);
}
/**
*
* @see railo.runtime.PageContext#getFunctionWithNamedValues(java.lang.Object, railo.runtime.type.Collection.Key, java.lang.Object[])
*/
public Object getFunctionWithNamedValues(Object coll, Key key, Object[] args) throws PageException {
return variableUtil.callFunctionWithNamedValues(this,coll,key,args);
}
/**
* @see railo.runtime.PageContext#getConfig()
*/
public ConfigWeb getConfig() {
return config;
}
/**
* @see railo.runtime.PageContext#getIterator(java.lang.String)
*/
public Iterator getIterator(String key) throws PageException {
Object o=VariableInterpreter.getVariable(this,key);
if(o instanceof Iterator) return (Iterator) o;
throw new ExpressionException("["+key+"] is not a iterator object");
}
/**
* @see PageContext#getQuery(java.lang.String)
*/
public Query getQuery(String key) throws PageException {
Object value=VariableInterpreter.getVariable(this,key);
if(Decision.isQuery(value)) return Caster.toQuery(value);
throw new CasterException(value,Query.class);///("["+key+"] is not a query object, object is from type ");
}
@Override
public Query getQuery(Object value) throws PageException {
if(Decision.isQuery(value)) return Caster.toQuery(value);
value=VariableInterpreter.getVariable(this,Caster.toString(value));
if(Decision.isQuery(value)) return Caster.toQuery(value);
throw new CasterException(value,Query.class);
}
/**
* @see javax.servlet.jsp.PageContext#setAttribute(java.lang.String, java.lang.Object)
*/
public void setAttribute(String name, Object value) {
try {
if(value==null)removeVariable(name);
else setVariable(name,value);
} catch (PageException e) {}
}
/**
* @see javax.servlet.jsp.PageContext#setAttribute(java.lang.String, java.lang.Object, int)
*/
public void setAttribute(String name, Object value, int scope) {
switch(scope){
case javax.servlet.jsp.PageContext.APPLICATION_SCOPE:
if(value==null) getServletContext().removeAttribute(name);
else getServletContext().setAttribute(name, value);
break;
case javax.servlet.jsp.PageContext.PAGE_SCOPE:
setAttribute(name, value);
break;
case javax.servlet.jsp.PageContext.REQUEST_SCOPE:
if(value==null) req.removeAttribute(name);
else setAttribute(name, value);
break;
case javax.servlet.jsp.PageContext.SESSION_SCOPE:
HttpSession s = req.getSession(true);
if(value==null)s.removeAttribute(name);
else s.setAttribute(name, value);
break;
}
}
/**
* @see javax.servlet.jsp.PageContext#getAttribute(java.lang.String)
*/
public Object getAttribute(String name) {
try {
return getVariable(name);
} catch (PageException e) {
return null;
}
}
/**
* @see javax.servlet.jsp.PageContext#getAttribute(java.lang.String, int)
*/
public Object getAttribute(String name, int scope) {
switch(scope){
case javax.servlet.jsp.PageContext.APPLICATION_SCOPE:
return getServletContext().getAttribute(name);
case javax.servlet.jsp.PageContext.PAGE_SCOPE:
return getAttribute(name);
case javax.servlet.jsp.PageContext.REQUEST_SCOPE:
return req.getAttribute(name);
case javax.servlet.jsp.PageContext.SESSION_SCOPE:
HttpSession s = req.getSession();
if(s!=null)return s.getAttribute(name);
break;
}
return null;
}
/**
* @see javax.servlet.jsp.PageContext#findAttribute(java.lang.String)
*/
public Object findAttribute(String name) {
// page
Object value=getAttribute(name);
if(value!=null) return value;
// request
value=req.getAttribute(name);
if(value!=null) return value;
// session
HttpSession s = req.getSession();
value=s!=null?s.getAttribute(name):null;
if(value!=null) return value;
// application
value=getServletContext().getAttribute(name);
if(value!=null) return value;
return null;
}
/**
* @see javax.servlet.jsp.PageContext#removeAttribute(java.lang.String)
*/
public void removeAttribute(String name) {
setAttribute(name, null);
}
/**
* @see javax.servlet.jsp.PageContext#removeAttribute(java.lang.String, int)
*/
public void removeAttribute(String name, int scope) {
setAttribute(name, null,scope);
}
/**
* @see javax.servlet.jsp.PageContext#getAttributesScope(java.lang.String)
*/
public int getAttributesScope(String name) {
// page
if(getAttribute(name)!=null) return PageContext.PAGE_SCOPE;
// request
if(req.getAttribute(name) != null) return PageContext.REQUEST_SCOPE;
// session
HttpSession s = req.getSession();
if(s!=null && s.getAttribute(name) != null) return PageContext.SESSION_SCOPE;
// application
if(getServletContext().getAttribute(name)!=null) return PageContext.APPLICATION_SCOPE;
return 0;
}
/**
* @see javax.servlet.jsp.PageContext#getAttributeNamesInScope(int)
*/
public Enumeration getAttributeNamesInScope(int scope) {
switch(scope){
case javax.servlet.jsp.PageContext.APPLICATION_SCOPE:
return getServletContext().getAttributeNames();
case javax.servlet.jsp.PageContext.PAGE_SCOPE:
return ItAsEnum.toStringEnumeration(variablesScope().keyIterator());
case javax.servlet.jsp.PageContext.REQUEST_SCOPE:
return req.getAttributeNames();
case javax.servlet.jsp.PageContext.SESSION_SCOPE:
return req.getSession(true).getAttributeNames();
}
return null;
}
/**
* @see javax.servlet.jsp.PageContext#getOut()
*/
public JspWriter getOut() {
return forceWriter;
}
/**
* @see javax.servlet.jsp.PageContext#getSession()
*/
public HttpSession getSession() {
return getHttpServletRequest().getSession();
}
/**
* @see javax.servlet.jsp.PageContext#getPage()
*/
public Object getPage() {
return variablesScope();
}
/**
* @see javax.servlet.jsp.PageContext#getRequest()
*/
public ServletRequest getRequest() {
return getHttpServletRequest();
}
/**
* @see railo.runtime.PageContext#getHttpServletRequest()
*/
public HttpServletRequest getHttpServletRequest() {
return req;
}
/**
* @see javax.servlet.jsp.PageContext#getResponse()
*/
public ServletResponse getResponse() {
return rsp;
}
/**
* @see railo.runtime.PageContext#getHttpServletResponse()
*/
public HttpServletResponse getHttpServletResponse() {
return rsp;
}
public OutputStream getResponseStream() throws IOException {
return getRootOut().getResponseStream();
}
/**
* @see javax.servlet.jsp.PageContext#getException()
*/
public Exception getException() {
// TODO impl
return exception;
}
/**
* @see javax.servlet.jsp.PageContext#getServletConfig()
*/
public ServletConfig getServletConfig() {
return config;
}
/**
* @see javax.servlet.jsp.PageContext#getServletContext()
*/
public ServletContext getServletContext() {
return servlet.getServletContext();
}
/*public static void main(String[] args) {
repl(" susi #error.susi# sorglos","susi", "Susanne");
repl(" susi #error.Susi# sorglos","susi", "Susanne");
}*/
private static String repl(String haystack, String needle, String replacement) {
//print.o("------------");
//print.o(haystack);
//print.o(needle);
StringBuilder regex=new StringBuilder("#[\\s]*error[\\s]*\\.[\\s]*");
char[] carr = needle.toCharArray();
for(int i=0;i<carr.length;i++){
regex.append("[");
regex.append(Character.toLowerCase(carr[i]));
regex.append(Character.toUpperCase(carr[i]));
regex.append("]");
}
regex.append("[\\s]*#");
//print.o(regex);
haystack=haystack.replaceAll(regex.toString(), replacement);
//print.o(haystack);
return haystack;
}
/**
* @see railo.runtime.PageContext#handlePageException(railo.runtime.exp.PageException)
*/
public void handlePageException(PageException pe) {
if(!Abort.isSilentAbort(pe)) {
String charEnc = rsp.getCharacterEncoding();
if(StringUtil.isEmpty(charEnc,true)) {
rsp.setContentType("text/html");
}
else {
rsp.setContentType("text/html; charset=" + charEnc);
}
int statusCode=getStatusCode(pe);
if(getConfig().getErrorStatusCode())rsp.setStatus(statusCode);
ErrorPage ep=errorPagePool.getErrorPage(pe,ErrorPageImpl.TYPE_EXCEPTION);
ExceptionHandler.printStackTrace(this,pe);
ExceptionHandler.log(getConfig(),pe);
// error page exception
if(ep!=null) {
try {
Struct sct=pe.getErrorBlock(this,ep);
variablesScope().setEL(KeyConstants._error,sct);
variablesScope().setEL(KeyConstants._cferror,sct);
doInclude(ep.getTemplate());
return;
} catch (Throwable t) {
if(Abort.isSilentAbort(t)) return;
pe=Caster.toPageException(t);
}
}
// error page request
ep=errorPagePool.getErrorPage(pe,ErrorPageImpl.TYPE_REQUEST);
if(ep!=null) {
PageSource ps = ep.getTemplate();
if(ps.physcalExists()){
Resource res = ps.getResource();
try {
String content = IOUtil.toString(res, getConfig().getTemplateCharset());
Struct sct=pe.getErrorBlock(this,ep);
java.util.Iterator<Entry<Key, Object>> it = sct.entryIterator();
Entry<Key, Object> e;
String v;
while(it.hasNext()){
e = it.next();
v=Caster.toString(e.getValue(),null);
if(v!=null)content=repl(content, e.getKey().getString(), v);
}
write(content);
return;
} catch (Throwable t) {
pe=Caster.toPageException(t);
}
}
else pe=new ApplicationException("The error page template for type request only works if the actual source file also exists . If the exception file is in an Railo archive (.rc/.rcs), you need to use type exception instead.");
}
try {
if(statusCode!=404)
forceWrite("<!-- Railo ["+Info.getVersionAsString()+"] Error -->");
String template=getConfig().getErrorTemplate(statusCode);
if(!StringUtil.isEmpty(template)) {
try {
Struct catchBlock=pe.getCatchBlock(this);
variablesScope().setEL(KeyConstants._cfcatch,catchBlock);
variablesScope().setEL(KeyConstants._catch,catchBlock);
doInclude(template);
return;
}
catch (PageException e) {
pe=e;
}
}
if(!Abort.isSilentAbort(pe))forceWrite(getConfig().getDefaultDumpWriter(DumpWriter.DEFAULT_RICH).toString(this,pe.toDumpData(this, 9999,DumpUtil.toDumpProperties()),true));
}
catch (Exception e) {
}
}
}
private int getStatusCode(PageException pe) {
int statusCode=500;
int maxDeepFor404=0;
if(pe instanceof ModernAppListenerException){
pe=((ModernAppListenerException)pe).getPageException();
maxDeepFor404=1;
}
else if(pe instanceof PageExceptionBox)
pe=((PageExceptionBox)pe).getPageException();
if(pe instanceof MissingIncludeException) {
MissingIncludeException mie=(MissingIncludeException) pe;
if(mie.getPageDeep()<=maxDeepFor404) statusCode=404;
}
// TODO Auto-generated method stub
return statusCode;
}
/**
* @see javax.servlet.jsp.PageContext#handlePageException(java.lang.Exception)
*/
public void handlePageException(Exception e) {
handlePageException(Caster.toPageException(e));
}
/**
* @see javax.servlet.jsp.PageContext#handlePageException(java.lang.Throwable)
*/
public void handlePageException(Throwable t) {
handlePageException(Caster.toPageException(t));
}
/**
* @see PageContext#setHeader(java.lang.String, java.lang.String)
*/
public void setHeader(String name, String value) {
rsp.setHeader(name,value);
}
/**
* @see javax.servlet.jsp.PageContext#pushBody()
*/
public BodyContent pushBody() {
forceWriter=bodyContentStack.push();
if(enablecfoutputonly>0 && outputState==0) {
writer=devNull;
}
else writer=forceWriter;
return (BodyContent)forceWriter;
}
/**
* @see javax.servlet.jsp.PageContext#popBody()
*/
public JspWriter popBody() {
forceWriter=bodyContentStack.pop();
if(enablecfoutputonly>0 && outputState==0) {
writer=devNull;
}
else writer=forceWriter;
return forceWriter;
}
/**
* @see railo.runtime.PageContext#outputStart()
*/
public void outputStart() {
outputState++;
if(enablecfoutputonly>0 && outputState==1)writer=forceWriter;
//if(enablecfoutputonly && outputState>0) unsetDevNull();
}
/**
* @see railo.runtime.PageContext#outputEnd()
*/
public void outputEnd() {
outputState--;
if(enablecfoutputonly>0 && outputState==0)writer=devNull;
}
/**
* @see railo.runtime.PageContext#setCFOutputOnly(boolean)
*/
public void setCFOutputOnly(boolean boolEnablecfoutputonly) {
if(boolEnablecfoutputonly)this.enablecfoutputonly++;
else if(this.enablecfoutputonly>0)this.enablecfoutputonly--;
setCFOutputOnly(enablecfoutputonly);
//if(!boolEnablecfoutputonly)setCFOutputOnly(enablecfoutputonly=0);
}
/**
* @see railo.runtime.PageContext#setCFOutputOnly(short)
*/
public void setCFOutputOnly(short enablecfoutputonly) {
this.enablecfoutputonly=enablecfoutputonly;
if(enablecfoutputonly>0) {
if(outputState==0) writer=devNull;
}
else {
writer=forceWriter;
}
}
/**
* @see railo.runtime.PageContext#setSilent()
*/
public boolean setSilent() {
boolean before=bodyContentStack.getDevNull();
bodyContentStack.setDevNull(true);
forceWriter = bodyContentStack.getWriter();
writer=forceWriter;
return before;
}
/**
* @see railo.runtime.PageContext#unsetSilent()
*/
public boolean unsetSilent() {
boolean before=bodyContentStack.getDevNull();
bodyContentStack.setDevNull(false);
forceWriter = bodyContentStack.getWriter();
if(enablecfoutputonly>0 && outputState==0) {
writer=devNull;
}
else writer=forceWriter;
return before;
}
@Override
public Debugger getDebugger() {
return debugger;
}
@Override
public void executeRest(String realPath, boolean throwExcpetion) throws PageException {
ApplicationListener listener=config.getApplicationListener();
try{
String pathInfo = req.getPathInfo();
// charset
try{
String charset=HTTPUtil.splitMimeTypeAndCharset(req.getContentType(),new String[]{"",""})[1];
if(StringUtil.isEmpty(charset))charset=ThreadLocalPageContext.getConfig().getWebCharset();
java.net.URL reqURL = new java.net.URL(req.getRequestURL().toString());
String path=ReqRspUtil.decode(reqURL.getPath(),charset,true);
String srvPath=req.getServletPath();
if(path.startsWith(srvPath)) {
pathInfo=path.substring(srvPath.length());
}
}
catch (Exception e){}
// Service mapping
if(StringUtil.isEmpty(pathInfo) || pathInfo.equals("/")) {// ToDo
// list available services (if enabled in admin)
if(config.getRestList()) {
try {
HttpServletRequest _req = getHttpServletRequest();
write("Available sevice mappings are:<ul>");
railo.runtime.rest.Mapping[] mappings = config.getRestMappings();
String path;
for(int i=0;i<mappings.length;i++){
path=_req.getContextPath()+ReqRspUtil.getScriptName(_req)+mappings[i].getVirtual();
write("<li>"+path+"</li>");
}
write("</ul>");
} catch (IOException e) {
throw Caster.toPageException(e);
}
}
else
RestUtil.setStatus(this, 404, null);
return;
}
// check for matrix
int index;
String entry;
Struct matrix=new StructImpl();
while((index=pathInfo.lastIndexOf(';'))!=-1){
entry=pathInfo.substring(index+1);
pathInfo=pathInfo.substring(0,index);
if(StringUtil.isEmpty(entry,true)) continue;
index=entry.indexOf('=');
if(index!=-1)matrix.setEL(entry.substring(0,index).trim(), entry.substring(index+1).trim());
else matrix.setEL(entry.trim(), "");
}
// get accept
List<MimeType> accept = ReqRspUtil.getAccept(this);
MimeType contentType = ReqRspUtil.getContentType(this);
// check for format extension
//int format = getApplicationContext().getRestSettings().getReturnFormat();
int format;
boolean hasFormatExtension=false;
if(StringUtil.endsWithIgnoreCase(pathInfo, ".json")) {
pathInfo=pathInfo.substring(0,pathInfo.length()-5);
format = UDF.RETURN_FORMAT_JSON;
accept.clear();
accept.add(MimeType.APPLICATION_JSON);
hasFormatExtension=true;
}
else if(StringUtil.endsWithIgnoreCase(pathInfo, ".wddx")) {
pathInfo=pathInfo.substring(0,pathInfo.length()-5);
format = UDF.RETURN_FORMAT_WDDX;
accept.clear();
accept.add(MimeType.APPLICATION_WDDX);
hasFormatExtension=true;
}
else if(StringUtil.endsWithIgnoreCase(pathInfo, ".cfml")) {
pathInfo=pathInfo.substring(0,pathInfo.length()-5);
format = UDF.RETURN_FORMAT_SERIALIZE;
accept.clear();
accept.add(MimeType.APPLICATION_CFML);
hasFormatExtension=true;
}
else if(StringUtil.endsWithIgnoreCase(pathInfo, ".serialize")) {
pathInfo=pathInfo.substring(0,pathInfo.length()-10);
format = UDF.RETURN_FORMAT_SERIALIZE;
accept.clear();
accept.add(MimeType.APPLICATION_CFML);
hasFormatExtension=true;
}
else if(StringUtil.endsWithIgnoreCase(pathInfo, ".xml")) {
pathInfo=pathInfo.substring(0,pathInfo.length()-4);
format = UDF.RETURN_FORMAT_XML;
accept.clear();
accept.add(MimeType.APPLICATION_XML);
hasFormatExtension=true;
}
else {
format = getApplicationContext().getRestSettings().getReturnFormat();
//MimeType mt=MimeType.toMimetype(format);
//if(mt!=null)accept.add(mt);
}
if(accept.size()==0) accept.add(MimeType.ALL);
// loop all mappings
//railo.runtime.rest.Result result = null;//config.getRestSource(pathInfo, null);
RestRequestListener rl=null;
railo.runtime.rest.Mapping[] restMappings = config.getRestMappings();
railo.runtime.rest.Mapping m,mapping=null,defaultMapping=null;
//String callerPath=null;
if(restMappings!=null)for(int i=0;i<restMappings.length;i++) {
m = restMappings[i];
if(m.isDefault())defaultMapping=m;
if(pathInfo.startsWith(m.getVirtualWithSlash(),0) && m.getPhysical()!=null) {
mapping=m;
//result = m.getResult(this,callerPath=pathInfo.substring(m.getVirtual().length()),format,matrix,null);
rl=new RestRequestListener(m,pathInfo.substring(m.getVirtual().length()),matrix,format,hasFormatExtension,accept,contentType,null);
break;
}
}
// default mapping
if(mapping==null && defaultMapping!=null && defaultMapping.getPhysical()!=null) {
mapping=defaultMapping;
//result = mapping.getResult(this,callerPath=pathInfo,format,matrix,null);
rl=new RestRequestListener(mapping,pathInfo,matrix,format,hasFormatExtension,accept,contentType,null);
}
//base = PageSourceImpl.best(config.getPageSources(this,null,realPath,true,false,true));
if(mapping==null || mapping.getPhysical()==null){
RestUtil.setStatus(this,404,"no rest service for ["+pathInfo+"] found");
}
else {
base=config.toPageSource(null, mapping.getPhysical(), null);
listener.onRequest(this, base,rl);
}
//RestRequestListener rl = new RestRequestListener(mapping,callerPath=pathInfo.substring(m.getVirtual().length()),format,matrix,null);
/*if(result!=null){
//railo.runtime.rest.Source source=result.getSource();
//print.e(source.getPageSource());
//base=source.getPageSource();
//req.setAttribute("client", "railo-rest-1-0");
//req.setAttribute("rest-path", callerPath);
//req.setAttribute("rest-result", result);
listener.onRequest(this, base);
//doInclude(source.getPageSource());
}
else {
if(mapping==null)RestUtil.setStatus(this,404,"no rest service for ["+pathInfo+"] found");
else RestUtil.setStatus(this,404,"no rest service for ["+pathInfo+"] found in mapping ["+mapping.getVirtual()+"]");
}*/
}
catch(Throwable t) {
PageException pe = Caster.toPageException(t);
if(!Abort.isSilentAbort(pe)){
log(true);
if(fdEnabled){
FDSignal.signal(pe, false);
}
listener.onError(this,pe);
}
else log(false);
if(throwExcpetion) throw pe;
}
finally {
if(enablecfoutputonly>0){
setCFOutputOnly((short)0);
}
base=null;
}
}
/**
* @throws PageException
* @see railo.runtime.PageContext#execute(java.lang.String)
*/
public void execute(String realPath, boolean throwExcpetion) throws PageException {
execute(realPath, throwExcpetion, true);
}
public void execute(String realPath, boolean throwExcpetion, boolean onlyTopLevel) throws PageException {
//SystemOut.printDate(config.getOutWriter(),"Call:"+realPath+" (id:"+getId()+";running-requests:"+config.getThreadQueue().size()+";)");
ApplicationListener listener=config.getApplicationListener();
if(realPath.startsWith("/mapping-")){
base=null;
int index = realPath.indexOf('/',9);
if(index>-1){
String type = realPath.substring(9,index);
if(type.equalsIgnoreCase("tag")){
base=getPageSource(
new Mapping[]{config.getTagMapping(),config.getServerTagMapping()},
realPath.substring(index)
);
}
else if(type.equalsIgnoreCase("customtag")){
base=getPageSource(
config.getCustomTagMappings(),
realPath.substring(index)
);
}
/*else if(type.equalsIgnoreCase("gateway")){
base=config.getGatewayEngine().getMapping().getPageSource(realPath.substring(index));
if(!base.exists())base=getPageSource(realPath.substring(index));
}*/
}
if(base==null) base=PageSourceImpl.best(config.getPageSources(this,null,realPath,onlyTopLevel,false,true));
}
else base=PageSourceImpl.best(config.getPageSources(this,null,realPath,onlyTopLevel,false,true));
try {
listener.onRequest(this,base,null);
log(false);
}
catch(Throwable t) {
PageException pe = Caster.toPageException(t);
if(!Abort.isSilentAbort(pe)){
log(true);
if(fdEnabled){
FDSignal.signal(pe, false);
}
listener.onError(this,pe);
}
else log(false);
if(throwExcpetion) throw pe;
}
finally {
if(enablecfoutputonly>0){
setCFOutputOnly((short)0);
}
if(!gatewayContext && getConfig().debug()) {
try {
listener.onDebug(this);
}
catch (PageException pe) {
if(!Abort.isSilentAbort(pe))listener.onError(this,pe);
}
}
base=null;
}
}
private void log(boolean error) {
if(!isGatewayContext() && config.isMonitoringEnabled()) {
RequestMonitor[] monitors = config.getRequestMonitors();
if(monitors!=null)for(int i=0;i<monitors.length;i++){
if(monitors[i].isLogEnabled()){
try {
monitors[i].log(this,error);
}
catch (Throwable e) {}
}
}
}
}
private PageSource getPageSource(Mapping[] mappings, String realPath) {
PageSource ps;
//print.err(mappings.length);
for(int i=0;i<mappings.length;i++) {
ps = mappings[i].getPageSource(realPath);
//print.err(ps.getDisplayPath());
if(ps.exists()) return ps;
}
return null;
}
/**
* @see javax.servlet.jsp.PageContext#include(java.lang.String)
*/
public void include(String realPath) throws ServletException,IOException {
HTTPUtil.include(this, realPath);
}
/**
* @see javax.servlet.jsp.PageContext#forward(java.lang.String)
*/
public void forward(String realPath) throws ServletException, IOException {
HTTPUtil.forward(this, realPath);
}
/**
* @see railo.runtime.PageContext#include(railo.runtime.PageSource)
*/
public void include(PageSource ps) throws ServletException {
try {
doInclude(ps);
} catch (PageException pe) {
throw new PageServletException(pe);
}
}
/**
* @see railo.runtime.PageContext#clear()
*/
public void clear() {
try {
//print.o(getOut().getClass().getName());
getOut().clear();
} catch (IOException e) {}
}
/**
* @see railo.runtime.PageContext#getRequestTimeout()
*/
public long getRequestTimeout() {
if(requestTimeout==-1)
requestTimeout=config.getRequestTimeout().getMillis();
return requestTimeout;
}
/**
* @see railo.runtime.PageContext#setRequestTimeout(long)
*/
public void setRequestTimeout(long requestTimeout) {
this.requestTimeout = requestTimeout;
}
/**
* @see PageContext#getCFID()
*/
public String getCFID() {
if(cfid==null) initIdAndToken();
return cfid;
}
/**
* @see PageContext#getCFToken()
*/
public String getCFToken() {
if(cftoken==null) initIdAndToken();
return cftoken;
}
/**
* @see PageContext#getURLToken()
*/
public String getURLToken() {
if(getConfig().getSessionType()==Config.SESSION_TYPE_J2EE) {
HttpSession s = getSession();
return "CFID="+getCFID()+"&CFTOKEN="+getCFToken()+"&jsessionid="+(s!=null?getSession().getId():"");
}
return "CFID="+getCFID()+"&CFTOKEN="+getCFToken();
}
/**
* @see railo.runtime.PageContext#getJSessionId()
*/
public String getJSessionId() {
if(getConfig().getSessionType()==Config.SESSION_TYPE_J2EE) {
return getSession().getId();
}
return null;
}
/**
* initialize the cfid and the cftoken
*/
private void initIdAndToken() {
boolean setCookie=true;
// From URL
Object oCfid = urlScope().get(KeyConstants._cfid,null);
Object oCftoken = urlScope().get(KeyConstants._cftoken,null);
// Cookie
if((oCfid==null || !Decision.isGUIdSimple(oCfid)) || oCftoken==null) {
setCookie=false;
oCfid = cookieScope().get(KeyConstants._cfid,null);
oCftoken = cookieScope().get(KeyConstants._cftoken,null);
}
if(oCfid!=null && !Decision.isGUIdSimple(oCfid) ) {
oCfid=null;
}
// New One
if(oCfid==null || oCftoken==null) {
setCookie=true;
cfid=ScopeContext.getNewCFId();
cftoken=ScopeContext.getNewCFToken();
}
else {
cfid=Caster.toString(oCfid,null);
cftoken=Caster.toString(oCftoken,null);
}
if(setCookie && applicationContext.isSetClientCookies()) {
cookieScope().setCookieEL(KeyConstants._cfid,cfid,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(KeyConstants._server_name,null):null);
cookieScope().setCookieEL(KeyConstants._cftoken,cftoken,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(KeyConstants._server_name,null):null);
}
}
public void resetIdAndToken() {
cfid=ScopeContext.getNewCFId();
cftoken=ScopeContext.getNewCFToken();
if(applicationContext.isSetClientCookies()) {
cookieScope().setCookieEL(KeyConstants._cfid,cfid,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(KeyConstants._server_name,null):null);
cookieScope().setCookieEL(KeyConstants._cftoken,cftoken,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(KeyConstants._server_name,null):null);
}
}
/**
* @see PageContext#getId()
*/
public int getId() {
return id;
}
/**
* @return returns the root JSP Writer
*
*/
public CFMLWriter getRootOut() {
return bodyContentStack.getBase();
}
public JspWriter getRootWriter() {
return bodyContentStack.getBase();
}
/**
* @see PageContext#getLocale()
*/
public Locale getLocale() {
if(locale==null) locale=config.getLocale();
return locale;
}
/**
* @see railo.runtime.PageContext#setPsq(boolean)
*/
public void setPsq(boolean psq) {
this.psq=psq;
}
/**
* @see railo.runtime.PageContext#getPsq()
*/
public boolean getPsq() {
return psq;
}
/**
* @see railo.runtime.PageContext#setLocale(java.util.Locale)
*/
public void setLocale(Locale locale) {
//String old=GetLocale.call(pc);
this.locale=locale;
HttpServletResponse rsp = getHttpServletResponse();
String charEnc = rsp.getCharacterEncoding();
rsp.setLocale(locale);
if(charEnc.equalsIgnoreCase("UTF-8")) {
rsp.setContentType("text/html; charset=UTF-8");
}
else if(!charEnc.equalsIgnoreCase(rsp.getCharacterEncoding())) {
rsp.setContentType("text/html; charset=" + charEnc);
}
}
/**
* @see railo.runtime.PageContext#setLocale(java.lang.String)
*/
public void setLocale(String strLocale) throws ExpressionException {
setLocale(Caster.toLocale(strLocale));
}
/**
* @see railo.runtime.PageContext#setErrorPage(railo.runtime.err.ErrorPage)
*/
public void setErrorPage(ErrorPage ep) {
errorPagePool.setErrorPage(ep);
}
/**
* @see railo.runtime.PageContext#use(java.lang.Class)
* /
public Tag use(Class tagClass) throws PageException {
parentTag=currentTag;
currentTag= tagHandlerPool.use(tagClass);
if(currentTag==parentTag) throw new ApplicationException("");
currentTag.setPageContext(this);
currentTag.setParent(parentTag);
return currentTag;
}*/
/**
*
* @see railo.runtime.PageContext#use(java.lang.String)
*/
public Tag use(String tagClassName) throws PageException {
parentTag=currentTag;
currentTag= tagHandlerPool.use(tagClassName);
if(currentTag==parentTag) throw new ApplicationException("");
currentTag.setPageContext(this);
currentTag.setParent(parentTag);
return currentTag;
}
/**
* @see railo.runtime.PageContext#use(java.lang.Class)
*/
public Tag use(Class clazz) throws PageException {
return use(clazz.getName());
}
/**
* @see railo.runtime.PageContext#reuse(javax.servlet.jsp.tagext.Tag)
*/
public void reuse(Tag tag) throws PageException {
currentTag=tag.getParent();
tagHandlerPool.reuse(tag);
}
/**
* @see railo.runtime.PageContext#getQueryCache()
*/
public QueryCache getQueryCache() {
return queryCache;
}
/**
* @see railo.runtime.PageContext#initBody(javax.servlet.jsp.tagext.BodyTag, int)
*/
public void initBody(BodyTag bodyTag, int state) throws JspException {
if (state != Tag.EVAL_BODY_INCLUDE) {
bodyTag.setBodyContent(pushBody());
bodyTag.doInitBody();
}
}
/**
* @see railo.runtime.PageContext#releaseBody(javax.servlet.jsp.tagext.BodyTag, int)
*/
public void releaseBody(BodyTag bodyTag, int state) {
if(bodyTag instanceof TryCatchFinally) {
((TryCatchFinally)bodyTag).doFinally();
}
if (state != Tag.EVAL_BODY_INCLUDE)popBody();
}
/* *
* @return returns the cfml compiler
* /
public CFMLCompiler getCompiler() {
return compiler;
}*/
/**
* @see railo.runtime.PageContext#setVariablesScope(railo.runtime.type.scope.Scope)
*/
public void setVariablesScope(Variables variables) {
this.variables=variables;
undefinedScope().setVariableScope(variables);
if(variables instanceof ComponentScope) {
activeComponent=((ComponentScope)variables).getComponent();
/*if(activeComponent.getAbsName().equals("jm.pixeltex.supersuperApp")){
print.dumpStack();
}*/
}
else {
activeComponent=null;
}
}
/**
* @see railo.runtime.PageContext#getActiveComponent()
*/
public Component getActiveComponent() {
return activeComponent;
}
/**
* @see railo.runtime.PageContext#getRemoteUser()
*/
public Credential getRemoteUser() throws PageException {
if(remoteUser==null) {
Key name = KeyImpl.init(Login.getApplicationName(applicationContext));
Resource roles = config.getConfigDir().getRealResource("roles");
if(applicationContext.getLoginStorage()==Scope.SCOPE_SESSION) {
Object auth = sessionScope().get(name,null);
if(auth!=null) {
remoteUser=CredentialImpl.decode(auth,roles);
}
}
else if(applicationContext.getLoginStorage()==Scope.SCOPE_COOKIE) {
Object auth = cookieScope().get(name,null);
if(auth!=null) {
remoteUser=CredentialImpl.decode(auth,roles);
}
}
}
return remoteUser;
}
/**
* @see railo.runtime.PageContext#clearRemoteUser()
*/
public void clearRemoteUser() {
if(remoteUser!=null)remoteUser=null;
String name=Login.getApplicationName(applicationContext);
cookieScope().removeEL(KeyImpl.init(name));
try {
sessionScope().removeEL(KeyImpl.init(name));
} catch (PageException e) {}
}
/**
* @see railo.runtime.PageContext#setRemoteUser(railo.runtime.security.Credential)
*/
public void setRemoteUser(Credential remoteUser) {
this.remoteUser = remoteUser;
}
/**
* @see railo.runtime.PageContext#getVariableUtil()
*/
public VariableUtil getVariableUtil() {
return variableUtil;
}
/**
* @see railo.runtime.PageContext#throwCatch()
*/
public void throwCatch() throws PageException {
if(exception!=null) throw exception;
throw new ApplicationException("invalid context for tag/script expression rethow");
}
/**
* @see railo.runtime.PageContext#setCatch(java.lang.Throwable)
*/
public PageException setCatch(Throwable t) {
if(t==null) {
exception=null;
undefinedScope().removeEL(KeyConstants._cfcatch);
}
else {
exception = Caster.toPageException(t);
undefinedScope().setEL(KeyConstants._cfcatch,exception.getCatchBlock(config));
if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception);
}
return exception;
}
public void setCatch(PageException pe) {
exception = pe;
if(pe==null) {
undefinedScope().removeEL(KeyConstants._cfcatch);
}
else {
undefinedScope().setEL(KeyConstants._cfcatch,pe.getCatchBlock(config));
if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception);
}
}
public void setCatch(PageException pe,boolean caught, boolean store) {
if(fdEnabled){
FDSignal.signal(pe, caught);
}
exception = pe;
if(store){
if(pe==null) {
undefinedScope().removeEL(KeyConstants._cfcatch);
}
else {
undefinedScope().setEL(KeyConstants._cfcatch,pe.getCatchBlock(config));
if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception);
}
}
}
/**
* @return return current catch
*/
public PageException getCatch() {
return exception;
}
/**
* @see railo.runtime.PageContext#clearCatch()
*/
public void clearCatch() {
exception = null;
undefinedScope().removeEL(KeyConstants._cfcatch);
}
/**
* @see railo.runtime.PageContext#addPageSource(railo.runtime.PageSource, boolean)
*/
public void addPageSource(PageSource ps, boolean alsoInclude) {
pathList.add(ps);
if(alsoInclude)
includePathList.add(ps);
}
public void addPageSource(PageSource ps, PageSource psInc) {
pathList.add(ps);
if(psInc!=null)
includePathList.add(psInc);
}
/**
* @see railo.runtime.PageContext#removeLastPageSource(boolean)
*/
public void removeLastPageSource(boolean alsoInclude) {
if(!pathList.isEmpty())pathList.removeLast();
if(alsoInclude && !includePathList.isEmpty())
includePathList.removeLast();
}
public UDF[] getUDFs() {
return udfs.toArray(new UDF[udfs.size()]);
}
public void addUDF(UDF udf) {
udfs.add(udf);
}
/**
* @see railo.runtime.PageContext#removeLastPageSource(boolean)
*/
public void removeUDF() {
if(!udfs.isEmpty())udfs.pop();
}
/**
* @see railo.runtime.PageContext#getFTPPool()
*/
public FTPPool getFTPPool() {
return ftpPool;
}
/* *
* @return Returns the manager.
* /
public DataSourceManager getManager() {
return manager;
}*/
/**
* @see railo.runtime.PageContext#getApplicationContext()
*/
public ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* @see railo.runtime.PageContext#setApplicationContext(railo.runtime.util.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext applicationContext) {
session=null;
application=null;
client=null;
this.applicationContext = applicationContext;
int scriptProtect = applicationContext.getScriptProtect();
// ScriptProtecting
if(config.mergeFormAndURL()) {
form.setScriptProtecting(applicationContext,
(scriptProtect&ApplicationContext.SCRIPT_PROTECT_FORM)>0
||
(scriptProtect&ApplicationContext.SCRIPT_PROTECT_URL)>0);
}
else {
form.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_FORM)>0);
url.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_URL)>0);
}
cookie.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_COOKIE)>0);
cgi.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_CGI)>0);
undefined.reinitialize(this);
}
/**
* @return return value of method "onApplicationStart" or true
* @throws PageException
*/
public boolean initApplicationContext() throws PageException {
boolean initSession=false;
AppListenerSupport listener = (AppListenerSupport) config.getApplicationListener();
KeyLock<String> lock = config.getContextLock();
String name=StringUtil.emptyIfNull(applicationContext.getName());
String token=name+":"+getCFID();
Lock tokenLock = lock.lock(token,getRequestTimeout());
//print.o("outer-lock :"+token);
try {
// check session before executing any code
initSession=applicationContext.isSetSessionManagement() && listener.hasOnSessionStart(this) && !scopeContext.hasExistingSessionScope(this);
// init application
Lock nameLock = lock.lock(name,getRequestTimeout());
//print.o("inner-lock :"+token);
try {
RefBoolean isNew=new RefBooleanImpl(false);
application=scopeContext.getApplicationScope(this,isNew);// this is needed that the application scope is initilized
if(isNew.toBooleanValue()) {
try {
if(!listener.onApplicationStart(this)) {
scopeContext.removeApplicationScope(this);
return false;
}
} catch (PageException pe) {
scopeContext.removeApplicationScope(this);
throw pe;
}
}
}
finally{
//print.o("inner-unlock:"+token);
lock.unlock(nameLock);
}
// init session
if(initSession) {
scopeContext.getSessionScope(this, DUMMY_BOOL);// this is needed that the session scope is initilized
listener.onSessionStart(this);
}
}
finally{
//print.o("outer-unlock:"+token);
lock.unlock(tokenLock);
}
return true;
}
/**
* @return the scope factory
*/
public ScopeFactory getScopeFactory() {
return scopeFactory;
}
/**
* @see railo.runtime.PageContext#getCurrentTag()
*/
public Tag getCurrentTag() {
return currentTag;
}
/**
* @see railo.runtime.PageContext#getStartTime()
*/
public long getStartTime() {
return startTime;
}
/**
* @see railo.runtime.PageContext#getThread()
*/
public Thread getThread() {
return thread;
}
public void setThread(Thread thread) {
this.thread=thread;
}
/**
* @see railo.runtime.PageContext#getExecutionTime()
*/
public int getExecutionTime() {
return executionTime;
}
/**
* @see railo.runtime.PageContext#setExecutionTime(int)
*/
public void setExecutionTime(int executionTime) {
this.executionTime = executionTime;
}
/**
* @see railo.runtime.PageContext#compile(railo.runtime.PageSource)
*/
public synchronized void compile(PageSource pageSource) throws PageException {
Resource classRootDir = pageSource.getMapping().getClassRootDirectory();
try {
config.getCompiler().compile(
config,
pageSource,
config.getTLDs(),
config.getFLDs(),
classRootDir,
pageSource.getJavaName()
);
} catch (Exception e) {
throw Caster.toPageException(e);
}
}
/**
* @see railo.runtime.PageContext#compile(java.lang.String)
*/
public void compile(String realPath) throws PageException {
SystemOut.printDate("method PageContext.compile(String) should no longer be used!");
compile(PageSourceImpl.best(getRelativePageSources(realPath)));
}
public HttpServlet getServlet() {
return servlet;
}
/**
* @see railo.runtime.PageContext#loadComponent(java.lang.String)
*/
public railo.runtime.Component loadComponent(String compPath) throws PageException {
return ComponentLoader.loadComponent(this,compPath,null,null);
}
/**
* @return the base
*/
public PageSource getBase() {
return base;
}
/**
* @param base the base to set
*/
public void setBase(PageSource base) {
this.base = base;
}
/**
* @return the isCFCRequest
*/
public boolean isCFCRequest() {
return isCFCRequest;
}
/**
* @see railo.runtime.config.Config#getDataSourceManager()
*/
public DataSourceManager getDataSourceManager() {
return manager;
}
/**
* @see railo.runtime.PageContext#evaluate(java.lang.String)
*/
public Object evaluate(String expression) throws PageException {
return new CFMLExpressionInterpreter().interpret(this,expression);
}
/**
* @see railo.runtime.PageContext#serialize(java.lang.Object)
*/
public String serialize(Object expression) throws PageException {
return Serialize.call(this, expression);
}
/**
* @return the activeUDF
*/
public UDF getActiveUDF() {
return activeUDF;
}
/**
* @param activeUDF the activeUDF to set
*/
public void setActiveUDF(UDF activeUDF) {
this.activeUDF = activeUDF;
}
/**
*
* @see railo.runtime.PageContext#getCFMLFactory()
*/
public CFMLFactory getCFMLFactory() {
return config.getFactory();
}
/**
* @see railo.runtime.PageContext#getParentPageContext()
*/
public PageContext getParentPageContext() {
return parent;
}
/**
* @see railo.runtime.PageContext#getThreadScopeNames()
*/
public String[] getThreadScopeNames() {
if(threads==null)return new String[0];
Set ks = threads.keySet();
return (String[]) ks.toArray(new String[ks.size()]);
}
/**
* @see railo.runtime.PageContext#getThreadScope(java.lang.String)
*/
public Threads getThreadScope(String name) {
return getThreadScope(KeyImpl.init(name));
}
public Threads getThreadScope(Collection.Key name) {
if(threads==null)threads=new StructImpl();
Object obj = threads.get(name,null);
if(obj instanceof Threads)return (Threads) obj;
return null;
}
public Object getThreadScope(Collection.Key name,Object defaultValue) {
if(threads==null)threads=new StructImpl();
if(name.equalsIgnoreCase(KeyConstants._cfthread)) return threads;
return threads.get(name,defaultValue);
}
public Object getThreadScope(String name,Object defaultValue) {
if(threads==null)threads=new StructImpl();
if(name.equalsIgnoreCase(KeyConstants._cfthread.getLowerString())) return threads;
return threads.get(KeyImpl.init(name),defaultValue);
}
/**
* @see railo.runtime.PageContext#setThreadScope(java.lang.String, railo.runtime.type.scope.Threads)
*/
public void setThreadScope(String name,Threads ct) {
hasFamily=true;
if(threads==null) threads=new StructImpl();
threads.setEL(KeyImpl.init(name), ct);
}
public void setThreadScope(Collection.Key name,Threads ct) {
hasFamily=true;
if(threads==null) threads=new StructImpl();
threads.setEL(name, ct);
}
/**
* @see railo.runtime.PageContext#hasFamily()
*/
public boolean hasFamily() {
return hasFamily;
}
public DatasourceConnection _getConnection(String datasource, String user,String pass) throws PageException {
return _getConnection(config.getDataSource(datasource),user,pass);
}
public DatasourceConnection _getConnection(DataSource ds, String user,String pass) throws PageException {
String id=DatasourceConnectionPool.createId(ds,user,pass);
DatasourceConnection dc=conns.get(id);
if(dc!=null && DatasourceConnectionPool.isValid(dc,null)){
return dc;
}
dc=config.getDatasourceConnectionPool().getDatasourceConnection(this,ds, user, pass);
conns.put(id, dc);
return dc;
}
/**
* @see railo.runtime.PageContext#getTimeZone()
*/
public TimeZone getTimeZone() {
if(timeZone==null) timeZone=config.getTimeZone();
return timeZone;
}
/**
* @see railo.runtime.PageContext#setTimeZone(java.util.TimeZone)
*/
public void setTimeZone(TimeZone timeZone) {
this.timeZone=timeZone;
}
/**
* @return the requestId
*/
public int getRequestId() {
return requestId;
}
private Set<String> pagesUsed=new HashSet<String>();
private DebugQuery activeQuery;
public boolean isTrusted(Page page) {
if(page==null)return false;
short it = config.getInspectTemplate();
if(it==ConfigImpl.INSPECT_NEVER)return true;
if(it==ConfigImpl.INSPECT_ALWAYS)return false;
return pagesUsed.contains(""+page.hashCode());
}
public void setPageUsed(Page page) {
pagesUsed.add(""+page.hashCode());
}
/**
* @see railo.runtime.PageContext#exeLogStart(int, java.lang.String)
*/
public void exeLogStart(int position,String id){
if(execLog!=null)execLog.start(position, id);
}
/**
* @see railo.runtime.PageContext#exeLogEnd(int, java.lang.String)
*/
public void exeLogEnd(int position,String id){
if(execLog!=null)execLog.end(position, id);
}
/**
* @param create if set to true, railo creates a session when not exist
* @return
* @throws PageException
*/
public ORMSession getORMSession(boolean create) throws PageException {
if(ormSession==null || !ormSession.isValid()) {
if(!create) return null;
ormSession=config.getORMEngine(this).createSession(this);
}
DatasourceManagerImpl manager = (DatasourceManagerImpl) getDataSourceManager();
manager.add(this,ormSession);
return ormSession;
}
public ClassLoader getClassLoader() throws IOException {
return getResourceClassLoader();
}
public ClassLoader getClassLoader(Resource[] reses) throws IOException{
return getResourceClassLoader().getCustomResourceClassLoader(reses);
}
private ResourceClassLoader getResourceClassLoader() throws IOException {
JavaSettingsImpl js = (JavaSettingsImpl) applicationContext.getJavaSettings();
if(js!=null) {
return config.getResourceClassLoader().getCustomResourceClassLoader(js.getResourcesTranslated());
}
return config.getResourceClassLoader();
}
public ClassLoader getRPCClassLoader(boolean reload) throws IOException {
JavaSettingsImpl js = (JavaSettingsImpl) applicationContext.getJavaSettings();
if(js!=null) {
return ((PhysicalClassLoader)config.getRPCClassLoader(reload)).getCustomClassLoader(js.getResourcesTranslated(),reload);
}
return config.getRPCClassLoader(reload);
}
public void resetSession() {
this.session=null;
}
/**
* @return the gatewayContext
*/
public boolean isGatewayContext() {
return gatewayContext;
}
/**
* @param gatewayContext the gatewayContext to set
*/
public void setGatewayContext(boolean gatewayContext) {
this.gatewayContext = gatewayContext;
}
public void setServerPassword(String serverPassword) {
this.serverPassword=serverPassword;
}
public String getServerPassword() {
return serverPassword;
}
public short getSessionType() {
if(isGatewayContext())return Config.SESSION_TYPE_CFML;
return applicationContext.getSessionType();
}
// this is just a wrapper method for ACF
public Scope SymTab_findBuiltinScope(String name) throws PageException {
return scope(name, null);
}
public void setActiveQuery(DebugQuery dq) {
activeQuery=dq;
}
public DebugQuery getActiveQuery() {
return activeQuery;
}
public void releaseActiveQuery() {
activeQuery=null;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/PokemonTD/src/com/xkings/pokemontd/graphics/ui/AbilityInfo.java b/PokemonTD/src/com/xkings/pokemontd/graphics/ui/AbilityInfo.java
index 2ea72f9..6fce79d 100644
--- a/PokemonTD/src/com/xkings/pokemontd/graphics/ui/AbilityInfo.java
+++ b/PokemonTD/src/com/xkings/pokemontd/graphics/ui/AbilityInfo.java
@@ -1,41 +1,48 @@
package com.xkings.pokemontd.graphics.ui;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.math.Rectangle;
import com.xkings.pokemontd.component.attack.projectile.data.EffectData;
/**
* User: Seda
* Date: 2.11.13
* Time: 11:15
*/
public class AbilityInfo extends GuiBox {
private final DisplayText text;
private EffectData abilityCache;
private float speed;
private float damage;
public AbilityInfo(Ui ui, Rectangle rectangle) {
super(ui, rectangle);
text = new DisplayText(ui, offsetRectange, ui.getFont(), BitmapFont.HAlignment.LEFT, true);
}
public void update(EffectData abilityCache, float speed, float damage) {
this.abilityCache = abilityCache;
this.speed = speed;
this.damage = damage;
}
@Override
public void render() {
if (abilityCache != null) {
super.render();
text.render(abilityCache.getEffectDescription(speed, damage));
}
}
public void reset() {
this.abilityCache = null;
}
+
+ @Override
+ public void refresh() {
+ super.refresh();
+ text.set(offsetRectange);
+ text.refresh();
+ }
}
diff --git a/PokemonTD/src/com/xkings/pokemontd/graphics/ui/TowerInfo.java b/PokemonTD/src/com/xkings/pokemontd/graphics/ui/TowerInfo.java
index c5c772e..3f9fa25 100644
--- a/PokemonTD/src/com/xkings/pokemontd/graphics/ui/TowerInfo.java
+++ b/PokemonTD/src/com/xkings/pokemontd/graphics/ui/TowerInfo.java
@@ -1,203 +1,202 @@
package com.xkings.pokemontd.graphics.ui;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.xkings.core.main.Assets;
import com.xkings.pokemontd.Treasure;
import com.xkings.pokemontd.component.attack.AbilityComponent;
import com.xkings.pokemontd.component.attack.EffectName;
import com.xkings.pokemontd.component.attack.projectile.HitAbility;
import com.xkings.pokemontd.component.attack.projectile.data.EffectData;
import com.xkings.pokemontd.component.attack.projectile.data.NormalData;
import com.xkings.pokemontd.entity.tower.TowerType;
/**
* User: Seda
* Date: 24.10.13
* Time: 20:42
*/
public class TowerInfo extends CommonInfo {
public static final Color SELL_COLOR = new Color(Color.RED).mul(0.6f);
public static final Color BUY_COLOR = new Color(Color.GREEN).mul(0.6f);
public static final Color ABILITY_COLOR = new Color(Color.GREEN).mul(0.6f);
protected final DisplayText damage;
protected final DisplayText speed;
protected final DisplayText range;
protected final Button sell;
protected final Button buy;
private final TowerCost cost;
private final Icon ability;
protected TowerType tower;
private float damageCache;
private float speedCache;
private float rangeCache;
private boolean sellCache;
private boolean buyCache;
private Treasure costCache;
private Color damageColorCache;
private Color speedColorCache;
private Color rangeColorCache;
private EffectData abilityCache;
private EffectName effectNameCache;
/**
* public constuctor makes 3 text rectangles uses class DisplayText (damage,range,speed).
* Makes two anonymous classes for buttons buy and sell these anonymous classes use public method process which
* allows sell or upgrade tower and because class TowerInfo extends class CommonInfo (which implements Clickable)
* there are clickables.add(buy) and clickables.add(sell) which makes function buy and sell.
*
* @param ui
* @param rectangle
* @param shapeRenderer
* @param spriteBatch
*/
public TowerInfo(final Ui ui, Rectangle rectangle, ShapeRenderer shapeRenderer, SpriteBatch spriteBatch,
BitmapFont font) {
super(ui, rectangle, shapeRenderer, spriteBatch, font);
float offset = height / 5;
float offsetBlocks = height / 2;
float offsetBlocks2 = offsetBlocks / 2f;
cost = new TowerCost(new Rectangle(x + offset, y, width - offset * 2, offset), width - offsetBlocks,
shapeRenderer, spriteBatch, font);
damage = new DisplayText(ui, new Rectangle(x + offset * 5, y + offset * 3, offset * 2, offset), font,
BitmapFont.HAlignment.LEFT);
speed = new DisplayText(ui, new Rectangle(x + offset * 5, y + offset * 2, offset * 2, offset), font,
BitmapFont.HAlignment.LEFT);
range = new DisplayText(ui, new Rectangle(x + offset * 5, y + offset, offset, offset), font,
BitmapFont.HAlignment.LEFT);
ability = new Icon(ui, damage.x + damage.width + offsetBlocks2, y + offsetBlocks2, height - offsetBlocks,
height - offsetBlocks) {
@Override
public void process(float x, float y) {
ui.getAbilityInfo().update(abilityCache, speedCache, damageCache);
//ui.abilityText();
// ui.getRectangle();
}
};
sell = new Button(ui, new Rectangle(x + width - offsetBlocks, y, offsetBlocks, offsetBlocks), font,
BitmapFont.HAlignment.CENTER) {
@Override
public void process(float x, float y) {
ui.getTowerManager().sellTower();
}
};
buy = new Button(ui, new Rectangle(x + width - offsetBlocks, y + offsetBlocks, offsetBlocks, offsetBlocks),
font, BitmapFont.HAlignment.CENTER) {
@Override
public void process(float x, float y) {
ui.getTowerManager().buyNewOrUpgrade();
}
};
ui.register(sell);
ui.register(buy);
ui.register(ability);
clickables.add(sell);
clickables.add(buy);
clickables.add(ability);
}
/**
* this method overrides method render in class CommonInfo and setted buttons sell and buy
*/
@Override
public void render() {
this.sell.setEnabled(sellCache);
this.buy.setEnabled(buyCache);
this.ability.setEnabled(abilityCache != null);
super.render();
this.damage.render("DMG: " + (int) (damageCache), damageColorCache);
this.speed.render("SPD: " + (int) (speedCache), speedColorCache);
this.range.render("RNG: " + (int) (rangeCache), rangeColorCache);
this.cost.render(costCache);
this.sell.render("sell", Color.WHITE, SELL_COLOR);
this.buy.render("buy", Color.WHITE, BUY_COLOR);
if (abilityCache != null) {
this.ability.render(Assets.getTexture("abilities/" + effectNameCache.name().toLowerCase()),
abilityCache.getEffect());
}
}
public void render(TextureAtlas.AtlasRegion region, Treasure cost, String name, boolean sell, boolean buy) {
render(region, 0f, 0f, 0f, cost, name, null, null, sell, buy);
}
public void render(TextureAtlas.AtlasRegion region, float damage, float speed, float range, Treasure cost,
String name, EffectName effectName, EffectData ability, boolean sell, boolean buy) {
render(region, damage, Color.WHITE, speed, Color.WHITE, range, Color.WHITE, cost, name, effectName, ability,
sell, buy);
}
public void render(TextureAtlas.AtlasRegion region, float damage, Color damageColor, float speed, Color speedColor,
float range, Color rangeColor, Treasure cost, String name, EffectName effectName,
EffectData ability, boolean sell, boolean buy) {
this.damageCache = damage;
this.damageColorCache = damageColor;
this.speedCache = speed;
this.speedColorCache = speedColor;
this.rangeCache = range;
this.rangeColorCache = rangeColor;
this.costCache = cost;
this.effectNameCache = effectName;
this.abilityCache = ability;
this.sellCache = sell;
this.buyCache = buy;
render(region, name);
}
@Override
public void process(float x, float y) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void refresh() {
super.refresh();
float offset = height / 5;
float offsetBlocks = height / 2;
float offsetBlocks2 = offsetBlocks / 2f;
cost.set(x + offset, y, width - offset * 2, offset);
damage.set(x + offset * 5, y + offset * 3, offset * 2, offset);
speed.set(x + offset * 5, y + offset * 2, offset * 2, offset);
range.set(x + offset * 5, y + offset, offset, offset);
ability.set(damage.x + damage.width + offsetBlocks2, y + offsetBlocks2, height - offsetBlocks,
height - offsetBlocks);
- ability.set(x + offset * 10f, y + offset * 3, offsetBlocks * 1.2f, offsetBlocks / 2f);
sell.set(x + width - offsetBlocks, y, offsetBlocks, offsetBlocks);
buy.set(x + width - offsetBlocks, y + offsetBlocks, offsetBlocks, offsetBlocks);
cost.refresh();
damage.refresh();
speed.refresh();
range.refresh();
ability.refresh();
sell.refresh();
buy.refresh();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
}
protected EffectData getAbility(TowerType tower) {
AbilityComponent attack = tower.getAttack();
return attack instanceof HitAbility ? getEffectData((HitAbility) attack) : (EffectData) attack;
}
private EffectData getEffectData(HitAbility attack) {
for (EffectData effectData : attack.getEffectData()) {
if (!(effectData instanceof NormalData)) {
return effectData;
}
}
return null;
}
}
diff --git a/PokemonTD/src/com/xkings/pokemontd/graphics/ui/Ui.java b/PokemonTD/src/com/xkings/pokemontd/graphics/ui/Ui.java
index 82e5387..552a616 100644
--- a/PokemonTD/src/com/xkings/pokemontd/graphics/ui/Ui.java
+++ b/PokemonTD/src/com/xkings/pokemontd/graphics/ui/Ui.java
@@ -1,136 +1,137 @@
package com.xkings.pokemontd.graphics.ui;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.xkings.pokemontd.App;
import com.xkings.pokemontd.entity.tower.TowerName;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Tomas on 10/8/13.
*/
public class Ui extends Gui {
private final int width;
private final TowerIcons towerIcons;
private final ShopIcons shopIcons;
private final EntityInfo entityInfo;
private final StatusBar statusBar;
private final GuiBox nextWaveInfo;
private final GuiBox status;
private final AbilityInfo abilityInfo;
private final List<GuiBox> boxes = new ArrayList<GuiBox>();
private int offset;
public Ui(App app) {
super(app);
int statusBarHeight = squareSize / 5;
int statusHeight = statusBarHeight * 4;
width = Gdx.graphics.getWidth();
int stripHeight = (int) (squareSize / 3f * 2f);
offset = squareSize / 36;
float statusHeightBlock = statusHeight / 5;
float statusOffSet = statusHeightBlock / 2;
statusHeight = (int) (statusHeightBlock * 4);
squareSize = (squareSize / 3) * 3 + offset * 2;
Rectangle pickTableRectangle = new Rectangle(width - squareSize, 0, squareSize, squareSize);
towerIcons = new TowerIcons(this, pickTableRectangle, towerManager);
shopIcons = new ShopIcons(this, pickTableRectangle);
Vector2 statusBarDimensions = new Vector2(width, statusBarHeight);
Vector2 statusDimensions = new Vector2(squareSize, statusHeight);
statusBar = new StatusBar(this,
new Rectangle(0, height - statusBarDimensions.y, statusBarDimensions.x, statusBarDimensions.y),
shopIcons, font);
status = new Status(this,
new Rectangle(width - statusDimensions.x, height - statusBar.height - statusOffSet - statusDimensions.y,
statusDimensions.x, statusDimensions.y), waveManager, interest, font);
abilityInfo = new AbilityInfo(this, pickTableRectangle);
nextWaveInfo = new WaveInfo(this, new Rectangle(0, 0, squareSize, squareSize), waveManager, font);
entityInfo = new EntityInfo(this,
new Rectangle(squareSize - offset, 0, width - (squareSize - offset) * 2, stripHeight), shapeRenderer,
spriteBatch, font, player);
register(entityInfo);
register(nextWaveInfo);
register(status);
boxes.add(towerIcons);
boxes.add(shopIcons);
boxes.add(statusBar);
boxes.add(status);
boxes.add(abilityInfo);
boxes.add(nextWaveInfo);
boxes.add(entityInfo);
}
@Override
public void render() {
TowerName towerName = towerManager.getCurrentTowerName();
unregister(towerIcons);
unregister(shopIcons);
if (towerName != null && towerName.equals(TowerName.Shop)) {
register(shopIcons);
} else {
towerIcons.update(towerName);
register(towerIcons);
}
unregister(abilityInfo);
register(abilityInfo);
super.render();
}
public void makeLarger() {
scale(squareSize + offset);
}
public void makeSmaller() {
scale(squareSize - offset);
}
public void resetSize() {
scale(defaultSize);
}
public void scale(float size) {
super.scale(size);
int statusBarHeight = squareSize / 5;
int statusHeight = statusBarHeight * 4;
int stripHeight = (int) (squareSize / 3f * 2f);
offset = squareSize / 36;
float statusHeightBlock = statusHeight / 5;
float statusOffSet = statusHeightBlock / 2;
statusHeight = (int) (statusHeightBlock * 4);
// squareSize = (squareSize / 3) * 3 + offset * 2;
Vector2 statusBarDimensions = new Vector2(width, statusBarHeight);
Vector2 statusDimensions = new Vector2(squareSize, statusHeight);
towerIcons.set(width - squareSize, 0, squareSize, squareSize);
shopIcons.set(width - squareSize, 0, squareSize, squareSize);
+ abilityInfo.set(width - squareSize, 0, squareSize, squareSize);
statusBar.set(0, height - statusBarDimensions.y, statusBarDimensions.x, statusBarDimensions.y);
statusBar.setSquare(towerIcons);
status.set(width - statusDimensions.x, height - statusBar.height - statusOffSet - statusDimensions.y,
statusDimensions.x, statusDimensions.y);
nextWaveInfo.set(0, 0, squareSize, squareSize);
entityInfo.set(squareSize - offset, 0, width - (squareSize - offset) * 2, stripHeight);
for (GuiBox guiBox : boxes) {
guiBox.setOffset(offset);
guiBox.refresh();
}
}
public AbilityInfo getAbilityInfo() {
return abilityInfo;
}
}
| false | false | null | null |
diff --git a/src/ooxml/java/org/apache/poi/xslf/extractor/XSLFPowerPointExtractor.java b/src/ooxml/java/org/apache/poi/xslf/extractor/XSLFPowerPointExtractor.java
index bb3e9143d..9728dcfe6 100644
--- a/src/ooxml/java/org/apache/poi/xslf/extractor/XSLFPowerPointExtractor.java
+++ b/src/ooxml/java/org/apache/poi/xslf/extractor/XSLFPowerPointExtractor.java
@@ -1,154 +1,164 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xslf.extractor;
import java.io.IOException;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xslf.XSLFSlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.xmlbeans.XmlException;
+import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
+import org.openxmlformats.schemas.drawingml.x2006.main.CTTextLineBreak;
import org.openxmlformats.schemas.presentationml.x2006.main.CTComment;
import org.openxmlformats.schemas.presentationml.x2006.main.CTCommentList;
import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape;
import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesSlide;
import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
import org.openxmlformats.schemas.presentationml.x2006.main.CTSlide;
import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry;
public class XSLFPowerPointExtractor extends POIXMLTextExtractor {
private XMLSlideShow slideshow;
private boolean slidesByDefault = true;
private boolean notesByDefault = false;
public XSLFPowerPointExtractor(XMLSlideShow slideshow) {
super(slideshow._getXSLFSlideShow());
this.slideshow = slideshow;
}
public XSLFPowerPointExtractor(XSLFSlideShow slideshow) throws XmlException, IOException {
this(new XMLSlideShow(slideshow));
}
public XSLFPowerPointExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException {
this(new XSLFSlideShow(container));
}
public static void main(String[] args) throws Exception {
if(args.length < 1) {
System.err.println("Use:");
System.err.println(" HXFPowerPointExtractor <filename.pptx>");
System.exit(1);
}
POIXMLTextExtractor extractor =
new XSLFPowerPointExtractor(
new XSLFSlideShow(args[0]));
System.out.println(extractor.getText());
}
/**
* Should a call to getText() return slide text?
* Default is yes
*/
public void setSlidesByDefault(boolean slidesByDefault) {
this.slidesByDefault = slidesByDefault;
}
/**
* Should a call to getText() return notes text?
* Default is no
*/
public void setNotesByDefault(boolean notesByDefault) {
this.notesByDefault = notesByDefault;
}
/**
* Gets the slide text, but not the notes text
*/
public String getText() {
return getText(slidesByDefault, notesByDefault);
}
/**
* Gets the requested text from the file
* @param slideText Should we retrieve text from slides?
* @param notesText Should we retrieve text from notes?
*/
public String getText(boolean slideText, boolean notesText) {
StringBuffer text = new StringBuffer();
XSLFSlide[] slides = slideshow.getSlides();
for(int i = 0; i < slides.length; i++) {
CTSlide rawSlide = slides[i]._getCTSlide();
CTSlideIdListEntry slideId = slides[i]._getCTSlideId();
try {
// For now, still very low level
CTNotesSlide notes =
slideshow._getXSLFSlideShow().getNotes(slideId);
CTCommentList comments =
slideshow._getXSLFSlideShow().getSlideComments(slideId);
if(slideText) {
extractText(rawSlide.getCSld().getSpTree(), text);
// Comments too for the slide
if(comments != null) {
for(CTComment comment : comments.getCmArray()) {
// TODO - comment authors too
// (They're in another stream)
text.append(
comment.getText() + "\n"
);
}
}
}
if(notesText && notes != null) {
extractText(notes.getCSld().getSpTree(), text);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
}
return text.toString();
}
private void extractText(CTGroupShape gs, StringBuffer text) {
CTShape[] shapes = gs.getSpArray();
for (int i = 0; i < shapes.length; i++) {
CTTextBody textBody =
shapes[i].getTxBody();
if(textBody != null) {
CTTextParagraph[] paras =
textBody.getPArray();
for (int j = 0; j < paras.length; j++) {
- CTRegularTextRun[] textRuns =
- paras[j].getRArray();
- for (int k = 0; k < textRuns.length; k++) {
- text.append( textRuns[k].getT() );
- }
+ XmlCursor c = paras[j].newCursor();
+ c.selectPath("./*");
+ while (c.toNextSelection()) {
+ XmlObject o = c.getObject();
+ if(o instanceof CTRegularTextRun){
+ CTRegularTextRun txrun = (CTRegularTextRun)o;
+ text.append( txrun.getT() );
+ } else if (o instanceof CTTextLineBreak){
+ text.append('\n');
+ }
+ }
+
// End each paragraph with a new line
text.append("\n");
}
}
}
}
}
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java
index bfcdd6065..17f267b7c 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java
@@ -1,1374 +1,1376 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xssf.usermodel;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellAlignment;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
/**
*
* High level representation of the the possible formatting information for the contents of the cells on a sheet in a
* SpreadsheetML document.
*
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createCellStyle()
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#getCellStyleAt(short)
* @see org.apache.poi.xssf.usermodel.XSSFCell#setCellStyle(org.apache.poi.ss.usermodel.CellStyle)
*/
public class XSSFCellStyle implements CellStyle {
private int cellXfId;
private StylesTable stylesSource;
private CTXf cellXf;
private CTXf cellStyleXf;
private XSSFFont font;
private XSSFCellAlignment cellAlignment;
/**
* Creates a Cell Style from the supplied parts
* @param cellXfId The main XF for the cell
* @param cellStyleXfId Optional, style xf
* @param stylesSource Styles Source to work off
*/
public XSSFCellStyle(int cellXfId, int cellStyleXfId, StylesTable stylesSource) {
this.cellXfId = cellXfId;
this.stylesSource = stylesSource;
this.cellXf = stylesSource.getCellXfAt(this.cellXfId);
this.cellStyleXf = stylesSource.getCellStyleXfAt(cellStyleXfId);
}
/**
* Used so that StylesSource can figure out our location
*/
public CTXf getCoreXf() {
return cellXf;
}
/**
* Used so that StylesSource can figure out our location
*/
public CTXf getStyleXf() {
return cellStyleXf;
}
/**
* Creates an empty Cell Style
*/
public XSSFCellStyle(StylesTable stylesSource) {
this.stylesSource = stylesSource;
// We need a new CTXf for the main styles
// TODO decide on a style ctxf
cellXf = CTXf.Factory.newInstance();
cellStyleXf = null;
}
/**
* Verifies that this style belongs to the supplied Workbook
* Styles Source.
* Will throw an exception if it belongs to a different one.
* This is normally called when trying to assign a style to a
* cell, to ensure the cell and the style are from the same
* workbook (if they're not, it won't work)
* @throws IllegalArgumentException if there's a workbook mis-match
*/
public void verifyBelongsToStylesSource(StylesTable src) {
if(this.stylesSource != src) {
throw new IllegalArgumentException("This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?");
}
}
/**
* Clones all the style information from another
* XSSFCellStyle, onto this one. This
* XSSFCellStyle will then have all the same
* properties as the source, but the two may
* be edited independently.
* Any stylings on this XSSFCellStyle will be lost!
*
* The source XSSFCellStyle could be from another
* XSSFWorkbook if you like. This allows you to
* copy styles from one XSSFWorkbook to another.
*/
public void cloneStyleFrom(CellStyle source) {
if(source instanceof XSSFCellStyle) {
- this.cloneStyleFrom(source);
+ XSSFCellStyle src = (XSSFCellStyle)source;
+ cellXf.set(src.getCoreXf());
+ cellStyleXf.set(src.getStyleXf());
} else {
throw new IllegalArgumentException("Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle");
}
}
/**
* Get the type of horizontal alignment for the cell
*
* @return short - the type of alignment
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_GENERAL
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_LEFT
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_RIGHT
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_FILL
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_JUSTIFY
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER_SELECTION
*/
public short getAlignment() {
return (short)(getAlignmentEnum().ordinal());
}
/**
* Get the type of horizontal alignment for the cell
*
* @return HorizontalAlignment - the type of alignment
* @see org.apache.poi.ss.usermodel.HorizontalAlignment
*/
public HorizontalAlignment getAlignmentEnum() {
CTCellAlignment align = cellXf.getAlignment();
if(align != null && align.isSetHorizontal()) {
return HorizontalAlignment.values()[align.getHorizontal().intValue()-1];
} else {
return HorizontalAlignment.GENERAL;
}
}
/**
* Get the type of border to use for the bottom border of the cell
*
* @return short - border type
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THIN
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOTTED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THICK
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOUBLE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_HAIR
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public short getBorderBottom() {
if(!cellXf.getApplyBorder()) return BORDER_NONE;
int idx = (int)cellXf.getBorderId();
CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetBottom() ? ct.getBottom().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
}
/**
* Get the type of border to use for the bottom border of the cell
*
* @return border type as Java enum
* @see BorderStyle
*/
public BorderStyle getBorderBottomEnum() {
int style = getBorderBottom();
return BorderStyle.values()[style];
}
/**
* Get the type of border to use for the left border of the cell
*
* @return short - border type, default value is {@link org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE}
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THIN
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOTTED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THICK
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOUBLE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_HAIR
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public short getBorderLeft() {
if(!cellXf.getApplyBorder()) return BORDER_NONE;
int idx = (int)cellXf.getBorderId();
CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetLeft() ? ct.getLeft().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
}
/**
* Get the type of border to use for the left border of the cell
*
* @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE}
*/
public BorderStyle getBorderLeftEnum() {
int style = getBorderLeft();
return BorderStyle.values()[style];
}
/**
* Get the type of border to use for the right border of the cell
*
* @return short - border type, default value is {@link org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE}
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THIN
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOTTED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THICK
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOUBLE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_HAIR
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public short getBorderRight() {
if(!cellXf.getApplyBorder()) return BORDER_NONE;
int idx = (int)cellXf.getBorderId();
CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetRight() ? ct.getRight().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
}
/**
* Get the type of border to use for the right border of the cell
*
* @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE}
*/
public BorderStyle getBorderRightEnum() {
int style = getBorderRight();
return BorderStyle.values()[style];
}
/**
* Get the type of border to use for the top border of the cell
*
* @return short - border type, default value is {@link org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE}
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THIN
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOTTED
* @see org.apache.poi.ss.usermodel.CellStyle #BORDER_THICK
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOUBLE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_HAIR
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public short getBorderTop() {
if(!cellXf.getApplyBorder()) return BORDER_NONE;
int idx = (int)cellXf.getBorderId();
CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetTop() ? ct.getTop().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
}
/**
* Get the type of border to use for the top border of the cell
*
* @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE}
*/
public BorderStyle getBorderTopEnum() {
int style = getBorderTop();
return BorderStyle.values()[style];
}
/**
* Get the color to use for the bottom border
* <br/>
* Color is optional. When missing, IndexedColors.AUTOMATIC is implied.
* @return the index of the color definition, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#AUTOMATIC}
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public short getBottomBorderColor() {
XSSFColor clr = getBottomBorderXSSFColor();
return clr == null ? IndexedColors.BLACK.getIndex() : (short)clr.getIndexed();
}
/**
* Get the color to use for the bottom border as a {@link XSSFColor}
*
* @return the used color or <code>null</code> if not set
*/
public XSSFColor getBottomBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId();
XSSFCellBorder border = stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.BOTTOM);
}
/**
* Get the index of the number format (numFmt) record used by this cell format.
*
* @return the index of the number format
*/
public short getDataFormat() {
return (short)cellXf.getNumFmtId();
}
/**
* Get the contents of the format string, by looking up
* the StylesSource
*
* @return the number format string
*/
public String getDataFormatString() {
int idx = getDataFormat();
return new XSSFDataFormat(stylesSource).getFormat((short)idx);
}
/**
* Get the background fill color.
* <p>
* Note - many cells are actually filled with a foreground
* fill, not a background fill - see {@link #getFillForegroundColor()}
* </p>
* @return fill color, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#AUTOMATIC}
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public short getFillBackgroundColor() {
XSSFColor clr = getFillBackgroundXSSFColor();
return clr == null ? IndexedColors.AUTOMATIC.getIndex() : (short)clr.getIndexed();
}
/**
* Get the background fill color.
* <p>
* Note - many cells are actually filled with a foreground
* fill, not a background fill - see {@link #getFillForegroundColor()}
* </p>
* @see org.apache.poi.xssf.usermodel.XSSFColor#getRgb()
* @return XSSFColor - fill color or <code>null</code> if not set
*/
public XSSFColor getFillBackgroundXSSFColor() {
if(!cellXf.getApplyFill()) return null;
int fillIndex = (int)cellXf.getFillId();
XSSFCellFill fg = stylesSource.getFillAt(fillIndex);
return fg.getFillBackgroundColor();
}
/**
* Get the foreground fill color.
* <p>
* Many cells are filled with this, instead of a
* background color ({@link #getFillBackgroundColor()})
* </p>
* @see IndexedColors
* @return fill color, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#AUTOMATIC}
*/
public short getFillForegroundColor() {
XSSFColor clr = getFillForegroundXSSFColor();
return clr == null ? IndexedColors.AUTOMATIC.getIndex() : (short)clr.getIndexed();
}
/**
* Get the foreground fill color.
*
* @return XSSFColor - fill color or <code>null</code> if not set
*/
public XSSFColor getFillForegroundXSSFColor() {
if(!cellXf.getApplyFill()) return null;
int fillIndex = (int)cellXf.getFillId();
XSSFCellFill fg = stylesSource.getFillAt(fillIndex);
return fg.getFillForegroundColor();
}
/**
* Get the fill pattern
* @return fill pattern, default value is {@link org.apache.poi.ss.usermodel.CellStyle#NO_FILL}
*
* @see org.apache.poi.ss.usermodel.CellStyle#NO_FILL
* @see org.apache.poi.ss.usermodel.CellStyle#SOLID_FOREGROUND
* @see org.apache.poi.ss.usermodel.CellStyle#FINE_DOTS
* @see org.apache.poi.ss.usermodel.CellStyle#ALT_BARS
* @see org.apache.poi.ss.usermodel.CellStyle#SPARSE_DOTS
* @see org.apache.poi.ss.usermodel.CellStyle#THICK_HORZ_BANDS
* @see org.apache.poi.ss.usermodel.CellStyle#THICK_VERT_BANDS
* @see org.apache.poi.ss.usermodel.CellStyle#THICK_BACKWARD_DIAG
* @see org.apache.poi.ss.usermodel.CellStyle#THICK_FORWARD_DIAG
* @see org.apache.poi.ss.usermodel.CellStyle#BIG_SPOTS
* @see org.apache.poi.ss.usermodel.CellStyle#BRICKS
* @see org.apache.poi.ss.usermodel.CellStyle#THIN_HORZ_BANDS
* @see org.apache.poi.ss.usermodel.CellStyle#THIN_VERT_BANDS
* @see org.apache.poi.ss.usermodel.CellStyle#THIN_BACKWARD_DIAG
* @see org.apache.poi.ss.usermodel.CellStyle#THIN_FORWARD_DIAG
* @see org.apache.poi.ss.usermodel.CellStyle#SQUARES
* @see org.apache.poi.ss.usermodel.CellStyle#DIAMONDS
*/
public short getFillPattern() {
if(!cellXf.getApplyFill()) return 0;
int fillIndex = (int)cellXf.getFillId();
XSSFCellFill fill = stylesSource.getFillAt(fillIndex);
STPatternType.Enum ptrn = fill.getPatternType();
if(ptrn == null) return CellStyle.NO_FILL;
return (short)(ptrn.intValue() - 1);
}
/**
* Get the fill pattern
*
* @return the fill pattern, default value is {@link org.apache.poi.ss.usermodel.FillPatternType#NO_FILL}
*/
public FillPatternType getFillPatternEnum() {
int style = getFillPattern();
return FillPatternType.values()[style];
}
/**
* Gets the font for this style
* @return Font - font
*/
public XSSFFont getFont() {
if (font == null) {
font = stylesSource.getFontAt(getFontId());
}
return font;
}
/**
* Gets the index of the font for this style
*
* @return short - font index
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#getFontAt(short)
*/
public short getFontIndex() {
return (short) getFontId();
}
/**
* Get whether the cell's using this style are to be hidden
*
* @return boolean - whether the cell using this style is hidden
*/
public boolean getHidden() {
return getCellProtection().getHidden();
}
/**
* Get the number of spaces to indent the text in the cell
*
* @return indent - number of spaces
*/
public short getIndention() {
CTCellAlignment align = cellXf.getAlignment();
return (short)(align == null ? 0 : align.getIndent());
}
/**
* Get the index within the StylesTable (sequence within the collection of CTXf elements)
*
* @return unique index number of the underlying record this style represents
*/
public short getIndex() {
return (short)this.cellXfId;
}
/**
* Get the color to use for the left border
*
* @return the index of the color definition, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#BLACK}
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public short getLeftBorderColor() {
XSSFColor clr = getLeftBorderXSSFColor();
return clr == null ? IndexedColors.BLACK.getIndex() : (short)clr.getIndexed();
}
/**
* Get the color to use for the left border
*
* @return the index of the color definition or <code>null</code> if not set
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public XSSFColor getLeftBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId();
XSSFCellBorder border = stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.LEFT);
}
/**
* Get whether the cell's using this style are locked
*
* @return whether the cell using this style are locked
*/
public boolean getLocked() {
return getCellProtection().getLocked();
}
/**
* Get the color to use for the right border
*
* @return the index of the color definition, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#BLACK}
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public short getRightBorderColor() {
XSSFColor clr = getRightBorderXSSFColor();
return clr == null ? IndexedColors.BLACK.getIndex() : (short)clr.getIndexed();
}
/**
* Get the color to use for the right border
*
* @return the used color or <code>null</code> if not set
*/
public XSSFColor getRightBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId();
XSSFCellBorder border = stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.RIGHT);
}
/**
* Get the degree of rotation for the text in the cell
* <p>
* Expressed in degrees. Values range from 0 to 180. The first letter of
* the text is considered the center-point of the arc.
* <br/>
* For 0 - 90, the value represents degrees above horizon. For 91-180 the degrees below the
* horizon is calculated as:
* <br/>
* <code>[degrees below horizon] = 90 - textRotation.</code>
* </p>
*
* @return rotation degrees (between 0 and 180 degrees)
*/
public short getRotation() {
CTCellAlignment align = cellXf.getAlignment();
return (short)(align == null ? 0 : align.getTextRotation());
}
/**
* Get the color to use for the top border
*
* @return the index of the color definition, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#BLACK}
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public short getTopBorderColor() {
XSSFColor clr = getTopBorderXSSFColor();
return clr == null ? IndexedColors.BLACK.getIndex() : (short)clr.getIndexed();
}
/**
* Get the color to use for the top border
*
* @return the used color or <code>null</code> if not set
*/
public XSSFColor getTopBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId();
XSSFCellBorder border = stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.TOP);
}
/**
* Get the type of vertical alignment for the cell
*
* @return align the type of alignment, default value is {@link org.apache.poi.ss.usermodel.CellStyle#VERTICAL_BOTTOM}
* @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_TOP
* @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_CENTER
* @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_BOTTOM
* @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_JUSTIFY
*/
public short getVerticalAlignment() {
return (short) (getVerticalAlignmentEnum().ordinal());
}
/**
* Get the type of vertical alignment for the cell
*
* @return the type of alignment, default value is {@link org.apache.poi.ss.usermodel.VerticalAlignment#BOTTOM}
* @see org.apache.poi.ss.usermodel.VerticalAlignment
*/
public VerticalAlignment getVerticalAlignmentEnum() {
CTCellAlignment align = cellXf.getAlignment();
if(align != null && align.isSetVertical()) {
return VerticalAlignment.values()[align.getVertical().intValue()-1];
} else {
return VerticalAlignment.BOTTOM;
}
}
/**
* Whether the text should be wrapped
*
* @return a boolean value indicating if the text in a cell should be line-wrapped within the cell.
*/
public boolean getWrapText() {
CTCellAlignment align = cellXf.getAlignment();
return align != null && align.getWrapText();
}
/**
* Set the type of horizontal alignment for the cell
*
* @param align - the type of alignment
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_GENERAL
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_LEFT
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_RIGHT
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_FILL
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_JUSTIFY
* @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER_SELECTION
*/
public void setAlignment(short align) {
getCellAlignment().setHorizontal(HorizontalAlignment.values()[align]);
}
/**
* Set the type of horizontal alignment for the cell
*
* @param align - the type of alignment
* @see org.apache.poi.ss.usermodel.HorizontalAlignment
*/
public void setAlignment(HorizontalAlignment align) {
setAlignment((short)align.ordinal());
}
/**
* Set the type of border to use for the bottom border of the cell
*
* @param border the type of border to use
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THIN
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOTTED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THICK
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOUBLE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_HAIR
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public void setBorderBottom(short border) {
CTBorder ct = getCTBorder();
CTBorderPr pr = ct.isSetBottom() ? ct.getBottom() : ct.addNewBottom();
if(border == BORDER_NONE) ct.unsetBottom();
else pr.setStyle(STBorderStyle.Enum.forInt(border + 1));
int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx);
cellXf.setApplyBorder(true);
}
/**
* Set the type of border to use for the bottom border of the cell
*
* @param border - type of border to use
* @see org.apache.poi.ss.usermodel.BorderStyle
*/
public void setBorderBottom(BorderStyle border) {
setBorderBottom((short)border.ordinal());
}
/**
* Set the type of border to use for the left border of the cell
* @param border the type of border to use
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THIN
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOTTED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THICK
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOUBLE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_HAIR
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public void setBorderLeft(short border) {
CTBorder ct = getCTBorder();
CTBorderPr pr = ct.isSetLeft() ? ct.getLeft() : ct.addNewLeft();
if(border == BORDER_NONE) ct.unsetLeft();
else pr.setStyle(STBorderStyle.Enum.forInt(border + 1));
int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx);
cellXf.setApplyBorder(true);
}
/**
* Set the type of border to use for the left border of the cell
*
* @param border the type of border to use
*/
public void setBorderLeft(BorderStyle border) {
setBorderLeft((short)border.ordinal());
}
/**
* Set the type of border to use for the right border of the cell
*
* @param border the type of border to use
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THIN
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOTTED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THICK
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOUBLE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_HAIR
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public void setBorderRight(short border) {
CTBorder ct = getCTBorder();
CTBorderPr pr = ct.isSetRight() ? ct.getRight() : ct.addNewRight();
if(border == BORDER_NONE) ct.unsetRight();
else pr.setStyle(STBorderStyle.Enum.forInt(border + 1));
int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx);
cellXf.setApplyBorder(true);
}
/**
* Set the type of border to use for the right border of the cell
*
* @param border the type of border to use
*/
public void setBorderRight(BorderStyle border) {
setBorderRight((short)border.ordinal());
}
/**
* Set the type of border to use for the top border of the cell
*
* @param border the type of border to use
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_NONE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THIN
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOTTED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_THICK
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DOUBLE
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_HAIR
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASHED
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_MEDIUM_DASH_DOT_DOT
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public void setBorderTop(short border) {
CTBorder ct = getCTBorder();
CTBorderPr pr = ct.isSetTop() ? ct.getTop() : ct.addNewTop();
if(border == BORDER_NONE) ct.unsetTop();
else pr.setStyle(STBorderStyle.Enum.forInt(border + 1));
int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx);
cellXf.setApplyBorder(true);
}
/**
* Set the type of border to use for the top border of the cell
*
* @param border the type of border to use
*/
public void setBorderTop(BorderStyle border) {
setBorderTop((short)border.ordinal());
}
/**
* Set the color to use for the bottom border
* @param color the index of the color definition
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public void setBottomBorderColor(short color) {
XSSFColor clr = new XSSFColor();
clr.setIndexed(color);
setBottomBorderColor(clr);
}
/**
* Set the color to use for the bottom border
*
* @param color the color to use, null means no color
*/
public void setBottomBorderColor(XSSFColor color) {
CTBorder ct = getCTBorder();
if(color == null && !ct.isSetBottom()) return;
CTBorderPr pr = ct.isSetBottom() ? ct.getBottom() : ct.addNewBottom();
if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor();
int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx);
cellXf.setApplyBorder(true);
}
/**
* Set the index of a data format
*
* @param fmt the index of a data format
*/
public void setDataFormat(short fmt) {
cellXf.setApplyNumberFormat(true);
cellXf.setNumFmtId((long)fmt);
}
/**
* Set the background fill color represented as a {@link XSSFColor} value.
* <p>
* For example:
* <pre>
* cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
* cs.setFillBackgroundXSSFColor(new XSSFColor(java.awt.Color.RED));
* </pre>
* optionally a Foreground and background fill can be applied:
* <i>Note: Ensure Foreground color is set prior to background</i>
* <pre>
* cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
* cs.setFillForegroundColor(new XSSFColor(java.awt.Color.BLUE));
* cs.setFillBackgroundColor(new XSSFColor(java.awt.Color.GREEN));
* </pre>
* or, for the special case of SOLID_FILL:
* <pre>
* cs.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND );
* cs.setFillForegroundColor(new XSSFColor(java.awt.Color.GREEN));
* </pre>
* It is necessary to set the fill style in order
* for the color to be shown in the cell.
*
* @param color - the color to use
*/
public void setFillBackgroundColor(XSSFColor color) {
CTFill ct = getCTFill();
CTPatternFill ptrn = ct.getPatternFill();
if(color == null) {
if(ptrn != null) ptrn.unsetBgColor();
} else {
if(ptrn == null) ptrn = ct.addNewPatternFill();
ptrn.setBgColor(color.getCTColor());
}
int idx = stylesSource.putFill(new XSSFCellFill(ct));
cellXf.setFillId(idx);
cellXf.setApplyFill(true);
}
/**
* Set the background fill color represented as a indexed color value.
* <p>
* For example:
* <pre>
* cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
* cs.setFillBackgroundXSSFColor(IndexedColors.RED.getIndex());
* </pre>
* optionally a Foreground and background fill can be applied:
* <i>Note: Ensure Foreground color is set prior to background</i>
* <pre>
* cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
* cs.setFillForegroundColor(IndexedColors.BLUE.getIndex());
* cs.setFillBackgroundColor(IndexedColors.RED.getIndex());
* </pre>
* or, for the special case of SOLID_FILL:
* <pre>
* cs.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND );
* cs.setFillForegroundColor(IndexedColors.RED.getIndex());
* </pre>
* It is necessary to set the fill style in order
* for the color to be shown in the cell.
*
* @param bg - the color to use
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public void setFillBackgroundColor(short bg) {
XSSFColor clr = new XSSFColor();
clr.setIndexed(bg);
setFillBackgroundColor(clr);
}
/**
* Set the foreground fill color represented as a {@link XSSFColor} value.
* <br/>
* <i>Note: Ensure Foreground color is set prior to background color.</i>
* @param color the color to use
* @see #setFillBackgroundColor(org.apache.poi.xssf.usermodel.XSSFColor) )
*/
public void setFillForegroundColor(XSSFColor color) {
CTFill ct = getCTFill();
CTPatternFill ptrn = ct.getPatternFill();
if(color == null) {
if(ptrn != null) ptrn.unsetFgColor();
} else {
if(ptrn == null) ptrn = ct.addNewPatternFill();
ptrn.setFgColor(color.getCTColor());
}
int idx = stylesSource.putFill(new XSSFCellFill(ct));
cellXf.setFillId(idx);
cellXf.setApplyFill(true);
}
/**
* Set the foreground fill color as a indexed color value
* <br/>
* <i>Note: Ensure Foreground color is set prior to background color.</i>
* @param fg the color to use
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public void setFillForegroundColor(short fg) {
XSSFColor clr = new XSSFColor();
clr.setIndexed(fg);
setFillForegroundColor(clr);
}
/**
* Get a <b>copy</b> of the currently used CTFill, if none is used, return a new instance.
*/
private CTFill getCTFill(){
CTFill ct;
if(cellXf.getApplyFill()) {
int fillIndex = (int)cellXf.getFillId();
XSSFCellFill cf = stylesSource.getFillAt(fillIndex);
ct = (CTFill)cf.getCTFill().copy();
} else {
ct = CTFill.Factory.newInstance();
}
return ct;
}
/**
* Get a <b>copy</b> of the currently used CTBorder, if none is used, return a new instance.
*/
private CTBorder getCTBorder(){
CTBorder ct;
if(cellXf.getApplyBorder()) {
int idx = (int)cellXf.getBorderId();
XSSFCellBorder cf = stylesSource.getBorderAt(idx);
ct = (CTBorder)cf.getCTBorder().copy();
} else {
ct = CTBorder.Factory.newInstance();
}
return ct;
}
/**
* This element is used to specify cell fill information for pattern and solid color cell fills.
* For solid cell fills (no pattern), foregorund color is used.
* For cell fills with patterns specified, then the cell fill color is specified by the background color.
*
* @see org.apache.poi.ss.usermodel.CellStyle#NO_FILL
* @see org.apache.poi.ss.usermodel.CellStyle#SOLID_FOREGROUND
* @see org.apache.poi.ss.usermodel.CellStyle#FINE_DOTS
* @see org.apache.poi.ss.usermodel.CellStyle#ALT_BARS
* @see org.apache.poi.ss.usermodel.CellStyle#SPARSE_DOTS
* @see org.apache.poi.ss.usermodel.CellStyle#THICK_HORZ_BANDS
* @see org.apache.poi.ss.usermodel.CellStyle#THICK_VERT_BANDS
* @see org.apache.poi.ss.usermodel.CellStyle#THICK_BACKWARD_DIAG
* @see org.apache.poi.ss.usermodel.CellStyle#THICK_FORWARD_DIAG
* @see org.apache.poi.ss.usermodel.CellStyle#BIG_SPOTS
* @see org.apache.poi.ss.usermodel.CellStyle#BRICKS
* @see org.apache.poi.ss.usermodel.CellStyle#THIN_HORZ_BANDS
* @see org.apache.poi.ss.usermodel.CellStyle#THIN_VERT_BANDS
* @see org.apache.poi.ss.usermodel.CellStyle#THIN_BACKWARD_DIAG
* @see org.apache.poi.ss.usermodel.CellStyle#THIN_FORWARD_DIAG
* @see org.apache.poi.ss.usermodel.CellStyle#SQUARES
* @see org.apache.poi.ss.usermodel.CellStyle#DIAMONDS
* @see #setFillBackgroundColor(short)
* @see #setFillForegroundColor(short)
* @param fp fill pattern (set to {@link org.apache.poi.ss.usermodel.CellStyle#SOLID_FOREGROUND} to fill w/foreground color)
*/
public void setFillPattern(short fp) {
CTFill ct = getCTFill();
CTPatternFill ptrn = ct.isSetPatternFill() ? ct.getPatternFill() : ct.addNewPatternFill();
if(fp == NO_FILL && ptrn.isSetPatternType()) ptrn.unsetPatternType();
else ptrn.setPatternType(STPatternType.Enum.forInt(fp + 1));
int idx = stylesSource.putFill(new XSSFCellFill(ct));
cellXf.setFillId(idx);
cellXf.setApplyFill(true);
}
/**
* This element is used to specify cell fill information for pattern and solid color cell fills. For solid cell fills (no pattern),
* foreground color is used is used. For cell fills with patterns specified, then the cell fill color is specified by the background color element.
*
* @param ptrn the fill pattern to use
* @see #setFillBackgroundColor(short)
* @see #setFillForegroundColor(short)
* @see org.apache.poi.ss.usermodel.FillPatternType
*/
public void setFillPattern(FillPatternType ptrn) {
setFillPattern((short)ptrn.ordinal());
}
/**
* Set the font for this style
*
* @param font a font object created or retreived from the XSSFWorkbook object
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createFont()
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#getFontAt(short)
*/
public void setFont(Font font) {
if(font != null){
long index = font.getIndex();
this.cellXf.setFontId(index);
this.cellXf.setApplyFont(true);
} else {
this.cellXf.setApplyFont(false);
}
}
/**
* Set the cell's using this style to be hidden
*
* @param hidden - whether the cell using this style should be hidden
*/
public void setHidden(boolean hidden) {
getCellProtection().setHidden(hidden);
}
/**
* Set the number of spaces to indent the text in the cell
*
* @param indent - number of spaces
*/
public void setIndention(short indent) {
getCellAlignment().setIndent(indent);
}
/**
* Set the color to use for the left border as a indexed color value
*
* @param color the index of the color definition
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public void setLeftBorderColor(short color) {
XSSFColor clr = new XSSFColor();
clr.setIndexed(color);
setLeftBorderColor(clr);
}
/**
* Set the color to use for the left border as a {@link XSSFColor} value
*
* @param color the color to use
*/
public void setLeftBorderColor(XSSFColor color) {
CTBorder ct = getCTBorder();
if(color == null && !ct.isSetLeft()) return;
CTBorderPr pr = ct.isSetLeft() ? ct.getLeft() : ct.addNewLeft();
if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor();
int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx);
cellXf.setApplyBorder(true);
}
/**
* Set the cell's using this style to be locked
*
* @param locked - whether the cell using this style should be locked
*/
public void setLocked(boolean locked) {
getCellProtection().setLocked(locked);
}
/**
* Set the color to use for the right border
*
* @param color the index of the color definition
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public void setRightBorderColor(short color) {
XSSFColor clr = new XSSFColor();
clr.setIndexed(color);
setRightBorderColor(clr);
}
/**
* Set the color to use for the right border as a {@link XSSFColor} value
*
* @param color the color to use
*/
public void setRightBorderColor(XSSFColor color) {
CTBorder ct = getCTBorder();
if(color == null && !ct.isSetRight()) return;
CTBorderPr pr = ct.isSetRight() ? ct.getRight() : ct.addNewRight();
if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor();
int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx);
cellXf.setApplyBorder(true);
}
/**
* Set the degree of rotation for the text in the cell
* <p>
* Expressed in degrees. Values range from 0 to 180. The first letter of
* the text is considered the center-point of the arc.
* <br/>
* For 0 - 90, the value represents degrees above horizon. For 91-180 the degrees below the
* horizon is calculated as:
* <br/>
* <code>[degrees below horizon] = 90 - textRotation.</code>
* </p>
*
* @param rotation - the rotation degrees (between 0 and 180 degrees)
*/
public void setRotation(short rotation) {
getCellAlignment().setTextRotation(rotation);
}
/**
* Set the color to use for the top border
*
* @param color the index of the color definition
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public void setTopBorderColor(short color) {
XSSFColor clr = new XSSFColor();
clr.setIndexed(color);
setTopBorderColor(clr);
}
/**
* Set the color to use for the top border as a {@link XSSFColor} value
*
* @param color the color to use
*/
public void setTopBorderColor(XSSFColor color) {
CTBorder ct = getCTBorder();
if(color == null && !ct.isSetTop()) return;
CTBorderPr pr = ct.isSetTop() ? ct.getTop() : ct.addNewTop();
if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor();
int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx);
cellXf.setApplyBorder(true);
}
/**
* Set the type of vertical alignment for the cell
*
* @param align - align the type of alignment
* @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_TOP
* @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_CENTER
* @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_BOTTOM
* @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_JUSTIFY
* @see org.apache.poi.ss.usermodel.VerticalAlignment
*/
public void setVerticalAlignment(short align) {
getCellAlignment().setVertical(VerticalAlignment.values()[align]);
}
/**
* Set the type of vertical alignment for the cell
*
* @param align - the type of alignment
*/
public void setVerticalAlignment(VerticalAlignment align) {
getCellAlignment().setVertical(align);
}
/**
* Set whether the text should be wrapped.
* <p>
* Setting this flag to <code>true</code> make all content visible
* whithin a cell by displaying it on multiple lines
* </p>
*
* @param wrapped a boolean value indicating if the text in a cell should be line-wrapped within the cell.
*/
public void setWrapText(boolean wrapped) {
getCellAlignment().setWrapText(wrapped);
}
/**
* Gets border color
*
* @param side the border side
* @return the used color
*/
public XSSFColor getBorderColor(BorderSide side) {
switch(side){
case BOTTOM:
return getBottomBorderXSSFColor();
case RIGHT:
return getRightBorderXSSFColor();
case TOP:
return getTopBorderXSSFColor();
case LEFT:
return getLeftBorderXSSFColor();
default:
throw new IllegalArgumentException("Unknown border: " + side);
}
}
/**
* Set the color to use for the selected border
*
* @param side - where to apply the color definition
* @param color - the color to use
*/
public void setBorderColor(BorderSide side, XSSFColor color) {
switch(side){
case BOTTOM:
setBottomBorderColor(color);
break;
case RIGHT:
setRightBorderColor(color);
break;
case TOP:
setTopBorderColor(color);
break;
case LEFT:
setLeftBorderColor(color);
break;
}
}
private int getFontId() {
if (cellXf.isSetFontId()) {
return (int) cellXf.getFontId();
}
return (int) cellStyleXf.getFontId();
}
/**
* get a cellProtection from the supplied XML definition
* @return CTCellProtection
*/
private CTCellProtection getCellProtection() {
if (cellXf.getProtection() == null) {
cellXf.addNewProtection();
}
return cellXf.getProtection();
}
/**
* get the cellAlignment object to use for manage alignment
* @return XSSFCellAlignment - cell alignment
*/
protected XSSFCellAlignment getCellAlignment() {
if (this.cellAlignment == null) {
this.cellAlignment = new XSSFCellAlignment(getCTCellAlignment());
}
return this.cellAlignment;
}
/**
* Return the CTCellAlignment instance for alignment
*
* @return CTCellAlignment
*/
private CTCellAlignment getCTCellAlignment() {
if (cellXf.getAlignment() == null) {
cellXf.setAlignment(CTCellAlignment.Factory.newInstance());
}
return cellXf.getAlignment();
}
/**
* Returns a hash code value for the object. The hash is derived from the underlying CTXf bean.
*
* @return the hash code value for this style
*/
public int hashCode(){
return cellXf.toString().hashCode();
}
/**
* Checks is the supplied style is equal to this style
*
* @param o the style to check
* @return true if the supplied style is equal to this style
*/
public boolean equals(Object o){
if(o == null || !(o instanceof XSSFCellStyle)) return false;
XSSFCellStyle cf = (XSSFCellStyle)o;
return cellXf.toString().equals(cf.getCoreXf().toString());
}
/**
* Make a copy of this style. The underlying CTXf bean is cloned,
* the references to fills and borders remain.
*
* @return a copy of this style
*/
public Object clone(){
CTXf xf = (CTXf)cellXf.copy();
int xfSize = stylesSource._getStyleXfsSize();
int indexXf = stylesSource.putCellXf(xf);
return new XSSFCellStyle(indexXf-1, xfSize-1, stylesSource);
}
}
| false | false | null | null |
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/ClickListener.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/ClickListener.java
index 34c1d9770..b7e50744b 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/ClickListener.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/ClickListener.java
@@ -1,192 +1,193 @@
/*******************************************************************************
* 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.scenes.scene2d.utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.utils.TimeUtils;
/** Detects mouse over, mouse or finger touch presses, and clicks on an actor. A touch must go down over the actor and is
* considered pressed as long as it is over the actor or within the {@link #setTapSquareSize(float) tap square}. This behavior
* makes it easier to press buttons on a touch interface when the initial touch happens near the edge of the actor. Double clicks
* can be detected using {@link #getTapCount()}. Any touch (not just the first) will trigger this listener. While pressed, other
* touch downs are ignored.
* @author Nathan Sweet */
public class ClickListener extends InputListener {
private float tapSquareSize = 14, touchDownX = -1, touchDownY = -1;
private int pressedPointer = -1;
private int pressedButton = -1;
private int button;
private boolean pressed, over, cancelled;
private long tapCountInterval = (long)(0.4f * 1000000000l);
private int tapCount;
private long lastTapTime;
public ClickListener () {
}
/** @see #setButton(int) */
public ClickListener (int button) {
this.button = button;
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (pressed) return false;
if (pointer == 0 && this.button != -1 && button != this.button) return false;
pressed = true;
pressedPointer = pointer;
pressedButton = button;
touchDownX = x;
touchDownY = y;
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
if (pointer != pressedPointer || cancelled) return;
pressed = isOver(event.getListenerActor(), x, y);
if (pressed && pointer == 0 && button != -1 && !Gdx.input.isButtonPressed(button)) pressed = false;
if (!pressed) {
// Once outside the tap square, don't use the tap square anymore.
invalidateTapSquare();
}
}
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if (pointer == pressedPointer) {
if (!cancelled) {
- over = isOver(event.getListenerActor(), x, y);
- if (over && pointer == 0 && this.button != -1 && button != this.button) over = false;
- if (over) {
+ boolean touchUpOver = isOver(event.getListenerActor(), x, y);
+ // Ignore touch up if the wrong mouse button.
+ if (touchUpOver && pointer == 0 && this.button != -1 && button != this.button) touchUpOver = false;
+ if (touchUpOver) {
long time = TimeUtils.nanoTime();
if (time - lastTapTime > tapCountInterval) tapCount = 0;
tapCount++;
lastTapTime = time;
clicked(event, x, y);
}
}
pressed = false;
pressedPointer = -1;
pressedButton = -1;
cancelled = false;
}
}
public void enter (InputEvent event, float x, float y, int pointer, Actor fromActor) {
if (pointer == -1 && !cancelled) over = true;
}
public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) {
if (pointer == -1 && !cancelled) over = false;
}
/** If a touch down is being monitored, the drag and touch up events are ignored until the next touch up. */
public void cancel () {
if (pressedPointer == -1) return;
cancelled = true;
over = false;
pressed = false;
}
public void clicked (InputEvent event, float x, float y) {
}
public void dragStart (InputEvent event, float x, float y, int pointer) {
}
public void drag (InputEvent event, float x, float y, int pointer) {
}
public void dragStop (InputEvent event, float x, float y, int pointer) {
}
/** Returns true if the specified position is over the specified actor or within the tap square. */
public boolean isOver (Actor actor, float x, float y) {
Actor hit = actor.hit(x, y, true);
if (hit == null || !hit.isDescendantOf(actor)) return inTapSquare(x, y);
return true;
}
public boolean inTapSquare (float x, float y) {
if (touchDownX == -1 && touchDownY == -1) return false;
return Math.abs(x - touchDownX) < tapSquareSize && Math.abs(y - touchDownY) < tapSquareSize;
}
/** The tap square will not longer be used for the current touch. */
public void invalidateTapSquare () {
touchDownX = -1;
touchDownY = -1;
}
/** Returns true if a touch is over the actor or within the tap square. */
public boolean isPressed () {
return pressed;
}
/** Returns true if the mouse or touch is over the actor or pressed and within the tap square. */
public boolean isOver () {
return over || pressed;
}
public void setTapSquareSize (float halfTapSquareSize) {
tapSquareSize = halfTapSquareSize;
}
public float getTapSquareSize () {
return tapSquareSize;
}
/** @param tapCountInterval time in seconds that must pass for two touch down/up sequences to be detected as consecutive taps. */
public void setTapCountInterval (float tapCountInterval) {
this.tapCountInterval = (long)(tapCountInterval * 1000000000l);
}
/** Returns the number of taps within the tap count interval for the most recent click event. */
public int getTapCount () {
return tapCount;
}
public float getTouchDownX () {
return touchDownX;
}
public float getTouchDownY () {
return touchDownY;
}
/** The button that initially pressed this button or -1 if the button is not pressed. */
public int getPressedButton () {
return pressedButton;
}
/** The pointer that initially pressed this button or -1 if the button is not pressed. */
public int getPressedPointer () {
return pressedPointer;
}
/** @see #setButton(int) */
public int getButton () {
return button;
}
/** Sets the button to listen for, all other buttons are ignored. Default is {@link Buttons#LEFT}. Use -1 for any button. */
public void setButton (int button) {
this.button = button;
}
}
| true | true | public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if (pointer == pressedPointer) {
if (!cancelled) {
over = isOver(event.getListenerActor(), x, y);
if (over && pointer == 0 && this.button != -1 && button != this.button) over = false;
if (over) {
long time = TimeUtils.nanoTime();
if (time - lastTapTime > tapCountInterval) tapCount = 0;
tapCount++;
lastTapTime = time;
clicked(event, x, y);
}
}
pressed = false;
pressedPointer = -1;
pressedButton = -1;
cancelled = false;
}
}
| public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if (pointer == pressedPointer) {
if (!cancelled) {
boolean touchUpOver = isOver(event.getListenerActor(), x, y);
// Ignore touch up if the wrong mouse button.
if (touchUpOver && pointer == 0 && this.button != -1 && button != this.button) touchUpOver = false;
if (touchUpOver) {
long time = TimeUtils.nanoTime();
if (time - lastTapTime > tapCountInterval) tapCount = 0;
tapCount++;
lastTapTime = time;
clicked(event, x, y);
}
}
pressed = false;
pressedPointer = -1;
pressedButton = -1;
cancelled = false;
}
}
|
diff --git a/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsDomainConfigurationUtil.java b/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsDomainConfigurationUtil.java
index bc58b5d56..8f2fcbeeb 100644
--- a/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsDomainConfigurationUtil.java
+++ b/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsDomainConfigurationUtil.java
@@ -1,281 +1,287 @@
/* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.orm.hibernate.cfg;
import groovy.lang.GroovyObject;
import java.beans.IntrospectionException;
+import java.net.URI;
+import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.commons.metaclass.DynamicMethods;
import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.codehaus.groovy.grails.metaclass.AddRelatedDynamicMethod;
import org.codehaus.groovy.grails.metaclass.AddToRelatedDynamicMethod;
import org.codehaus.groovy.grails.metaclass.DomainClassMethods;
import org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateDomainClass;
import org.codehaus.groovy.grails.orm.support.TransactionManagerAware;
import org.hibernate.EntityMode;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.type.TypeFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
/**
* Utility methods used in configuring the Grails Hibernate integration
*
* @author Graeme Rocher
* @since 18-Feb-2006
*/
public class GrailsDomainConfigurationUtil {
private static final Log LOG = LogFactory.getLog(GrailsDomainConfigurationUtil.class);
/**
* Configures the relationships between domain classes after they have been all loaded.
*
* @param domainClasses
* @param domainMap
*/
public static void configureDomainClassRelationships(GrailsDomainClass[] domainClasses, Map domainMap) {
// configure super/sub class relationships
// and configure how domain class properties reference each other
for (int i = 0; i < domainClasses.length; i++) {
if(!domainClasses[i].isRoot()) {
Class superClass = domainClasses[i].getClazz().getSuperclass();
while(!superClass.equals(Object.class)&&!superClass.equals(GroovyObject.class)) {
GrailsDomainClass gdc = (GrailsDomainClass)domainMap.get(superClass.getName());
if (gdc == null || gdc.getSubClasses()==null)
break;
gdc.getSubClasses().add(domainClasses[i]);
superClass = superClass.getSuperclass();
}
}
GrailsDomainClassProperty[] props = domainClasses[i].getPersistantProperties();
for (int j = 0; j < props.length; j++) {
if(props[j].isAssociation()) {
GrailsDomainClassProperty prop = props[j];
GrailsDomainClass referencedGrailsDomainClass = (GrailsDomainClass)domainMap.get( props[j].getReferencedPropertyType().getName() );
prop.setReferencedDomainClass(referencedGrailsDomainClass);
}
}
}
// now configure so that the 'other side' of a property can be resolved by the property itself
for (int i = 0; i < domainClasses.length; i++) {
GrailsDomainClassProperty[] props = domainClasses[i].getPersistantProperties();
for (int j = 0; j < props.length; j++) {
if(props[j].isAssociation()) {
GrailsDomainClassProperty prop = props[j];
GrailsDomainClass referenced = prop.getReferencedDomainClass();
if(referenced != null) {
String refPropertyName = prop.getReferencedPropertyName();
if(!StringUtils.isBlank(refPropertyName)) {
prop.setOtherSide(referenced.getPropertyByName(refPropertyName));
}
else {
GrailsDomainClassProperty[] referencedProperties = referenced.getPersistantProperties();
for (int k = 0; k < referencedProperties.length; k++) {
// for bi-directional circular dependencies we don't want the other side
// to be equal to self
if(prop.equals(referencedProperties[k]) && prop.isBidirectional())
continue;
if(domainClasses[i].getClazz().equals(referencedProperties[k].getReferencedPropertyType())) {
prop.setOtherSide(referencedProperties[k]);
break;
}
}
}
}
}
}
}
}
/**
* Configures dynamic methods on all Hibernate mapped domain classes that are found in the application context
*
* @param applicationContext The session factory instance
* @param application The grails application instance
*/
public static void configureDynamicMethods(ApplicationContext applicationContext, GrailsApplication application) {
if(applicationContext == null)
throw new IllegalArgumentException("Cannot configure dynamic methods for null ApplicationContext");
SessionFactory sessionFactory = (SessionFactory)applicationContext.getBean(GrailsRuntimeConfigurator.SESSION_FACTORY_BEAN);
Collection dynamicMethods = configureDynamicMethods(sessionFactory, application);
for (Iterator i = dynamicMethods.iterator(); i.hasNext();) {
DomainClassMethods methods = (DomainClassMethods) i.next();
boolean isTransactionAware = applicationContext.containsBean(GrailsRuntimeConfigurator.TRANSACTION_MANAGER_BEAN) &&
(methods instanceof TransactionManagerAware);
if(isTransactionAware) {
PlatformTransactionManager ptm = (PlatformTransactionManager)applicationContext.getBean(GrailsRuntimeConfigurator.TRANSACTION_MANAGER_BEAN);
((TransactionManagerAware)methods).setTransactionManager(ptm);
}
}
}
public static Collection configureDynamicMethods(SessionFactory sessionFactory, GrailsApplication application) {
// if its not a grails domain class and one written in java then add it
// to grails
Map hibernateDomainClassMap = new HashMap();
Collection dynamicMethods = new ArrayList();
Collection classMetaData = sessionFactory.getAllClassMetadata().values();
for (Iterator i = classMetaData.iterator(); i.hasNext();) {
ClassMetadata cmd = (ClassMetadata) i.next();
Class persistentClass = cmd.getMappedClass(EntityMode.POJO);
GrailsDomainClass dc = null;
if(application != null && persistentClass != null) {
dc = configureDomainClass(sessionFactory, application, cmd, persistentClass, hibernateDomainClassMap);
}
if(dc != null) {
dynamicMethods.add( configureDynamicMethodsFor(sessionFactory, application, persistentClass, dc) );
}
}
configureInheritanceMappings(hibernateDomainClassMap);
return dynamicMethods;
}
private static DynamicMethods configureDynamicMethodsFor(SessionFactory sessionFactory, GrailsApplication application, Class persistentClass, GrailsDomainClass dc) {
LOG.debug("[GrailsDomainConfiguration] Registering dynamic methods on class ["+persistentClass+"]");
DynamicMethods dm = null;
try {
dm = new DomainClassMethods(application,persistentClass,sessionFactory,application.getClassLoader());
dm.addDynamicMethodInvocation(new AddToRelatedDynamicMethod(dc));
for (int j = 0; j < dc.getPersistantProperties().length; j++) {
GrailsDomainClassProperty p = dc.getPersistantProperties()[j];
if(p.isOneToMany() || p.isManyToMany()) {
dm.addDynamicMethodInvocation(new AddRelatedDynamicMethod(p));
}
}
} catch (IntrospectionException e) {
LOG.warn("[GrailsDomainConfiguration] Introspection exception registering dynamic methods for ["+persistentClass+"]:" + e.getMessage(), e);
}
return dm;
}
private static void configureInheritanceMappings(Map hibernateDomainClassMap) {
// now get through all domainclasses, and add all subclasses to root class
for (Iterator it = hibernateDomainClassMap.values().iterator(); it.hasNext(); ) {
GrailsDomainClass baseClass = (GrailsDomainClass) it.next();
if (! baseClass.isRoot()) {
Class superClass = baseClass
.getClazz().getSuperclass();
while(!superClass.equals(Object.class)&&!superClass.equals(GroovyObject.class)) {
GrailsDomainClass gdc = (GrailsDomainClass)hibernateDomainClassMap.get(superClass.getName());
if (gdc == null || gdc.getSubClasses()==null) {
LOG.error("did not find superclass names when mapping inheritance....");
break;
}
gdc.getSubClasses().add(baseClass);
superClass = superClass.getSuperclass();
}
}
}
}
private static GrailsDomainClass configureDomainClass(SessionFactory sessionFactory, GrailsApplication application, ClassMetadata cmd, Class persistentClass, Map hibernateDomainClassMap) {
GrailsDomainClass dc = application.getGrailsDomainClass(persistentClass.getName());
if( dc == null) {
// a patch to add inheritance to this system
GrailsHibernateDomainClass ghdc = new
GrailsHibernateDomainClass(persistentClass, sessionFactory,cmd);
hibernateDomainClassMap.put(persistentClass
.getClass()
.getName(),
ghdc);
dc = application.addDomainClass(ghdc);
}
return dc;
}
/**
* Returns the ORM frameworks mapping file name for the specified class name
*
* @param className
* @return The mapping file name
*/
public static String getMappingFileName(String className) {
String fileName = className.replaceAll("\\.", "/");
return fileName+=".hbm.xml";
}
/**
* Returns the association map for the specified domain class
* @param domainClass the domain class
* @return The association map
*/
public static Map getAssociationMap(Class domainClass) {
Map associationMap = (Map)GrailsClassUtils.getPropertyValueOfNewInstance( domainClass, GrailsDomainClassProperty.RELATES_TO_MANY, Map.class );
if(associationMap == null) {
associationMap = (Map)GrailsClassUtils.getPropertyValueOfNewInstance(domainClass, GrailsDomainClassProperty.HAS_MANY, Map.class);
if(associationMap == null) {
associationMap = Collections.EMPTY_MAP;
}
}
return associationMap;
}
/**
* Retrieves the mappedBy map for the specified class
* @param domainClass The domain class
* @return The mappedBy map
*/
public static Map getMappedByMap(Class domainClass) {
Map mappedByMap = (Map)GrailsClassUtils.getPropertyValueOfNewInstance(domainClass, GrailsDomainClassProperty.MAPPED_BY, Map.class);
if(mappedByMap == null) {
return Collections.EMPTY_MAP;
}
return mappedByMap;
}
/**
* Establish whether its a basic type
*
* @param prop The domain class property
* @return True if it is basic
*/
public static boolean isBasicType(GrailsDomainClassProperty prop) {
- return TypeFactory.basic(prop.getType().getName()) != null;
+ if(prop == null)return false;
+ Class propType = prop.getType();
+ return TypeFactory.basic(propType.getName()) != null ||
+ propType == URL.class ||
+ propType == URI.class;
}
}
| false | false | null | null |
diff --git a/api/src/main/java/org/openmrs/PersonAddress.java b/api/src/main/java/org/openmrs/PersonAddress.java
index 73c5b2b3..bb3a190f 100644
--- a/api/src/main/java/org/openmrs/PersonAddress.java
+++ b/api/src/main/java/org/openmrs/PersonAddress.java
@@ -1,641 +1,641 @@
/**
* 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;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.util.OpenmrsUtil;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
* This class is the representation of a person's address. This class is many-to-one to the Person
* class, so a Person/Patient/User can have zero to n addresses
*/
@Root(strict = false)
public class PersonAddress extends BaseOpenmrsData implements java.io.Serializable, Cloneable, Comparable<PersonAddress> {
public static final long serialVersionUID = 343333L;
private static final Log log = LogFactory.getLog(PersonAddress.class);
// Fields
private Integer personAddressId;
private Person person;
private Boolean preferred = false;
private String address1;
private String address2;
private String cityVillage;
private String address3;
private String countyDistrict;
private String address4;
private String address6;
private String address5;
private String stateProvince;
private String country;
private String postalCode;
private String latitude;
private String longitude;
private Date startDate;
private Date endDate;
// Constructors
/** default constructor */
public PersonAddress() {
}
/** constructor with id */
public PersonAddress(Integer personAddressId) {
this.personAddressId = personAddressId;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return "a1:" + getAddress1() + ", a2:" + getAddress2() + ", cv:" + getCityVillage() + ", sp:" + getStateProvince()
+ ", c:" + getCountry() + ", cd:" + getCountyDistrict() + ", nc:" + getNeighborhoodCell() + ", pc:"
+ getPostalCode() + ", lat:" + getLatitude() + ", long:" + getLongitude();
}
/**
* Compares this address to the given object/address for similarity. Uses the very basic
* comparison of just the PersonAddress.personAddressId
*
* @param obj Object (Usually PersonAddress) with which to compare
* @return boolean true/false whether or not they are the same objects
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (obj instanceof PersonAddress) {
PersonAddress p = (PersonAddress) obj;
if (this.getPersonAddressId() != null && p.getPersonAddressId() != null)
return (this.getPersonAddressId().equals(p.getPersonAddressId()));
}
return false;
}
/**
* Compares this PersonAddress object to the given otherAddress. This method differs from
* {@link #equals(Object)} in that this method compares the inner fields of each address for
* equality. Note: Null/empty fields on <code>otherAddress</code> /will not/ cause a false value
* to be returned
*
* @param otherAddress PersonAddress with which to compare
* @return boolean true/false whether or not they are the same addresses
*/
@SuppressWarnings("unchecked")
public boolean equalsContent(PersonAddress otherAddress) {
boolean returnValue = true;
// these are the methods to compare. All are expected to be Strings
- String[] methods = { "getAddress1", "getAddress2", "getAddress3", "getAddress4", "getAddress5", "getCityVillage",
- "getNeighborhoodCell", "getCountyDistrict", "getStateProvince", "getCountry", "getPostalCode",
- "getLatitude", "getLongitude" };
+ String[] methods = { "getAddress1", "getAddress2", "getAddress3", "getAddress4", "getAddress5", "getAddress6",
+ "getCityVillage", "getCountyDistrict", "getStateProvince", "getCountry", "getPostalCode", "getLatitude",
+ "getLongitude" };
Class addressClass = this.getClass();
// loop over all of the selected methods and compare this and other
for (String methodName : methods) {
try {
Method method = addressClass.getMethod(methodName, new Class[] {});
String thisValue = (String) method.invoke(this);
String otherValue = (String) method.invoke(otherAddress);
if (otherValue != null && otherValue.length() > 0)
returnValue &= otherValue.equals(thisValue);
}
catch (NoSuchMethodException e) {
log.warn("No such method for comparison " + methodName, e);
}
catch (IllegalAccessException e) {
log.error("Error while comparing addresses", e);
}
catch (InvocationTargetException e) {
log.error("Error while comparing addresses", e);
}
}
return returnValue;
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
if (this.getPersonAddressId() == null)
return super.hashCode();
return this.getPersonAddressId().hashCode();
}
/**
* bitwise copy of the personAddress object. NOTICE: THIS WILL NOT COPY THE PATIENT OBJECT. The
* PersonAddress.person object in this object AND the cloned object will point at the same
* person
*
* @return New PersonAddress object
*/
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
throw new InternalError("PersonAddress should be cloneable");
}
}
/**
* @return Returns the address1.
*/
@Element(data = true, required = false)
public String getAddress1() {
return address1;
}
/**
* @param address1 The address1 to set.
*/
@Element(data = true, required = false)
public void setAddress1(String address1) {
this.address1 = address1;
}
/**
* @return Returns the address2.
*/
@Element(data = true, required = false)
public String getAddress2() {
return address2;
}
/**
* @param address2 The address2 to set.
*/
@Element(data = true, required = false)
public void setAddress2(String address2) {
this.address2 = address2;
}
/**
* @return Returns the cityVillage.
*/
@Element(data = true, required = false)
public String getCityVillage() {
return cityVillage;
}
/**
* @param cityVillage The cityVillage to set.
*/
@Element(data = true, required = false)
public void setCityVillage(String cityVillage) {
this.cityVillage = cityVillage;
}
/**
* @return Returns the country.
*/
@Element(data = true, required = false)
public String getCountry() {
return country;
}
/**
* @param country The country to set.
*/
@Element(data = true, required = false)
public void setCountry(String country) {
this.country = country;
}
/**
* @return Returns the preferred.
*/
public Boolean isPreferred() {
if (preferred == null)
return new Boolean(false);
return preferred;
}
@Attribute(required = true)
public Boolean getPreferred() {
return isPreferred();
}
/**
* @param preferred The preferred to set.
*/
@Attribute(required = true)
public void setPreferred(Boolean preferred) {
this.preferred = preferred;
}
/**
* @return Returns the latitude.
*/
@Attribute(required = false)
public String getLatitude() {
return latitude;
}
/**
* @param latitude The latitude to set.
*/
@Attribute(required = false)
public void setLatitude(String latitude) {
this.latitude = latitude;
}
/**
* @return Returns the longitude.
*/
@Attribute(required = false)
public String getLongitude() {
return longitude;
}
/**
* @param longitude The longitude to set.
*/
@Attribute(required = false)
public void setLongitude(String longitude) {
this.longitude = longitude;
}
/**
* @return Returns the person.
*/
@Element(required = true)
public Person getPerson() {
return person;
}
/**
* @param person The person to set.
*/
@Element(required = true)
public void setPerson(Person person) {
this.person = person;
}
/**
* @return Returns the personAddressId.
*/
@Attribute(required = true)
public Integer getPersonAddressId() {
return personAddressId;
}
/**
* @param personAddressId The personAddressId to set.
*/
@Attribute(required = true)
public void setPersonAddressId(Integer personAddressId) {
this.personAddressId = personAddressId;
}
/**
* @return Returns the postalCode.
*/
@Element(data = true, required = false)
public String getPostalCode() {
return postalCode;
}
/**
* @param postalCode The postalCode to set.
*/
@Element(data = true, required = false)
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
/**
* @return Returns the stateProvince.
*/
@Element(data = true, required = false)
public String getStateProvince() {
return stateProvince;
}
/**
* @param stateProvince The stateProvince to set.
*/
@Element(data = true, required = false)
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
/**
* @return Returns the countyDistrict.
*/
@Element(data = true, required = false)
public String getCountyDistrict() {
return countyDistrict;
}
/**
* @param countyDistrict The countyDistrict to set.
*/
@Element(data = true, required = false)
public void setCountyDistrict(String countyDistrict) {
this.countyDistrict = countyDistrict;
}
/**
* @deprecated As of 1.8, replaced by {@link #getAddress3()}
* @return Returns the neighborhoodCell.
*/
@Deprecated
@Element(data = true, required = false)
public String getNeighborhoodCell() {
return getAddress3();
}
/**
* @deprecated As of 1.8, replaced by {@link #setAddress3(String)}
* @param address3 The neighborhoodCell to set.
*/
@Deprecated
@Element(data = true, required = false)
public void setNeighborhoodCell(String address3) {
this.setAddress3(address3);
}
/**
* Convenience method to test whether any of the fields in this address are set
*
* @return whether any of the address fields (address1, address2, cityVillage, stateProvince,
* country, countyDistrict, neighborhoodCell, postalCode, latitude, longitude) are
* non-null
*/
public boolean isBlank() {
return getAddress1() == null && getAddress2() == null && getCityVillage() == null && getStateProvince() == null
&& getCountry() == null && getCountyDistrict() == null && getNeighborhoodCell() == null
&& getPostalCode() == null && getLatitude() == null && getLongitude() == null;
}
/**
* @deprecated As of 1.8, replaced by {@link #getAddress6()}
* @return the region
*/
@Deprecated
@Element(data = true, required = false)
public String getRegion() {
return getAddress6();
}
/**
* @deprecated As of 1.8, replaced by {@link #setAddress6(String)}
* @param address6 the region to set
*/
@Deprecated
@Element(data = true, required = false)
public void setRegion(String address6) {
this.setAddress6(address6);
}
/**
* @deprecated As of 1.8, replaced by {@link #getAddress5()}
* @return the subregion
*/
@Deprecated
@Element(data = true, required = false)
public String getSubregion() {
return getAddress5();
}
/**
* @deprecated As of 1.8, replaced by {@link #setAddress5(String)}
* @param address5 the subregion to set
*/
@Deprecated
@Element(data = true, required = false)
public void setSubregion(String address5) {
this.setAddress5(address5);
}
/**
* @deprecated As of 1.8, replaced by {@link #getAddress4()}
* @return the townshipDivision
*/
@Deprecated
@Element(data = true, required = false)
public String getTownshipDivision() {
return getAddress4();
}
/**
* @deprecated As of 1.8, replaced by {@link #setAddress4(String)}
* @param address4 the address4 to set
*/
@Deprecated
@Element(data = true, required = false)
public void setTownshipDivision(String address4) {
this.setAddress4(address4);
}
/**
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(PersonAddress other) {
int retValue = 0;
if (other != null) {
retValue = isVoided().compareTo(other.isVoided());
if (retValue == 0)
retValue = other.isPreferred().compareTo(isPreferred());
if (retValue == 0 && getDateCreated() != null)
retValue = OpenmrsUtil.compareWithNullAsLatest(getDateCreated(), other.getDateCreated());
if (retValue == 0)
retValue = OpenmrsUtil.compareWithNullAsGreatest(getPersonAddressId(), other.getPersonAddressId());
// if we've gotten this far, just check all address values. If they are
// equal, leave the objects at 0. If not, arbitrarily pick retValue=1
// and return that (they are not equal).
if (retValue == 0 && !equalsContent(other))
retValue = 1;
}
return retValue;
}
/**
* @since 1.8
* @return the address3
*/
public String getAddress3() {
return address3;
}
/**
* @since 1.8
* @param address3 the address3 to set
*/
public void setAddress3(String address3) {
this.address3 = address3;
}
/**
* @since 1.8
* @return the address4
*/
public String getAddress4() {
return address4;
}
/**
* @since 1.8
* @param address4 the address4 to set
*/
public void setAddress4(String address4) {
this.address4 = address4;
}
/**
* @since 1.8
* @return the address6
*/
public String getAddress6() {
return address6;
}
/**
* @since 1.8
* @param address6 the address6 to set
*/
public void setAddress6(String address6) {
this.address6 = address6;
}
/**
* @since 1.8
* @return the address5
*/
public String getAddress5() {
return address5;
}
/**
* @since 1.8
* @param address5 the address5 to set
*/
public void setAddress5(String address5) {
this.address5 = address5;
}
/**
* @since 1.5
* @see org.openmrs.OpenmrsObject#getId()
*/
public Integer getId() {
return getPersonAddressId();
}
/**
* @since 1.5
* @see org.openmrs.OpenmrsObject#setId(java.lang.Integer)
*/
public void setId(Integer id) {
setPersonAddressId(id);
}
/**
* @return the startDate
* @since 1.9
*/
public Date getStartDate() {
return startDate;
}
/**
* @param startDate to set to
* @since 1.9
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
/**
* @return the endDate
* @since 1.9
*/
public Date getEndDate() {
return this.endDate;
}
/**
* @param endDate to set to
* @since 1.9
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* Returns true if the address' endDate is null
*
* @return true or false
* @since 1.9
*/
public Boolean isActive() {
return (this.endDate == null);
}
/**
* Makes an address inactive by setting its endDate to the current time
*
* @since 1.9
*/
public void inactivate() {
setEndDate(Calendar.getInstance().getTime());
}
/**
* Makes an address active by setting its endDate to null
*
* @since 1.9
*/
public void activate() {
setEndDate(null);
}
}
| true | true | public boolean equalsContent(PersonAddress otherAddress) {
boolean returnValue = true;
// these are the methods to compare. All are expected to be Strings
String[] methods = { "getAddress1", "getAddress2", "getAddress3", "getAddress4", "getAddress5", "getCityVillage",
"getNeighborhoodCell", "getCountyDistrict", "getStateProvince", "getCountry", "getPostalCode",
"getLatitude", "getLongitude" };
Class addressClass = this.getClass();
// loop over all of the selected methods and compare this and other
for (String methodName : methods) {
try {
Method method = addressClass.getMethod(methodName, new Class[] {});
String thisValue = (String) method.invoke(this);
String otherValue = (String) method.invoke(otherAddress);
if (otherValue != null && otherValue.length() > 0)
returnValue &= otherValue.equals(thisValue);
}
catch (NoSuchMethodException e) {
log.warn("No such method for comparison " + methodName, e);
}
catch (IllegalAccessException e) {
log.error("Error while comparing addresses", e);
}
catch (InvocationTargetException e) {
log.error("Error while comparing addresses", e);
}
}
return returnValue;
}
| public boolean equalsContent(PersonAddress otherAddress) {
boolean returnValue = true;
// these are the methods to compare. All are expected to be Strings
String[] methods = { "getAddress1", "getAddress2", "getAddress3", "getAddress4", "getAddress5", "getAddress6",
"getCityVillage", "getCountyDistrict", "getStateProvince", "getCountry", "getPostalCode", "getLatitude",
"getLongitude" };
Class addressClass = this.getClass();
// loop over all of the selected methods and compare this and other
for (String methodName : methods) {
try {
Method method = addressClass.getMethod(methodName, new Class[] {});
String thisValue = (String) method.invoke(this);
String otherValue = (String) method.invoke(otherAddress);
if (otherValue != null && otherValue.length() > 0)
returnValue &= otherValue.equals(thisValue);
}
catch (NoSuchMethodException e) {
log.warn("No such method for comparison " + methodName, e);
}
catch (IllegalAccessException e) {
log.error("Error while comparing addresses", e);
}
catch (InvocationTargetException e) {
log.error("Error while comparing addresses", e);
}
}
return returnValue;
}
|
diff --git a/annis-gui/src/main/java/annis/gui/servlets/BinaryServlet.java b/annis-gui/src/main/java/annis/gui/servlets/BinaryServlet.java
index ebd905066..2d1ed1983 100644
--- a/annis-gui/src/main/java/annis/gui/servlets/BinaryServlet.java
+++ b/annis-gui/src/main/java/annis/gui/servlets/BinaryServlet.java
@@ -1,208 +1,206 @@
/*
* Copyright 2009-2011 Collaborative Research Centre SFB 632
*
* 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 annis.gui.servlets;
import annis.provider.SaltProjectProvider;
import annis.service.objects.AnnisBinary;
import annis.service.objects.AnnisBinaryMetaData;
import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientHandlerException;
+import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import java.io.IOException;
import java.net.URLEncoder;
import java.rmi.RemoteException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This Servlet provides binary-files with a stream of partial-content. The
* first GET-request is answered with the status-code 206 Partial Content.
*
* TODO: handle more than one byte-range TODO: split rmi-requests TODO: wrote
* tests TODO:
*
* @author benjamin
*
*/
public class BinaryServlet extends HttpServlet
{
private final Logger log = LoggerFactory.getLogger(BinaryServlet.class);
private static final int MAX_LENGTH = 50*1024; // max portion which is transfered over REST at once
private String toplevelCorpusName;
private String documentName;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
// get Parameter from url, actually it' s only the corpusId
Map<String, String[]> binaryParameter = request.getParameterMap();
toplevelCorpusName = binaryParameter.get("toplevelCorpusName")[0];
documentName = binaryParameter.get("documentName")[0];
ServletOutputStream out = null;
try
{
out = response.getOutputStream();
String range = request.getHeader("Range");
ClientConfig rc = new DefaultClientConfig(SaltProjectProvider.class);
Client c = Client.create(rc);
String annisServiceURL = getServletContext().getInitParameter("AnnisWebService.URL");
if(annisServiceURL == null)
{
throw new ServletException("AnnisWebService.URL was not set as init parameter in web.xml");
}
WebResource annisRes = c.resource(annisServiceURL);
WebResource binaryRes = annisRes.path("corpora")
.path(URLEncoder.encode(toplevelCorpusName, "UTF-8"))
.path(URLEncoder.encode(documentName, "UTF-8")).path("binary");
if (range != null)
{
responseStatus206(binaryRes, out, response, range);
}
else
{
responseStatus200(binaryRes, out, response);
}
out.flush();
}
catch(IOException ex)
{
log.debug("IOException in BinaryServlet", ex);
}
- finally
+ catch(ClientHandlerException ex)
{
- if(out != null)
- {
- try
- {
- out.close();
- }
- catch (IOException ex)
- {
- log.error(null, ex);
- }
- }
+ log.error(null, ex);
+ response.setStatus(500);
+ }
+ catch(UniformInterfaceException ex)
+ {
+ log.error(null, ex);
+ response.setStatus(500);
}
}
private void responseStatus206(WebResource binaryRes, ServletOutputStream out,
HttpServletResponse response, String range) throws RemoteException, IOException
{
AnnisBinaryMetaData bm = binaryRes.path("meta")
.get(AnnisBinary.class);
// Range: byte=x-y | Range: byte=0-
String[] rangeTupel = range.split("-");
int offset = Integer.parseInt(rangeTupel[0].split("=")[1]);
int slice;
if (rangeTupel.length > 1)
{
slice = Integer.parseInt(rangeTupel[1]);
}
else
{
slice = bm.getLength();
}
int lengthToFetch = slice - offset;
response.setHeader("Content-Range", "bytes " + offset + "-"
+ (bm.getLength() - 1) + "/" + bm.getLength());
response.setContentType(bm.getMimeType());
response.setStatus(206);
response.setContentLength(lengthToFetch);
writeStepByStep(offset, lengthToFetch, binaryRes, out);
}
private void responseStatus200(WebResource binaryRes, ServletOutputStream out,
HttpServletResponse response) throws RemoteException, IOException
{
AnnisBinaryMetaData binaryMeta = binaryRes.path("meta")
.get(AnnisBinary.class);
response.setStatus(200);
response.setHeader("Accept-Ranges", "bytes");
response.setContentType(binaryMeta.getMimeType());
response.setHeader("Content-Range", "bytes 0-" + (binaryMeta.getLength() - 1)
+ "/" + binaryMeta.getLength());
response.setContentLength(binaryMeta.getLength());
getCompleteFile(binaryRes, out);
}
/**
* This function get the whole binary-file and put it to responds.out there
* must exist at least one byte
*
*
* @param service
* @param out
* @param corpusId
*/
private void getCompleteFile(WebResource binaryRes, ServletOutputStream out)
throws RemoteException, IOException
{
AnnisBinaryMetaData annisBinary = binaryRes.path("meta")
.get(AnnisBinary.class);
int offset = 0;
int length = annisBinary.getLength();
writeStepByStep(offset, length, binaryRes, out);
}
private void writeStepByStep(int offset, int completeLength, WebResource binaryRes, ServletOutputStream out) throws IOException
{
int remaining = completeLength;
while(remaining > 0)
{
int stepLength = Math.min(MAX_LENGTH, remaining);
AnnisBinary bin = binaryRes.path("" + offset).path("" + stepLength).get(AnnisBinary.class);
Validate.isTrue(bin.getBytes().length == stepLength);
out.write(bin.getBytes());
out.flush();
offset += stepLength;
remaining = remaining - stepLength;
}
}
}
| false | false | null | null |
diff --git a/modules/standard/src/rescuecore2/standard/entities/StandardPropertyFactory.java b/modules/standard/src/rescuecore2/standard/entities/StandardPropertyFactory.java
index 12bd72b..cd75b96 100644
--- a/modules/standard/src/rescuecore2/standard/entities/StandardPropertyFactory.java
+++ b/modules/standard/src/rescuecore2/standard/entities/StandardPropertyFactory.java
@@ -1,71 +1,72 @@
package rescuecore2.standard.entities;
import rescuecore2.registry.AbstractPropertyFactory;
import rescuecore2.worldmodel.Property;
import rescuecore2.worldmodel.properties.IntProperty;
import rescuecore2.worldmodel.properties.IntArrayProperty;
import rescuecore2.worldmodel.properties.EntityRefProperty;
import rescuecore2.worldmodel.properties.EntityRefListProperty;
import rescuecore2.worldmodel.properties.BooleanProperty;
/**
PropertyFactory that builds standard Robocup Standard properties.
*/
public final class StandardPropertyFactory extends AbstractPropertyFactory<StandardPropertyURN> {
/**
Singleton class. Use this instance to do stuff.
*/
public static final StandardPropertyFactory INSTANCE = new StandardPropertyFactory();
/**
Singleton class: private constructor.
*/
private StandardPropertyFactory() {
super(StandardPropertyURN.class);
}
@Override
public Property makeProperty(StandardPropertyURN urn) {
switch (urn) {
case START_TIME:
case LONGITUDE:
case LATITUDE:
case WIND_FORCE:
case WIND_DIRECTION:
case X:
case Y:
case FLOORS:
case BUILDING_ATTRIBUTES:
case FIERYNESS:
case BROKENNESS:
case BUILDING_CODE:
case BUILDING_AREA_GROUND:
case BUILDING_AREA_TOTAL:
case DIRECTION:
case STAMINA:
case HP:
case DAMAGE:
case BURIEDNESS:
case WATER_QUANTITY:
case TEMPERATURE:
case IMPORTANCE:
case TRAVEL_DISTANCE:
+ case REPAIR_COST:
return new IntProperty(urn);
case APEXES:
case POSITION_HISTORY:
return new IntArrayProperty(urn);
case IGNITION:
return new BooleanProperty(urn);
case POSITION:
return new EntityRefProperty(urn);
case NEIGHBOURS:
case BLOCKADES:
return new EntityRefListProperty(urn);
case EDGES:
return new EdgeListProperty(urn);
default:
throw new IllegalArgumentException("Unrecognised property urn: " + urn);
}
}
}
\ No newline at end of file
diff --git a/modules/standard/src/rescuecore2/standard/kernel/StandardAgentRegistrar.java b/modules/standard/src/rescuecore2/standard/kernel/StandardAgentRegistrar.java
index 8718764..03001bb 100644
--- a/modules/standard/src/rescuecore2/standard/kernel/StandardAgentRegistrar.java
+++ b/modules/standard/src/rescuecore2/standard/kernel/StandardAgentRegistrar.java
@@ -1,169 +1,169 @@
package rescuecore2.standard.kernel;
import java.util.Set;
import java.util.HashSet;
import java.util.regex.PatternSyntaxException;
import kernel.AgentRegistrar;
import kernel.ComponentManager;
import kernel.KernelException;
import rescuecore2.config.Config;
import rescuecore2.worldmodel.WorldModel;
import rescuecore2.worldmodel.Entity;
import rescuecore2.worldmodel.Property;
import rescuecore2.Constants;
import rescuecore2.standard.entities.FireBrigade;
import rescuecore2.standard.entities.FireStation;
import rescuecore2.standard.entities.AmbulanceTeam;
import rescuecore2.standard.entities.AmbulanceCentre;
import rescuecore2.standard.entities.PoliceForce;
import rescuecore2.standard.entities.PoliceOffice;
import rescuecore2.standard.entities.Civilian;
import rescuecore2.standard.entities.Human;
import rescuecore2.standard.entities.Road;
import rescuecore2.standard.entities.Area;
import rescuecore2.standard.entities.Building;
import rescuecore2.standard.entities.StandardPropertyURN;
import rescuecore2.standard.entities.StandardEntityURN;
import rescuecore2.standard.entities.StandardWorldModel;
-import rescuecore2.standard.entities.Blockade;
-import rescuecore2.standard.entities.Civilian;
-import rescuecore2.standard.entities.StandardPropertyURN;
import rescuecore2.standard.StandardConstants;
/**
Class that registers standard agents.
*/
public class StandardAgentRegistrar implements AgentRegistrar {
private static final Set<String> VISIBLE_CONFIG_OPTIONS = new HashSet<String>();
static {
VISIBLE_CONFIG_OPTIONS.add("kernel\\.agents\\.think-time");
VISIBLE_CONFIG_OPTIONS.add("kernel\\.startup\\.connect-time");
VISIBLE_CONFIG_OPTIONS.add(Constants.COMMUNICATION_MODEL_KEY.replace(".", "\\."));
VISIBLE_CONFIG_OPTIONS.add(Constants.PERCEPTION_KEY.replace(".", "\\."));
VISIBLE_CONFIG_OPTIONS.add("fire\\.tank\\.maximum");
VISIBLE_CONFIG_OPTIONS.add("fire\\.tank\\.refill-rate");
VISIBLE_CONFIG_OPTIONS.add("fire\\.extinguish\\.max-sum");
VISIBLE_CONFIG_OPTIONS.add("fire\\.extinguish\\.max-distance");
VISIBLE_CONFIG_OPTIONS.add(StandardConstants.FIRE_BRIGADE_COUNT_KEY.replace(".", "\\."));
VISIBLE_CONFIG_OPTIONS.add(StandardConstants.FIRE_STATION_COUNT_KEY.replace(".", "\\."));
VISIBLE_CONFIG_OPTIONS.add(StandardConstants.AMBULANCE_TEAM_COUNT_KEY.replace(".", "\\."));
VISIBLE_CONFIG_OPTIONS.add(StandardConstants.AMBULANCE_CENTRE_COUNT_KEY.replace(".", "\\."));
VISIBLE_CONFIG_OPTIONS.add(StandardConstants.POLICE_FORCE_COUNT_KEY.replace(".", "\\."));
VISIBLE_CONFIG_OPTIONS.add(StandardConstants.POLICE_OFFICE_COUNT_KEY.replace(".", "\\."));
VISIBLE_CONFIG_OPTIONS.add("comms\\.channels\\.count");
VISIBLE_CONFIG_OPTIONS.add("comms\\.channels\\.max\\.platoon");
VISIBLE_CONFIG_OPTIONS.add("comms\\.channels\\.max\\.centre");
VISIBLE_CONFIG_OPTIONS.add("comms\\.channels\\.\\d+\\.type");
VISIBLE_CONFIG_OPTIONS.add("comms\\.channels\\.\\d+\\.range");
VISIBLE_CONFIG_OPTIONS.add("comms\\.channels\\.\\d+\\.messages\\.size");
VISIBLE_CONFIG_OPTIONS.add("comms\\.channels\\.\\d+\\.messages\\.max");
VISIBLE_CONFIG_OPTIONS.add("comms\\.channels\\.\\d+\\.bandwidth");
VISIBLE_CONFIG_OPTIONS.add("clear\\.repair\\.rate");
}
@Override
public void registerAgents(WorldModel<? extends Entity> world, Config config, ComponentManager manager) throws KernelException {
StandardWorldModel model = StandardWorldModel.createStandardWorldModel(world);
Config agentConfig = new Config(config);
try {
agentConfig.removeExceptRegex(VISIBLE_CONFIG_OPTIONS);
}
catch (PatternSyntaxException e) {
throw new KernelException(e);
}
agentConfig.setIntValue(StandardConstants.FIRE_BRIGADE_COUNT_KEY, model.getEntitiesOfType(StandardEntityURN.FIRE_BRIGADE).size());
agentConfig.setIntValue(StandardConstants.FIRE_STATION_COUNT_KEY, model.getEntitiesOfType(StandardEntityURN.FIRE_STATION).size());
agentConfig.setIntValue(StandardConstants.AMBULANCE_TEAM_COUNT_KEY, model.getEntitiesOfType(StandardEntityURN.AMBULANCE_TEAM).size());
agentConfig.setIntValue(StandardConstants.AMBULANCE_CENTRE_COUNT_KEY, model.getEntitiesOfType(StandardEntityURN.AMBULANCE_CENTRE).size());
agentConfig.setIntValue(StandardConstants.POLICE_FORCE_COUNT_KEY, model.getEntitiesOfType(StandardEntityURN.POLICE_FORCE).size());
agentConfig.setIntValue(StandardConstants.POLICE_OFFICE_COUNT_KEY, model.getEntitiesOfType(StandardEntityURN.POLICE_OFFICE).size());
Set<Entity> initialEntities = new HashSet<Entity>();
for (Entity e : world) {
maybeAddInitialEntity(e, initialEntities);
}
for (Entity e : world) {
if (e instanceof FireBrigade
|| e instanceof FireStation
|| e instanceof AmbulanceTeam
|| e instanceof AmbulanceCentre
|| e instanceof PoliceForce
|| e instanceof PoliceOffice
|| e instanceof Civilian) {
Set<Entity> s = new HashSet<Entity>(initialEntities);
s.add(e);
manager.registerAgentControlledEntity(e, s, agentConfig);
}
}
}
private void maybeAddInitialEntity(Entity e, Set<Entity> initialEntities) {
if (e instanceof Road) {
Road r = (Road)e.copy();
filterAreaProperties(r);
initialEntities.add(r);
}
if (e instanceof Building) {
Building b = (Building)e.copy();
filterBuildingProperties(b);
initialEntities.add(b);
}
if (e instanceof Human) {
if (!(e instanceof Civilian)) {
Human h = (Human)e.copy();
filterHumanProperties(h);
initialEntities.add(h);
}
}
}
private void filterAreaProperties(Area a) {
for (Property next : a.getProperties()) {
// Hide blockades
StandardPropertyURN urn = StandardPropertyURN.fromString(next.getURN());
switch (urn) {
case BLOCKADES:
next.undefine();
break;
default:
break;
}
}
}
private void filterBuildingProperties(Building b) {
filterAreaProperties(b);
for (Property next : b.getProperties()) {
// Hide ignition, fieryness, brokenness, temperature
StandardPropertyURN urn = StandardPropertyURN.fromString(next.getURN());
switch (urn) {
case IGNITION:
case FIERYNESS:
case BROKENNESS:
case TEMPERATURE:
next.undefine();
+ break;
+ default:
+ // Ignore
}
}
}
private void filterHumanProperties(Human h) {
for (Property next : h.getProperties()) {
// Human properties: POSITION, X, Y
// Everything else should be undefined
- StandardPropertyURN urn = StandardPropertyURN.valueOf(next.getURN());
+ StandardPropertyURN urn = StandardPropertyURN.fromString(next.getURN());
switch (urn) {
case X:
case Y:
case POSITION:
break;
default:
next.undefine();
}
}
}
}
\ No newline at end of file
diff --git a/modules/standard/src/rescuecore2/standard/view/AreaLayer.java b/modules/standard/src/rescuecore2/standard/view/AreaLayer.java
index 5ed73cf..4210a82 100644
--- a/modules/standard/src/rescuecore2/standard/view/AreaLayer.java
+++ b/modules/standard/src/rescuecore2/standard/view/AreaLayer.java
@@ -1,70 +1,69 @@
package rescuecore2.standard.view;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.Polygon;
import java.util.List;
import java.util.Iterator;
-import rescuecore2.worldmodel.EntityID;
import rescuecore2.misc.gui.ScreenTransform;
import rescuecore2.standard.entities.Area;
import rescuecore2.standard.entities.Edge;
/**
A view layer that renders areas.
@param <E> The subclass of Area that this layer knows how to draw.
*/
public abstract class AreaLayer<E extends Area> extends StandardEntityViewLayer<E> {
/**
Construct an area view layer.
@param clazz The subclass of Area this can render.
*/
protected AreaLayer(Class<E> clazz) {
super(clazz);
}
@Override
public Shape render(E area, Graphics2D g, ScreenTransform t) {
List<Edge> edges = area.getEdges();
if (edges.isEmpty()) {
return null;
}
int count = edges.size();
int[] xs = new int[count];
int[] ys = new int[count];
int i = 0;
for (Iterator<Edge> it = edges.iterator(); it.hasNext();) {
Edge e = it.next();
xs[i] = t.xToScreen(e.getStartX());
ys[i] = t.yToScreen(e.getStartY());
++i;
}
Polygon shape = new Polygon(xs, ys, count);
paintShape(area, shape, g);
for (Edge edge : edges) {
paintEdge(edge, g, t);
}
return shape;
}
/**
Paint an individual edge.
@param e The edge to paint.
@param g The graphics to paint on.
@param t The screen transform.
*/
protected void paintEdge(Edge e, Graphics2D g, ScreenTransform t) {
}
/**
Paint the overall shape.
@param area The area.
@param p The overall polygon.
@param g The graphics to paint on.
*/
protected void paintShape(E area, Polygon p, Graphics2D g) {
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/Calendar.java b/src/Calendar.java
index b62b7b9..df2fc98 100644
--- a/src/Calendar.java
+++ b/src/Calendar.java
@@ -1,38 +1,40 @@
import gui.CalendarBar;
import gui.LoginView;
import gui.WeekView;
import model.User;
public class Calendar {
private User user;
static Calendar calendar;
public Calendar() {
CalendarView view = new CalendarView();
- if (this.getUser() != null) {
+ if (this.getUser() == null) {
+ System.out.println("No user logged in");
LoginView loginView = new LoginView();
view.setContentView(loginView);
}
else {
+ System.out.println("Bruker logget inn");
WeekView week = new WeekView();
CalendarBar bar = new CalendarBar(2012, 3);
view.setContentView(week);
view.setSideBar(bar);
}
}
public void setUser(User user) {
this.user = user;
}
public User getUser() {
return this.user;
}
public static void main (String[] args) {
calendar = new Calendar();
}
}
diff --git a/src/CalendarView.java b/src/CalendarView.java
index 73cf6dd..5e56fe0 100644
--- a/src/CalendarView.java
+++ b/src/CalendarView.java
@@ -1,46 +1,48 @@
import gui.ContentView;
import gui.GUI_CONSTANTS;
import gui.StatusBar;
import gui.SideBar;
import javax.swing.*;
import java.awt.*;
public class CalendarView extends JFrame {
private StatusBar statusBar;
private SideBar sideBar;
private ContentView contentView;
public CalendarView() {
this.setTitle("Calendar");
this.setSize(GUI_CONSTANTS.calendarViewDimension);
this.setLayout(new BorderLayout());
this.setUp();
this.setVisible(true);
}
public void setUp() {
statusBar = new StatusBar();
this.add(statusBar, BorderLayout.NORTH);
sideBar = new SideBar();
this.add(sideBar, BorderLayout.WEST);
contentView = new ContentView();
this.add(contentView, BorderLayout.CENTER);
}
public void setSideBar(JPanel sideBar) {
+ System.out.println("Added sidebar");
this.sideBar.removeAll();
this.sideBar.add(sideBar);
}
public void setContentView(JPanel contentView) {
+ System.out.println("Added contentview");
this.contentView.removeAll();
this.contentView.add(contentView);
}
}
| false | false | null | null |
diff --git a/MODSRC/vazkii/tinkerer/lib/LibItemIDs.java b/MODSRC/vazkii/tinkerer/lib/LibItemIDs.java
index 70e405d4..64990685 100644
--- a/MODSRC/vazkii/tinkerer/lib/LibItemIDs.java
+++ b/MODSRC/vazkii/tinkerer/lib/LibItemIDs.java
@@ -1,38 +1,40 @@
package vazkii.tinkerer.lib;
public final class LibItemIDs {
public static final int DEFAULT_WAND_TINKERER = 21150;
public static final int DEFAULT_GLOWSTONE_GAS = 21151;
public static final int DEFAULT_SPELL_CLOTH = 21152;
public static final int DEFAULT_STOPWATCH = 21153;
public static final int DEFAULT_WAND_DISLOCATION = 21154;
public static final int DEFAULT_NAMETAG = 21155;
public static final int DEFAULT_XP_TALISMAN = 21156;
public static final int DEFAULT_FIRE_BRACELET = 21157;
public static final int DEFAULT_DARK_QUARTZ = 21158;
public static final int DEFAULT_TELEPORT_SIGIL = 21159;
public static final int DEFAULT_WAND_UPRISING = 21160;
public static final int DEFAULT_SWORD_CONDOR = 21161;
public static final int DEFAULT_DEATH_RUNE = 21162;
- public static final int DEFAULT_SILK_SWORD = 21162;
- public static final int DEFAULT_FORTUNE_MAUL = 21163;
- public static final int DEFAULT_ENDER_MIRROR = 21164;
+ public static final int DEFAULT_SILK_SWORD = 21163;
+ public static final int DEFAULT_FORTUNE_MAUL = 21164;
+ public static final int DEFAULT_ENDER_MIRROR = 21165;
+ public static final int DEFAULT_GOLIATH_LEGS = 21166;
public static int idWandTinkerer;
public static int idGlowstoneGas;
public static int idSpellCloth;
public static int idStopwatch;
public static int idWandDislocation;
public static int idNametag;
public static int idXpTalisman;
public static int idFireBracelet;
public static int idDarkQuartz;
public static int idTeleportSigil;
public static int idWandUprising;
public static int idSwordCondor;
public static int idDeathRune;
public static int idSilkSword;
public static int idFortuneMaul;
public static int idEnderMirror;
+ public static int idGoliathLegs;
}
| false | false | null | null |
diff --git a/src/org/mxupdate/update/AbstractObject_mxJPO.java b/src/org/mxupdate/update/AbstractObject_mxJPO.java
index fce2dbe7..9a7a34c1 100644
--- a/src/org/mxupdate/update/AbstractObject_mxJPO.java
+++ b/src/org/mxupdate/update/AbstractObject_mxJPO.java
@@ -1,709 +1,713 @@
/*
* Copyright 2008-2009 The MxUpdate Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.mxupdate.update;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.util.Set;
import java.util.TreeSet;
import matrix.util.MatrixException;
import org.mxupdate.mapping.PropertyDef_mxJPO;
import org.mxupdate.mapping.TypeDef_mxJPO;
import org.mxupdate.update.util.ParameterCache_mxJPO;
import org.mxupdate.update.util.StringUtil_mxJPO;
import org.mxupdate.util.MqlUtil_mxJPO;
import org.xml.sax.SAXException;
/**
* Abstract class from which must be derived for exporting and importing all
* administration (business) objects.
*
* @author The MxUpdate Team
* @version $Id$
*/
public abstract class AbstractObject_mxJPO
implements Serializable
{
/**
* Defines the serialize version unique identifier.
*/
private static final long serialVersionUID = -5505850566853070973L;
/**
* Key used to store the name of the program where all administration
* objects must be registered with symbolic names. For an OOTB installation
* the value is typically "eServiceSchemaVariableMapping.tcl".
*
* @see #readSymbolicNames(ParameterCache_mxJPO)
*/
private static final String PARAM_SYMB_NAME_PROG = "RegisterSymbolicNames";
/**
* Stores the version information of this object. If the value is
* <code>null</code>, the version information is not defined.
*
* @see #getVersion()
* @see #setVersion(String)
*/
private String version = null;
/**
* Defines the related type definition enumeration.
*
* @see #getTypeDef()
* @see #AbstractObject_mxJPO(TypeDef_mxJPO, String)
*/
private final TypeDef_mxJPO typeDef;
/**
* MX Name of the administration object.
*
* @see #getName()
*/
private final String mxName;
/**
* Author of the MX administration object.
*
* @see #setAuthor(String)
* @see #getAuthor()
*/
private String author;
/**
* Application of the MX administration object.
*
* @see #setApplication(String)
* @see #getApplication()
*/
private String application;
/**
* Description of the MX administration object.
*
* @see #setDescription(String)
* @see #getDescription()
*/
private String description = "";
/**
* Installation date of the MX administration object.
*
* @see #setInstallationDate(String)
* @see #getInstallationDate()
*/
private String installationDate;
/**
* Installer of the MX administration object.
*
* @see #setInstaller(String)
* @see #getInstaller()
*/
private String installer;
/**
* Original name of the MX administration object.
*
* @see #setOriginalName(String)
* @see #getOriginalName()
*/
private String originalName;
/**
* All current defined symbolic names for MX administration objects (not
* for business administration objects!) are stored.
*/
private final Set<String> symbolicNames = new TreeSet<String>();
/**
* Initialize the type definition enumeration.
*
* @param _typeDef defines the related type definition enumeration
* @param _mxName MX name of the administration object
*/
protected AbstractObject_mxJPO(final TypeDef_mxJPO _typeDef,
final String _mxName)
{
this.typeDef = _typeDef;
this.mxName = _mxName;
}
/**
* Returns the path where the file is located of this matrix object. The
* method used the information annotation.
*
* @return sub path
* @see #getTypeDef()
*/
public String getPath()
{
return this.getTypeDef().getFilePath();
}
/**
* Returns the type definition instance.
*
* @return type definition enumeration
* @see #typeDef
*/
public final TypeDef_mxJPO getTypeDef()
{
return this.typeDef;
}
/**
* Export given administration (business) object with given name into given
* path. The name of the file where is written through is evaluated within
* this export method.
*
* @param _paramCache parameter cache
* @param _path path to write through (if required also including
* depending file path defined from the information
* annotation)
* @throws MatrixException if some MQL statement failed
* @throws SAXException if the XML export of the object could not
* parsed (for admin objects)
* @throws IOException if the TCL update code could not be written
*/
public void export(final ParameterCache_mxJPO _paramCache,
final File _path)
throws MatrixException, SAXException, IOException
{
this.parse(_paramCache);
- final File file = new File(_path, StringUtil_mxJPO.convertToFileName(this.getFileName()));
+ final File file = new File(_path, this.getFileName());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
final Writer out = new FileWriter(file);
this.write(_paramCache, out);
out.flush();
out.close();
}
/**
*
* @param _paramCache parameter cache
* @param _out appendable instance where the TCL update code is
* written
* @throws MatrixException if some MQL statement failed
* @throws SAXException if the XML export of the object could not
* parsed (for admin objects)
* @throws IOException if the TCL update code could not be written
* @see #parse(ParameterCache_mxJPO)
* @see #write(ParameterCache_mxJPO, Appendable)
*/
public void export(final ParameterCache_mxJPO _paramCache,
final Appendable _out)
throws MatrixException, SAXException, IOException
{
this.parse(_paramCache);
this.write(_paramCache, _out);
}
/**
*
* @param _paramCache parameter cache
* @param _out appendable instance to write the TCL update
* code
* @throws IOException if write of the TCL update failed
* @throws MatrixException if MQL commands failed
*/
protected abstract void write(final ParameterCache_mxJPO _paramCache,
final Appendable _out)
throws IOException, MatrixException;
/**
* Parses all information for given administration object.
*
* @param _paramCache parameter cache
- * @throws MatrixException
- * @throws SAXException
- * @throws IOException
+ * @throws MatrixException if XML export could not be created or if
+ * another MX action failed
+ * @throws SAXException if the XML document could not be parsed
+ * @throws IOException if the XML document could not be opened (should
+ * never happen)
*/
protected abstract void parse(final ParameterCache_mxJPO _paramCache)
throws MatrixException, SAXException, IOException;
/**
* Returns a list of names exists within MX.
*
* @param _paramCache parameter cache
* @return set of names of this administration type
* @throws MatrixException if the search within MX failed
*/
public abstract Set<String> getMxNames(final ParameterCache_mxJPO _paramCache)
throws MatrixException;
/**
* Checks if given MX name without prefix and suffix matches given match
* string.
*
* @param _paramCache parameter cache
* @param _mxName name of the administration object to check
* @param _match string which must be matched
* @return <i>true</i> if the given MX name matches; otherwise <i>false</i>
*/
public boolean matchMxName(final ParameterCache_mxJPO _paramCache,
final String _mxName,
final String _match)
{
return StringUtil_mxJPO.match(_mxName, _match);
}
/**
* Extracts the MX name from given file name if the file prefix and suffix
* matches. If the file prefix and suffix not matches a <code>null</code>
* is returned.
*
* @param _paramCache parameter cache
* @param _file file for which the MX name is searched
* @return MX name or <code>null</code> if the file is not an update file
* for current type definition
*/
public String extractMxName(final ParameterCache_mxJPO _paramCache,
final File _file)
{
final String suffix = this.getTypeDef().getFileSuffix();
final int suffixLength = (suffix != null) ? suffix.length() : 0;
final String prefix = this.getTypeDef().getFilePrefix();
final int prefixLength = (prefix != null) ? prefix.length() : 0;
final String fileName = _file.getName();
final String mxName;
if (((prefix == null) || fileName.startsWith(prefix)) && ((suffix == null) || fileName.endsWith(suffix))) {
mxName = StringUtil_mxJPO.convertFromFileName(fileName.substring(0, fileName.length() - suffixLength)
.substring(prefixLength));
} else {
mxName = null;
}
return mxName;
}
/**
* Deletes administration object with given name.
*
* @param _paramCache parameter cache
* @throws Exception if delete failed
*/
public abstract void delete(final ParameterCache_mxJPO _paramCache)
throws Exception;
/**
* Creates a new administration object with given name.
*
* @param _paramCache parameter cache
* @throws Exception if create failed
*/
public abstract void create(final ParameterCache_mxJPO _paramCache)
throws Exception;
/**
* Updated this administration (business) object.
*
* @param _paramCache parameter cache
* @param _file reference to the file to update
* @param _newVersion new version which must be set within the update
* (or <code>null</code> if the version must not
* be set).
* @throws Exception if update failed
*/
public abstract void update(final ParameterCache_mxJPO _paramCache,
final File _file,
final String _newVersion)
throws Exception;
/**
* Compiles this administration object. Because typically ad administration
* object must not be compile, nothing is done here.
*
* @param _paramCache parameter cache
* @return <i>true</i> if administration object is compiled; otherwise
* <i>false</i> (and here used always)
* @throws Exception if the compile failed
*/
public boolean compile(final ParameterCache_mxJPO _paramCache)
throws Exception
{
return false;
}
/**
* Reads for given file the code and returns them.
*
* @param _file file to read the code
* @return read code of the file
* @throws IOException if the file could not be opened or read
*/
protected StringBuilder getCode(final File _file)
throws IOException
{
// read code
final StringBuilder code = new StringBuilder();
final BufferedReader reader = new BufferedReader(new FileReader(_file));
String line = reader.readLine();
while (line != null) {
code.append(line).append('\n');
line = reader.readLine();
}
reader.close();
return code;
}
/**
* Returns the stored value within Matrix for administration object
* with given property name. For performance reason the method uses
* "print" commands, because a complete XML parse including a
* complete export takes longer time.
*
* @param _paramCache parameter cache
* @param _prop property for which the value is searched
* @return value for given property
* @throws MatrixException if the property value could not be extracted
*/
public String getPropValue(final ParameterCache_mxJPO _paramCache,
final PropertyDef_mxJPO _prop)
throws MatrixException
{
final String curVersion;
// check for existing administration type...
if (this.getTypeDef().getMxAdminName() != null) {
final String tmp = MqlUtil_mxJPO.execMql(_paramCache.getContext(), new StringBuilder()
.append("print ").append(this.getTypeDef().getMxAdminName())
.append(" \"").append(this.getName()).append("\" ")
.append(this.getTypeDef().getMxAdminSuffix())
.append(" select property[").append(_prop.getPropName(_paramCache)).append("] dump"));
final int length = 7 + _prop.getPropName(_paramCache).length();
curVersion = (tmp.length() >= length)
? tmp.substring(length)
: "";
// otherwise we have a business object....
} else {
final String[] nameRev = this.getName().split("________");
curVersion = MqlUtil_mxJPO.execMql(_paramCache.getContext(), new StringBuilder()
.append("print bus \"")
.append(this.getTypeDef().getMxBusType())
.append("\" \"").append(nameRev[0])
.append("\" \"").append((nameRev.length > 1) ? nameRev[1] : "")
.append("\" select attribute[").append(_prop.getAttrName(_paramCache)).append("] dump"));
}
return curVersion;
}
/**
* Getter method for instance variable {@link #mxName}.
*
* @return value of instance variable {@link #mxName}.
* @see #mxName
*/
public String getName()
{
return this.mxName;
}
/**
* Getter method for instance variable {@link #author}.
*
* @return value of instance variable {@link #author}.
* @see #author
*/
protected String getAuthor()
{
return this.author;
}
/**
* Setter method for instance variable {@link #author}.
*
* @param _author new value for instance variable {@link #author}
* @see #author
*/
protected void setAuthor(final String _author)
{
this.author = _author;
}
/**
* Getter method for instance variable {@link #application}.
*
* @return value of instance variable {@link #application}.
* @see #application
*/
protected String getApplication()
{
return this.application;
}
/**
* Setter method for instance variable {@link #application}.
*
* @param _application new value for instance variable
* {@link #application}
* @see #application
*/
protected void setApplication(final String _application)
{
this.application = _application;
}
/**
* Getter method for instance variable {@link #description}.
*
* @return value of instance variable {@link #description}.
*/
protected String getDescription()
{
return this.description;
}
/**
* Setter method for instance variable {@link #description}.
*
* @param _description new value for instance variable {@link #description}.
*/
protected void setDescription(final String _description)
{
this.description = _description;
}
/**
* Getter method for instance variable {@link #installationDate}.
*
* @return value of instance variable {@link #installationDate}.
* @see #installationDate
*/
protected String getInstallationDate()
{
return this.installationDate;
}
/**
* Setter method for instance variable {@link #installationDate}.
*
* @param _installationDate new value for instance variable
* {@link #installationDate}
* @see #installationDate
*/
protected void setInstallationDate(final String _installationDate)
{
this.installationDate = _installationDate;
}
/**
* Getter method for instance variable {@link #installer}.
*
* @return value of instance variable {@link #installer}.
* @see #installer
*/
protected String getInstaller()
{
return this.installer;
}
/**
* Setter method for instance variable {@link #installer}.
*
* @param _installer new value for instance variable {@link #installer}
* @see #installer
*/
protected void setInstaller(final String _installer)
{
this.installer = _installer;
}
/**
* Getter method for instance variable {@link #originalName}.
*
* @return value of instance variable {@link #originalName}.
*/
protected String getOriginalName()
{
return this.originalName;
}
/**
* Setter method for instance variable {@link #originalName}.
*
* @param _originalName new value for instance variable
* {@link #originalName}.
*/
protected void setOriginalName(final String _originalName)
{
this.originalName = _originalName;
}
/**
* Returns the version string of this administration (business) object. The
* method is the getter method for {@link #version}.
*
* @return version string
* @see #version
*/
protected String getVersion()
{
return this.version;
}
/**
* Returns the set of all defined symbolic names of this administration
* (not business!) object. The method is the getter method for
* {@link #symbolicNames}.
*
* @return all defined symbolic names
* @see #symbolicNames
*/
protected Set<String> getSymblicNames()
{
return this.symbolicNames;
}
/**
* Reads the symbolic names for current admin objects and stores them in
* {@link #symbolicNames}.
*
* @param _paramCache parameter cache
* @throws MatrixException if the symbolic names could not be read
* @see #symbolicNames
*/
protected void readSymbolicNames(final ParameterCache_mxJPO _paramCache)
throws MatrixException
{
if (this.getTypeDef().getMxAdminName() != null) {
final String symbProg = _paramCache.getValueString(AbstractObject_mxJPO.PARAM_SYMB_NAME_PROG);
final String symbProgIdxOf = new StringBuilder()
.append(" on program ").append(symbProg).append(' ').toString();
final StringBuilder cmd = new StringBuilder()
.append("escape list property on program \"")
.append(StringUtil_mxJPO.convertMql(symbProg)).append("\" to ")
.append(this.getTypeDef().getMxAdminName())
.append(" \"").append(this.getName()).append("\" ")
.append(this.getTypeDef().getMxAdminSuffix());
for (final String symbName : MqlUtil_mxJPO.execMql(_paramCache.getContext(), cmd).split("\n")) {
if (!"".equals(symbName)) {
this.symbolicNames.add(symbName.substring(0, symbName.indexOf(symbProgIdxOf)));
}
}
}
}
/**
* Appends the escaped MQL code to register given symbolic name
* <code>_symbName</code> depending on current defined symbolic names
* {@link #symbolicNames}. If not registered, a new registration is done.
* If wrong symbolic names are defined, they are removed.
*
* @param _paramCache parameter cache
* @param _symbName symbolic name which must be set
* @param _mqlCode string builder where the MQL command must be
* appended
* @see #symbolicNames
*/
protected void appendSymbolicNameRegistration(final ParameterCache_mxJPO _paramCache,
final String _symbName,
final StringBuilder _mqlCode)
{
if (this.getTypeDef().getMxAdminName() != null) {
final String symbProg = _paramCache.getValueString(AbstractObject_mxJPO.PARAM_SYMB_NAME_PROG);
if (!this.symbolicNames.contains(_symbName)) {
_paramCache.logTrace(" - register symbolic name '" + _symbName + "'");
_mqlCode.append("escape add property \"").append(StringUtil_mxJPO.convertMql(_symbName)).append("\" ")
.append(" on program \"").append(StringUtil_mxJPO.convertMql(symbProg)).append("\" to ")
.append(this.getTypeDef().getMxAdminName())
.append(" \"").append(StringUtil_mxJPO.convertMql(this.getName())).append("\" ")
.append(this.getTypeDef().getMxAdminSuffix())
.append(";\n");
}
for (final String exSymbName : this.symbolicNames) {
if (!_symbName.equals(exSymbName)) {
_paramCache.logTrace(" - remove symbolic name '" + exSymbName + "'");
_mqlCode.append("escape delete property \"")
.append(StringUtil_mxJPO.convertMql(exSymbName)).append("\" ")
.append(" on program \"").append(StringUtil_mxJPO.convertMql(symbProg)).append("\" to ")
.append(this.getTypeDef().getMxAdminName())
.append(" \"").append(StringUtil_mxJPO.convertMql(this.getName())).append("\" ")
.append(this.getTypeDef().getMxAdminSuffix())
.append(";\n");
}
}
}
}
/**
* The calculates and returns the default symbolic name. A typical symbolic
* name has as prefix the admin type name, then an underscore and at least
* the name of the admin object. All spaces and slashes are replaced by
* "nothing" (zero length string).
*
* @return calculated default symbolic name for administration objects (if
* the administration object is a business object <code>null</code>
* is returned)
*/
protected String calcDefaultSymbolicName()
{
return (this.getTypeDef().getMxAdminName() == null)
? null
: new StringBuilder()
.append(this.getTypeDef().getMxAdminName())
.append("_")
.append(this.getName().replaceAll(" ", "").replaceAll("/", ""))
.toString();
}
/**
* Sets the new version string for this administration (business) object.
* It is the setter method for {@link #version}.
*
* @param _version new version to set
* @see #version
*/
protected void setVersion(final String _version)
{
this.version = _version;
}
/**
* Returns the file name for this MxUpdate administration object. The file
* name is a concatenation of the defined file prefix within the
- * information annotation , the name of the Mx object and the file suffix
- * within the information annotation.
+ * information annotation , the name of the MX object and the file suffix
+ * within the information annotation. All special characters are converted
+ * automatically from {@link StringUtil_mxJPO#convertToFileName(String)}.
*
* @return file name of this administration (business) object
+ * @see #export(ParameterCache_mxJPO, File)
*/
protected String getFileName() {
final StringBuilder ret = new StringBuilder();
if (this.getTypeDef().getFilePrefix() != null) {
ret.append(this.getTypeDef().getFilePrefix());
}
ret.append(this.getName());
if (this.getTypeDef().getFileSuffix() != null) {
ret.append(this.getTypeDef().getFileSuffix());
}
- return ret.toString();
+ return StringUtil_mxJPO.convertToFileName(ret.toString());
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/test/test-restlet/src/test/java/org/test/restlet/ocl/TestOcl.java b/test/test-restlet/src/test/java/org/test/restlet/ocl/TestOcl.java
index cb045975..9f1a2eae 100644
--- a/test/test-restlet/src/test/java/org/test/restlet/ocl/TestOcl.java
+++ b/test/test-restlet/src/test/java/org/test/restlet/ocl/TestOcl.java
@@ -1,50 +1,72 @@
package org.test.restlet.ocl;
import org.junit.Test;
import org.test.restlet.TestRestletDefaultDataCreator;
import org.tuml.root.Root;
import org.tuml.runtime.collection.TinkerBag;
import org.tuml.runtime.collection.TinkerOrderedSet;
+import org.tuml.runtime.collection.TinkerSequence;
import org.tuml.runtime.collection.ocl.BodyExpressionEvaluator;
import org.tuml.runtime.test.BaseLocalDbTest;
import org.tuml.test.Finger;
import org.tuml.test.Hand;
import org.tuml.test.Human;
import org.tuml.test.Ring;
/**
* Date: 2013/02/13
* Time: 1:21 PM
*/
public class TestOcl extends BaseLocalDbTest {
@Test
public void testocl() {
TestRestletDefaultDataCreator testRestletDefaultDataCreator = new TestRestletDefaultDataCreator();
testRestletDefaultDataCreator.createData();
Human human = Root.INSTANCE.getHuman().get(0);
TinkerBag<Human> humans = execute(human);
System.out.println(humans.size());
}
private TinkerBag<Human> execute(Human human) {
TinkerBag<Human> result = human.getHand().<Finger, TinkerOrderedSet<Finger>>collect(new BodyExpressionEvaluator<TinkerOrderedSet<Finger>, Hand>() {
@Override
public TinkerOrderedSet<Finger> evaluate(Hand temp1) {
return temp1.getFinger();
}
}).<Ring, Ring>collect(new BodyExpressionEvaluator<Ring, Finger>() {
@Override
public Ring evaluate(Finger temp2) {
return temp2.getRing();
}
}).<Human, Human>collect(new BodyExpressionEvaluator<Human, Ring>() {
@Override
public Human evaluate(Ring temp3) {
return temp3.getHuman();
}
});
return result;
}
+
+ @Test
+ public void testocl2() {
+ TestRestletDefaultDataCreator testRestletDefaultDataCreator = new TestRestletDefaultDataCreator();
+ testRestletDefaultDataCreator.createData();
+ Human human = Root.INSTANCE.getHuman().get(0);
+ Hand hand = human.getHand().iterator().next();
+ TinkerSequence<Ring> rings = execute(hand);
+ System.out.println(rings.size());
+
+ }
+
+ private TinkerSequence<Ring> execute(Hand hand) {
+ TinkerSequence<Ring> result = hand.getFinger().<Ring, Ring>collect(new BodyExpressionEvaluator<Ring, Finger>() {
+ @Override
+ public Ring evaluate(Finger temp1) {
+ return temp1.getRing();
+ }
+ });
+ return result;
+ }
}
| false | false | null | null |
diff --git a/src/main/java/org/jboss/wolf/validator/impl/version/VersionOverlapValidator.java b/src/main/java/org/jboss/wolf/validator/impl/version/VersionOverlapValidator.java
index 1a72d23..2f6db34 100644
--- a/src/main/java/org/jboss/wolf/validator/impl/version/VersionOverlapValidator.java
+++ b/src/main/java/org/jboss/wolf/validator/impl/version/VersionOverlapValidator.java
@@ -1,116 +1,116 @@
package org.jboss.wolf.validator.impl.version;
import static org.jboss.wolf.validator.internal.Utils.relativize;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.maven.model.Model;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.LocalRepositoryManager;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.jboss.wolf.validator.Validator;
import org.jboss.wolf.validator.ValidatorContext;
import org.jboss.wolf.validator.internal.ValidatorSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Named
public class VersionOverlapValidator implements Validator {
private static final Logger logger = LoggerFactory.getLogger(VersionOverlapValidator.class);
@Inject @Named("versionOverlapValidatorFilter")
private IOFileFilter fileFilter;
@Inject
private ValidatorSupport validatorSupport;
@Inject
private RepositorySystem repositorySystem;
@Inject
private RepositorySystemSession repositorySystemSession;
@Override
public void validate(ValidatorContext ctx) {
Iterator<Model> modelIterator = validatorSupport.effectiveModelIterator(ctx, fileFilter);
while (modelIterator.hasNext()) {
Model model = modelIterator.next();
if (model != null) {
logger.trace("validating {}", relativize(ctx, model.getPomFile()));
validateVersionOverlap(ctx, model);
}
}
}
private void validateVersionOverlap(ValidatorContext ctx, Model model) {
File tmpLocalRepository = createTempLocalRepository();
RepositorySystemSession tmpSession = createTempSession(tmpLocalRepository);
boolean first = true;
for (RemoteRepository remoteRepository : ctx.getRemoteRepositories()) {
if (first) {
first = false;
continue; // first remote repository is the validated repository, so we want to skip it
}
cleanTempLocalRepository(tmpLocalRepository);
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(new DefaultArtifact(model.getGroupId(), model.getArtifactId(), "pom", model.getVersion()));
request.addRepository(remoteRepository);
try {
repositorySystem.resolveArtifact(tmpSession, request);
ctx.addException(model.getPomFile(), new VersionOverlapException(model.getId(), remoteRepository));
} catch (ArtifactResolutionException e) {
// noop
}
}
deleteTempLocalRepository(tmpLocalRepository);
}
private RepositorySystemSession createTempSession(File tmpLocalRepository) {
DefaultRepositorySystemSession tempSession = new DefaultRepositorySystemSession(repositorySystemSession);
LocalRepositoryManager tempLocalRepositoryManager = repositorySystem.newLocalRepositoryManager(tempSession, new LocalRepository(tmpLocalRepository));
tempSession.setLocalRepositoryManager(tempLocalRepositoryManager);
return tempSession;
}
private File createTempLocalRepository() {
- File tempLocalRepository = new File(FileUtils.getTempDirectory(), "wolf-validator-temp");
+ File tempLocalRepository = new File("workspace", "temp");
try {
FileUtils.forceMkdir(tempLocalRepository);
} catch (IOException e) {
throw new RuntimeException(e);
}
return tempLocalRepository;
}
private void cleanTempLocalRepository(File tempLocalRepository) {
try {
FileUtils.cleanDirectory(tempLocalRepository);
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
private void deleteTempLocalRepository(File tempLocalRepository) {
try {
FileUtils.deleteDirectory(tempLocalRepository);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/jetty/src/main/java/org/mortbay/jetty/servlet/HashSessionManager.java b/jetty/src/main/java/org/mortbay/jetty/servlet/HashSessionManager.java
index 8f370b9f6..86fededa6 100644
--- a/jetty/src/main/java/org/mortbay/jetty/servlet/HashSessionManager.java
+++ b/jetty/src/main/java/org/mortbay/jetty/servlet/HashSessionManager.java
@@ -1,322 +1,326 @@
// ========================================================================
// Copyright 1996-2005 Mort Bay Consulting Pty. 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.mortbay.jetty.servlet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.mortbay.log.Log;
import org.mortbay.util.LazyList;
/* ------------------------------------------------------------ */
/** An in-memory implementation of SessionManager.
*
* @author Greg Wilkins (gregw)
*/
public class HashSessionManager extends AbstractSessionManager
{
private int _scavengePeriodMs=30000;
private Thread _scavenger=null;
protected Map _sessions;
/* ------------------------------------------------------------ */
public HashSessionManager()
{
super();
}
/* ------------------------------------------------------------ */
/* (non-Javadoc)
* @see org.mortbay.jetty.servlet.AbstractSessionManager#doStart()
*/
public void doStart() throws Exception
{
_sessions=new HashMap();
super.doStart();
// Start the session scavenger if we haven't already
getSessionHandler().getServer().getThreadPool().dispatch(new SessionScavenger());
}
/* ------------------------------------------------------------ */
/* (non-Javadoc)
* @see org.mortbay.jetty.servlet.AbstractSessionManager#doStop()
*/
public void doStop() throws Exception
{
super.doStop();
_sessions.clear();
_sessions=null;
// stop the scavenger
Thread scavenger=_scavenger;
_scavenger=null;
if (scavenger!=null)
scavenger.interrupt();
}
/* ------------------------------------------------------------ */
/**
* @return seconds
*/
public int getScavengePeriod()
{
return _scavengePeriodMs/1000;
}
/* ------------------------------------------------------------ */
public Map getSessionMap()
{
return Collections.unmodifiableMap(_sessions);
}
/* ------------------------------------------------------------ */
public int getSessions()
{
return _sessions.size();
}
/* ------------------------------------------------------------ */
public void setMaxInactiveInterval(int seconds)
{
super.setMaxInactiveInterval(seconds);
if (_dftMaxIdleSecs>0&&_scavengePeriodMs>_dftMaxIdleSecs*1000)
setScavengePeriod((_dftMaxIdleSecs+9)/10);
}
/* ------------------------------------------------------------ */
/**
* @param seconds
*/
public void setScavengePeriod(int seconds)
{
if (seconds==0)
seconds=60;
int old_period=_scavengePeriodMs;
int period=seconds*1000;
if (period>60000)
period=60000;
if (period<1000)
period=1000;
if (period!=old_period)
{
synchronized (this)
{
_scavengePeriodMs=period;
if (_scavenger!=null)
_scavenger.interrupt();
}
}
}
/* -------------------------------------------------------------- */
/**
* Find sessions that have timed out and invalidate them. This runs in the
* SessionScavenger thread.
*/
private void scavenge()
{
+ //don't attempt to scavenge if we are shutting down
+ if (isStopping() || isStopped())
+ return;
+
Thread thread=Thread.currentThread();
ClassLoader old_loader=thread.getContextClassLoader();
try
{
if (_loader!=null)
thread.setContextClassLoader(_loader);
long now=System.currentTimeMillis();
// Since Hashtable enumeration is not safe over deletes,
// we build a list of stale sessions, then go back and invalidate
// them
Object stale=null;
synchronized (HashSessionManager.this)
{
// For each session
for (Iterator i=_sessions.values().iterator(); i.hasNext();)
{
Session session=(Session)i.next();
long idleTime=session._maxIdleMs;
if (idleTime>0&&session._accessed+idleTime<now)
{
// Found a stale session, add it to the list
stale=LazyList.add(stale,session);
}
}
}
// Remove the stale sessions
for (int i=LazyList.size(stale); i-->0;)
{
// check it has not been accessed in the meantime
Session session=(Session)LazyList.get(stale,i);
long idleTime=session._maxIdleMs;
if (idleTime>0&&session._accessed+idleTime<System.currentTimeMillis())
{
session.invalidate();
int nbsess=this._sessions.size();
if (nbsess<this._minSessions)
this._minSessions=nbsess;
}
}
}
finally
{
thread.setContextClassLoader(old_loader);
}
}
/* ------------------------------------------------------------ */
protected void addSession(AbstractSessionManager.Session session)
{
_sessions.put(session.getClusterId(),session);
}
/* ------------------------------------------------------------ */
protected AbstractSessionManager.Session getSession(String idInCluster)
{
return (Session)_sessions.get(idInCluster);
}
/* ------------------------------------------------------------ */
protected void invalidateSessions()
{
// Invalidate all sessions to cause unbind events
ArrayList sessions=new ArrayList(_sessions.values());
for (Iterator i=sessions.iterator(); i.hasNext();)
{
Session session=(Session)i.next();
session.invalidate();
}
_sessions.clear();
}
/* ------------------------------------------------------------ */
protected AbstractSessionManager.Session newSession(HttpServletRequest request)
{
return new Session(request);
}
/* ------------------------------------------------------------ */
protected void removeSession(String idInCluster)
{
_sessions.remove(idInCluster);
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
protected class Session extends AbstractSessionManager.Session
{
/* ------------------------------------------------------------ */
private static final long serialVersionUID=-2134521374206116367L;
/* ------------------------------------------------------------- */
protected Session(HttpServletRequest request)
{
super(request);
}
/* ------------------------------------------------------------- */
public void setMaxInactiveInterval(int secs)
{
super.setMaxInactiveInterval(secs);
if (_maxIdleMs>0&&(_maxIdleMs/10)<_scavengePeriodMs)
HashSessionManager.this.setScavengePeriod((secs+9)/10);
}
/* ------------------------------------------------------------ */
protected Map newAttributeMap()
{
return new HashMap(3);
}
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* -------------------------------------------------------------- */
/** SessionScavenger is a background thread that kills off old sessions */
class SessionScavenger implements Runnable
{
public void run()
{
_scavenger=Thread.currentThread();
String name=Thread.currentThread().getName();
if (_context!=null)
Thread.currentThread().setName(name+" - Invalidator - "+_context.getContextPath());
int period=-1;
try
{
do
{
try
{
if (period!=_scavengePeriodMs)
{
if (Log.isDebugEnabled())
Log.debug("Session scavenger period = "+_scavengePeriodMs/1000+"s");
period=_scavengePeriodMs;
}
Thread.sleep(period>1000?period:1000);
HashSessionManager.this.scavenge();
}
catch (InterruptedException ex)
{
continue;
}
catch (Error e)
{
Log.warn(Log.EXCEPTION,e);
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION,e);
}
}
while (isStarted());
}
finally
{
HashSessionManager.this._scavenger=null;
String exit="Session scavenger exited";
if (isStarted())
Log.warn(exit);
else
Log.debug(exit);
Thread.currentThread().setName(name);
}
}
} // SessionScavenger
}
| true | false | null | null |
diff --git a/closure/closure-templates/java/src/com/google/template/soy/exprtree/ListLiteralNode.java b/closure/closure-templates/java/src/com/google/template/soy/exprtree/ListLiteralNode.java
index 0ff0a5181..c0bea06df 100644
--- a/closure/closure-templates/java/src/com/google/template/soy/exprtree/ListLiteralNode.java
+++ b/closure/closure-templates/java/src/com/google/template/soy/exprtree/ListLiteralNode.java
@@ -1,100 +1,78 @@
/*
* Copyright 2011 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.template.soy.exprtree;
import java.util.List;
-import com.google.common.collect.Lists;
-import com.google.template.soy.data.SoyData;
-import com.google.template.soy.data.SoyListData;
-import com.google.template.soy.data.internalutils.DataUtils;
-import com.google.template.soy.data.restricted.PrimitiveData;
-
/**
* A node representing a list literal (with items as children).
*
* <p> Important: Do not use outside of Soy code (treat as superpackage-private).
*
* @author Kai Huang
*/
public class ListLiteralNode extends AbstractParentExprNode {
/**
* @param items The expressions for the items in this list.
*/
public ListLiteralNode(List<ExprNode> items) {
addChildren(items);
}
/**
* Copy constructor.
* @param orig The node to copy.
*/
protected ListLiteralNode(ListLiteralNode orig) {
super(orig);
}
@Override public Kind getKind() {
return Kind.LIST_LITERAL_NODE;
}
@Override public String toSourceString() {
StringBuilder sourceSb = new StringBuilder();
sourceSb.append("[");
boolean isFirst = true;
for (ExprNode child : getChildren()) {
if (isFirst) {
isFirst = false;
} else {
sourceSb.append(", ");
}
sourceSb.append(child.toSourceString());
}
sourceSb.append("]");
return sourceSb.toString();
}
@Override public ListLiteralNode clone() {
return new ListLiteralNode(this);
}
- public static ListLiteralNode createFrom(SoyListData soyListData) {
- List<ExprNode> nodes = Lists.newArrayList();
- for (SoyData item : soyListData) {
- ExprNode node;
- if (item instanceof PrimitiveData) {
- node = DataUtils.convertPrimitiveDataToExpr((PrimitiveData)item);
- } else if (item instanceof SoyListData) {
- node = createFrom((SoyListData)item);
- } else {
- // TODO: Support SoyMapData and SanitizedContent.
- throw new IllegalArgumentException("Could not translate: " + item);
- }
- nodes.add(node);
- }
- return new ListLiteralNode(nodes);
- }
}
| false | false | null | null |
diff --git a/de.walware.statet.rtm.base.ui/src/de/walware/ecommons/emf/ui/forms/EFEditor.java b/de.walware.statet.rtm.base.ui/src/de/walware/ecommons/emf/ui/forms/EFEditor.java
index df2ae103..df7c0947 100644
--- a/de.walware.statet.rtm.base.ui/src/de/walware/ecommons/emf/ui/forms/EFEditor.java
+++ b/de.walware.statet.rtm.base.ui/src/de/walware/ecommons/emf/ui/forms/EFEditor.java
@@ -1,1113 +1,1118 @@
/*******************************************************************************
* Copyright (c) 2012-2013 WalWare/StatET-Project (www.walware.de/goto/statet).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.ecommons.emf.ui.forms;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.commands.IHandler2;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.ui.MarkerHelper;
import org.eclipse.emf.common.ui.editor.ProblemEditorPart;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EValidator;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.emf.edit.ui.dnd.EditingDomainViewerDropAdapter;
import org.eclipse.emf.edit.ui.dnd.LocalTransfer;
import org.eclipse.emf.edit.ui.dnd.ViewerDragAdapter;
import org.eclipse.emf.edit.ui.provider.UnwrappingSelectionProvider;
import org.eclipse.emf.edit.ui.util.EditUIMarkerHelper;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.window.Window;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.services.IServiceLocator;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor;
import de.walware.ecommons.emf.core.util.RuleSet;
import de.walware.ecommons.emf.internal.forms.CopyEObjectHandler;
import de.walware.ecommons.emf.internal.forms.CutEObjectHandler;
import de.walware.ecommons.emf.internal.forms.EFEditingDomain;
import de.walware.ecommons.emf.internal.forms.EditorSelectionProvider;
import de.walware.ecommons.emf.internal.forms.PasteEObjectHandler;
import de.walware.ecommons.ui.actions.HandlerCollection;
import de.walware.statet.rtm.base.internal.ui.editors.Messages;
public abstract class EFEditor extends FormEditor
implements IEditingDomainProvider, IMenuListener, IGotoMarker,
ITabbedPropertySheetPageContributor {
private class ResourceManager implements IResourceChangeListener {
/**
* Resources that have been removed since last activation.
* @generated
*/
private final Collection<Resource> fRemovedResources = new ArrayList<Resource>();
/**
* Resources that have been changed since last activation.
* @generated
*/
private final Collection<Resource> fChangedResources = new ArrayList<Resource>();
/**
* Resources that have been saved.
* @generated
*/
private final Collection<Resource> fSavedResources = new ArrayList<Resource>();
@Override
public void resourceChanged(final IResourceChangeEvent event) {
final IResourceDelta delta = event.getDelta();
try {
class ResourceDeltaVisitor implements IResourceDeltaVisitor {
protected ResourceSet resourceSet = getEditingDomain().getResourceSet();
protected Collection<Resource> changedResources = new ArrayList<Resource>();
protected Collection<Resource> removedResources = new ArrayList<Resource>();
@Override
public boolean visit(final IResourceDelta delta) {
if (delta.getResource().getType() == IResource.FILE) {
if (delta.getKind() == IResourceDelta.REMOVED ||
delta.getKind() == IResourceDelta.CHANGED && delta.getFlags() != IResourceDelta.MARKERS) {
final Resource resource = resourceSet.getResource(URI.createPlatformResourceURI(delta.getFullPath().toString(), true), false);
if (resource != null) {
if (delta.getKind() == IResourceDelta.REMOVED) {
removedResources.add(resource);
}
else if (!fSavedResources.remove(resource)) {
changedResources.add(resource);
}
}
}
}
return true;
}
public Collection<Resource> getChangedResources() {
return changedResources;
}
public Collection<Resource> getRemovedResources() {
return removedResources;
}
}
final ResourceDeltaVisitor visitor = new ResourceDeltaVisitor();
delta.accept(visitor);
if (!visitor.getRemovedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
@Override
public void run() {
fRemovedResources.addAll(visitor.getRemovedResources());
if (!isDirty()) {
getSite().getPage().closeEditor(EFEditor.this, false);
}
}
});
}
if (!visitor.getChangedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
fChangedResources.addAll(visitor.getChangedResources());
if (getSite().getPage().getActiveEditor() == EFEditor.this) {
handleActivate();
}
}
});
}
}
catch (final CoreException e) {
operationFailed("processing resource change", e); //$NON-NLS-1$
}
}
public void processChanges() {
if (!fRemovedResources.isEmpty()) {
if (handleDirtyConflict()) {
getSite().getPage().closeEditor(EFEditor.this, false);
}
else {
fRemovedResources.clear();
fChangedResources.clear();
fSavedResources.clear();
}
}
else if (!fChangedResources.isEmpty()) {
fChangedResources.removeAll(fSavedResources);
handleChangedResources();
fChangedResources.clear();
fSavedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation.
* @generated
*/
protected void handleChangedResources() {
if (!fChangedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
if (isDirty()) {
fChangedResources.addAll(fEditingDomain.getResourceSet().getResources());
}
fEditingDomain.getCommandStack().flush();
fUpdateProblemIndication = false;
for (final Resource resource : fChangedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
}
catch (final IOException exception) {
if (!fResourceToDiagnosticMap.containsKey(resource)) {
fResourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
}
}
}
final ISelectionProvider selectionProvider = getSite().getSelectionProvider();
if (AdapterFactoryEditingDomain.isStale(selectionProvider.getSelection())) {
selectionProvider.setSelection(StructuredSelection.EMPTY);
}
fUpdateProblemIndication = true;
updateProblemIndication();
}
}
}
private final IEFModelDescriptor fModelDescriptor;
/**
* This listens for workspace changes.
*/
private final ResourceManager fResourceListener = new ResourceManager();
/**
* Map to store the diagnostic associated with a resource.
* @generated
*/
private final Map<Resource, Diagnostic> fResourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>();
/**
* The MarkerHelper is responsible for creating workspace resource markers presented
* in Eclipse's Problems View.
* @generated
*/
private final MarkerHelper fMarkerHelper = new EditUIMarkerHelper();
/**
* Controls whether the problem indication should be updated.
* @generated
*/
protected boolean fUpdateProblemIndication = true;
/**
* Adapter used to update the problem indication when resources are demanded loaded.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final EContentAdapter fProblemIndicationAdapter = new EContentAdapter() {
@Override
public void notifyChanged(final Notification notification) {
if (notification.getNotifier() instanceof Resource) {
switch (notification.getFeatureID(Resource.class)) {
case Resource.RESOURCE__IS_LOADED:
case Resource.RESOURCE__ERRORS:
case Resource.RESOURCE__WARNINGS: {
final Resource resource = (Resource)notification.getNotifier();
final Diagnostic diagnostic = analyzeResourceProblems(resource, null);
if (diagnostic.getSeverity() != Diagnostic.OK) {
fResourceToDiagnosticMap.put(resource, diagnostic);
}
else {
fResourceToDiagnosticMap.remove(resource);
}
if (fUpdateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
updateProblemIndication();
}
});
}
break;
}
}
}
else {
super.notifyChanged(notification);
}
}
@Override
protected void setTarget(final Resource target) {
basicSetTarget(target);
}
@Override
protected void unsetTarget(final Resource target) {
basicUnsetTarget(target);
}
};
public class ContextAdapterFactory implements IAdapterFactory {
@Override
public Class[] getAdapterList() {
return null;
}
@Override
public Object getAdapter(final Object adaptableObject, final Class required) {
if (required.equals(RuleSet.class)) {
return fModelDescriptor.getRuleSet();
}
return null;
}
}
/**
* This is the content outline page.
* @generated
*/
private IContentOutlinePage fContentOutlinePage;
private final List<IPropertySheetPage> fPropertySheetPages = new ArrayList<IPropertySheetPage>(2);
/**
* This listens for when the outline becomes active
* @generated
*/
private final IPartListener fPartListener = new IPartListener() {
@Override
public void partActivated(final IWorkbenchPart p) {
if (p instanceof ContentOutline) {
if (((ContentOutline) p).getCurrentPage() == fContentOutlinePage) {
getActionBarContributor().setActiveEditor(EFEditor.this);
// setCurrentViewer(fContentOutlineViewer);
}
}
else if (p instanceof PropertySheet) {
if (fPropertySheetPages.contains(((PropertySheet) p).getCurrentPage())) {
getActionBarContributor().setActiveEditor(EFEditor.this);
handleActivate();
}
}
else if (p == EFEditor.this) {
handleActivate();
}
}
@Override
public void partBroughtToTop(final IWorkbenchPart p) {
}
@Override
public void partClosed(final IWorkbenchPart p) {
}
@Override
public void partDeactivated(final IWorkbenchPart p) {
}
@Override
public void partOpened(final IWorkbenchPart p) {
}
};
/**
* This keeps track of the editing domain that is used to track all changes to the model.
*/
private EFEditingDomain fEditingDomain;
/**
* This is the one adapter factory used for providing views of the model.
* @generated
*/
private ComposedAdapterFactory fAdapterFactory;
private EFDataBindingSupport fDataBinding;
private final EditorSelectionProvider fSelectionProvider = new EditorSelectionProvider(this);
protected HandlerCollection fHandlers;
protected EFEditor(final IEFModelDescriptor modelDescriptor) {
super();
fModelDescriptor = modelDescriptor;
initializeEditingDomain(modelDescriptor.createItemProviderAdapterFactory());
}
public IEFModelDescriptor getModelDescriptor() {
return fModelDescriptor;
}
@Override
public String getContributorId() {
return fModelDescriptor.getEditorID();
}
protected void initializeEditingDomain(final AdapterFactory itemAdapterFactory) {
// Create an adapter factory that yields item providers.
fAdapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
fAdapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());
fAdapterFactory.addAdapterFactory(itemAdapterFactory);
fAdapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
// Create the command stack that will notify this editor as commands are executed.
final BasicCommandStack commandStack = new BasicCommandStack();
// Add a listener to set the most recent command's affected objects to be the selection of the viewer with focus.
commandStack.addCommandStackListener(new CommandStackListener() {
@Override
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
// Try to select the affected objects.
//
final Command mostRecentCommand = ((CommandStack)event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
selectObject((Collection<? extends EObject>) mostRecentCommand.getAffectedObjects());
}
}
});
}
});
// Create the editing domain with a special command stack.
fEditingDomain = new EFEditingDomain(fAdapterFactory, commandStack);
}
/**
* This returns the editing domain as required by the {@link IEditingDomainProvider} interface.
* This is important for implementing the static methods of {@link AdapterFactoryEditingDomain}
* and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}.
* @generated
*/
@Override
public EditingDomain getEditingDomain() {
return fEditingDomain;
}
/**
* @generated
*/
public AdapterFactory getAdapterFactory() {
return fAdapterFactory;
}
/**
* @generated
*/
protected EFEditorActionBarContributor getActionBarContributor() {
return (EFEditorActionBarContributor) getEditorSite().getActionBarContributor();
}
/**
* This is called during startup.
* @generated
*/
@Override
public void init(final IEditorSite site, final IEditorInput editorInput) {
setSite(site);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
site.setSelectionProvider(fSelectionProvider);
site.getPage().addPartListener(fPartListener);
ResourcesPlugin.getWorkspace().addResourceChangeListener(fResourceListener, IResourceChangeEvent.POST_CHANGE);
}
/**
* Handles activation of the editor or it's associated views.
* @generated
*/
protected void handleActivate() {
// Recompute the read only state.
final Map<Resource, Boolean> resourceToReadOnlyMap = fEditingDomain.getResourceToReadOnlyMap();
if (resourceToReadOnlyMap != null) {
resourceToReadOnlyMap.clear();
// Refresh any actions that may become enabled or disabled.
final ISelectionProvider selectionProvider = getSite().getSelectionProvider();
selectionProvider.setSelection(selectionProvider.getSelection());
}
fResourceListener.processChanges();
}
/**
* This is the method called to load a resource into the editing domain's resource set based on the editor's input.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createModel() {
final IEditorInput input = getEditorInput();
if (input instanceof DirectResourceEditorInput) {
fEditingDomain.getResourceSet().getResources().add(((DirectResourceEditorInput) input).getResource());
return;
}
final URI resourceURI = EditUIUtil.getURI(input);
Exception exception = null;
Resource resource = null;
try {
// Load the resource through the editing domain.
//
resource = fEditingDomain.getResourceSet().getResource(resourceURI, true);
}
catch (final Exception e) {
exception = e;
resource = fEditingDomain.getResourceSet().getResource(resourceURI, false);
}
final Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
fResourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
fEditingDomain.getResourceSet().eAdapters().add(fProblemIndicationAdapter);
}
protected void resourceLoaded() {
if (fDataBinding != null) {
}
}
/**
* Returns a diagnostic describing the errors and warnings listed in the resource
* and the specified exception (if any).
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Diagnostic analyzeResourceProblems(final Resource resource, final Exception exception) {
if (!resource.getErrors().isEmpty() || !resource.getWarnings().isEmpty()) {
final BasicDiagnostic basicDiagnostic = new BasicDiagnostic(Diagnostic.ERROR,
fModelDescriptor.getEditorPluginID(), 0,
NLS.bind(Messages.EFEditor_error_ProblemsInFile_message, resource.getURI()),
new Object [] { exception == null ? (Object)resource : exception } );
basicDiagnostic.merge(EcoreUtil.computeDiagnostic(resource, true));
return basicDiagnostic;
}
else if (exception != null) {
return new BasicDiagnostic(Diagnostic.ERROR,
fModelDescriptor.getEditorPluginID(), 0,
NLS.bind(Messages.EFEditor_error_ProblemsInFile_message, resource.getURI()),
new Object[] { exception } );
}
else {
return Diagnostic.OK_INSTANCE;
}
}
/**
* Shows a dialog that asks if conflicting changes should be discarded.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected boolean handleDirtyConflict() {
return MessageDialog.openQuestion(getSite().getShell(),
Messages.EFEditor_FileConflict_title,
Messages.EFEditor_FileConflict_message );
}
/**
* This is for implementing {@link IEditorPart} and simply tests the command stack.
* @generated
*/
@Override
public boolean isDirty() {
return ((BasicCommandStack) fEditingDomain.getCommandStack()).isSaveNeeded();
}
/**
* This always returns true because it is not currently supported.
* @generated
*/
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* This is for implementing {@link IEditorPart} and simply saves the model file.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void doSave(final IProgressMonitor progressMonitor) {
if (getEditorInput() instanceof DirectResourceEditorInput
&& fEditingDomain.getResourceSet().getResources().get(0).getURI().equals(DirectResourceEditorInput.NO_URI)) {
doSaveAs();
+ return;
}
// Save only resources that have actually changed
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
// Do the work within an operation because this is a long running activity that modifies the workbench
final WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
// This is the method that gets invoked when the operation runs
@Override
public void execute(final IProgressMonitor monitor) {
// Save the resources to the file system
boolean first = true;
for (final Resource resource : fEditingDomain.getResourceSet().getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource)) && !fEditingDomain.isReadOnly(resource)) {
try {
final long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
fResourceListener.fSavedResources.add(resource);
}
}
catch (final Exception exception) {
fResourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
first = false;
}
}
}
};
fUpdateProblemIndication = false;
try {
// This runs the options, and shows progress
new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation);
// Refresh the necessary state
((BasicCommandStack) fEditingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
}
catch (final Exception e) {
// Something went wrong that shouldn't
operationFailed("saving config", e); //$NON-NLS-1$
}
fUpdateProblemIndication = true;
updateProblemIndication();
}
/**
* This returns whether something has been persisted to the URI of the specified resource.
* The implementation uses the URI converter from the editor's resource set to try to open an input stream.
* @generated
*/
protected boolean isPersisted(final Resource resource) {
boolean result = false;
try {
final InputStream stream = fEditingDomain.getResourceSet().getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
}
catch (final IOException e) {
// Ignore
}
return result;
}
/**
* This also changes the editor's input.
* @generated
*/
@Override
public void doSaveAs() {
+ IPath path;
+
final SaveAsDialog saveAsDialog = new SaveAsDialog(getSite().getShell());
- saveAsDialog.open();
- IPath path = saveAsDialog.getResult();
- if (path != null) {
- if (path.getFileExtension() == null && fModelDescriptor.getDefaultFileExtension() != null) {
- path = path.addFileExtension(fModelDescriptor.getDefaultFileExtension());
- }
- final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
- if (file != null) {
- doSaveAs(URI.createPlatformResourceURI(file.getFullPath().toString(), true), new FileEditorInput(file));
- }
+ if (saveAsDialog.open() != Window.OK
+ || (path = saveAsDialog.getResult()) == null) {
+ return;
+ }
+
+ if (path.getFileExtension() == null && fModelDescriptor.getDefaultFileExtension() != null) {
+ path = path.addFileExtension(fModelDescriptor.getDefaultFileExtension());
+ }
+ final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
+ if (file != null) {
+ doSaveAs(URI.createPlatformResourceURI(file.getFullPath().toString(), true), new FileEditorInput(file));
}
}
/**
* @generated
*/
protected void doSaveAs(final URI uri, final IEditorInput editorInput) {
(fEditingDomain.getResourceSet().getResources().get(0)).setURI(uri);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
final IStatusLineManager statusLine = getActionBarContributor().getActionBars().getStatusLineManager();
final IProgressMonitor progressMonitor = (statusLine != null) ?
statusLine.getProgressMonitor() : new NullProgressMonitor();
doSave(progressMonitor);
}
/**
* Updates the problems indication with the information described in the specified diagnostic.
* @generated
*/
protected void updateProblemIndication() {
if (fUpdateProblemIndication) {
final BasicDiagnostic diagnostic = new BasicDiagnostic(Diagnostic.OK,
fModelDescriptor.getEditorPluginID(), 0,
null,
new Object [] { fEditingDomain.getResourceSet() });
for (final Diagnostic childDiagnostic : fResourceToDiagnosticMap.values()) {
if (childDiagnostic.getSeverity() != Diagnostic.OK) {
diagnostic.add(childDiagnostic);
}
}
int lastEditorPage = getPageCount() - 1;
if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
((ProblemEditorPart)getEditor(lastEditorPage)).setDiagnostic(diagnostic);
if (diagnostic.getSeverity() != Diagnostic.OK) {
setActivePage(lastEditorPage);
}
}
else if (diagnostic.getSeverity() != Diagnostic.OK) {
final ProblemEditorPart problemEditorPart = new ProblemEditorPart();
problemEditorPart.setDiagnostic(diagnostic);
problemEditorPart.setMarkerHelper(fMarkerHelper);
try {
addPage(++lastEditorPage, problemEditorPart, getEditorInput());
setPageText(lastEditorPage, problemEditorPart.getPartName());
setActivePage(lastEditorPage);
showTabs();
}
catch (final PartInitException e) {
operationFailed("updating problem indicators", e); //$NON-NLS-1$
}
}
if (fMarkerHelper.hasMarkers(fEditingDomain.getResourceSet())) {
fMarkerHelper.deleteMarkers(fEditingDomain.getResourceSet());
if (diagnostic.getSeverity() != Diagnostic.OK) {
try {
fMarkerHelper.createMarkers(diagnostic);
}
catch (final CoreException e) {
operationFailed("updating problem indicators", e); //$NON-NLS-1$
}
}
}
}
}
/**
* @generated
*/
@Override
public void gotoMarker(final IMarker marker) {
try {
if (marker.getType().equals(EValidator.MARKER)) {
final String uriAttribute = marker.getAttribute(EValidator.URI_ATTRIBUTE, null);
if (uriAttribute != null) {
final URI uri = URI.createURI(uriAttribute);
final EObject eObject = fEditingDomain.getResourceSet().getEObject(uri, true);
if (eObject != null) {
selectObject(Collections.singletonList((EObject) fEditingDomain.getWrapper(eObject)));
}
}
}
}
catch (final CoreException e) {
operationFailed("going to marker", e); //$NON-NLS-1$
}
}
@Override
public EFToolkit getToolkit() {
return (EFToolkit) super.getToolkit();
}
@Override
protected abstract EFToolkit createToolkit(Display display);
@Override
protected void createPages() {
// Creates the model from the editor input
createModel();
fDataBinding = new EFDataBindingSupport(this, createContextAdapterFactory());
super.createPages(); // #addPages()
getContainer().addControlListener(new ControlAdapter() {
boolean guard = false;
@Override
public void controlResized(final ControlEvent event) {
if (!guard) {
guard = true;
hideTabs();
guard = false;
}
}
});
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
updateProblemIndication();
}
});
fHandlers = new HandlerCollection();
createActions(getSite(), fHandlers);
}
protected IAdapterFactory createContextAdapterFactory() {
return new ContextAdapterFactory();
}
public EFDataBindingSupport getDataBinding() {
return fDataBinding;
}
protected void createActions(final IServiceLocator locator, final HandlerCollection handlers) {
final IHandlerService handlerService = (IHandlerService) locator.getService(IHandlerService.class);
// { final IHandler2 handler = new UndoCommandHandler(getEditingDomain());
// handlers.add(IWorkbenchCommandConstants.EDIT_UNDO, handler);
// handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_UNDO, handler);
// }
// { final IHandler2 handler = new RedoCommandHandler(getEditingDomain());
// handlers.add(IWorkbenchCommandConstants.EDIT_REDO, handler);
// handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_REDO, handler);
// }
{ final IHandler2 handler = new CutEObjectHandler();
handlers.add(IWorkbenchCommandConstants.EDIT_CUT + '~' +
IEFPropertyExpressions.EOBJECT_LIST_ID, handler );
handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_CUT, handler,
IEFPropertyExpressions.EOBJECT_LIST_EXPRESSION );
}
{ final IHandler2 handler = new CopyEObjectHandler();
handlers.add(IWorkbenchCommandConstants.EDIT_COPY + '~' +
IEFPropertyExpressions.EOBJECT_LIST_ID, handler );
handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_COPY, handler,
IEFPropertyExpressions.EOBJECT_LIST_EXPRESSION );
}
{ final IHandler2 handler = new PasteEObjectHandler();
handlers.add(IWorkbenchCommandConstants.EDIT_PASTE + '~' +
IEFPropertyExpressions.EOBJECT_LIST_ID, handler );
handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_PASTE, handler,
IEFPropertyExpressions.EOBJECT_LIST_EXPRESSION );
}
}
protected void contributeToPages(final IToolBarManager manager) {
}
/**
* This creates a context menu for the viewer and adds a listener as well registering the menu for extension.
* @generated
*/
protected void createRawContextMenuFor(final StructuredViewer viewer) {
final MenuManager contextMenu = new MenuManager("#PopUp"); //$NON-NLS-1$
contextMenu.add(new Separator("additions")); //$NON-NLS-1$
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(this);
final Menu menu= contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer));
final int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
final Transfer[] transfers = new Transfer[] { LocalTransfer.getInstance() };
viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer));
viewer.addDropSupport(dndOperations, transfers, new EditingDomainViewerDropAdapter(getEditingDomain(), viewer));
}
/**
* This implements {@link org.eclipse.jface.action.IMenuListener} to help fill the context menus with contributions from the Edit menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void menuAboutToShow(final IMenuManager menuManager) {
// ((IMenuListener)getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager);
}
protected void selectObject(final Collection<? extends EObject> objects) {
// getSite().getShell().getDisplay().asyncExec(runnable)
}
protected void setStatusLineManager(final ISelection selection) {
// final IStatusLineManager statusLineManager = fCurrentViewer != null && fCurrentViewer == fContentOutlineViewer ?
// fContentOutlineStatusLineManager : getActionBars().getStatusLineManager();
final IStatusLineManager statusLineManager = getActionBarContributor().getActionBars().getStatusLineManager();
if (statusLineManager != null) {
if (selection instanceof IStructuredSelection) {
final Collection<?> collection = ((IStructuredSelection)selection).toList();
switch (collection.size()) {
case 0: {
statusLineManager.setMessage(""); //$NON-NLS-1$
break;
}
case 1: {
final String text = new AdapterFactoryItemDelegator(getAdapterFactory()).getText(collection.iterator().next());
statusLineManager.setMessage(text);
break;
}
default: {
statusLineManager.setMessage(NLS.bind(Messages.EFEditor_MultiObjectSelected_message,
Integer.toString(collection.size() )));
break;
}
}
}
else {
statusLineManager.setMessage(""); //$NON-NLS-1$
}
}
}
/**
* If there is just one page in the multi-page editor part,
* this hides the single tab at the bottom.
* @generated
*/
protected void hideTabs() {
if (getPageCount() <= 1) {
// setPageText(0, ""); //$NON-NLS-1$
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(1);
final Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y + 6);
}
}
}
/**
* If there is more than one page in the multi-page editor part,
* this shows the tabs at the bottom.
* @generated
*/
protected void showTabs() {
if (getPageCount() > 1) {
// setPageText(0, Messages.RTaskEditor_FirstPage_label);
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(SWT.DEFAULT);
final Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y - 6);
}
}
}
protected IContentOutlinePage getContentOutlinePage() {
if (fContentOutlinePage == null) {
fContentOutlinePage = createContentOutlinePage();
}
return fContentOutlinePage;
}
protected IContentOutlinePage createContentOutlinePage() {
return null;
}
protected IPropertySheetPage getPropertySheetPage() {
final IPropertySheetPage page = createPropertySheetPage();
fPropertySheetPages.add(page);
return page;
}
protected IPropertySheetPage createPropertySheetPage() {
return new EFPropertySheetPage(this);
}
EditorSelectionProvider getSelectionProvider() {
return fSelectionProvider;
}
@Override
protected void pageChange(final int newPageIndex) {
fSelectionProvider.update();
super.pageChange(newPageIndex);
}
/**
* This is here for the listener to be able to call it.
* @generated
*/
@Override
protected void firePropertyChange(final int action) {
super.firePropertyChange(action);
}
protected abstract void operationFailed(String string, Exception e);
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(final Class required) {
if (Control.class.equals(required)) {
return getContainer();
}
if (IContentOutlinePage.class.equals(required)) {
return getContentOutlinePage();
}
if (IPropertySheetPage.class.equals(required)) {
return getPropertySheetPage();
}
if (IGotoMarker.class.equals(required)) {
return this;
}
return super.getAdapter(required);
}
void onPropertySheetDisposed(final IPropertySheetPage page) {
fPropertySheetPages.remove(page);
}
/**
* @generated
*/
@Override
public void dispose() {
fUpdateProblemIndication = false;
ResourcesPlugin.getWorkspace().removeResourceChangeListener(fResourceListener);
getSite().getPage().removePartListener(fPartListener);
fAdapterFactory.dispose();
if (getActionBarContributor().getActiveEditor() == this) {
getActionBarContributor().setActiveEditor(null);
}
for (final IPropertySheetPage page : fPropertySheetPages) {
page.dispose();
}
fPropertySheetPages.clear();
if (fContentOutlinePage != null) {
fContentOutlinePage.dispose();
fContentOutlinePage = null;
}
if (fHandlers != null) {
fHandlers.dispose();
fHandlers = null;
}
super.dispose();
}
}
| false | false | null | null |
diff --git a/Addendum/src/com/cs1530/group4/addendum/client/CommentBox.java b/Addendum/src/com/cs1530/group4/addendum/client/CommentBox.java
index cfb41a9..2c8cfe5 100644
--- a/Addendum/src/com/cs1530/group4/addendum/client/CommentBox.java
+++ b/Addendum/src/com/cs1530/group4/addendum/client/CommentBox.java
@@ -1,121 +1,126 @@
package com.cs1530.group4.addendum.client;
import com.cs1530.group4.addendum.shared.Comment;
import com.cs1530.group4.addendum.shared.Post;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Label;
public class CommentBox extends Composite
{
CommentBox commentBox = this;
UserServiceAsync userService = UserService.Util.getInstance();
RichTextArea textArea;
Label errorLabel;
public CommentBox(final PromptedTextBox addComment, final Post post, final UserPost userPost)
{
VerticalPanel verticalPanel = new VerticalPanel();
verticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
verticalPanel.setStyleName("CommentBoxBackground");
verticalPanel.getElement().getStyle().setProperty("padding", "10px");
initWidget(verticalPanel);
verticalPanel.setSize("100%", "124px");
HorizontalPanel horizontalPanel = new HorizontalPanel();
horizontalPanel.setStyleName("CommentBox");
verticalPanel.add(horizontalPanel);
horizontalPanel.setWidth("100%");
Image image = new Image("/addendum/getImage?username="+Cookies.getCookie("loggedIn"));
image.getElement().getStyle().setProperty("marginRight", "10px");
horizontalPanel.add(image);
image.setSize("28px", "28px");
VerticalPanel editorPanel = new VerticalPanel();
editorPanel.setStyleName("body");
textArea = new RichTextArea();
RichTextToolbar toolbar = new RichTextToolbar(textArea);
textArea.addStyleName("small");
textArea.setSize("95%", "75px");
editorPanel.add(toolbar);
editorPanel.add(textArea);
horizontalPanel.add(editorPanel);
editorPanel.setWidth("100%");
errorLabel = new Label("Error: Message length must be greater than 0");
errorLabel.setStyleName("gwt-Label-Error");
errorLabel.setVisible(false);
verticalPanel.add(errorLabel);
HorizontalPanel horizontalPanel_1 = new HorizontalPanel();
horizontalPanel_1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
horizontalPanel_1.setSpacing(10);
verticalPanel.add(horizontalPanel_1);
horizontalPanel_1.setSize("307px", "43px");
verticalPanel.setCellHorizontalAlignment(horizontalPanel_1, HasHorizontalAlignment.ALIGN_RIGHT);
final Button btnSubmit = new Button("Post Comment");
btnSubmit.setStyleName("ADCButton");
btnSubmit.addClickHandler(new ClickHandler()
{
@Override
public void onClick(ClickEvent event)
{
if(textArea.getHTML().length() == 0)
{
errorLabel.setVisible(true);
return;
}
btnSubmit.setEnabled(false);
final Comment comment = new Comment(Cookies.getCookie("loggedIn"),textArea.getHTML());
AsyncCallback<Void> callback = new AsyncCallback<Void>()
{
@Override
public void onFailure(Throwable caught)
{
btnSubmit.setEnabled(true);
errorLabel.setVisible(true);
errorLabel.setText("There was a problem uploading your post, please try again later.");
}
@Override
public void onSuccess(Void v)
{
userPost.addSubmittedComment(comment);
commentBox.setVisible(false);
addComment.setVisible(true);
+ btnSubmit.setEnabled(true);
+ errorLabel.setText("Error: Message length must be greater than 0");
+ errorLabel.setVisible(false);
}
};
userService.uploadComment(post.getPostKey(), comment, callback);
}
});
- horizontalPanel_1.add(btnSubmit);
btnSubmit.setSize("131px", "29px");
Button btnCancel = new Button("Cancel");
btnCancel.setStyleName("ADCButton");
btnCancel.addClickHandler(new ClickHandler()
{
@Override
public void onClick(ClickEvent event)
{
commentBox.setVisible(false);
addComment.setVisible(true);
+ btnSubmit.setEnabled(true);
+ errorLabel.setVisible(false);
}
});
horizontalPanel_1.add(btnCancel);
+ horizontalPanel_1.add(btnSubmit);
btnCancel.setSize("131px", "29px");
setStyleName("CommentBoxBackground");
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/baixing_quanleimu/src/com/baixing/sharing/WeiboSSOSharingManager.java b/baixing_quanleimu/src/com/baixing/sharing/WeiboSSOSharingManager.java
index bd1c3454..399fcd86 100644
--- a/baixing_quanleimu/src/com/baixing/sharing/WeiboSSOSharingManager.java
+++ b/baixing_quanleimu/src/com/baixing/sharing/WeiboSSOSharingManager.java
@@ -1,214 +1,216 @@
package com.baixing.sharing;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.baixing.activity.BaseActivity;
import com.baixing.activity.MainActivity;
import com.baixing.broadcast.CommonIntentAction;
import com.baixing.data.GlobalDataManager;
import com.baixing.entity.Ad;
import com.baixing.entity.ChatMessage;
import com.baixing.entity.ImageList;
import com.baixing.imageCache.ImageCacheManager;
import com.baixing.util.Util;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.sso.SsoHandler;
public class WeiboSSOSharingManager extends BaseSharingManager {
public static class WeiboAccessTokenWrapper implements Serializable {
/**
*
*/
private static final long serialVersionUID = 973987291134876738L;
private String token;
private String expires_in;
// public WeiboAccessTokenWrapper(String token, String expires){
// this.token = token;
// this.expires_in = expires;
// }
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
}
private Ad mAd;
private BaseActivity mActivity;
static final String kWBBaixingAppKey = "3747392969";
private static final String kWBBaixingAppSecret = "ff394d0df1cfc41c7d89ce934b5aa8fc";
public static final String STRING_WEIBO_ACCESS_TOKEN = "weiboaccesstoken";
private Weibo mWeibo;
private WeiboAccessTokenWrapper mToken;
private SsoHandler mSsoHandler;
public void doAuthorizeCallBack(int requestCode, int resultCode, Intent data) {
if (mSsoHandler != null) {
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
private WeiboAccessTokenWrapper loadToken() {
return (WeiboAccessTokenWrapper) Util.loadDataFromLocate(mActivity,
STRING_WEIBO_ACCESS_TOKEN, WeiboAccessTokenWrapper.class);
}
static public void saveToken(Context context, WeiboAccessTokenWrapper token) {
Util.saveDataToLocate(context, STRING_WEIBO_ACCESS_TOKEN, token);
}
public WeiboSSOSharingManager(BaseActivity activity) {
mActivity = activity;
mToken = loadToken();
}
class AuthDialogListener implements WeiboAuthListener {
@Override
public void onComplete(Bundle values) {
String token = values.getString("access_token");
String expires_in = values.getString("expires_in");
Oauth2AccessToken accessToken = new Oauth2AccessToken(token,
expires_in);
if (accessToken.isSessionValid()) {
WeiboAccessTokenWrapper wtw = new WeiboAccessTokenWrapper();
wtw.setToken(token);
wtw.setExpires_in(expires_in);
saveToken(mActivity, wtw);
doShare2Weibo(accessToken);
}
}
@Override
public void onError(WeiboDialogError e) {
}
@Override
public void onCancel() {
}
@Override
public void onWeiboException(WeiboException e) {
}
}
@Override
public void auth() {
try {
Class sso = Class.forName("com.weibo.sdk.android.sso.SsoHandler");
authSSO();
} catch (ClassNotFoundException e) {
authTraditional();
}
}
@Override
public void share(Ad ad) {
mAd = ad;
if (mToken != null && mToken.getExpires_in() != null
&& mToken.getExpires_in().length() > 0
&& mToken.getToken() != null && mToken.getToken().length() > 0) {
Oauth2AccessToken accessToken = new Oauth2AccessToken(
mToken.getToken(), mToken.getExpires_in());
if (accessToken.isSessionValid()) {
doShare2Weibo(accessToken);
return;
}
}
auth();
}
private void authTraditional() {
mWeibo = Weibo.getInstance(kWBBaixingAppKey, "http://www.baixing.com");
mWeibo.authorize(mActivity, new AuthDialogListener());
}
private void unregisterListener() {
if (msgListener != null) {
mActivity.unregisterReceiver(msgListener);
}
}
private BroadcastReceiver msgListener;
private boolean isActive = true;
private void authSSO() {
Intent intent = new Intent();
intent.setClass(mActivity, WeiboManagerActivity.class);
intent.putExtra("ad", mAd);
mActivity.startActivity(intent);
isActive = false;
unregisterListener();
msgListener = new BroadcastReceiver() {
public void onReceive(Context outerContext, Intent outerIntent) {
if (outerIntent.getAction().equals(CommonIntentAction.ACTION_BROADCAST_WEIBO_AUTH_DONE)) {
mToken = loadToken();
}else if(outerIntent.getAction().equals(CommonIntentAction.ACTION_BROADCAST_SHARE_BACK_TO_FRONT)){
isActive = true;
}
if(mToken != null && isActive){
- share(mAd);
+ if(mAd != null){
+ share(mAd);
+ }
unregisterListener();
}
}
};
mActivity.registerReceiver(msgListener, new IntentFilter(
CommonIntentAction.ACTION_BROADCAST_WEIBO_AUTH_DONE));
mActivity.registerReceiver(msgListener, new IntentFilter(
CommonIntentAction.ACTION_BROADCAST_SHARE_BACK_TO_FRONT));
}
@Override
public void release() {
// TODO Auto-generated method stub
}
private void doShare2Weibo(Oauth2AccessToken accessToken) {
String imgUrl = super.getThumbnailUrl(mAd);
String imgPath = (imgUrl == null || imgUrl.length() == 0) ? "" : ImageCacheManager.getInstance().getFileInDiskCache(imgUrl);
Bundle bundle = new Bundle();
bundle.putString(WeiboSharingFragment.EXTRA_WEIBO_CONTENT,
"我用百姓网App发布了\"" + mAd.getValueByKey("title") + "\"" + "麻烦朋友们帮忙转发一下~ " + mAd.getValueByKey("link"));
bundle.putString(WeiboSharingFragment.EXTRA_PIC_URI,
(imgPath == null || imgPath.length() == 0) ? "" : imgPath);
bundle.putString(WeiboSharingFragment.EXTRA_ACCESS_TOKEN,
accessToken.getToken());
bundle.putString(WeiboSharingFragment.EXTRA_EXPIRES_IN,
String.valueOf(accessToken.getExpiresTime()));
mActivity.pushFragment(new WeiboSharingFragment(), bundle, false);
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/LogInServlet.java b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/LogInServlet.java
index 00cadc4..af21266 100644
--- a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/LogInServlet.java
+++ b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/LogInServlet.java
@@ -1,23 +1,22 @@
package org.cvut.wa2.projectcontrol;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class LogInServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
-
-
- resp.setContentType("text/plain");
- resp.getWriter().println("You have been logged in");
+ UserService userService = UserServiceFactory.getUserService();
+ resp.sendRedirect(userService.createLoginURL("http://vrchlpet-projectcontrol.appspot.com"));
+
}
}
diff --git a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/ProjectControlServlet.java b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/ProjectControlServlet.java
index bb4f182..935d8a4 100644
--- a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/ProjectControlServlet.java
+++ b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/ProjectControlServlet.java
@@ -1,33 +1,33 @@
package org.cvut.wa2.projectcontrol;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class ProjectControlServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
- if ( user != null) {
+ if ( user == null) {
resp.sendRedirect("/LogIn.jsp");
} else {
resp.sendRedirect("/TeamsTask.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
| false | false | null | null |
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/EEDefinitionTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/EEDefinitionTests.java
index 3d1e76cdf..76aea2db4 100644
--- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/EEDefinitionTests.java
+++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/EEDefinitionTests.java
@@ -1,182 +1,182 @@
/*******************************************************************************
* Copyright (c) 2007 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.jdt.debug.tests.core;
import java.io.File;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.debug.testplugin.JavaTestPlugin;
import org.eclipse.jdt.debug.tests.AbstractDebugTest;
import org.eclipse.jdt.internal.launching.EEVMType;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMInstallType;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.LibraryLocation;
import org.eclipse.jdt.launching.VMStandin;
import org.eclipse.jdt.launching.environments.IExecutionEnvironment;
import org.eclipse.jdt.launching.environments.IExecutionEnvironmentsManager;
/**
* Tests for ".ee" files - installed JRE definition files
*/
public class EEDefinitionTests extends AbstractDebugTest {
public static IPath TEST_EE_FILE = null;
{
if (Platform.OS_WIN32.equals(Platform.getOS())) {
TEST_EE_FILE = new Path("testfiles/test-jre/bin/test-foundation11-win32.ee");
} else {
TEST_EE_FILE = new Path("testfiles/test-jre/bin/test-foundation11.ee");
}
}
public EEDefinitionTests(String name) {
super(name);
}
/**
* Tests that the EE file is a valid file
*/
public void testValidateDefinitionFile() {
File file = getEEFile();
assertNotNull("Missing EE file", file);
IStatus status = EEVMType.validateDefinitionFile(file);
assertTrue("Invalid install location", status.isOK());
}
/**
* Tests that the EE install location validation returns an INFO status.
*/
public void testValidateInstallLocation() {
File file = getEEFile();
IVMInstallType vmType = getVMInstallType();
assertNotNull("Missing EE file", file);
assertNotNull("Missing EE VM type", vmType);
IStatus status = vmType.validateInstallLocation(file);
- assertTrue("Invalid install location", status.getSeverity() == IStatus.INFO);
+ assertTrue("Invalid install location", status.getSeverity() == IStatus.OK);
}
/**
* Tests libraries for the EE file
*/
public void testLibraries() {
File file = getEEFile();
assertNotNull("Missing EE file", file);
LibraryLocation[] libs = EEVMType.getLibraryLocations(file);
String[] expected = new String[]{"end.jar", "classes.txt", "others.txt", "ext1.jar", "ext2.jar", "opt-ext.jar"};
assertEquals("Wrong number of libraries", expected.length, libs.length);
for (int i = 0; i < expected.length; i++) {
if (i == 3) {
// ext1 and ext2 can be in either order due to file system ordering
assertTrue("Wrong library", expected[i].equals(libs[i].getSystemLibraryPath().lastSegment()) ||
expected[i].equals(libs[i+1].getSystemLibraryPath().lastSegment()));
} else if (i == 4) {
// ext1 and ext2 can be in either order due to file system ordering
assertTrue("Wrong library", expected[i].equals(libs[i].getSystemLibraryPath().lastSegment()) ||
expected[i].equals(libs[i-1].getSystemLibraryPath().lastSegment()));
} else {
assertEquals("Wrong library", expected[i], libs[i].getSystemLibraryPath().lastSegment());
}
if ("classes.txt".equals(expected[i])) {
assertEquals("source.txt", libs[i].getSystemLibrarySourcePath().lastSegment());
}
}
}
/**
* Tests default libraries for an EE VM type are empty.
*/
public void testDefaultLibraries() {
File file = getEEFile();
IVMInstallType vmType = getVMInstallType();
assertNotNull("Missing EE file", file);
assertNotNull("Missing EE VM type", vmType);
LibraryLocation[] libs = vmType.getDefaultLibraryLocations(file);
assertEquals("Wrong number of libraries", 0, libs.length);
}
/**
* Tests default VM arguments. All arguments from the EE file should get passed through in the
* same order to the command line.
*/
public void testVMArguments() {
File file = getEEFile();
assertNotNull("Missing EE file", file);
String defaultVMArguments = EEVMType.getVMArguments(file);
String[] expected = new String[] {
"-Dee.executable",
"-Dee.executable.console",
"-Dee.bootclasspath",
"-Dee.src",
"-Dee.ext.dirs",
"-Dee.endorsed.dirs",
"-Dee.language.level",
"-Dee.class.library.level",
"-Dee.id",
"-Dee.name",
"-Dee.description",
"-Dee.copyright",
"-XspecialArg:123"
};
int prev = -1;
for (int i = 0; i < expected.length; i++) {
int next = defaultVMArguments.indexOf(expected[i]);
assertTrue("Missing argument: " + expected[i], next >= 0);
assertTrue("Wrong argument order: " + expected[i], next > prev);
prev = next;
}
}
/**
* Test compatible environments
*/
public void testCompatibleEEs() throws CoreException {
IVMInstall install = null;
EEVMType vmType = (EEVMType) getVMInstallType();
try {
File file = getEEFile();
assertNotNull("Missing EE file", file);
assertNotNull("Missing EE VM type", vmType);
VMStandin standin = JavaRuntime.createVMFromDefinitionFile(file, "test-ee-file", "test-ee-file-id");
install = standin.convertToRealVM();
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment[] envs = manager.getExecutionEnvironments();
boolean found11 = false;
for (int i = 0; i < envs.length; i++) {
IExecutionEnvironment env = envs[i];
if (env.getId().equals("CDC-1.1/Foundation-1.1")) {
found11 = true;
assertTrue("Should be strictly compatible with " + env.getId(), env.isStrictlyCompatible(install));
} else if (env.getId().indexOf("jdt.debug.tests") < 0) {
assertFalse("Should *not* be strictly compatible with " + env.getId(), env.isStrictlyCompatible(install));
}
}
assertTrue("Did not find foundation 1.1 environment", found11);
} finally {
if (install != null && vmType != null) {
vmType.disposeVMInstall(install.getId());
}
}
}
protected File getEEFile() {
return JavaTestPlugin.getDefault().getFileInPlugin(TEST_EE_FILE);
}
protected IVMInstallType getVMInstallType() {
return JavaRuntime.getVMInstallType(EEVMType.ID_EE_VM_TYPE);
}
}
| true | false | null | null |
diff --git a/src/org/openstreetmap/josm/gui/SplashScreen.java b/src/org/openstreetmap/josm/gui/SplashScreen.java
index c95faa44..fe5cf582 100644
--- a/src/org/openstreetmap/josm/gui/SplashScreen.java
+++ b/src/org/openstreetmap/josm/gui/SplashScreen.java
@@ -1,173 +1,174 @@
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.gui;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
+import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JSeparator;
-import javax.swing.JWindow;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import org.openstreetmap.josm.data.Version;
import org.openstreetmap.josm.gui.progress.ProgressMonitor;
import org.openstreetmap.josm.gui.progress.ProgressRenderer;
import org.openstreetmap.josm.gui.progress.SwingRenderingProgressMonitor;
import org.openstreetmap.josm.tools.ImageProvider;
/**
* Show a splash screen so the user knows what is happening during startup.
*
*/
-public class SplashScreen extends JWindow {
+public class SplashScreen extends JFrame {
private SplashScreenProgressRenderer progressRenderer;
private SwingRenderingProgressMonitor progressMonitor;
public SplashScreen() {
super();
+ setUndecorated(true);
// Add a nice border to the main splash screen
JPanel contentPane = (JPanel)this.getContentPane();
Border margin = new EtchedBorder(1, Color.white, Color.gray);
contentPane.setBorder(margin);
// Add a margin from the border to the content
JPanel innerContentPane = new JPanel();
innerContentPane.setBorder(new EmptyBorder(10, 10, 2, 10));
contentPane.add(innerContentPane);
innerContentPane.setLayout(new GridBagLayout());
// Add the logo
JLabel logo = new JLabel(ImageProvider.get("logo.png"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridheight = 2;
innerContentPane.add(logo, gbc);
// Add the name of this application
JLabel caption = new JLabel("JOSM - " + tr("Java OpenStreetMap Editor"));
caption.setFont(new Font("Helvetica", Font.BOLD, 20));
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.insets = new Insets(30, 0, 0, 0);
innerContentPane.add(caption, gbc);
// Add the version number
JLabel version = new JLabel(tr("Version {0}", Version.getInstance().getVersionString()));
gbc.gridy = 1;
gbc.insets = new Insets(0, 0, 0, 0);
innerContentPane.add(version, gbc);
// Add a separator to the status text
JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(15, 0, 5, 0);
innerContentPane.add(separator, gbc);
// Add a status message
progressRenderer = new SplashScreenProgressRenderer();
gbc.gridy = 3;
gbc.insets = new Insets(5, 5, 10, 5);
innerContentPane.add(progressRenderer, gbc);
progressMonitor = new SwingRenderingProgressMonitor(progressRenderer);
pack();
// Center the splash screen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension labelSize = contentPane.getPreferredSize();
setLocation(screenSize.width / 2 - (labelSize.width / 2),
screenSize.height / 2 - (labelSize.height / 2));
// Add ability to hide splash screen by clicking it
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent event) {
setVisible(false);
}
});
}
public ProgressMonitor getProgressMonitor() {
return progressMonitor;
}
static private class SplashScreenProgressRenderer extends JPanel implements ProgressRenderer {
private JLabel lblTaskTitle;
private JLabel lblCustomText;
private JProgressBar progressBar;
protected void build() {
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.insets = new Insets(5,0,0,5);
add(lblTaskTitle = new JLabel(""), gc);
gc.gridx = 0;
gc.gridy = 1;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.insets = new Insets(5,0,0,5);
add(lblCustomText = new JLabel(""), gc);
gc.gridx = 0;
gc.gridy = 2;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 1.0;
gc.weighty = 0.0;
gc.insets = new Insets(5,0,0,5);
add(progressBar = new JProgressBar(JProgressBar.HORIZONTAL), gc);
}
public SplashScreenProgressRenderer() {
build();
}
public void setCustomText(String message) {
lblCustomText.setText(message);
repaint();
}
public void setIndeterminate(boolean indeterminate) {
progressBar.setIndeterminate(indeterminate);
repaint();
}
public void setMaximum(int maximum) {
progressBar.setMaximum(maximum);
repaint();
}
public void setTaskTitle(String taskTitle) {
lblTaskTitle.setText(taskTitle);
repaint();
}
public void setValue(int value) {
progressBar.setValue(value);
repaint();
}
}
}
| false | false | null | null |
diff --git a/src/Board.java b/src/Board.java
index e5ccb42..260cc69 100644
--- a/src/Board.java
+++ b/src/Board.java
@@ -1,271 +1,271 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Random;
/**
* Class used to initialize a board configuration. It contains
* all the static elements of the board and a <code>State</code>
* object which holds the initial configuration of the dynamic elements.
*
* @author Erik
*
*/
public class Board {
public static final byte FLOOR = (1 << 0);
public static final byte WALL = (1 << 1);
public static final byte GOAL = (1 << 2);
public static final byte DEAD = (1 << 3);
private static final byte NOT_CORNERED = -1;
private static final byte NW = 0;
private static final byte NE = 1;
private static final byte SW = 2;
private static final byte SE = 3;
/**
* Matrix of static elements on the board.
*/
private static byte[][] board;
/**
* Random values used to calculate hash functions.
*/
public static long[][] zValues;
/**
* Number of board rows.
*/
public static byte rows = 0;
/**
* Number of row columns.
*/
public static byte cols = 0;
/**
* Vector of goal positions.
*/
public static Collection<BoardPosition> goalPositions = new LinkedList<BoardPosition>();
/**
* The initial state of the board.
*/
public static State initialState;
/**
* Constructs a board using an vector of
* strings supplied from the course server.
*
* @param lines Lines from the server
*/
public Board(ArrayList<String> lines) {
rows = (byte) lines.size();
cols = (byte) 0;
for(String r : lines) {
if(r.length()>cols) {
cols = (byte) r.length();
}
}
/*
* Pad the sides so we don't have to worry about edge effects.
*/
board = new byte[rows+2][cols+2];
zValues = new long[rows+2][cols+2];
BoardPosition playerPosition = null;
Collection<BoardPosition> boxPositions = new LinkedList<BoardPosition>();
Random random = new Random();
for (byte i=1; i<=rows; i++) {
String line = lines.get(i-1);
for (byte j=1; j<=line.length(); j++) {
char character = line.charAt(j-1);
zValues[i][j] = random.nextLong();
board[i][j] = FLOOR;
switch (character) {
case '#': // wall
board[i][j] = WALL;
break;
case '@': // player
playerPosition = new BoardPosition(i, j);
break;
case '+': // player on goal
board[i][j] |= GOAL;
goalPositions.add(new BoardPosition(i, j));
playerPosition = new BoardPosition(i, j);
break;
case '$': // box
boxPositions.add(new BoardPosition(i, j));
break;
case '*': // box on goal
board[i][j] |= GOAL;
goalPositions.add(new BoardPosition(i, j));
boxPositions.add(new BoardPosition(i, j));
break;
case '.': // goal
board[i][j] |= GOAL;
goalPositions.add(new BoardPosition(i, j));
break;
case ' ': // floor
board[i][j] = FLOOR;
break;
}
}
}
markDead();
initialState = new State(this, playerPosition, boxPositions);
}
public static boolean floorAt(byte row, byte col) {
return (board[row][col] & FLOOR) != 0;
}
public static boolean goalAt(byte row, byte col) {
return (board[row][col] & GOAL) != 0;
}
public static boolean wallAt(byte row, byte col) {
return board[row][col] == WALL;
}
public static final boolean deadAt(byte row, byte col) {
return (board[row][col] & DEAD) != 0;
}
/**
* Marks dead-end squares, from which a box cannot be moved to a goal.
*
* Example (view in fixed-width font!):
* <pre><code>
* #########
* # # #####
* # #### #
* # #
* # G #
* # #
* ################
* <code></pre>
* The above example, where <code>G</code> marks a goal, would be marked as:
* <pre><code>
* #########
* #DDDDDDD# #####
- * #DDDDDDD####DDD#
+ * #D ####DDD#
* #D D#
* #D G D#
* #DDDDDDDDDDDDDD#
* ################
* </code></pre>
* Where <code>D</code> marks a dead end.
*/
private static void markDead() {
for (byte row = 1; row<=rows; row++) {
for (byte col = 1; col<=cols; col++) {
if (!floorAt(row, col)) {
continue;
}
byte isCornered = isCornered(row, col);
if (isCornered != NOT_CORNERED) {
if (goalAt(row, col)) {
continue;
}
// It's a non-goal corner => dead end
board[row][col] |= DEAD;
byte rInc = 0, cInc = 0;
switch (isCornered) {
case NW:
rInc = -1;
cInc = -1;
break;
case NE:
rInc = -1;
cInc = 1;
break;
case SW:
rInc = 1;
cInc = -1;
break;
case SE:
rInc = 1;
cInc = 1;
break;
}
byte currCol = col;
while (currCol>0 && currCol<=cols) {
currCol -= cInc;
if (goalAt(row, currCol)) {
break;
} else if (wallAt(row, currCol)) {
for (byte c = (byte) (currCol + cInc); c != col; c += cInc) {
board[row][c] |= DEAD;
}
break;
} else if (!wallAt((byte) (row + rInc), currCol)) {
break;
}
}
byte currRow = row;
while (currRow>0 && currRow<=rows) {
currRow -= rInc;
if (goalAt(currRow, col)) {
break;
} else if (wallAt(currRow, col)) {
for (byte r = (byte) (currRow + rInc); r != row; r += rInc) {
board[r][col] |= DEAD;
}
break;
} else if (!wallAt(currRow, (byte) (col + cInc))) {
break;
}
}
}
}
}
}
private static byte isCornered(byte r, byte c) {
if (wallAt((byte) (r-1), c) && wallAt(r, (byte) (c-1)))
return NW;
if (wallAt((byte) (r-1), c) && wallAt(r, (byte) (c+1)))
return NE;
if (wallAt(r, (byte) (c+1)) && wallAt((byte) (r+1), c))
return SE;
if (wallAt(r, (byte) (c-1)) && wallAt((byte) (r+1), c))
return SW;
return NOT_CORNERED;
}
@Override
public String toString() {
String result = "";
for(byte i=1; i<=rows; i++) {
for(byte j=1; j<=cols; j++) {
if(deadAt(i, j)) {
result += 'x';
}
else if(goalAt(i, j)) {
result += '.';
}
else if(floorAt(i, j)) {
result += ' ';
}
else if(wallAt(i, j)) {
result += '#';
}
}
result += "\n";
}
return result;
}
}
| true | false | null | null |
diff --git a/core/src/main/java/org/infinispan/lifecycle/ComponentStatus.java b/core/src/main/java/org/infinispan/lifecycle/ComponentStatus.java
index 4ef01ccb5b..e5ff05d172 100644
--- a/core/src/main/java/org/infinispan/lifecycle/ComponentStatus.java
+++ b/core/src/main/java/org/infinispan/lifecycle/ComponentStatus.java
@@ -1,109 +1,109 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2000 - 2008, 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.infinispan.lifecycle;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Different states a component may be in.
*
* @author Manik Surtani
* @see org.infinispan.lifecycle.Lifecycle
* @since 4.0
*/
public enum ComponentStatus {
/**
* Object has been instantiated, but start() has not been called.
*/
INSTANTIATED,
/**
* The <code>start()</code> method has been called but not yet completed.
*/
INITIALIZING,
/**
* The <code>start()</code> method has been completed and the component is running.
*/
RUNNING,
/**
* The <code>stop()</code> method has been called but has not yet completed.
*/
STOPPING,
/**
* The <code>stop()</code> method has completed and the component has terminated.
*/
TERMINATED,
/**
* The component is in a failed state due to a problem with one of the other lifecycle transition phases.
*/
FAILED;
private static final Log log = LogFactory.getLog(ComponentStatus.class);
public boolean needToDestroyFailedCache() {
return this == ComponentStatus.FAILED;
}
public boolean startAllowed() {
switch (this) {
case INSTANTIATED:
return true;
default:
return false;
}
}
public boolean needToInitializeBeforeStart() {
switch (this) {
case TERMINATED:
return true;
default:
return false;
}
}
public boolean stopAllowed() {
switch (this) {
case INSTANTIATED:
case TERMINATED:
case STOPPING:
case INITIALIZING:
log.debug("Ignoring call to stop() as current state is " + this);
return false;
default:
return true;
}
}
public boolean allowInvocations() {
return this == ComponentStatus.RUNNING;
}
public boolean startingUp() {
- return this == ComponentStatus.RUNNING || this == ComponentStatus.INITIALIZING || this == ComponentStatus.INSTANTIATED;
+ return this == ComponentStatus.INITIALIZING || this == ComponentStatus.INSTANTIATED;
}
public boolean isTerminated() {
return this == ComponentStatus.TERMINATED;
}
}
| true | false | null | null |
diff --git a/tests/com/google/caja/plugin/templates/TemplateCompilerTest.java b/tests/com/google/caja/plugin/templates/TemplateCompilerTest.java
index 6db3572a..f688de8a 100644
--- a/tests/com/google/caja/plugin/templates/TemplateCompilerTest.java
+++ b/tests/com/google/caja/plugin/templates/TemplateCompilerTest.java
@@ -1,856 +1,860 @@
// Copyright (C) 2009 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.plugin.templates;
import com.google.caja.SomethingWidgyHappenedError;
import com.google.caja.lang.css.CssSchema;
import com.google.caja.lang.html.HtmlSchema;
import com.google.caja.lexer.CharProducer;
import com.google.caja.lexer.ExternalReference;
import com.google.caja.lexer.FilePosition;
import com.google.caja.lexer.ParseException;
import com.google.caja.parser.AncestorChain;
import com.google.caja.parser.MutableParseTreeNode;
import com.google.caja.parser.ParseTreeNode;
import com.google.caja.parser.Visitor;
import com.google.caja.parser.css.CssTree;
import com.google.caja.parser.html.DomParser;
import com.google.caja.parser.html.Namespaces;
import com.google.caja.parser.html.Nodes;
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.TranslatedCode;
import com.google.caja.plugin.CssRuleRewriter;
import com.google.caja.plugin.ExtractedHtmlContent;
import com.google.caja.plugin.PluginEnvironment;
import com.google.caja.plugin.PluginMeta;
import com.google.caja.reporting.Message;
import com.google.caja.reporting.MessageLevel;
import com.google.caja.reporting.MessagePart;
import com.google.caja.reporting.MessageType;
import com.google.caja.util.CajaTestCase;
import com.google.caja.util.Lists;
import com.google.caja.util.Pair;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class TemplateCompilerTest extends CajaTestCase {
private PluginMeta meta;
@Override
public void setUp() throws Exception {
super.setUp();
meta = new PluginMeta(new PluginEnvironment() {
public CharProducer loadExternalResource(
ExternalReference ref, String mimeType) {
throw new SomethingWidgyHappenedError(
new Message(MessageType.INTERNAL_ERROR, MessageLevel.FATAL_ERROR,
MessagePart.Factory.valueOf(
"Loading from external resource unimplemented")));
}
// return the URI unchanged, so we can test URI normalization
public String rewriteUri(ExternalReference ref, String mimeType) {
return ref.getUri().toString();
}
});
}
public final void testEmptyModule() throws Exception {
assertSafeHtml(
htmlFragment(fromString("")),
htmlFragment(fromString("")),
new Block());
}
public final void testTopLevelTextNodes() throws Exception {
assertSafeHtml(
htmlFragment(fromString("Hello, <b title=howdy>World</b>!!!")),
htmlFragment(fromString("Hello, <b title=howdy>World</b>!!!")),
new Block());
}
public final void testSafeHtmlWithDynamicModuleId() throws Exception {
assertSafeHtml(
htmlFragment(fromResource("template-compiler-input1.html", is)),
htmlFragment(fromResource("template-compiler-golden1-dynamic.html")),
js(fromResource("template-compiler-golden1-dynamic.js")));
}
public final void testSafeHtmlWithStaticModuleId() throws Exception {
meta.setIdClass("xyz___");
assertSafeHtml(
htmlFragment(fromResource("template-compiler-input1.html", is)),
htmlFragment(fromResource("template-compiler-golden1-static.html")),
js(fromResource("template-compiler-golden1-static.js")));
}
public final void testSignalLoadedAtEnd() throws Exception {
// Ensure that, although finish() is called as soon as possible after the
// last HTML is rolled forward, signalLoaded() is called at the very end,
// after all scripts are encountered.
assertSafeHtml(
htmlFragment(fromString(
""
+ "<p id=\"a\">a</p>"
+ "<script type=\"text/javascript\">1;</script>")),
htmlFragment(fromString(
"<p id=\"id_1___\">a</p>")),
js(fromString(
""
+ "function module() {"
+ " {"
+ " var el___;"
+ " var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.byId('id_1___');"
+ " emitter___.setAttr("
+ " el___, 'id', 'a-' + IMPORTS___.getIdClass___());"
+ " el___ = emitter___.finish();"
+ " }"
+ "}"
+ "function module() {"
+ " try {"
+ " { 1; }"
+ " } catch (ex___) {"
+ " ___.getNewModuleHandler().handleUncaughtException(ex___,"
+ " onerror, 'testSignalLoadedAtEnd', '1');"
+ " }"
+ "}"
+ "function module() {"
+ " {"
+ " IMPORTS___.htmlEmitter___.signalLoaded();"
+ " }"
+ "}")));
}
public final void testTargetsRewritten() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<a href='foo' target='_self'>hello</a>")),
htmlFragment(fromString("<a href='foo' target='_blank'>hello</a>")),
new Block());
}
public final void testFormRewritten() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<form></form>")),
htmlFragment(fromString(
"<form action='test:///testFormRewritten' autocomplete='off'"
+ " target='_blank'></form>")),
new Block());
}
public final void testNamesRewritten() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<a name='hi'></a>")),
htmlFragment(fromString("<a id='id_1___' target='_blank'></a>")),
js(fromString(
""
+ "function module() {"
+ " {"
+ " var el___; var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.byId('id_1___');"
+ " emitter___.setAttr("
+ " el___, 'name', 'hi-' + IMPORTS___.getIdClass___());"
+ " el___.removeAttribute('id');"
+ " el___ = emitter___.finish();"
+ " emitter___.signalLoaded();"
+ " }"
+ "}")));
meta.setIdClass("xyz___");
assertSafeHtml(
htmlFragment(fromString("<a name='hi'></a>")),
htmlFragment(fromString("<a name='hi-xyz___' target='_blank'></a>")),
new Block());
}
public final void testSanityCheck() throws Exception {
// The name attribute is not allowed on <p> elements, so
// normally it would have been stripped out by the TemplateSanitizer pass.
// Under no circumstances should it be emitted.
assertSafeHtml(
htmlFragment(fromString("<p name='hi'>Howdy</p>")),
htmlFragment(fromString("<p>Howdy</p>")),
new Block());
}
public final void testFormName() throws Exception {
meta.setIdClass("suffix___");
assertSafeHtml(
htmlFragment(fromString("<form name='hi'></form>")),
htmlFragment(fromString(
"<form action='test:///testFormName' autocomplete='off'"
+ " name='hi-suffix___' target=_blank></form>")),
new Block());
}
// See bug 722
public final void testFormOnSubmitTrue() throws Exception {
assertSafeHtml(
htmlFragment(fromString(
"<form onsubmit='alert("hi"); return true;'></form>")),
htmlFragment(fromString(
"<form action='test:///testFormOnSubmitTrue' autocomplete='off'"
+ " id=id_2___ target='_blank'></form>")),
js(fromString(
""
+ "function module() {"
+ " {"
+ " var el___; var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.byId('id_2___');"
// The extracted handler.
+ " var c_1___ = ___.markFuncFreeze("
+ " function(event, thisNode___) {"
+ " alert('hi');" // Cajoled later
+ " return true;"
+ " });"
+ " el___.onsubmit = function (event) {"
+ " return plugin_dispatchEvent___("
+ " this, event, ___.getId(IMPORTS___), c_1___);"
+ " };"
+ " el___.removeAttribute('id');"
+ " el___ = emitter___.finish();"
+ " emitter___.signalLoaded();"
+ " }"
+ "}")));
}
public final void testJavascriptUrl() throws Exception {
assertSafeHtml(
htmlFragment(fromString(
"<a href='javascript:alert(1+1)'>Two!!</a>")),
htmlFragment(fromString(
"<a id=\"id_2___\" target=\"_blank\">Two!!</a>")),
js(fromString(
""
+ "function module() {"
+ " {"
+ " IMPORTS___.c_1___ = ___.markFuncFreeze("
+ " function() { alert(1 + 1); });" // body is cajoled later
+ " var el___; var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.byId('id_2___');"
// The extracted handler.
+ " emitter___.setAttr(el___, 'href', 'javascript:'"
+ " + encodeURIComponent("
+ " 'try{void plugin_dispatchToHandler___('"
+ " + ___.getId(IMPORTS___) + ',' + '\\'c_1___\\''"
+ " + ',[{}])}catch(_){}'));"
+ " el___.removeAttribute('id');"
+ " el___ = emitter___.finish();"
+ " emitter___.signalLoaded();"
+ " }"
+ "}")));
}
public final void testJavascriptUrlWithUseCajita() throws Exception {
assertSafeHtml(
htmlFragment(fromString(
"<a href='javascript:%22use%20cajita%22;alert(1+1)'>Two!!</a>")),
htmlFragment(fromString(
"<a id=\"id_2___\" target=\"_blank\">Two!!</a>")),
js(fromString(
""
+ "function module() {"
+ " {"
// The extracted handler.
+ " IMPORTS___.c_1___ = ___.markFuncFreeze(function () {"
+ " 'use cajita';"
+ " alert(1 + 1);" // Cajoled later
+ " });"
+ " var el___; var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.byId('id_2___');"
+ " emitter___.setAttr(el___, 'href', 'javascript:'"
+ " + encodeURIComponent("
+ " 'try{void plugin_dispatchToHandler___('"
+ " + ___.getId(IMPORTS___) + ',' + '\\'c_1___\\''"
+ " + ',[{}])}catch(_){}'));"
+ " el___.removeAttribute('id');"
+ " el___ = emitter___.finish();"
+ " emitter___.signalLoaded();"
+ " }"
+ "}")));
}
// See bug 722
public final void testFormOnSubmitEmpty() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<form onsubmit=''></form>")),
htmlFragment(fromString(
"<form action='test:///testFormOnSubmitEmpty' autocomplete='off'"
+ " target='_blank'></form>")),
new Block());
}
public final void testImageSrc() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<img src='blank.gif' width='20'/>")),
htmlFragment(fromString("<img src='blank.gif' width='20'/>")),
new Block());
}
public final void testStyleRewriting() throws Exception {
assertSafeHtml(
htmlFragment(fromString(
"<div style=\"position: absolute; background: url('bg-image')\">\n"
+ "Hello\n"
+ "</div>\n")),
htmlFragment(fromString(
"<div style=\"position: absolute; background: url('test:/bg-image')"
+ "\">\nHello\n</div>")),
new Block());
}
public final void testEmptyStyleRewriting() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<div style=>\nHello\n</div>\n")),
htmlFragment(fromString("<div>\nHello\n</div>")),
new Block());
assertSafeHtml(
htmlFragment(fromString("<div style=''>\nHello\n</div>\n")),
htmlFragment(fromString("<div>\nHello\n</div>")),
new Block());
}
public final void testEmptyScriptRewriting() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<div onclick=''>\nHello\n</div>\n")),
htmlFragment(fromString("<div>\nHello\n</div>")),
new Block());
}
public final void testDeferredScripts() throws Exception {
// If all the scripts are deferred, there is never any need to detach any
// of the DOM tree.
assertSafeHtml(
htmlFragment(fromString("Hi<script>alert('howdy');</script>\n")),
htmlFragment(fromString("Hi")),
js(fromString(
""
+ "function module() {"
+ " try {"
+ " { alert('howdy'); }"
+ " } catch (ex___) {"
+ " ___.getNewModuleHandler().handleUncaughtException("
+ " ex___, onerror, 'testDeferredScripts', '1');"
+ " }"
+ "}"
+ "function module() {"
+ " {"
+ " IMPORTS___.htmlEmitter___.signalLoaded();"
+ " }"
+ "}"))
);
}
public final void testMailto() throws Exception {
assertSafeHtml(
htmlFragment(fromString(
"<a href='mailto:x@y' target='_blank'>z</a>")),
htmlFragment(fromString(
"<a href='mailto:x@y' target='_blank'>z</a>")),
new Block());
}
public final void testComplexUrl() throws Exception {
assertSafeHtml(
htmlFragment(fromString(
"<a href='http://b/c;_d=e?f=g&i=%26' target='_blank'>z</a>")),
htmlFragment(fromString(
"<a href='http://b/c;_d=e?f=g&i=%26' target='_blank'>z</a>")),
new Block());
}
public final void testTextAreas() throws Exception {
assertSafeHtml(
htmlFragment(fromString(
""
+ "<textarea>Howdy!</textarea>"
+ "<script>alert('Howdy yourself!');</script>"
+ "<textarea>Bye!</textarea>")),
htmlFragment(fromString(
""
// textareas can't contain nodes, so the span had better follow it
// which leaves it in the same position according to the
// depth-first-ordering ignoring end tags used by the HTML emitter.
+ "<textarea>Howdy!</textarea>"
+ "<span id=\"id_1___\"></span>"
+ "<textarea>Bye!</textarea>")),
js(fromString(
""
+ "function module() {"
+ " {"
+ " var el___; var emitter___ = IMPORTS___.htmlEmitter___;"
+ " emitter___.discard(emitter___.attach('id_1___'));"
+ " }"
+ "}"
+ "function module() {"
+ " try {"
+ " { alert('Howdy yourself!'); }"
+ " }catch (ex___) {"
+ " ___.getNewModuleHandler().handleUncaughtException("
+ " ex___, onerror, 'testTextAreas', '1');"
+ " }"
+ "}"
+ "function module() {"
+ " {"
+ " var el___; var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.finish();"
+ " emitter___.signalLoaded();"
+ " }"
+ "}")));
}
private class Holder<T> { T value; }
public final void testUriAttributeResolution() throws Exception {
// Ensure that the TemplateCompiler calls its PluginEnvironment with the
// correct information when it encounters a URI-valued HTML attribute.
final Holder<ExternalReference> savedRef = new Holder<ExternalReference>();
meta = new PluginMeta(new PluginEnvironment() {
public CharProducer loadExternalResource(
ExternalReference ref, String mimeType) {
throw new SomethingWidgyHappenedError(
new Message(MessageType.INTERNAL_ERROR, MessageLevel.FATAL_ERROR,
MessagePart.Factory.valueOf(
"Loading from external resource unimplemented")));
}
public String rewriteUri(ExternalReference ref, String mimeType) {
savedRef.value = ref;
return "rewritten";
}
});
DocumentFragment htmlInput =
htmlFragment(fromString("<a href=\"x.html\"></a>"));
assertSafeHtml(
htmlInput,
htmlFragment(fromString(
"<a href=\"rewritten\" target=\"_blank\"></a>")),
new Block());
// The ExternalReference reference position should contain the URI of the
// source in which the HREF was seen.
assertEquals(
Nodes.getFilePositionFor(htmlInput).source(),
savedRef.value.getReferencePosition().source());
// The ExternalReference target URI should be the URI that was embedded in
// the original source. The TemplateCompiler should not attempt to resolve
// it; that is the job of the PluginEnvironment.
assertEquals(
new URI("x.html"),
savedRef.value.getUri());
}
public final void testFinishCalledAtEnd() throws Exception {
// bug 1050, sometimes finish() is misplaced
// http://code.google.com/p/google-caja/issues/detail?id=1050
assertSafeHtml(
htmlFragment(fromString(
""
+ "<div id=\"a\"></div>"
+ "<div id=\"b\"></div>"
+ "<script>1</script>")),
htmlFragment(fromString(
""
+ "<div id=\"id_1___\"></div>"
+ "<div id=\"id_2___\"></div>")),
js(fromString(
""
+ "function module() {"
+ " {"
+ " var el___;"
+ " var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.byId('id_1___');"
+ " emitter___.setAttr(el___, 'id',"
+ " 'a-' + IMPORTS___.getIdClass___());"
+ " el___ = emitter___.byId('id_2___');"
+ " emitter___.setAttr(el___, 'id',"
+ " 'b-' + IMPORTS___.getIdClass___());"
+ " el___ = emitter___.finish();"
+ " }"
+ "}"
+ "function module() {"
+ " try {"
+ " {"
+ " 1;"
+ " }"
+ " } catch (ex___) {"
+ " ___.getNewModuleHandler().handleUncaughtException(ex___,"
+ " onerror, 'testFinishCalledAtEnd', '1');"
+ " }"
+ "}"
+ "function module() {"
+ " {"
+ " IMPORTS___.htmlEmitter___.signalLoaded();"
+ " }"
+ "}"
)));
}
/**
* {@code <textarea>} without cols= was triggering an NPE due to buggy
* handling of mandatory attributes.
* <a href="http://code.google.com/p/google-caja/issues/detail?id=1056">1056
* </a>
*/
public final void testBareTextarea() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<textarea></textarea>")),
htmlFragment(fromString("<textarea></textarea>")),
new Block());
}
public final void testValidClassNames() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<div class='$-.:;()[]='></div>")),
htmlFragment(fromString("<div class='$-.:;()[]='></div>")),
new Block());
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString("<div class='!@{} ok__1'></div>")),
htmlFragment(fromString("<div class='!@{} ok__1'></div>")),
new Block());
assertNoWarnings();
}
public final void testValidIdNames() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<input name='tag[]'>")),
htmlFragment(fromString("<input autocomplete='off' name='tag[]'>")),
new Block());
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString("<input name='form$location'>")),
htmlFragment(fromString(
"<input autocomplete='off' name='form$location'>")),
new Block());
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString("<input name='$-.:;()[]='>")),
htmlFragment(fromString(
"<input autocomplete='off' name='$-.:;()[]='>")),
new Block());
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString(
"<div id='23skiddoo'></div>"
+ "<div id='8675309'></div>"
+ "<div id='$-.:;()[]='></div>")),
htmlFragment(fromString(
"<div id='id_1___'></div>"
+ "<div id='id_2___'></div>"
+ "<div id='id_3___'></div>")),
js(fromString(
""
+ "function module() {"
+ " {"
+ " var el___;"
+ " var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.byId('id_1___');"
+ " emitter___.setAttr(el___, 'id',"
+ " '23skiddoo-' + IMPORTS___.getIdClass___());"
+ " el___ = emitter___.byId('id_2___');"
+ " emitter___.setAttr(el___, 'id',"
+ " '8675309-' + IMPORTS___.getIdClass___());"
+ " el___ = emitter___.byId('id_3___');"
+ " emitter___.setAttr(el___, 'id',"
+ " '$-.:;()[]=-' + IMPORTS___.getIdClass___());"
+ " el___ = emitter___.finish();"
+ " emitter___.signalLoaded();"
+ " }"
+ "}")));
assertNoWarnings();
}
public final void testInvalidClassNames() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<div class='ok bad__'></div>")),
htmlFragment(fromString("<div></div>")),
new Block());
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.WARNING,
MessagePart.Factory.valueOf("bad__"));
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString("<div class='ok bad__ '></div>")),
htmlFragment(fromString("<div></div>")),
new Block());
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.WARNING,
MessagePart.Factory.valueOf("bad__"));
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString("<div class='bad__ ok'></div>")),
htmlFragment(fromString("<div></div>")),
new Block());
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.WARNING,
MessagePart.Factory.valueOf("bad__"));
assertNoWarnings();
}
public final void testInvalidIdNames() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<input id='bad1__' name='bad2__'>")),
htmlFragment(fromString("<input autocomplete='off'>")),
new Block());
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.WARNING,
MessagePart.Factory.valueOf("bad1__"));
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.WARNING,
MessagePart.Factory.valueOf("bad2__"));
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString("<input id='bad1__ ' name='bad2__ '>")),
htmlFragment(fromString("<input autocomplete='off'>")),
new Block());
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.WARNING,
MessagePart.Factory.valueOf("bad1__ "));
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.WARNING,
MessagePart.Factory.valueOf("bad2__ "));
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString("<input id='b__ c'>")),
htmlFragment(fromString("<input autocomplete='off'>")),
new Block(),
false);
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.ERROR,
MessagePart.Factory.valueOf("b__ c"));
assertNoWarnings();
assertSafeHtml(
htmlFragment(fromString("<input name='d__ e'>")),
htmlFragment(fromString("<input autocomplete='off'>")),
new Block(),
false);
assertMessage(true, IhtmlMessageType.ILLEGAL_NAME, MessageLevel.ERROR,
MessagePart.Factory.valueOf("d__ e"));
assertNoWarnings();
}
public final void testIdRefsRewriting() throws Exception {
assertSafeHtml(
htmlFragment(fromString(
"<table><tr><td headers='a b'></td></tr></table>")),
htmlFragment(fromString(
"<table><tr><td id='id_1___'></td></tr></table>")),
js(fromString(
""
+ "function module() {"
+ " {"
+ " var el___;"
+ " var emitter___ = IMPORTS___.htmlEmitter___;"
+ " el___ = emitter___.byId('id_1___');"
+ " emitter___.setAttr(el___, 'headers',"
+ " 'a-' + IMPORTS___.getIdClass___()"
+ " + ' b-' + IMPORTS___.getIdClass___());"
+ " el___.removeAttribute('id');"
+ " el___ = emitter___.finish();"
+ " emitter___.signalLoaded();"
+ " }"
+ "}")));
}
public final void testMultiDocs() throws Exception {
assertSafeHtml(
Arrays.asList(
htmlFragment(fromString("Hello")),
htmlFragment(fromString(", World!"))),
htmlFragment(fromString("Hello, World!")),
new Block());
}
public final void testUsemapSanitized() throws Exception {
meta.setIdClass("suffix___");
assertSafeHtml(
htmlFragment(fromString(
""
+ "<map name=foo><area href=foo.html></map>"
+ "<img usemap=#foo src=pic.gif>")),
htmlFragment(fromString(
""
+ "<map name='foo-suffix___'>"
+ "<area target=_blank href=foo.html />"
+ "</map>"
+ "<img usemap=#foo-suffix___ src=pic.gif>")),
new Block());
}
public final void testBadUriFragments() throws Exception {
meta.setIdClass("suffix___");
assertSafeHtml(
htmlFragment(fromString(
""
+ "<map name=foo><area href=foo.html></map>"
+ "<img usemap=foo src=foo.gif>"
+ "<img usemap=##foo src=bar.gif>")),
htmlFragment(fromString(
""
+ "<map name='foo-suffix___'>"
+ "<area target=_blank href=foo.html />"
+ "</map>"
+ "<img src=foo.gif>"
+ "<img src=bar.gif>")),
new Block(), false);
}
public final void testSingleValueAttrs() throws Exception {
assertSafeHtml(
htmlFragment(fromString("<input type=\"text\">")),
htmlFragment(fromString("<input autocomplete=\"off\" type=\"text\">")),
new Block(), false);
+ assertSafeHtml(
+ htmlFragment(fromString("<input autocomplete=\"on\" type=\"text\">")),
+ htmlFragment(fromString("<input autocomplete=\"off\" type=\"text\">")),
+ new Block(), false);
}
private void assertSafeHtml(
DocumentFragment input, DocumentFragment htmlGolden, Block jsGolden)
throws ParseException {
assertSafeHtml(input, htmlGolden, jsGolden, true);
}
private void assertSafeHtml(
DocumentFragment input, DocumentFragment htmlGolden, Block jsGolden,
boolean checkErrors) throws ParseException {
assertSafeHtml(
Collections.singletonList(input), htmlGolden, jsGolden, checkErrors);
}
private void assertSafeHtml(
List<DocumentFragment> inputs, DocumentFragment htmlGolden,
Block jsGolden) throws ParseException {
assertSafeHtml(inputs, htmlGolden, jsGolden, true);
}
private void assertSafeHtml(
List<DocumentFragment> inputs, DocumentFragment htmlGolden,
Block jsGolden, boolean checkErrors) throws ParseException {
List<Pair<Node, URI>> html = Lists.newArrayList();
List<CssTree.StyleSheet> css = Lists.newArrayList();
for (DocumentFragment input : inputs) {
extractScriptsAndStyles(
input, Nodes.getFilePositionFor(input).source().getUri(), html, css);
}
TemplateCompiler tc = new TemplateCompiler(
html, css, CssSchema.getDefaultCss21Schema(mq),
HtmlSchema.getDefault(mq), meta, mc, mq);
Document doc = DomParser.makeDocument(null, null);
Pair<Node, List<Block>> safeContent = tc.getSafeHtml(doc);
if (checkErrors) {
assertNoErrors();
// No warnings about skipped elements. Warning is not the compiler's job.
}
assertEquals(safeContent.a.getOwnerDocument(), doc);
assertEquals(Nodes.render(htmlGolden, true),
Nodes.render(safeContent.a, true));
assertEquals(render(jsGolden), render(consolidate(safeContent.b)));
}
private void extractScriptsAndStyles(
Node n, URI baseUri, List<Pair<Node, URI>> htmlOut,
List<CssTree.StyleSheet> cssOut)
throws ParseException {
n = extractScripts(n);
htmlOut.add(Pair.pair(n, baseUri));
extractStyles(n, cssOut);
}
private static String HTML_NS = Namespaces.HTML_NAMESPACE_URI;
private Node extractScripts(Node n) throws ParseException {
if (n instanceof Element && "script".equals(n.getLocalName())
&& HTML_NS.equals(n.getNamespaceURI())) {
Element span = n.getOwnerDocument().createElementNS(HTML_NS, "span");
if (n.getParentNode() != null) {
n.getParentNode().replaceChild(span, n);
}
FilePosition pos = Nodes.getFilePositionFor(n);
String text = n.getFirstChild().getNodeValue();
Block js = js(fromString(text, pos));
ExtractedHtmlContent.setExtractedScriptFor(span, js);
Nodes.setFilePositionFor(span, Nodes.getFilePositionFor(n));
return span;
}
for (Node child : Nodes.childrenOf(n)) { extractScripts(child); }
return n;
}
private void extractStyles(Node n, List<CssTree.StyleSheet> styles)
throws ParseException {
if (n instanceof Element && "style".equals(n.getNodeName())
&& HTML_NS.equals(n.getNamespaceURI())) {
FilePosition pos = Nodes.getFilePositionFor(n);
if (n.getFirstChild() != null) {
String text = n.getFirstChild().getNodeValue();
CssTree.StyleSheet css = css(fromString(text, pos));
CssRuleRewriter rrw = new CssRuleRewriter(meta);
rrw.rewriteCss(css);
assertMessagesLessSevereThan(MessageLevel.ERROR);
styles.add(css);
}
n.getParentNode().removeChild(n);
return;
}
for (Node child : Nodes.childrenOf(n)) { extractStyles(child, styles); }
}
private Block consolidate(List<Block> blocks) {
Block consolidated = new Block();
MutableParseTreeNode.Mutation mut = consolidated.createMutation();
FilePosition unk = FilePosition.UNKNOWN;
for (Block bl : blocks) {
Identifier ident = new Identifier(unk, "module");
mut.appendChild(new FunctionDeclaration(new FunctionConstructor(
unk, ident, Collections.<FormalParam>emptyList(), bl)));
}
mut.execute();
stripTranslatedCode(consolidated);
return consolidated;
}
private static void stripTranslatedCode(ParseTreeNode node) {
node.acceptPostOrder(new Visitor() {
public boolean visit(AncestorChain<?> ac) {
ParseTreeNode node = ac.node;
if (node instanceof TranslatedCode) {
((MutableParseTreeNode) ac.parent.node)
.replaceChild(((TranslatedCode) node).getTranslation(), node);
}
return true;
}
}, null);
}
}
| true | false | null | null |
diff --git a/OpenStreetMapViewer/src/org/andnav/osm/views/util/LRUMapTileCache.java b/OpenStreetMapViewer/src/org/andnav/osm/views/util/LRUMapTileCache.java
index c4d13db..5f95f74 100644
--- a/OpenStreetMapViewer/src/org/andnav/osm/views/util/LRUMapTileCache.java
+++ b/OpenStreetMapViewer/src/org/andnav/osm/views/util/LRUMapTileCache.java
@@ -1,34 +1,45 @@
package org.andnav.osm.views.util;
import java.util.LinkedHashMap;
import org.andnav.osm.services.util.OpenStreetMapTile;
import android.graphics.Bitmap;
public class LRUMapTileCache extends LinkedHashMap<OpenStreetMapTile, Bitmap> {
private static final long serialVersionUID = -541142277575493335L;
private final int mCapacity;
public LRUMapTileCache(final int pCapacity) {
super(pCapacity + 2, 0.1f, true);
mCapacity = pCapacity;
}
@Override
public Bitmap remove(Object pKey) {
final Bitmap bm = super.remove(pKey);
if (bm != null) {
bm.recycle();
}
return bm;
}
@Override
+ public void clear() {
+ // remove them all individually so that they get recycled
+ for(final OpenStreetMapTile key : keySet()) {
+ remove(key);
+ }
+
+ // and then clear
+ super.clear();
+ }
+
+ @Override
protected boolean removeEldestEntry(Entry<OpenStreetMapTile, Bitmap> pEldest) {
return size() > mCapacity;
}
}
diff --git a/OpenStreetMapViewer/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java b/OpenStreetMapViewer/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java
index c0235c0..813afa2 100644
--- a/OpenStreetMapViewer/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java
+++ b/OpenStreetMapViewer/src/org/andnav/osm/views/util/OpenStreetMapTileCache.java
@@ -1,69 +1,73 @@
// Created by plusminus on 17:58:57 - 25.09.2008
package org.andnav.osm.views.util;
import org.andnav.osm.services.util.OpenStreetMapTile;
import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
import android.graphics.Bitmap;
/**
*
* @author Nicolas Gramlich
*
*/
public class OpenStreetMapTileCache implements OpenStreetMapViewConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected LRUMapTileCache mCachedTiles;
// ===========================================================
// Constructors
// ===========================================================
public OpenStreetMapTileCache() {
this(CACHE_MAPTILECOUNT_DEFAULT);
}
/**
* @param aMaximumCacheSize Maximum amount of MapTiles to be hold within.
*/
public OpenStreetMapTileCache(final int aMaximumCacheSize){
this.mCachedTiles = new LRUMapTileCache(aMaximumCacheSize);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public synchronized Bitmap getMapTile(final OpenStreetMapTile aTile) {
return this.mCachedTiles.get(aTile);
}
public synchronized void putTile(final OpenStreetMapTile aTile, final Bitmap aImage) {
if (aImage != null) {
this.mCachedTiles.put(aTile, aImage);
}
}
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public boolean containsTile(final OpenStreetMapTile aTile) {
return this.mCachedTiles.containsKey(aTile);
}
+
+ public void clear() {
+ this.mCachedTiles.clear();
+ }
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
diff --git a/OpenStreetMapViewer/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java b/OpenStreetMapViewer/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java
index a854350..95531e4 100644
--- a/OpenStreetMapViewer/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java
+++ b/OpenStreetMapViewer/src/org/andnav/osm/views/util/OpenStreetMapTileProvider.java
@@ -1,157 +1,159 @@
// Created by plusminus on 21:46:22 - 25.09.2008
package org.andnav.osm.views.util;
import java.io.File;
import org.andnav.osm.services.IOpenStreetMapTileProviderCallback;
import org.andnav.osm.services.IOpenStreetMapTileProviderService;
import org.andnav.osm.services.util.OpenStreetMapTile;
import org.andnav.osm.util.constants.OpenStreetMapConstants;
import org.andnav.osm.views.util.constants.OpenStreetMapViewConstants;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
/**
*
* @author Nicolas Gramlich
*
*/
public class OpenStreetMapTileProvider implements ServiceConnection, OpenStreetMapConstants,
OpenStreetMapViewConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
/** cache provider */
protected OpenStreetMapTileCache mTileCache;
private IOpenStreetMapTileProviderService mTileService;
private Handler mDownloadFinishedHandler;
// ===========================================================
// Constructors
// ===========================================================
public OpenStreetMapTileProvider(final Context ctx,
final Handler aDownloadFinishedListener) {
this.mTileCache = new OpenStreetMapTileCache();
if(!ctx.bindService(new Intent(IOpenStreetMapTileProviderService.class.getName()), this, Context.BIND_AUTO_CREATE))
Log.e(DEBUGTAG, "Could not bind to " + IOpenStreetMapTileProviderService.class.getName());
this.mDownloadFinishedHandler = aDownloadFinishedListener;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
public void onServiceConnected(final ComponentName name, final IBinder service) {
mTileService = IOpenStreetMapTileProviderService.Stub.asInterface(service);
try {
mDownloadFinishedHandler.sendEmptyMessage(OpenStreetMapTile.MAPTILE_SUCCESS_ID);
} catch(Exception e) {
Log.e(DEBUGTAG, "Error sending success message on connect", e);
}
Log.d(DEBUGTAG, "connected");
};
@Override
public void onServiceDisconnected(final ComponentName name) {
mTileService = null;
Log.d(DEBUGTAG, "disconnected");
}
// ===========================================================
// Methods
// ===========================================================
/**
* Get the tile from the cache.
* If it's in the cache then it will be returned.
* If not it will return null and request it from the service.
* In turn, the service will request it from the file system.
* If it's found in the file system it will notify the callback.
* If not it will initiate a download.
* When the download has finished it will notify the callback.
* @param aTile the tile being requested
* @return the tile bitmap if found in the cache, null otherwise
*/
public Bitmap getMapTile(final OpenStreetMapTile aTile) {
if (this.mTileCache.containsTile(aTile)) { // from cache
if (DEBUGMODE)
Log.d(DEBUGTAG, "MapTileCache succeeded for: " + aTile);
return mTileCache.getMapTile(aTile);
} else { // from service
if (mTileService == null) {
if (DEBUGMODE)
Log.d(DEBUGTAG, "Cache failed, can't get from FS because no tile service: " + aTile);
} else {
if (DEBUGMODE)
Log.d(DEBUGTAG, "Cache failed, trying from FS: " + aTile);
try {
mTileService.requestMapTile(aTile.rendererID, aTile.zoomLevel, aTile.x, aTile.y, mServiceCallback);
} catch (Throwable e) {
Log.e(DEBUGTAG, "Error getting map tile from tile service: " + aTile, e);
}
}
return null;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
IOpenStreetMapTileProviderCallback mServiceCallback = new IOpenStreetMapTileProviderCallback.Stub() {
@Override
- public void mapTileRequestCompleted(int rendererID, int zoomLevel, int tileX, int tileY, String aTilePath) throws RemoteException {
+ public void mapTileRequestCompleted(final int aRendererID, final int aZoomLevel, final int aTileX, final int aTileY, final String aTilePath) throws RemoteException {
- final OpenStreetMapTile tile = new OpenStreetMapTile(rendererID, zoomLevel, tileX, tileY);
+ final OpenStreetMapTile tile = new OpenStreetMapTile(aRendererID, aZoomLevel, aTileX, aTileY);
// if the tile path has been returned, add the tile to the cache
if (aTilePath != null) {
try {
final Bitmap bitmap = BitmapFactory.decodeFile(aTilePath);
if (bitmap != null) {
mTileCache.putTile(tile, bitmap);
} else {
// if we couldn't load it then it's invalid - delete it
try {
new File(aTilePath).delete();
} catch (Throwable e) {
Log.e(DEBUGTAG, "Error deleting invalid file: " + aTilePath, e);
}
}
- } catch (OutOfMemoryError e) {
+ } catch (final OutOfMemoryError e) {
Log.e(DEBUGTAG, "OutOfMemoryError putting tile in cache: " + tile);
+ mTileCache.clear();
+ System.gc();
}
}
// tell our caller we've finished and it should update its view
mDownloadFinishedHandler.sendEmptyMessage(OpenStreetMapTile.MAPTILE_SUCCESS_ID);
if (DEBUGMODE)
Log.d(DEBUGTAG, "MapTile request complete: " + tile);
}
};
}
| false | false | null | null |
diff --git a/src/Core/org/objectweb/proactive/core/component/NFBinding.java b/src/Core/org/objectweb/proactive/core/component/NFBinding.java
index 80e3dcef4..0ddc014e7 100644
--- a/src/Core/org/objectweb/proactive/core/component/NFBinding.java
+++ b/src/Core/org/objectweb/proactive/core/component/NFBinding.java
@@ -1,72 +1,72 @@
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library 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; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core.component;
import org.objectweb.fractal.api.Interface;
/**
- * Extended binding, with additionnal information about a binding
- * @author The ProActive Team
+ * Extended binding, with additional information about a binding.
*
+ * @author The ProActive Team
*/
public class NFBinding extends Binding {
private final String clientComponent;
private final String serverComponent;
private final String serverInterfaceName;
public NFBinding(Interface clientInterface, String clientItfName, Interface serverInterface,
String clientComponent, String serverComponent) {
super(clientInterface, clientItfName, serverInterface);
this.clientComponent = clientComponent;
this.serverComponent = serverComponent;
this.serverInterfaceName = serverInterface.getFcItfName();
}
public String getClientComponentName() {
return clientComponent;
}
public String getServerComponentName() {
return serverComponent;
}
public String getServerInterfaceName() {
return serverInterfaceName;
}
}
diff --git a/src/Core/org/objectweb/proactive/core/component/NFBindings.java b/src/Core/org/objectweb/proactive/core/component/NFBindings.java
index 428eca4bc..8d951d35a 100644
--- a/src/Core/org/objectweb/proactive/core/component/NFBindings.java
+++ b/src/Core/org/objectweb/proactive/core/component/NFBindings.java
@@ -1,193 +1,193 @@
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library 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; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core.component;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
/**
- * Extended bindings class, containing more information about bindings inside the mmebrane
- * @author The ProActive Team
+ * Extended bindings class, containing more information about bindings inside the membrane.
*
+ * @author The ProActive Team
*/
public class NFBindings {
private Map<String, NFBinding> serverAliasBindings;
private Map<String, NFBinding> clientAliasBindings;
private Map<String, NFBinding> normalBindings;
public NFBindings() {
serverAliasBindings = new HashMap<String, NFBinding>();
clientAliasBindings = new HashMap<String, NFBinding>();
normalBindings = new HashMap<String, NFBinding>();
}
public void addServerAliasBinding(NFBinding b) {
serverAliasBindings.put(b.getClientInterfaceName(), b);
}
public void addClientAliasBinding(NFBinding b) {
clientAliasBindings.put(b.getClientInterfaceName(), b);
}
public void addNormalBinding(NFBinding b) {
normalBindings.put(b.getClientInterfaceName(), b);
}
public Object remove(String clientItfName) {
if (serverAliasBindings.containsKey(clientItfName)) {
return serverAliasBindings.remove(clientItfName);
}
if (clientAliasBindings.containsKey(clientItfName)) {
return clientAliasBindings.remove(clientItfName);
}
if (normalBindings.containsKey(clientItfName)) {
return normalBindings.remove(clientItfName);
}
return null;
}
public Object get(String clientItfName) {
if (serverAliasBindings.containsKey(clientItfName)) {
return serverAliasBindings.get(clientItfName);
}
if (clientAliasBindings.containsKey(clientItfName)) {
return clientAliasBindings.get(clientItfName);
}
if (normalBindings.containsKey(clientItfName)) {
return normalBindings.get(clientItfName);
}
return null;
}
public boolean containsBindingOn(String clientItfName) {
return (serverAliasBindings.containsKey(clientItfName) ||
clientAliasBindings.containsKey(clientItfName) || normalBindings.containsKey(clientItfName));
}
public boolean hasServerAliasBindingOn(String component, String itf) {
Vector<NFBinding> v = new Vector<NFBinding>(serverAliasBindings.values());
for (NFBinding val : v) {
if (val.getServerComponentName().equals(component) && val.getServerInterface().equals(itf)) {
return true;
}
}
return false;
}
public boolean hasServerAliasBindingOn(String component) {//Returns true when there is an alias binding on the component, the name of which is passed as an argument
Vector<NFBinding> v = new Vector<NFBinding>(serverAliasBindings.values());
for (NFBinding val : v) {
if (val.getServerComponentName().equals(component)) {
return true;
}
}
return false;
}
public void removeNormalBinding(String component, String itf) {
Vector<NFBinding> v = new Vector<NFBinding>(normalBindings.values());
for (NFBinding val : v) {
if (val.getServerComponentName().equals(component) && val.getClientInterface().equals(itf)) {
normalBindings.remove(val.getClientInterfaceName());
}
}
}
public void removeClientAliasBinding(String component, String itf) {//Removes a client alias binding. The component name and the interface name belong to the component on the client side.
Vector<NFBinding> v = new Vector<NFBinding>(clientAliasBindings.values());
for (NFBinding val : v) {
if (val.getServerComponentName().equals(component) && val.getClientInterface().equals(itf)) {
clientAliasBindings.remove(val.getClientInterfaceName());
}
}
}
public void removeServerAliasBindingsOn(String component) {
Vector<NFBinding> v = new Vector<NFBinding>(serverAliasBindings.values());
for (NFBinding val : v) {
if (val.getServerComponentName().equals(component)) {
serverAliasBindings.remove(val.getClientInterfaceName());
}
}
}
public boolean hasBinding(String clientComponent, String clientItf, String serverComponent,
String serverItf) {
Vector<NFBinding> v = new Vector<NFBinding>(serverAliasBindings.values());
for (NFBinding val : v) {
if (val.getClientComponentName().equals(clientComponent) &&
val.getClientInterfaceName().equals(clientItf) &&
val.getServerComponentName().equals(serverComponent) &&
val.getServerInterface().equals(serverItf)) {
return true;
}
}
return false;
}
public Vector<NFBinding> getServerAliasBindingsOn(String component, String itf) {
Vector<NFBinding> v = new Vector<NFBinding>(serverAliasBindings.values());
Vector<NFBinding> result = new Vector<NFBinding>();
for (NFBinding val : v) {
if (val.getServerComponentName().equals(component) && val.getServerInterface().equals(itf)) {
result.add(val);
}
}
return result;
}
}
| false | false | null | null |
diff --git a/plugins/org.eclipse.emf.common/src/org/eclipse/emf/common/util/BasicEMap.java b/plugins/org.eclipse.emf.common/src/org/eclipse/emf/common/util/BasicEMap.java
index acc4a5ab5..c46a8edba 100644
--- a/plugins/org.eclipse.emf.common/src/org/eclipse/emf/common/util/BasicEMap.java
+++ b/plugins/org.eclipse.emf.common/src/org/eclipse/emf/common/util/BasicEMap.java
@@ -1,1785 +1,1789 @@
/**
* <copyright>
*
* Copyright (c) 2002-2006 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 - Initial API and implementation
*
* </copyright>
*
- * $Id: BasicEMap.java,v 1.11 2010/11/05 12:17:13 emerks Exp $
+ * $Id: BasicEMap.java,v 1.12 2011/10/25 17:35:13 emerks Exp $
*/
package org.eclipse.emf.common.util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A highly extensible map implementation.
*/
public class BasicEMap<K, V> implements EMap<K, V>, Cloneable, Serializable
{
private static final long serialVersionUID = 1L;
/**
* An extended implementation interface for caching hash values
* and for updating an entry that may be manufactured as a uninitialized instance by a factory.
* No client is expected to use this interface,
* other than to implement it in conjunction with a map implementation.
*/
public interface Entry<K, V> extends Map.Entry<K, V>
{
/**
* Sets the key.
* This should only be called by the map implementation,
* since the key of an entry already in the map must be immutable.
* @param key the key.
*/
void setKey(K key);
/**
* Returns the hash code of the key.
* Only the map implementation would really care.
*/
int getHash();
/**
* Sets the hash code of the key.
* This should only be called by the map implementation,
* since the hash code of the key of an entry already in the map must be immutable.
* @param hash the hash.
*/
void setHash(int hash);
}
/**
* The underlying list of entries.
*/
protected transient EList<Entry<K, V>> delegateEList;
/**
* The size of the map.
*/
protected transient int size;
/**
* The array of entry lists into which the hash codes are indexed.
*/
protected transient BasicEList<Entry<K, V>> [] entryData;
/**
* The modification indicator used to ensure iterator integrity.
*/
protected transient int modCount;
/**
* An implementation class to hold the views.
*/
protected static class View<K, V>
{
/**
* The map view.
*/
public transient Map<K, V> map;
/**
* The map key set view.
*/
public transient Set<K> keySet;
/**
* The entry set view.
*/
public transient Set<Map.Entry<K, V>> entrySet;
/**
* The values collection view.
*/
public transient Collection<V> values;
/**
* Creates an empty instance.
*/
public View()
{
super();
}
}
/**
* The various alternative views of the map.
*/
protected transient View<K, V> view;
/**
* Creates an empty instance.
*/
public BasicEMap()
{
initializeDelegateEList();
}
/**
* Initializes the {@link #delegateEList}.
* This implementation illustrates the precise pattern that is used to
* delegate a list implementation's callback methods to the map implementation.
*/
protected void initializeDelegateEList()
{
delegateEList =
new BasicEList<Entry<K, V>>()
{
private static final long serialVersionUID = 1L;
@Override
protected void didAdd(int index, Entry<K, V> newObject)
{
doPut(newObject);
}
@Override
protected void didSet(int index, Entry<K, V> newObject, Entry<K, V> oldObject)
{
didRemove(index, oldObject);
didAdd(index, newObject);
}
@Override
protected void didRemove(int index, Entry<K, V> oldObject)
{
doRemove(oldObject);
}
@Override
protected void didClear(int size, Object [] oldObjects)
{
doClear();
}
@Override
protected void didMove(int index, Entry<K, V> movedObject, int oldIndex)
{
doMove(movedObject);
}
};
}
/**
* Creates an empty instance with the given capacity.
* @param initialCapacity the initial capacity of the map before it must grow.
* @exception IllegalArgumentException if the <code>initialCapacity</code> is negative.
*/
public BasicEMap(int initialCapacity)
{
this();
if (initialCapacity < 0)
{
throw new IllegalArgumentException("Illegal Capacity:" + initialCapacity);
}
entryData = newEntryData(initialCapacity);
}
/**
* Creates an instance that is a copy of the map.
* @param map the initial contents of the map.
*/
public BasicEMap(Map<? extends K, ? extends V> map)
{
this();
int mapSize = map.size();
if (mapSize > 0)
{
entryData = newEntryData(2 * mapSize);
putAll(map);
}
}
/**
* Returns new allocated entry data storage.
* Clients may override this to create typed storage, but it's not likely.
* The cost of type checking via a typed array is negligible.
* @param capacity the capacity of storage needed.
* @return new entry data storage.
*/
@SuppressWarnings("unchecked")
protected BasicEList<Entry<K, V>> [] newEntryData(int capacity)
{
return new BasicEList[capacity];
}
/**
* Ensures that the entry data is created
* and is populated with contents of the delegate list.
*/
protected void ensureEntryDataExists()
{
if (entryData == null)
{
entryData = newEntryData(2 * size + 1);
// This should be transparent.
//
int oldModCount = modCount;
size = 0;
for (Entry<K, V> entry : delegateEList)
{
doPut(entry);
}
modCount = oldModCount;
}
}
/**
* Returns a new allocated list of entries.
* Clients may override this to create typed storage.
* The cost of type checking via a typed array is negligible.
* The type must be kept in synch with {@link #newEntry(int, Object, Object) newEntry}.
* @return a new list of entries.
* @see #newEntry(int, Object, Object)
*/
protected BasicEList<Entry<K, V>> newList()
{
return
new BasicEList<Entry<K, V>>()
{
private static final long serialVersionUID = 1L;
@Override
public Object [] newData(int listCapacity)
{
return new BasicEMap.EntryImpl[listCapacity];
}
};
}
/**
* Returns a new entry.
* The key is {@link #validateKey validated} and the value is {@link #validateValue validated}.
* Clients may override this to create typed storage.
* The type must be kept in synch with {@link #newList newEntry}.
* @param hash the cached hash code of the key.
* @param key the key.
* @param value the value.
* @return a new entry.
* @see #newList
*/
protected Entry<K, V> newEntry(int hash, K key, V value)
{
validateKey(key);
validateValue(value);
return new EntryImpl(hash, key, value);
}
/**
* Sets the value of the entry, and returns the former value.
* The value is {@link #validateValue validated}.
* @param entry the entry.
* @param value the value.
* @return the former value, or <code>null</code>.
*/
protected V putEntry(Entry<K, V> entry, V value)
{
return entry.setValue(value);
}
/**
* Returns whether <code>equals</code> rather than <code>==</code> should be used to compare keys.
* The default is to return <code>true</code> but clients can optimize performance by returning <code>false</code>.
* The performance difference is highly significant.
* @return whether <code>equals</code> rather than <code>==</code> should be used to compare keys.
*/
protected boolean useEqualsForKey()
{
return true;
}
/**
* Returns whether <code>equals</code> rather than <code>==</code> should be used to compare values.
* The default is to return <code>true</code> but clients can optimize performance by returning <code>false</code>.
* The performance difference is highly significant.
* @return whether <code>equals</code> rather than <code>==</code> should be used to compare values.
*/
protected boolean useEqualsForValue()
{
return true;
}
/**
* Resolves the value associated with the key and returns the result.
* This implementation simply returns the <code>value</code>;
* clients can use this to transform objects as they are fetched.
* @param key the key of an entry.
* @param value the value of an entry.
* @return the resolved value.
*/
protected V resolve(K key, V value)
{
return value;
}
/**
* Validates a new key.
* This implementation does nothing,
* but clients may throw runtime exceptions
* in order to handle constraint violations.
* @param key the new key.
* @exception IllegalArgumentException if a constraint prevents the object from being added.
*/
protected void validateKey(K key)
{
// Do nothing.
}
/**
* Validates a new key.
* This implementation does nothing,
* but clients may throw runtime exceptions
* in order to handle constraint violations.
* @param value the new value.
* @exception IllegalArgumentException if a constraint prevents the object from being added.
*/
protected void validateValue(V value)
{
// Do nothing.
}
/**
* Called to indicate that the entry has been added.
* This implementation does nothing;
* clients can use this to monitor additions to the map.
* @param entry the added entry.
*/
protected void didAdd(Entry<K, V> entry)
{
// Do nothing.
}
/**
* Called to indicate that the entry has an updated value.
* This implementation does nothing;
* clients can use this to monitor value changes in the map.
* @param entry the new entry.
*/
protected void didModify(Entry<K, V> entry, V oldValue)
{
// Do nothing.
}
/**
* Called to indicate that the entry has been removed.
* This implementation does nothing;
* clients can use this to monitor removals from the map.
* @param entry the removed entry.
*/
protected void didRemove(Entry<K, V> entry)
{
// Do nothing.
}
/**
* Called to indicate that the map has been cleared.
* This implementation does calls {@link #didRemove didRemove} for each entry;
* clients can use this to monitor clearing of the map.
* @param oldEntryData the removed entries.
*/
protected void didClear(BasicEList<Entry<K, V>> [] oldEntryData)
{
if (oldEntryData != null)
{
for (int i = 0; i < oldEntryData.length; ++i)
{
BasicEList<Entry<K, V>> eList = oldEntryData[i];
if (eList != null)
{
@SuppressWarnings("unchecked") Entry<K, V> [] entries = (Entry<K, V> [])eList.data;
int size = eList.size;
for (int j = 0; j < size; ++j)
{
Entry<K, V> entry = entries[j];
didRemove(entry);
}
}
}
}
}
/**
* Returns the number of entries in the map.
* @return the number of entries in the map.
*/
public int size()
{
return size;
}
/**
* Returns whether the map has zero size.
* @return whether the map has zero size.
*/
public boolean isEmpty()
{
return size == 0;
}
/*
* Javadoc copied from interface.
*/
public int indexOfKey(Object key)
{
if (useEqualsForKey() && key != null)
{
for (int i = 0, size = delegateEList.size(); i < size; ++i)
{
Entry<K, V> entry = delegateEList.get(i);
if (key.equals(entry.getKey()))
{
return i;
}
}
}
else
{
for (int i = 0, size = delegateEList.size(); i < size; ++i)
{
Entry<K, V> entry = delegateEList.get(i);
if (key == entry.getKey())
{
return i;
}
}
}
return -1;
}
/*
* Javadoc copied from interface.
*/
public boolean containsKey(Object key)
{
if (size > 0)
{
ensureEntryDataExists();
int hash = hashOf(key);
int index = indexOf(hash);
int entryIndex = entryIndexForKey(index, hash, key);
return entryIndex != -1;
}
else
{
return false;
}
}
/*
* Javadoc copied from interface.
*/
public boolean containsValue(Object value)
{
if (size > 0)
{
ensureEntryDataExists();
if (useEqualsForValue() && value != null)
{
for (int i = 0; i < entryData.length; ++i)
{
BasicEList<Entry<K, V>> eList = entryData[i];
if (eList != null)
{
@SuppressWarnings("unchecked") Entry<K, V> [] entries = (Entry<K, V> [])eList.data;
int size = eList.size;
for (int j = 0; j < size; ++j)
{
Entry<K, V> entry = entries[j];
if (value.equals(entry.getValue()))
{
return true;
}
}
}
}
}
else
{
for (int i = 0; i < entryData.length; ++i)
{
BasicEList<Entry<K, V>> eList = entryData[i];
if (eList != null)
{
@SuppressWarnings("unchecked") Entry<K, V> [] entries = (Entry<K, V> [])eList.data;
int size = eList.size;
for (int j = 0; j < size; ++j)
{
Entry<K, V> entry = entries[j];
if (value == entry.getValue())
{
return true;
}
}
}
}
}
}
return false;
}
/*
* Javadoc copied from interface.
*/
public V get(Object key)
{
if (size > 0)
{
ensureEntryDataExists();
int hash = hashOf(key);
int index = indexOf(hash);
Entry<K, V> entry = entryForKey(index, hash, key);
if (entry != null)
{
@SuppressWarnings("unchecked") K object = (K)key;
return resolve(object, entry.getValue());
}
}
return null;
}
/*
* Javadoc copied from interface.
*/
public V put(K key, V value)
{
ensureEntryDataExists();
int hash = hashOf(key);
if (size > 0)
{
int index = indexOf(hash);
Entry<K, V> entry = entryForKey(index, hash, key);
if (entry != null)
{
V result = putEntry(entry, value);
didModify(entry, result);
return result;
}
}
Entry<K, V> entry = newEntry(hash, key, value);
delegateEList.add(entry);
return null;
}
/**
* Adds the new entry to the map.
* @param entry the new entry.
*/
protected void doPut(Entry<K, V> entry)
{
if (entryData == null)
{
++modCount;
++size;
}
else
{
int hash = entry.getHash();
grow(size + 1);
int index = indexOf(hash);
BasicEList<Entry<K, V>> eList = entryData[index];
if (eList == null)
{
eList = entryData[index] = newList();
}
eList.add(entry);
++size;
didAdd(entry);
}
}
/*
* Javadoc copied from source.
*/
public V removeKey(Object key)
{
ensureEntryDataExists();
int hash = hashOf(key);
int index = indexOf(hash);
Entry<K, V> entry = entryForKey(index, hash, key);
if (entry != null)
{
remove(entry);
return entry.getValue();
}
else
{
return null;
}
}
/**
* Removes the entry from the map.
* @param entry an entry in the map.
*/
protected void doRemove(Entry<K, V> entry)
{
if (entryData == null)
{
++modCount;
--size;
}
else
{
Object key = entry.getKey();
int hash = entry.getHash();
int index = indexOf(hash);
removeEntry(index, entryIndexForKey(index, hash, key));
didRemove(entry);
}
}
/**
* Removes the fully indexed entry from the map and returns it's value.
* @param index the index in the entry data
* @param entryIndex the index in the list of entries.
* @return the value of the entry.
*/
protected V removeEntry(int index, int entryIndex)
{
++modCount;
--size;
Entry<K, V> entry = entryData[index].remove(entryIndex);
return entry.getValue();
}
/*
* Javadoc copied from interface.
*/
public void putAll(Map<? extends K, ? extends V> map)
{
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet())
{
put(entry.getKey(), entry.getValue());
}
}
/*
* Javadoc copied from interface.
*/
public void putAll(EMap<? extends K, ? extends V> map)
{
for (Map.Entry<? extends K, ? extends V> entry : map)
{
put(entry.getKey(), entry.getValue());
}
}
/**
* Clears the map.
*/
protected void doClear()
{
if (entryData == null)
{
++modCount;
size = 0;
didClear(null);
}
else
{
++modCount;
BasicEList<Entry<K, V>> [] oldEntryData = entryData;
entryData = null;
size = 0;
didClear(oldEntryData);
}
}
/**
* Increments the modification count.
*/
protected void doMove(Entry<K, V> entry)
{
++modCount;
}
/**
* Returns a shallow copy of this map.
* @return a shallow copy of this map.
*/
@Override
public Object clone()
{
try
{
@SuppressWarnings("unchecked") BasicEMap<K, V> result = (BasicEMap<K, V>)super.clone();
if (entryData != null)
{
result.entryData = newEntryData(entryData.length);
for (int i = 0; i < entryData.length; ++i)
{
@SuppressWarnings("unchecked")
BasicEList<Entry<K, V>> basicEList = entryData[i] == null ? null : (BasicEList<Entry<K, V>>)entryData[i].clone();
result.entryData[i] = basicEList;
}
}
result.view = null;
result.modCount = 0;
return result;
}
catch (CloneNotSupportedException exception)
{
throw new InternalError();
}
}
protected class DelegatingMap implements EMap.InternalMapView<K, V>
{
public DelegatingMap()
{
super();
}
public EMap<K, V> eMap()
{
return BasicEMap.this;
}
public int size()
{
return BasicEMap.this.size();
}
public boolean isEmpty()
{
return BasicEMap.this.isEmpty();
}
public boolean containsKey(Object key)
{
return BasicEMap.this.containsKey(key);
}
public boolean containsValue(Object value)
{
return BasicEMap.this.containsValue(value);
}
public V get(Object key)
{
return BasicEMap.this.get(key);
}
public V put(K key, V value)
{
return BasicEMap.this.put(key, value);
}
public V remove(Object key)
{
return BasicEMap.this.removeKey(key);
}
public void putAll(Map<? extends K, ? extends V> map)
{
BasicEMap.this.putAll(map);
}
public void clear()
{
BasicEMap.this.clear();
}
public Set<K> keySet()
{
return BasicEMap.this.keySet();
}
public Collection<V> values()
{
return BasicEMap.this.values();
}
public Set<Entry<K, V>> entrySet()
{
return BasicEMap.this.entrySet();
}
@Override
public boolean equals(Object object)
{
return BasicEMap.this.equals(object);
}
@Override
public int hashCode()
{
return BasicEMap.this.hashCode();
}
}
/*
* Javadoc copied from interface.
*/
public Map<K, V> map()
{
if (view == null)
{
view = new View<K, V>();
}
if (view.map == null)
{
view.map = new DelegatingMap();
}
return view.map;
}
/*
* Javadoc copied from interface.
*/
public Set<K> keySet()
{
if (view == null)
{
view = new View<K, V>();
}
if (view.keySet == null)
{
view.keySet =
new AbstractSet<K>()
{
@Override
public Iterator<K> iterator()
{
return BasicEMap.this.size == 0 ? ECollections.<K>emptyEList().iterator() : new BasicEMapKeyIterator();
}
@Override
public int size()
{
return BasicEMap.this.size;
}
@Override
public boolean contains(Object key)
{
return BasicEMap.this.containsKey(key);
}
@Override
public boolean remove(Object key)
{
int oldSize = BasicEMap.this.size;
BasicEMap.this.removeKey(key);
return BasicEMap.this.size != oldSize;
}
@Override
public void clear()
{
BasicEMap.this.clear();
}
};
}
return view.keySet;
}
/*
* Javadoc copied from interface.
*/
public Collection<V> values()
{
if (view == null)
{
view = new View<K, V>();
}
if (view.values == null)
{
view.values =
new AbstractCollection<V>()
{
@Override
public Iterator<V> iterator()
{
return BasicEMap.this.size == 0 ? ECollections.<V>emptyEList().iterator() : new BasicEMapValueIterator();
}
@Override
public int size()
{
return size;
}
@Override
public boolean contains(Object value)
{
return containsValue(value);
}
@Override
public void clear()
{
BasicEMap.this.clear();
}
};
}
return view.values;
}
/*
* Javadoc copied from interface.
*/
public Set<Map.Entry<K, V>> entrySet()
{
if (view == null)
{
view = new View<K, V>();
}
if (view.entrySet == null)
{
view.entrySet = new AbstractSet<Map.Entry<K, V>>()
{
@Override
public int size()
{
return BasicEMap.this.size;
}
@Override
public boolean contains(Object object)
{
if (BasicEMap.this.size > 0 && object instanceof Map.Entry<?, ?>)
{
BasicEMap.this.ensureEntryDataExists();
@SuppressWarnings("unchecked") Map.Entry<K, V> otherEntry = (Map.Entry<K, V>)object;
Object key = otherEntry.getKey();
int hash = key == null ? 0 : key.hashCode();
int index = BasicEMap.this.indexOf(hash);
BasicEList<Entry<K, V>> eList = entryData[index];
if (eList != null)
{
@SuppressWarnings("unchecked") Entry<K, V> [] entries = (Entry<K, V> [])eList.data;
int size = eList.size;
for (int j = 0; j < size; ++j)
{
Entry<K, V> entry = entries[j];
if (entry.getHash() == hash && entry.equals(otherEntry))
{
return true;
}
}
}
}
return false;
}
@Override
public boolean remove(Object object)
{
if (BasicEMap.this.size > 0 && object instanceof Map.Entry<?, ?>)
{
BasicEMap.this.ensureEntryDataExists();
@SuppressWarnings("unchecked") Map.Entry<K, V> otherEntry = (Map.Entry<K, V>)object;
Object key = otherEntry.getKey();
int hash = key == null ? 0 : key.hashCode();
int index = BasicEMap.this.indexOf(hash);
BasicEList<Entry<K, V>> eList = entryData[index];
if (eList != null)
{
@SuppressWarnings("unchecked") Entry<K, V> [] entries = (Entry<K, V> [])eList.data;
int size = eList.size;
for (int j = 0; j < size; ++j)
{
Entry<K, V> entry = entries[j];
if (entry.getHash() == hash && entry.equals(otherEntry))
{
// BasicEMap.this.removeEntry(index, j);
remove(otherEntry);
return true;
}
}
}
}
return false;
}
@Override
public void clear()
{
BasicEMap.this.clear();
}
@Override
public Iterator<Map.Entry<K, V>> iterator()
{
return BasicEMap.this.size == 0 ? ECollections.<Map.Entry<K, V>>emptyEList().iterator() : new BasicEMapIterator<Map.Entry<K, V>>();
}
};
}
return view.entrySet;
}
/**
* A simple and obvious entry implementation.
*/
protected class EntryImpl implements Entry<K, V>
{
/**
* The cached hash code of the key.
*/
protected int hash;
/**
* The key.
*/
protected K key;
/**
* The value.
*/
protected V value;
/**
* Creates a fully initialized instance.
* @param hash the hash code of the key.
* @param key the key.
* @param value the value.
*/
public EntryImpl(int hash, K key, V value)
{
this.hash = hash;
this.key = key;
this.value = value;
}
/**
* Returns a new entry just like this one.
* @return a new entry just like this one.
*/
@Override
protected Object clone()
{
return newEntry(hash, key, value);
}
public int getHash()
{
return hash;
}
public void setHash(int hash)
{
this.hash = hash;
}
public K getKey()
{
return key;
}
public void setKey(K key)
{
throw new RuntimeException();
}
public V getValue()
{
return value;
}
public V setValue(V value)
{
BasicEMap.this.validateValue(value);
V oldValue = this.value;
this.value = value;
return oldValue;
}
@Override
public boolean equals(Object object)
{
if (object instanceof Map.Entry<?, ?>)
{
@SuppressWarnings("unchecked") Map.Entry<K, V> entry = (Map.Entry<K, V>)object;
return
(BasicEMap.this.useEqualsForKey() && key != null ? key.equals(entry.getKey()) : key == entry.getKey()) &&
(BasicEMap.this.useEqualsForValue() && value != null ? value.equals(entry.getValue()) : value == entry.getValue());
}
else
{
return false;
}
}
@Override
public int hashCode()
{
return hash ^ (value == null ? 0 : value.hashCode());
}
@Override
public String toString()
{
return key + "->" + value;
}
}
/**
* An iterator over the map entry data.
*/
protected class BasicEMapIterator<U> implements Iterator<U>
{
/**
* The cursor in the entry data.
*/
protected int cursor;
/**
* The cursor in the list of entries.
*/
protected int entryCursor = -1;
/**
* The last cursor in the entry data.
*/
protected int lastCursor;
/**
* The cursor in the list of entries.
*/
protected int lastEntryCursor;
/**
* The modification count expected of the map.
*/
protected int expectedModCount = modCount;
/**
* Creates an instance.
*/
BasicEMapIterator()
{
if (BasicEMap.this.size > 0)
{
scan();
}
}
/**
* Called to yield the iterator result for the entry.
* This implementation returns the entry itself.
* @param entry the entry.
* @return the iterator result for the entry.
*/
@SuppressWarnings("unchecked")
protected U yield(Entry<K, V> entry)
{
return (U)entry;
}
/**
* Scans to the new entry.
*/
protected void scan()
{
BasicEMap.this.ensureEntryDataExists();
if (entryCursor != -1)
{
++entryCursor;
BasicEList<Entry<K, V>> eList = BasicEMap.this.entryData[cursor];
if (entryCursor < eList.size)
{
return;
}
++cursor;
}
for (; cursor < BasicEMap.this.entryData.length; ++cursor)
{
BasicEList<Entry<K, V>> eList = BasicEMap.this.entryData[cursor];
if (eList != null && !eList.isEmpty())
{
entryCursor = 0;
return;
}
}
entryCursor = -1;
}
/**
* Returns whether there are more objects.
* @return whether there are more objects.
*/
public boolean hasNext()
{
return entryCursor != -1;
}
/**
* Returns the next object and advances the iterator.
* @return the next object.
* @exception NoSuchElementException if the iterator is done.
*/
public U next()
{
if (BasicEMap.this.modCount != expectedModCount)
{
throw new ConcurrentModificationException();
}
if (entryCursor == -1)
{
throw new NoSuchElementException();
}
lastCursor = cursor;
lastEntryCursor = entryCursor;
scan();
@SuppressWarnings("unchecked") Entry<K, V> result = (Entry<K, V>)BasicEMap.this.entryData[lastCursor].data[lastEntryCursor];
return yield(result);
}
/**
* Removes the entry of the last object returned by {@link #next()} from the map,
* it's an optional operation.
* @exception IllegalStateException
* if <code>next</code> has not yet been called,
* or <code>remove</code> has already been called after the last call to <code>next</code>.
*/
public void remove()
{
if (modCount != expectedModCount)
{
throw new ConcurrentModificationException();
}
if (lastEntryCursor == -1)
{
throw new IllegalStateException();
}
delegateEList.remove(entryData[lastCursor].get(lastEntryCursor));
expectedModCount = BasicEMap.this.modCount;
lastEntryCursor = -1;
+ if (cursor == lastCursor && entryCursor != -1)
+ {
+ --entryCursor;
+ }
}
}
/**
* An iterator over the map key data.
*/
protected class BasicEMapKeyIterator extends BasicEMapIterator<K>
{
/**
* Creates an instance.
*/
BasicEMapKeyIterator()
{
super();
}
/**
* Called to yield the iterator result for the entry.
* This implementation returns the key of the entry.
* @param entry the entry.
* @return the key of the entry.
*/
@Override
protected K yield(Entry<K, V> entry)
{
return entry.getKey();
}
}
/**
* An iterator over the map value data.
*/
protected class BasicEMapValueIterator extends BasicEMapIterator<V>
{
/**
* Creates an instance.
*/
BasicEMapValueIterator()
{
super();
}
/**
* Called to yield the iterator result for the entry.
* This implementation returns the value of the entry.
* @param entry the entry.
* @return the value of the entry.
*/
@Override
protected V yield(Entry<K, V> entry)
{
return entry.getValue();
}
}
/**
* Called to return the hash code of the key.
* @param key the key.
* @return the hash code of the object.
*/
protected int hashOf(Object key)
{
return key == null ? 0 : key.hashCode();
}
/**
* Called to return the entry data index corresponding to the hash code.
* @param hash the hash code.
* @return the index corresponding to the hash code.
*/
protected int indexOf(int hash)
{
return (hash & 0x7FFFFFFF) % entryData.length;
}
/**
* Called to return the entry given the index, the hash, and the key.
* @param index the entry data index of the key.
* @param hash the hash code of the key.
* @param key the key.
* @return the entry.
*/
protected Entry<K, V> entryForKey(int index, int hash, Object key)
{
BasicEList<Entry<K, V>> eList = entryData[index];
if (eList != null)
{
Object [] entries = eList.data;
int size = eList.size;
if (useEqualsForKey() && key != null)
{
for (int j = 0; j < size; ++j)
{
@SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>)entries[j];
if (entry.getHash() == hash && key.equals(entry.getKey()))
{
return entry;
}
}
}
else
{
for (int j = 0; j < size; ++j)
{
@SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>)entries[j];
if (entry.getKey() == key)
{
return entry;
}
}
}
}
return null;
}
/**
* Called to return the entry list index given the index, the hash, and the key.
* @param index the entry data index of the key.
* @param hash the hash code of the key.
* @param key the key.
* @return the entry list index.
*/
protected int entryIndexForKey(int index, int hash, Object key)
{
if (useEqualsForKey() && key != null)
{
BasicEList<Entry<K, V>> eList = entryData[index];
if (eList != null)
{
Object [] entries = eList.data;
int size = eList.size;
for (int j = 0; j < size; ++j)
{
@SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>)entries[j];
if (entry.getHash() == hash && key.equals(entry.getKey()))
{
return j;
}
}
}
}
else
{
BasicEList<Entry<K, V>> eList = entryData[index];
if (eList != null)
{
Object [] entries = eList.data;
int size = eList.size;
for (int j = 0; j < size; ++j)
{
@SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>)entries[j];
if (entry.getKey() == key)
{
return j;
}
}
}
}
return -1;
}
/**
* Grows the capacity of the map
* to ensure that no additional growth is needed until the size exceeds the specified minimum capacity.
*/
protected boolean grow(int minimumCapacity)
{
++modCount;
int oldCapacity = entryData == null ? 0 : entryData.length;
if (minimumCapacity > oldCapacity)
{
BasicEList<Entry<K, V>> [] oldEntryData = entryData;
entryData = newEntryData(2 * oldCapacity + 4);
for (int i = 0; i < oldCapacity; ++i)
{
BasicEList<Entry<K, V>> oldEList = oldEntryData[i];
if (oldEList != null)
{
Object [] entries = oldEList.data;
int size = oldEList.size;
for (int j = 0; j < size; ++j)
{
@SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>)entries[j];
int index = indexOf(entry.getHash());
BasicEList<Entry<K, V>> eList = entryData[index];
if (eList == null)
{
eList = entryData[index] = newList();
}
eList.add(entry);
}
}
}
return true;
}
else
{
return false;
}
}
private void writeObject(ObjectOutputStream objectOutputStream) throws IOException
{
objectOutputStream.defaultWriteObject();
if (entryData == null)
{
objectOutputStream.writeInt(0);
}
else
{
// Write the capacity and the size.
//
objectOutputStream.writeInt(entryData.length);
objectOutputStream.writeInt(size);
// Write all the entryData; there will be size of them.
//
for (int i = 0; i < entryData.length; ++i)
{
BasicEList<Entry<K, V>> eList = entryData[i];
if (eList != null)
{
Object [] entries = eList.data;
int size = eList.size;
for (int j = 0; j < size; ++j)
{
@SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>)entries[j];
objectOutputStream.writeObject(entry.getKey());
objectOutputStream.writeObject(entry.getValue());
}
}
}
}
}
private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException
{
initializeDelegateEList();
// Restore the capacity, if there was any.
//
int capacity = objectInputStream.readInt();
if (capacity > 0)
{
entryData = newEntryData(capacity);
// Read all size number of entryData.
//
for (int i = 0, size = objectInputStream.readInt(); i < size; ++i)
{
@SuppressWarnings("unchecked") K key = (K)objectInputStream.readObject();
@SuppressWarnings("unchecked") V value = (V)objectInputStream.readObject();
put(key, value);
}
}
}
/**
* Delegates to {@link #delegateEList}.
*/
public boolean contains(Object object)
{
return delegateEList.contains(object);
}
/**
* Delegates to {@link #delegateEList}.
*/
public boolean containsAll(Collection<?> collection)
{
return delegateEList.containsAll(collection);
}
/**
* Delegates to {@link #delegateEList}.
*/
public int indexOf(Object object)
{
return delegateEList.indexOf(object);
}
/**
* Delegates to {@link #delegateEList}.
*/
public int lastIndexOf(Object object)
{
return delegateEList.lastIndexOf(object);
}
/**
* Delegates to {@link #delegateEList}.
*/
public Object[] toArray()
{
return delegateEList.toArray();
}
/**
* Delegates to {@link #delegateEList}.
*/
public <T> T[] toArray(T [] array)
{
return delegateEList.toArray(array);
}
/**
* Delegates to {@link #delegateEList}.
*/
public Entry<K, V> get(int index)
{
return delegateEList.get(index);
}
/**
* Delegates to {@link #delegateEList}.
*/
public Map.Entry<K, V> set(int index, Map.Entry<K, V> object)
{
return delegateEList.set(index, (Entry<K, V>)object);
}
/**
* Delegates to {@link #delegateEList}.
*/
public boolean add(Map.Entry<K, V> object)
{
return delegateEList.add((Entry<K, V>)object);
}
/**
* Delegates to {@link #delegateEList}.
*/
public void add(int index, Map.Entry<K, V> object)
{
delegateEList.add(index, (Entry<K, V>)object);
}
/**
* Delegates to {@link #delegateEList}.
*/
@SuppressWarnings("unchecked")
public boolean addAll(Collection<? extends Map.Entry<K, V>> collection)
{
return delegateEList.addAll((Collection<? extends Entry<K, V>>)collection);
}
/**
* Delegates to {@link #delegateEList}.
*/
@SuppressWarnings("unchecked")
public boolean addAll(int index, Collection<? extends Map.Entry<K, V>> collection)
{
return delegateEList.addAll(index, (Collection<? extends Entry<K, V>>)collection);
}
/**
* Delegates to {@link #delegateEList}.
*/
public boolean remove(Object object)
{
if (object instanceof Map.Entry<?, ?>)
{
return delegateEList.remove(object);
}
else
{
boolean result = containsKey(object);
removeKey(object);
return result;
}
}
/**
* Delegates to {@link #delegateEList}.
*/
public boolean removeAll(Collection<?> collection)
{
return delegateEList.removeAll(collection);
}
/**
* Delegates to {@link #delegateEList}.
*/
public Map.Entry<K, V> remove(int index)
{
return delegateEList.remove(index);
}
/**
* Delegates to {@link #delegateEList}.
*/
public boolean retainAll(Collection<?> collection)
{
return delegateEList.retainAll(collection);
}
/**
* Delegates to {@link #delegateEList}.
*/
public void clear()
{
delegateEList.clear();
}
/**
* Delegates to {@link #delegateEList}.
*/
public void move(int index, Map.Entry<K, V> object)
{
delegateEList.move(index, (Entry<K, V>)object);
}
/**
* Delegates to {@link #delegateEList}.
*/
public Map.Entry<K, V> move(int targetIndex, int sourceIndex)
{
return delegateEList.move(targetIndex, sourceIndex);
}
/**
* Delegates to {@link #delegateEList}.
*/
@SuppressWarnings("unchecked")
public Iterator<Map.Entry<K, V>> iterator()
{
return (Iterator<Map.Entry<K, V>>)(Iterator<?>)delegateEList.iterator();
}
/**
* Delegates to {@link #delegateEList}.
*/
@SuppressWarnings("unchecked")
public ListIterator<Map.Entry<K, V>> listIterator()
{
return (ListIterator<Map.Entry<K, V>>)(ListIterator<?>)(delegateEList.listIterator());
}
/**
* Delegates to {@link #delegateEList}.
*/
@SuppressWarnings("unchecked")
public ListIterator<Map.Entry<K, V>> listIterator(int index)
{
return (ListIterator<Map.Entry<K, V>>)(ListIterator<?>)delegateEList.listIterator(index);
}
/**
* Delegates to {@link #delegateEList}.
*/
@SuppressWarnings("unchecked")
public List<Map.Entry<K, V>> subList(int start, int end)
{
return (List<Map.Entry<K, V>>)(List<?>)delegateEList.subList(start, end);
}
@Override
public int hashCode()
{
return delegateEList.hashCode();
}
@Override
public boolean equals(Object object)
{
if (object instanceof EMap<?, ?>)
{
return delegateEList.equals(object);
}
else
{
return false;
}
}
/**
* Delegates to {@link #delegateEList}.
*/
@Override
public String toString()
{
return delegateEList.toString();
}
}
| false | false | null | null |
diff --git a/src/com/android/settings/notificationlight/ApplicationLightPreference.java b/src/com/android/settings/notificationlight/ApplicationLightPreference.java
index 3c44e269f..ea62cc251 100644
--- a/src/com/android/settings/notificationlight/ApplicationLightPreference.java
+++ b/src/com/android/settings/notificationlight/ApplicationLightPreference.java
@@ -1,401 +1,397 @@
/*
* Copyright (C) 2012 The CyanogenMod 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.settings.notificationlight;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.android.settings.R;
import com.android.settings.Utils;
public class ApplicationLightPreference extends Preference implements
View.OnClickListener {
private static String TAG = "AppLightPreference";
public static final int DEFAULT_TIME = 1000;
public static final int DEFAULT_COLOR = 0xFFFFFF; //White
private ImageView mLightColorView;
private TextView mOnValueView;
private TextView mOffValueView;
private int mColorValue;
private int mOnValue;
private int mOffValue;
private boolean mOnOffChangeable;
private OnLongClickListener mParent;
private Resources mResources;
private ScreenReceiver mReceiver = null;
private AlertDialog mTestDialog;
/**
* @param context
* @param attrs
*/
public ApplicationLightPreference(Context context, AttributeSet attrs) {
super(context, attrs);
mColorValue = DEFAULT_COLOR;
mOnValue = DEFAULT_TIME;
mOffValue = DEFAULT_TIME;
mOnOffChangeable = true;
mParent = null;
init();
}
/**
* @param context
* @param color
* @param onValue
* @param offValue
*/
public ApplicationLightPreference(Context context, int color, int onValue, int offValue) {
super(context);
mColorValue = color;
mOnValue = onValue;
mOffValue = offValue;
mParent = null;
mOnOffChangeable = true;
init();
}
/**
* @param context
* @param onLongClickListener
* @param color
* @param onValue
* @param offValue
*/
public ApplicationLightPreference(Context context, int color, int onValue, int offValue, boolean onOffChangeable) {
super(context);
mColorValue = color;
mOnValue = onValue;
mOffValue = offValue;
mOnOffChangeable = onOffChangeable;
init();
}
/**
* @param context
* @param onLongClickListener
* @param color
* @param onValue
* @param offValue
*/
public ApplicationLightPreference(Context context, OnLongClickListener parent, int color, int onValue, int offValue) {
super(context);
mColorValue = color;
mOnValue = onValue;
mOffValue = offValue;
mParent = parent;
mOnOffChangeable = true;
init();
}
private void init() {
setLayoutResource(R.layout.preference_application_light);
mResources = getContext().getResources();
}
@Override
public View getView(View convertView, ViewGroup parent) {
View view = super.getView(convertView, parent);
View lightPref = (LinearLayout) view.findViewById(R.id.app_light_pref);
if ((lightPref != null) && lightPref instanceof LinearLayout) {
lightPref.setOnClickListener(this);
if (mParent != null) {
lightPref.setOnLongClickListener(mParent);
}
}
return view;
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mLightColorView = (ImageView) view.findViewById(R.id.light_color);
mOnValueView = (TextView) view.findViewById(R.id.textViewTimeOnValue);
mOffValueView = (TextView) view.findViewById(R.id.textViewTimeOffValue);
// Hide the summary text - it takes up too much space on a low res device
// We use it for storing the package name for the longClickListener
TextView tView = (TextView) view.findViewById(android.R.id.summary);
tView.setVisibility(View.GONE);
updatePreferenceViews();
}
private void updatePreferenceViews() {
final int width = (int) mResources.getDimension(R.dimen.device_memory_usage_button_width);
final int height = (int) mResources.getDimension(R.dimen.device_memory_usage_button_height);
if (mLightColorView != null) {
mLightColorView.setEnabled(true);
mLightColorView.setImageDrawable(createRectShape(width, height, 0xFF000000 + mColorValue));
}
if (mOnValueView != null) {
mOnValueView.setText(mapLengthValue(mOnValue));
}
if (mOffValueView != null) {
- if (mOnValue == 0) {
+ if (mOnValue == 1) {
mOffValueView.setVisibility(View.GONE);
} else {
mOffValueView.setVisibility(View.VISIBLE);
}
mOffValueView.setText(mapSpeedValue(mOffValue));
}
}
@Override
public void onClick(View v) {
if ((v != null) && (R.id.app_light_pref == v.getId())) {
editPreferenceValues();
}
}
private void editPreferenceValues() {
final LightSettingsDialog d = new LightSettingsDialog(getContext(), 0xFF000000 + mColorValue,
mOnValue, mOffValue,
mOnOffChangeable);
final int width = (int) mResources.getDimension(R.dimen.dialog_light_settings_width);
d.setAlphaSliderVisible(false);
Resources resources = getContext().getResources();
d.setButton(AlertDialog.BUTTON_POSITIVE, resources.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mColorValue = d.getColor() - 0xFF000000; // strip alpha, led does not support it
mOnValue = d.getPulseSpeedOn();
mOffValue = d.getPulseSpeedOff();
updatePreferenceViews();
callChangeListener(this);
}
});
d.setButton(AlertDialog.BUTTON_NEUTRAL, resources.getString(R.string.dialog_test), (DialogInterface.OnClickListener) null);
d.setButton(AlertDialog.BUTTON_NEGATIVE, resources.getString(R.string.cancel), (DialogInterface.OnClickListener) null);
d.show();
// Intercept the click on the middle button to show the test dialog and prevent the onDismiss
d.findViewById(android.R.id.button3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int onTime = d.getPulseSpeedOn();
int offTime = d.getPulseSpeedOff();
- if (onTime == 0) {
- // 'Always on' is selected, display the test with a long timeout as
- // an onTime of 0 does not turn the light on at all
- showTestDialog(d.getColor() - 0xFF000000, 180000, 1);
- } else {
- showTestDialog(d.getColor() - 0xFF000000, onTime, offTime);
- }
+ showTestDialog(d.getColor() - 0xFF000000, onTime, offTime);
}
});
if (Utils.isTablet(getContext())) {
// Make the dialog smaller on large screen devices
d.getWindow().setLayout(width, LayoutParams.WRAP_CONTENT);
}
}
private void showTestDialog(int color, int speedOn, int speedOff) {
final Context context = getContext();
if (mReceiver != null) {
context.getApplicationContext().unregisterReceiver(mReceiver);
}
if (mTestDialog != null) {
mTestDialog.dismiss();
}
mReceiver = new ScreenReceiver(color, speedOn, speedOff);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
context.getApplicationContext().registerReceiver(mReceiver, filter);
mTestDialog = new AlertDialog.Builder(context)
.setTitle(R.string.dialog_test)
.setMessage(R.string.dialog_test_message)
.setPositiveButton(R.string.dialog_test_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mReceiver != null) {
context.getApplicationContext().unregisterReceiver(mReceiver);
mReceiver = null;
}
}
})
.create();
mTestDialog.show();
}
/**
* Getters and Setters
*/
public int getColor() {
return mColorValue;
}
public void setColor(int color) {
mColorValue = color;
updatePreferenceViews();
}
public void setOnValue(int value) {
mOnValue = value;
updatePreferenceViews();
}
public int getOnValue() {
return mOnValue;
}
public void setOffValue(int value) {
mOffValue = value;
updatePreferenceViews();
}
public int getOffValue() {
return mOffValue;
}
public void setAllValues(int color, int onValue, int offValue) {
mColorValue = color;
mOnValue = onValue;
mOffValue = offValue;
mOnOffChangeable = true;
updatePreferenceViews();
}
public void setAllValues(int color, int onValue, int offValue, boolean onOffChangeable) {
mColorValue = color;
mOnValue = onValue;
mOffValue = offValue;
mOnOffChangeable = onOffChangeable;
updatePreferenceViews();
}
public void setOnOffValue(int onValue, int offValue) {
mOnValue = onValue;
mOffValue = offValue;
updatePreferenceViews();
}
public void setOnOffChangeable(boolean value) {
mOnOffChangeable = value;
}
/**
* Utility methods
*/
public class ScreenReceiver extends BroadcastReceiver {
protected int timeon;
protected int timeoff;
protected int color;
public ScreenReceiver(int color, int timeon, int timeoff) {
this.timeon = timeon;
this.timeoff = timeoff;
this.color = color;
}
@Override
public void onReceive(Context context, Intent intent) {
final NotificationManager nm =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Notification.Builder builder = new Notification.Builder(context);
builder.setAutoCancel(true);
builder.setLights(color, timeon, timeoff);
- nm.notify(1, builder.getNotification());
+ Notification n = builder.getNotification();
+ n.flags |= Notification.FLAG_SHOW_LIGHTS;
+ nm.notify(1, n);
} else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
nm.cancel(1);
context.getApplicationContext().unregisterReceiver(mReceiver);
mReceiver = null;
mTestDialog.dismiss();
mTestDialog = null;
}
}
}
private static ShapeDrawable createRectShape(int width, int height, int color) {
ShapeDrawable shape = new ShapeDrawable(new RectShape());
shape.setIntrinsicHeight(height);
shape.setIntrinsicWidth(width);
shape.getPaint().setColor(color);
return shape;
}
private String mapLengthValue(Integer time) {
if (time == DEFAULT_TIME) {
return getContext().getString(R.string.default_time);
}
String[] timeNames = mResources.getStringArray(R.array.notification_pulse_length_entries);
String[] timeValues = mResources.getStringArray(R.array.notification_pulse_length_values);
for (int i = 0; i < timeValues.length; i++) {
if (Integer.decode(timeValues[i]).equals(time)) {
return timeNames[i];
}
}
return getContext().getString(R.string.custom_time);
}
private String mapSpeedValue(Integer time) {
if (time == DEFAULT_TIME) {
return getContext().getString(R.string.default_time);
}
String[] timeNames = mResources.getStringArray(R.array.notification_pulse_speed_entries);
String[] timeValues = mResources.getStringArray(R.array.notification_pulse_speed_values);
for (int i = 0; i < timeValues.length; i++) {
if (Integer.decode(timeValues[i]).equals(time)) {
return timeNames[i];
}
}
return getContext().getString(R.string.custom_time);
}
}
diff --git a/src/com/android/settings/notificationlight/LightSettingsDialog.java b/src/com/android/settings/notificationlight/LightSettingsDialog.java
index 7f8e71c80..1aa46c5f7 100644
--- a/src/com/android/settings/notificationlight/LightSettingsDialog.java
+++ b/src/com/android/settings/notificationlight/LightSettingsDialog.java
@@ -1,250 +1,251 @@
/*
* Copyright (C) 2010 Daniel Nilsson
* Copyright (C) 2012 THe CyanogenMod 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.settings.notificationlight;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.PixelFormat;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import com.android.settings.R;
import com.android.settings.notificationlight.ColorPickerView.OnColorChangedListener;
public class LightSettingsDialog extends AlertDialog implements
ColorPickerView.OnColorChangedListener {
private ColorPickerView mColorPicker;
private ColorPanelView mOldColor;
private ColorPanelView mNewColor;
private Spinner mPulseSpeedOn;
private Spinner mPulseSpeedOff;
private LayoutInflater mInflater;
private OnColorChangedListener mListener;
/**
* @param context
* @param initialColor
* @param initialSpeedOn
* @param initialSpeedOff
*/
protected LightSettingsDialog(Context context, int initialColor, int initialSpeedOn,
int initialSpeedOff) {
super(context);
init(initialColor, initialSpeedOn, initialSpeedOff, true);
}
/**
* @param context
* @param initialColor
* @param initialSpeedOn
* @param initialSpeedOff
* @param onOffChangeable
*/
protected LightSettingsDialog(Context context, int initialColor, int initialSpeedOn,
int initialSpeedOff, boolean onOffChangeable) {
super(context);
init(initialColor, initialSpeedOn, initialSpeedOff, onOffChangeable);
}
private void init(int color, int speedOn, int speedOff, boolean onOffChangeable) {
// To fight color banding.
getWindow().setFormat(PixelFormat.RGBA_8888);
setUp(color, speedOn, speedOff, onOffChangeable);
}
/**
* This function sets up the dialog with the proper values. If the speedOff parameters
* has a -1 value disable both spinners
*
* @param color - the color to set
* @param speedOn - the flash time in ms
* @param speedOff - the flash length in ms
*/
private void setUp(int color, int speedOn, int speedOff, boolean onOffChangeable) {
mInflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = mInflater.inflate(R.layout.dialog_light_settings, null);
mColorPicker = (ColorPickerView) layout.findViewById(R.id.color_picker_view);
mOldColor = (ColorPanelView) layout.findViewById(R.id.old_color_panel);
mNewColor = (ColorPanelView) layout.findViewById(R.id.new_color_panel);
((LinearLayout) mOldColor.getParent()).setPadding(Math
.round(mColorPicker.getDrawingOffset()), 0, Math
.round(mColorPicker.getDrawingOffset()), 0);
mColorPicker.setOnColorChangedListener(this);
mOldColor.setColor(color);
mColorPicker.setColor(color, true);
mPulseSpeedOn = (Spinner) layout.findViewById(R.id.on_spinner);
PulseSpeedAdapter pulseSpeedAdapter = new PulseSpeedAdapter(
R.array.notification_pulse_length_entries,
R.array.notification_pulse_length_values,
speedOn);
mPulseSpeedOn.setAdapter(pulseSpeedAdapter);
mPulseSpeedOn.setSelection(pulseSpeedAdapter.getTimePosition(speedOn));
mPulseSpeedOn.setOnItemSelectedListener(mSelectionListener);
mPulseSpeedOff = (Spinner) layout.findViewById(R.id.off_spinner);
pulseSpeedAdapter = new PulseSpeedAdapter(R.array.notification_pulse_speed_entries,
R.array.notification_pulse_speed_values,
speedOff);
mPulseSpeedOff.setAdapter(pulseSpeedAdapter);
mPulseSpeedOff.setSelection(pulseSpeedAdapter.getTimePosition(speedOff));
mPulseSpeedOn.setEnabled(onOffChangeable);
- mPulseSpeedOff.setEnabled((speedOn != 0) && onOffChangeable);
+ mPulseSpeedOff.setEnabled((speedOn != 1) && onOffChangeable);
setView(layout);
setTitle(R.string.edit_light_settings);
}
private AdapterView.OnItemSelectedListener mSelectionListener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- mPulseSpeedOff.setEnabled(getPulseSpeedOn() != 0);
+ mPulseSpeedOff.setEnabled(getPulseSpeedOn() != 1);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
@Override
public void onColorChanged(int color) {
mNewColor.setColor(color);
if (mListener != null) {
mListener.onColorChanged(color);
}
}
public void setAlphaSliderVisible(boolean visible) {
mColorPicker.setAlphaSliderVisible(visible);
}
public int getColor() {
return mColorPicker.getColor();
}
public int getPulseSpeedOn() {
return ((Pair<String, Integer>) mPulseSpeedOn.getSelectedItem()).second;
}
public int getPulseSpeedOff() {
- return ((Pair<String, Integer>) mPulseSpeedOff.getSelectedItem()).second;
+ // return 0 if 'Always on' is selected
+ return getPulseSpeedOn() == 1 ? 0 : ((Pair<String, Integer>) mPulseSpeedOff.getSelectedItem()).second;
}
class PulseSpeedAdapter extends BaseAdapter implements SpinnerAdapter {
private ArrayList<Pair<String, Integer>> times;
public PulseSpeedAdapter(int timeNamesResource, int timeValuesResource) {
times = new ArrayList<Pair<String, Integer>>();
String[] time_names = getContext().getResources().getStringArray(timeNamesResource);
String[] time_values = getContext().getResources().getStringArray(timeValuesResource);
for(int i = 0; i < time_values.length; ++i) {
times.add(new Pair<String, Integer>(time_names[i], Integer.decode(time_values[i])));
}
}
/**
* This constructor apart from taking a usual time entry array takes the
* currently configured time value which might cause the addition of a
* "Custom" time entry in the spinner in case this time value does not
* match any of the predefined ones in the array.
*
* @param timeNamesResource The time entry names array
* @param timeValuesResource The time entry values array
* @param customTime Current time value that might be one of the
* predefined values or a totally custom value
*/
public PulseSpeedAdapter(int timeNamesResource, int timeValuesResource, Integer customTime) {
this(timeNamesResource, timeValuesResource);
// Check if we also need to add the custom value entry
if (getTimePosition(customTime) == -1) {
times.add(new Pair<String, Integer>(getContext().getResources()
.getString(R.string.custom_time), customTime));
}
}
/**
* Will return the position of the spinner entry with the specified
* time. Returns -1 if there is no such entry.
*
* @param time Time in ms
* @return Position of entry with given time or -1 if not found.
*/
public int getTimePosition(Integer time) {
for (int position = 0; position < getCount(); ++position) {
if (getItem(position).second.equals(time)) {
return position;
}
}
return -1;
}
@Override
public int getCount() {
return times.size();
}
@Override
public Pair<String, Integer> getItem(int position) {
return times.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = mInflater.inflate(R.layout.pulse_time_item, null);
}
Pair<String, Integer> entry = getItem(position);
((TextView) view.findViewById(R.id.textViewName)).setText(entry.first);
return view;
}
}
}
| false | false | null | null |