diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/org/basex/core/Context.java b/src/main/java/org/basex/core/Context.java
index 2491289e0..3c1c7055b 100644
--- a/src/main/java/org/basex/core/Context.java
+++ b/src/main/java/org/basex/core/Context.java
@@ -1,239 +1,240 @@
package org.basex.core;
import static org.basex.core.Text.*;
import org.basex.data.Data;
import org.basex.data.MetaData;
import org.basex.data.Nodes;
import org.basex.io.IO;
import org.basex.query.util.pkg.Repo;
import org.basex.server.ClientListener;
import org.basex.server.Sessions;
/**
* This class serves as a central database context.
* It references the currently opened database. Moreover, it provides
* references to the currently used, marked and copied node sets.
*
* @author BaseX Team 2005-11, BSD License
* @author Christian Gruen
*/
public final class Context {
/** Database properties. */
public final Prop prop = new Prop(true);
/** Client connections. */
public final Sessions sessions;
/** Event pool. */
public final Events events;
/** Database pool. */
public final Datas datas;
/** Users. */
public final Users users;
/** Package repository. */
public final Repo repo;
/** Session reference. */
public ClientListener session;
/** User reference. */
public User user;
/** Current query file. */
public IO query;
/** Data reference. */
public Data data;
/** Node context. */
public Nodes current;
// GUI references
/** Marked nodes. */
public Nodes marked;
/** Copied nodes. */
public Nodes copied;
/** Focused node. */
public int focused = -1;
/** Process locking. */
private final Lock lock;
/**
* Constructor.
*/
public Context() {
datas = new Datas();
events = new Events();
sessions = new Sessions();
lock = new Lock(this);
users = new Users(true);
user = users.get(ADMIN);
repo = new Repo(this);
}
/**
* Constructor. {@link #user} reference must be set after calling this.
* @param ctx parent database context
* @param s server process
*/
public Context(final Context ctx, final ClientListener s) {
session = s;
datas = ctx.datas;
events = ctx.events;
sessions = ctx.sessions;
lock = ctx.lock;
users = ctx.users;
repo = ctx.repo;
prop.set(Prop.EVENTPORT, ctx.prop.num(Prop.EVENTPORT));
prop.set(Prop.TIMEOUT, ctx.prop.num(Prop.TIMEOUT));
+ prop.set(Prop.PARALLEL, ctx.prop.num(Prop.PARALLEL));
}
/**
* Closes the database context.
*/
public synchronized void close() {
while(sessions.size() > 0) sessions.get(0).exit();
datas.close();
}
/**
* Returns true if the current node set contains all documents.
* @return result of check
*/
public boolean root() {
return current != null && current.root;
}
/**
* Returns all document nodes.
* @return result of check
*/
public int[] doc() {
return current.root ? current.list : data.doc().toArray();
}
/**
* Sets the specified data instance as current database.
* @param d data reference
*/
public void openDB(final Data d) {
openDB(d, null);
}
/**
* Sets the specified data instance as current database and restricts
* the context nodes to the given path.
* @param d data reference
* @param path database path
*/
public void openDB(final Data d, final String path) {
data = d;
copied = null;
set(new Nodes((path == null ? d.doc() : d.doc(path)).toArray(), d),
new Nodes(d));
current.root = path == null;
}
/**
* Removes the current database context.
*/
public void closeDB() {
data = null;
copied = null;
set(null, null);
}
/**
* Sets the current context and marked node set and resets the focus.
* @param curr context set
* @param mark marked nodes
*/
public void set(final Nodes curr, final Nodes mark) {
current = curr;
marked = mark;
focused = -1;
}
/**
* Updates references to the document nodes.
*/
public void update() {
current = new Nodes(data.doc().toArray(), data);
current.root = true;
}
/**
* Adds the specified data reference to the pool.
* @param d data reference
*/
public void pin(final Data d) {
datas.add(d);
}
/**
* Pins the specified database.
* @param name name of database
* @return data reference
*/
public Data pin(final String name) {
return datas.pin(name);
}
/**
* Unpins a data reference.
* @param d data reference
* @return true if reference was removed from the pool
*/
public boolean unpin(final Data d) {
return datas.unpin(d);
}
/**
* Checks if the specified database is pinned.
* @param db name of database
* @return int use-status
*/
public boolean pinned(final String db) {
return datas.pinned(db);
}
/**
* Registers a process.
* @param w writing flag
*/
public void register(final boolean w) {
lock.lock(w);
}
/**
* Unregisters a process.
* @param w writing flag
*/
public void unregister(final boolean w) {
lock.unlock(w);
}
/**
* Adds the specified session.
* @param s session to be added
*/
public void add(final ClientListener s) {
sessions.add(s);
}
/**
* Removes the specified session.
* @param s session to be removed
*/
public void delete(final ClientListener s) {
sessions.remove(s);
}
/**
* Checks if the current user has the specified permission.
* @param p requested permission
* @param md optional meta data reference
* @return result of check
*/
public boolean perm(final int p, final MetaData md) {
final User us = md == null || p == User.CREATE || p == User.ADMIN ? null :
md.users.get(user.name);
return (us == null ? user : us).perm(p);
}
}
| true | true | public Context(final Context ctx, final ClientListener s) {
session = s;
datas = ctx.datas;
events = ctx.events;
sessions = ctx.sessions;
lock = ctx.lock;
users = ctx.users;
repo = ctx.repo;
prop.set(Prop.EVENTPORT, ctx.prop.num(Prop.EVENTPORT));
prop.set(Prop.TIMEOUT, ctx.prop.num(Prop.TIMEOUT));
}
| public Context(final Context ctx, final ClientListener s) {
session = s;
datas = ctx.datas;
events = ctx.events;
sessions = ctx.sessions;
lock = ctx.lock;
users = ctx.users;
repo = ctx.repo;
prop.set(Prop.EVENTPORT, ctx.prop.num(Prop.EVENTPORT));
prop.set(Prop.TIMEOUT, ctx.prop.num(Prop.TIMEOUT));
prop.set(Prop.PARALLEL, ctx.prop.num(Prop.PARALLEL));
}
|
diff --git a/src/wikipathways-client/org/pathvisio/wikipathways/bots/XRefBot.java b/src/wikipathways-client/org/pathvisio/wikipathways/bots/XRefBot.java
index bf82f6f0..b95b1b36 100644
--- a/src/wikipathways-client/org/pathvisio/wikipathways/bots/XRefBot.java
+++ b/src/wikipathways-client/org/pathvisio/wikipathways/bots/XRefBot.java
@@ -1,240 +1,240 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2009 BiGCaT Bioinformatics
//
// 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.pathvisio.wikipathways.bots;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.bridgedb.IDMapperException;
import org.bridgedb.Xref;
import org.bridgedb.bio.GdbProvider;
import org.bridgedb.bio.Organism;
import org.bridgedb.rdb.IDMapperRdb;
import org.pathvisio.debug.Logger;
import org.pathvisio.model.ObjectType;
import org.pathvisio.model.Pathway;
import org.pathvisio.model.PathwayElement;
import org.pathvisio.wikipathways.webservice.WSPathwayInfo;
/**
* Checks for DataNode XRef annotations and adds a curation tag for
* pathways that contain more wrongly annotated DataNodes than a given threshold.
*/
public class XRefBot extends Bot {
private static final String CURATIONTAG = "Curation:MissingXRef";
private static final String PROP_THRESHOLD = "threshold";
private static final String PROP_GDBS = "gdb-config";
GdbProvider gdbs;
double threshold;
public XRefBot(Properties props) throws BotException {
super(props);
String thr = props.getProperty(PROP_THRESHOLD);
if(thr != null) threshold = Double.parseDouble(thr);
File gdbFile = new File(props.getProperty(PROP_GDBS));
try {
gdbs = GdbProvider.fromConfigFile(gdbFile);
} catch (Exception e) {
throw new BotException(e);
}
}
public String getTagName() {
return CURATIONTAG;
}
public BotReport createReport(Collection<Result> results) {
BotReport report = new BotReport(
new String[] {
"Nr Xrefs", "Nr valid", "% valid", "Invalid DataNodes"
}
);
report.setTitle("XRefBot scan report");
report.setDescription("The XRefBot checks for valid DataNode annotations");
for(Result r : results) {
XRefResult xr = (XRefResult)r;
report.setRow(
r.getPathwayInfo(),
new String[] {
"" + xr.getNrXrefs(),
"" + xr.getNrValid(),
"" + (int)(xr.getPercentValid() * 100) / 100, //Round to two decimals
"" + xr.getLabelsForInvalid()
}
);
}
return report;
}
protected Result scanPathway(File pathwayFile) throws BotException {
try {
XRefResult report = new XRefResult(getCache().getPathwayInfo(pathwayFile));
Pathway pathway = new Pathway();
pathway.readFromXml(pathwayFile, true);
String orgName = pathway.getMappInfo().getOrganism();
Organism org = Organism.fromLatinName(orgName);
if(org == null) org = Organism.fromShortName(orgName);
for(PathwayElement pwe : pathway.getDataObjects()) {
if(pwe.getObjectType() == ObjectType.DATANODE) {
boolean exists = false;
Xref xref = pwe.getXref();
for(IDMapperRdb gdb : gdbs.getGdbs(org)) {
try {
- if(gdb.xrefExists(xref)) {
+ if(xref.getId() != null && xref.getDataSource() != null && gdb.xrefExists(xref)) {
exists = true;
break;
}
} catch (IDMapperException e) {
Logger.log.error("Error checking xref exists", e);
}
}
report.addXref(pwe, exists);
}
}
return report;
} catch(Exception e) {
throw new BotException(e);
}
}
private class XRefResult extends Result {
Map<PathwayElement, Boolean> xrefs = new HashMap<PathwayElement, Boolean>();
public XRefResult(WSPathwayInfo pathwayInfo) {
super(pathwayInfo);
}
public boolean shouldTag() {
return getPercentValid() < threshold;
}
public boolean equalsTag(String tag) {
return getTagText().equals(tag);
}
public void addXref(PathwayElement pwe, boolean valid) {
xrefs.put(pwe, valid);
}
public int getNrXrefs() {
return xrefs.size();
}
public double getPercentValid() {
return (double)(100 * getNrValid()) / getNrXrefs();
}
public double getPercentInvalid() {
return (double)(100 * getNrInvalid()) / getNrXrefs();
}
public int getNrInvalid() {
return getNrXrefs() - getNrValid();
}
public int getNrValid() {
int v = 0;
for(PathwayElement pwe : xrefs.keySet()) {
if(xrefs.get(pwe)) {
v++;
}
}
return v;
}
public List<String> getLabelsForInvalid() {
List<String> labels = new ArrayList<String>();
for(PathwayElement pwe : xrefs.keySet()) {
if(!xrefs.get(pwe)) {
labels.add(pwe.getTextLabel());
}
}
return labels;
}
private String[] getLabelStrings() {
List<String> labels = getLabelsForInvalid();
Collections.sort(labels);
String labelString = "";
String labelStringTrun = "";
for(int i = 0; i < labels.size(); i++) {
labelString += labels.get(i) + ", ";
if(i < 3) {
labelStringTrun += labels.get(i) + ", ";
} else if(i == 3) {
labelStringTrun += " ..., ";
}
}
if(labelString.length() > 2) {
labelString = labelString.substring(0, labelString.length() - 2);
}
if(labelStringTrun.length() > 2) {
labelStringTrun = labelStringTrun.substring(0, labelStringTrun.length() - 2);
}
return new String[] { labelString, labelStringTrun };
}
public String getTagText() {
String[] labels = getLabelStrings();
//Limit length of label string
if(labels[0].length() > 300) {
labels[0] = labels[0].substring(0, 300) + "...";
}
String txt = getNrInvalid() + " out of " + getNrXrefs() +
" DataNodes have an incorrect or missing external reference: " +
"<span title=\"" + labels[0] + "\">" + labels[1] + "</span>";
return txt;
}
}
public static void main(String[] args) {
try {
Logger.log.trace("Starting XRefBot");
Properties props = new Properties();
props.load(new FileInputStream(new File(args[0])));
XRefBot bot = new XRefBot(props);
Bot.runAll(bot, new File(args[1] + ".html"), new File(args[1] + ".txt"));
} catch(Exception e) {
e.printStackTrace();
printUsage();
}
}
static private void printUsage() {
System.out.println(
"Usage:\n" +
"java org.pathvisio.wikipathways.bots.XRefBot propsfile reportfilename\n" +
"Where:\n" +
"-propsfile: a properties file containing the bot properties\n" +
"-reportfilename: the base name of the file that will be used to write reports to " +
"(extension will be added automatically)\n"
);
}
}
| true | true | protected Result scanPathway(File pathwayFile) throws BotException {
try {
XRefResult report = new XRefResult(getCache().getPathwayInfo(pathwayFile));
Pathway pathway = new Pathway();
pathway.readFromXml(pathwayFile, true);
String orgName = pathway.getMappInfo().getOrganism();
Organism org = Organism.fromLatinName(orgName);
if(org == null) org = Organism.fromShortName(orgName);
for(PathwayElement pwe : pathway.getDataObjects()) {
if(pwe.getObjectType() == ObjectType.DATANODE) {
boolean exists = false;
Xref xref = pwe.getXref();
for(IDMapperRdb gdb : gdbs.getGdbs(org)) {
try {
if(gdb.xrefExists(xref)) {
exists = true;
break;
}
} catch (IDMapperException e) {
Logger.log.error("Error checking xref exists", e);
}
}
report.addXref(pwe, exists);
}
}
return report;
} catch(Exception e) {
throw new BotException(e);
}
}
| protected Result scanPathway(File pathwayFile) throws BotException {
try {
XRefResult report = new XRefResult(getCache().getPathwayInfo(pathwayFile));
Pathway pathway = new Pathway();
pathway.readFromXml(pathwayFile, true);
String orgName = pathway.getMappInfo().getOrganism();
Organism org = Organism.fromLatinName(orgName);
if(org == null) org = Organism.fromShortName(orgName);
for(PathwayElement pwe : pathway.getDataObjects()) {
if(pwe.getObjectType() == ObjectType.DATANODE) {
boolean exists = false;
Xref xref = pwe.getXref();
for(IDMapperRdb gdb : gdbs.getGdbs(org)) {
try {
if(xref.getId() != null && xref.getDataSource() != null && gdb.xrefExists(xref)) {
exists = true;
break;
}
} catch (IDMapperException e) {
Logger.log.error("Error checking xref exists", e);
}
}
report.addXref(pwe, exists);
}
}
return report;
} catch(Exception e) {
throw new BotException(e);
}
}
|
diff --git a/stripes/src/net/sourceforge/stripes/tag/MessagesTag.java b/stripes/src/net/sourceforge/stripes/tag/MessagesTag.java
index f0dbe2d..f2a84f0 100644
--- a/stripes/src/net/sourceforge/stripes/tag/MessagesTag.java
+++ b/stripes/src/net/sourceforge/stripes/tag/MessagesTag.java
@@ -1,156 +1,156 @@
/* Copyright (C) 2005 Tim Fennell
*
* 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 license with this software. If not,
* it can be found online at http://www.fsf.org/licensing/licenses/lgpl.html
*/
package net.sourceforge.stripes.tag;
import net.sourceforge.stripes.action.Message;
import net.sourceforge.stripes.controller.StripesConstants;
import net.sourceforge.stripes.controller.StripesFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* <p>Displays a list of non-error messages to the user. The list of messages can come from
* either the request (preferred) or the session (checked 2nd). Lists of messages can be stored
* under any arbitrary key in request or session and the key can be specified to the messages
* tag. If no key is specified then the default key (and therefore default set of messages) is
* used. Note that by default the ActionBeanContext stores messages in a
* {@link net.sourceforge.stripes.controller.FlashScope} which causes them to be exposed as
* request attributes in both the current and subsequent request (assuming a redirect is used).</p>
*
* <p>While similar in concept to the ErrorsTag, the MessagesTag is significantly simpler. It deals
* with a List of Message objects, and does not understand any association between messages and
* form fields, or even between messages and forms. It is designed to be used to show arbitrary
* messages to the user, the prime example being a confirmation message displayed on the subsequent
* page following an action.</p>
*
* <p>The messages tag outputs a header before the messages, the messages themselves, and a footer
* after the messages. Default values are set for each of these four items. Different values
* can be specified in the error messages resource bundle (StripesResources.properties unless you
* have configured another). The default configuration would look like this:
*
* <ul>
* <li>stripes.messages.header={@literal <ul class="messages">}</li>
* <li>stripes.messages.footer={@literal </ul>}</li>
* <li>stripes.messages.beforeMessage={@literal <li>}</li>
* <li>stripes.messages.afterMessage={@literal </li>}</li>
* </ul>
*
* <p>It should also be noted that while the errors tag supports custom headers and footers
* through the use of nested tags, the messages tag does not support this. In fact the
* messages tag does not support body content at all - it will simply be ignored.</p>
*
* @author Tim Fennell
* @since Stripes 1.1.2
*/
public class MessagesTag extends HtmlTagSupport {
/** The header that will be emitted if no header is defined in the resource bundle. */
public static final String DEFAULT_HEADER = "<ul class=\"messages\">";
/** The footer that will be emitted if no footer is defined in the resource bundle. */
public static final String DEFAULT_FOOTER = "</ul>";
/** The key that will be used to perform a scope search for messages. */
private String key = StripesConstants.REQ_ATTR_MESSAGES;
/**
* Does nothing, all processing is performed in doEndTag().
* @return SKIP_BODY in all cases.
*/
public int doStartTag() throws JspException {
return SKIP_BODY;
}
/**
* Outputs the set of messages approprate for this tag.
* @return EVAL_PAGE always
*/
public int doEndTag() throws JspException {
try {
List<Message> messages = getMessages();
if (messages != null && messages.size() > 0) {
JspWriter writer = getPageContext().getOut();
// Output all errors in a standard format
Locale locale = getPageContext().getRequest().getLocale();
ResourceBundle bundle = StripesFilter.getConfiguration()
.getLocalizationBundleFactory().getErrorMessageBundle(locale);
// Fetch the header and footer
String header, footer, beforeMessage, afterMessage;
try { header = bundle.getString("stripes.messages.header"); }
catch (MissingResourceException mre) { header = DEFAULT_HEADER; }
try { footer = bundle.getString("stripes.messages.footer"); }
catch (MissingResourceException mre) { footer = DEFAULT_FOOTER; }
try { beforeMessage = bundle.getString("stripes.messages.beforeMessage"); }
catch (MissingResourceException mre) { beforeMessage = "<li>"; }
- try { afterMessage = bundle.getString("stripes.errors.afterMessage"); }
+ try { afterMessage = bundle.getString("stripes.messages.afterMessage"); }
catch (MissingResourceException mre) { afterMessage = "</li>"; }
// Write out the error messages
writer.write(header);
for (Message message : messages) {
writer.write(beforeMessage);
writer.write(message.getMessage(locale));
writer.write(afterMessage);
}
writer.write(footer);
}
return EVAL_PAGE;
}
catch (IOException e) {
throw new JspException("IOException encountered while writing messages " +
"tag to the JspWriter.", e);
}
}
/** Gets the key that will be used to scope search for messages to display. */
public String getKey() { return key; }
/** Sets the key that will be used to scope search for messages to display. */
public void setKey(String key) { this.key = key; }
/**
* Gets the list of messages that will be displayed by the tag. Looks first in the request
* under the specified key, and if none are found, then looks in session under the same key.
*
* @return List<Message> a possibly null list of messages to display
*/
protected List<Message> getMessages() {
HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();
List<Message> messages = (List<Message>) request.getAttribute( getKey() );
if (messages == null) {
messages = (List<Message>) request.getSession().getAttribute( getKey() );
request.getSession().removeAttribute( getKey() );
}
return messages;
}
}
| true | true | public int doEndTag() throws JspException {
try {
List<Message> messages = getMessages();
if (messages != null && messages.size() > 0) {
JspWriter writer = getPageContext().getOut();
// Output all errors in a standard format
Locale locale = getPageContext().getRequest().getLocale();
ResourceBundle bundle = StripesFilter.getConfiguration()
.getLocalizationBundleFactory().getErrorMessageBundle(locale);
// Fetch the header and footer
String header, footer, beforeMessage, afterMessage;
try { header = bundle.getString("stripes.messages.header"); }
catch (MissingResourceException mre) { header = DEFAULT_HEADER; }
try { footer = bundle.getString("stripes.messages.footer"); }
catch (MissingResourceException mre) { footer = DEFAULT_FOOTER; }
try { beforeMessage = bundle.getString("stripes.messages.beforeMessage"); }
catch (MissingResourceException mre) { beforeMessage = "<li>"; }
try { afterMessage = bundle.getString("stripes.errors.afterMessage"); }
catch (MissingResourceException mre) { afterMessage = "</li>"; }
// Write out the error messages
writer.write(header);
for (Message message : messages) {
writer.write(beforeMessage);
writer.write(message.getMessage(locale));
writer.write(afterMessage);
}
writer.write(footer);
}
return EVAL_PAGE;
}
catch (IOException e) {
throw new JspException("IOException encountered while writing messages " +
"tag to the JspWriter.", e);
}
}
| public int doEndTag() throws JspException {
try {
List<Message> messages = getMessages();
if (messages != null && messages.size() > 0) {
JspWriter writer = getPageContext().getOut();
// Output all errors in a standard format
Locale locale = getPageContext().getRequest().getLocale();
ResourceBundle bundle = StripesFilter.getConfiguration()
.getLocalizationBundleFactory().getErrorMessageBundle(locale);
// Fetch the header and footer
String header, footer, beforeMessage, afterMessage;
try { header = bundle.getString("stripes.messages.header"); }
catch (MissingResourceException mre) { header = DEFAULT_HEADER; }
try { footer = bundle.getString("stripes.messages.footer"); }
catch (MissingResourceException mre) { footer = DEFAULT_FOOTER; }
try { beforeMessage = bundle.getString("stripes.messages.beforeMessage"); }
catch (MissingResourceException mre) { beforeMessage = "<li>"; }
try { afterMessage = bundle.getString("stripes.messages.afterMessage"); }
catch (MissingResourceException mre) { afterMessage = "</li>"; }
// Write out the error messages
writer.write(header);
for (Message message : messages) {
writer.write(beforeMessage);
writer.write(message.getMessage(locale));
writer.write(afterMessage);
}
writer.write(footer);
}
return EVAL_PAGE;
}
catch (IOException e) {
throw new JspException("IOException encountered while writing messages " +
"tag to the JspWriter.", e);
}
}
|
diff --git a/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java b/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java
index 654738a22..984066c9f 100644
--- a/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java
+++ b/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java
@@ -1,3734 +1,3733 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.loader;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.lang.model.type.TypeKind;
import com.redhat.ceylon.cmr.api.ArtifactResult;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.common.Versions;
import com.redhat.ceylon.compiler.java.codegen.AbstractTransformer;
import com.redhat.ceylon.compiler.java.codegen.AnnotationArgument;
import com.redhat.ceylon.compiler.java.codegen.AnnotationConstructorParameter;
import com.redhat.ceylon.compiler.java.codegen.AnnotationFieldName;
import com.redhat.ceylon.compiler.java.codegen.AnnotationInvocation;
import com.redhat.ceylon.compiler.java.codegen.AnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.BooleanLiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.CharacterLiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.CollectionLiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.Decl;
import com.redhat.ceylon.compiler.java.codegen.DeclarationLiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.FloatLiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.IntegerLiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.InvocationAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.LiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.Naming;
import com.redhat.ceylon.compiler.java.codegen.ObjectLiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.ParameterAnnotationTerm;
import com.redhat.ceylon.compiler.java.codegen.StringLiteralAnnotationTerm;
import com.redhat.ceylon.compiler.java.util.Timer;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.loader.mirror.AccessibleMirror;
import com.redhat.ceylon.compiler.loader.mirror.AnnotatedMirror;
import com.redhat.ceylon.compiler.loader.mirror.AnnotationMirror;
import com.redhat.ceylon.compiler.loader.mirror.ClassMirror;
import com.redhat.ceylon.compiler.loader.mirror.FieldMirror;
import com.redhat.ceylon.compiler.loader.mirror.MethodMirror;
import com.redhat.ceylon.compiler.loader.mirror.PackageMirror;
import com.redhat.ceylon.compiler.loader.mirror.TypeMirror;
import com.redhat.ceylon.compiler.loader.mirror.TypeParameterMirror;
import com.redhat.ceylon.compiler.loader.mirror.VariableMirror;
import com.redhat.ceylon.compiler.loader.model.FieldValue;
import com.redhat.ceylon.compiler.loader.model.JavaBeanValue;
import com.redhat.ceylon.compiler.loader.model.JavaMethod;
import com.redhat.ceylon.compiler.loader.model.LazyClass;
import com.redhat.ceylon.compiler.loader.model.LazyClassAlias;
import com.redhat.ceylon.compiler.loader.model.LazyContainer;
import com.redhat.ceylon.compiler.loader.model.LazyElement;
import com.redhat.ceylon.compiler.loader.model.LazyInterface;
import com.redhat.ceylon.compiler.loader.model.LazyInterfaceAlias;
import com.redhat.ceylon.compiler.loader.model.LazyMethod;
import com.redhat.ceylon.compiler.loader.model.LazyModule;
import com.redhat.ceylon.compiler.loader.model.LazyPackage;
import com.redhat.ceylon.compiler.loader.model.LazyTypeAlias;
import com.redhat.ceylon.compiler.loader.model.LazyValue;
import com.redhat.ceylon.compiler.typechecker.analyzer.DeclarationVisitor;
import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Element;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.ModuleImport;
import com.redhat.ceylon.compiler.typechecker.model.Modules;
import com.redhat.ceylon.compiler.typechecker.model.NothingType;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.UnknownType;
import com.redhat.ceylon.compiler.typechecker.model.Value;
/**
* Abstract class of a model loader that can load a model from a compiled Java representation,
* while being agnostic of the reflection API used to load the compiled Java representation.
*
* @author Stéphane Épardaud <[email protected]>
*/
public abstract class AbstractModelLoader implements ModelCompleter, ModelLoader {
public static final String JAVA_BASE_MODULE_NAME = "java.base";
public static final String CEYLON_LANGUAGE = "ceylon.language";
public static final String CEYLON_LANGUAGE_MODEL = "ceylon.language.meta.model";
public static final String CEYLON_LANGUAGE_MODEL_DECLARATION = "ceylon.language.meta.declaration";
private static final String TIMER_MODEL_LOADER_CATEGORY = "model loader";
public static final String JDK_MODULE_VERSION = "7";
public static final String CEYLON_CEYLON_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ceylon";
private static final String CEYLON_MODULE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Module";
private static final String CEYLON_PACKAGE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Package";
private static final String CEYLON_IGNORE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ignore";
private static final String CEYLON_CLASS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Class";
public static final String CEYLON_NAME_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Name";
private static final String CEYLON_SEQUENCED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Sequenced";
private static final String CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FunctionalParameter";
private static final String CEYLON_DEFAULTED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Defaulted";
private static final String CEYLON_SATISFIED_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes";
private static final String CEYLON_CASE_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CaseTypes";
private static final String CEYLON_TYPE_PARAMETERS = "com.redhat.ceylon.compiler.java.metadata.TypeParameters";
private static final String CEYLON_TYPE_INFO_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeInfo";
public static final String CEYLON_ATTRIBUTE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Attribute";
public static final String CEYLON_OBJECT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Object";
public static final String CEYLON_METHOD_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Method";
public static final String CEYLON_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Container";
public static final String CEYLON_LOCAL_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.LocalContainer";
private static final String CEYLON_MEMBERS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Members";
private static final String CEYLON_ANNOTATIONS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Annotations";
public static final String CEYLON_VALUETYPE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ValueType";
public static final String CEYLON_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Alias";
public static final String CEYLON_TYPE_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeAlias";
private static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiation";
private static final String CEYLON_ANNOTATION_INSTANTIATION_ARGUMENTS_MEMBER = "arguments";
private static final String CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION_MEMBER = "primary";
private static final String CEYLON_ANNOTATION_INSTANTIATION_TREE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.AnnotationInstantiationTree";
private static final String CEYLON_STRING_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.StringValue";
private static final String CEYLON_STRING_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.StringExprs";
private static final String CEYLON_BOOLEAN_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.BooleanValue";
private static final String CEYLON_BOOLEAN_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.BooleanExprs";
private static final String CEYLON_INTEGER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.IntegerValue";
private static final String CEYLON_INTEGER_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.IntegerExprs";
private static final String CEYLON_CHARACTER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CharacterValue";
private static final String CEYLON_CHARACTER_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CharacterExprs";
private static final String CEYLON_FLOAT_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FloatValue";
private static final String CEYLON_FLOAT_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.FloatExprs";
private static final String CEYLON_OBJECT_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ObjectValue";
private static final String CEYLON_OBJECT_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ObjectExprs";
private static final String CEYLON_DECLARATION_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.DeclarationValue";
private static final String CEYLON_DECLARATION_EXPRS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.DeclarationExprs";
private static final String CEYLON_PARAMETER_VALUE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ParameterValue";
private static final String CEYLON_TRANSIENT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Transient";
private static final String JAVA_DEPRECATED_ANNOTATION = "java.lang.Deprecated";
private static final String CEYLON_LANGUAGE_ABSTRACT_ANNOTATION = "ceylon.language.AbstractAnnotation$annotation$";
private static final String CEYLON_LANGUAGE_ACTUAL_ANNOTATION = "ceylon.language.ActualAnnotation$annotation$";
private static final String CEYLON_LANGUAGE_ANNOTATION_ANNOTATION = "ceylon.language.AnnotationAnnotation$annotation$";
private static final String CEYLON_LANGUAGE_DEFAULT_ANNOTATION = "ceylon.language.DefaultAnnotation$annotation$";
private static final String CEYLON_LANGUAGE_FORMAL_ANNOTATION = "ceylon.language.FormalAnnotation$annotation$";
private static final String CEYLON_LANGUAGE_LATE_ANNOTATION = "ceylon.language.LateAnnotation$annotation$";
private static final String CEYLON_LANGUAGE_SHARED_ANNOTATION = "ceylon.language.SharedAnnotation$annotation$";
private static final TypeMirror OBJECT_TYPE = simpleCeylonObjectType("java.lang.Object");
private static final TypeMirror CEYLON_OBJECT_TYPE = simpleCeylonObjectType("ceylon.language.Object");
private static final TypeMirror CEYLON_BASIC_TYPE = simpleCeylonObjectType("ceylon.language.Basic");
private static final TypeMirror CEYLON_EXCEPTION_TYPE = simpleCeylonObjectType("ceylon.language.Exception");
private static final TypeMirror CEYLON_REIFIED_TYPE_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.model.ReifiedType");
private static final TypeMirror CEYLON_TYPE_DESCRIPTOR_TYPE = simpleCeylonObjectType("com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor");
private static final TypeMirror STRING_TYPE = simpleJDKObjectType("java.lang.String");
private static final TypeMirror CEYLON_STRING_TYPE = simpleCeylonObjectType("ceylon.language.String");
private static final TypeMirror PRIM_BOOLEAN_TYPE = simpleJDKObjectType("boolean");
private static final TypeMirror BOOLEAN_TYPE = simpleJDKObjectType("java.lang.Boolean");
private static final TypeMirror CEYLON_BOOLEAN_TYPE = simpleCeylonObjectType("ceylon.language.Boolean");
private static final TypeMirror PRIM_BYTE_TYPE = simpleJDKObjectType("byte");
private static final TypeMirror BYTE_TYPE = simpleJDKObjectType("java.lang.Byte");
private static final TypeMirror PRIM_SHORT_TYPE = simpleJDKObjectType("short");
private static final TypeMirror SHORT_TYPE = simpleJDKObjectType("java.lang.Short");
private static final TypeMirror PRIM_INT_TYPE = simpleJDKObjectType("int");
private static final TypeMirror INTEGER_TYPE = simpleJDKObjectType("java.lang.Integer");
private static final TypeMirror PRIM_LONG_TYPE = simpleJDKObjectType("long");
private static final TypeMirror LONG_TYPE = simpleJDKObjectType("java.lang.Long");
private static final TypeMirror CEYLON_INTEGER_TYPE = simpleCeylonObjectType("ceylon.language.Integer");
private static final TypeMirror PRIM_FLOAT_TYPE = simpleJDKObjectType("float");
private static final TypeMirror FLOAT_TYPE = simpleJDKObjectType("java.lang.Float");
private static final TypeMirror PRIM_DOUBLE_TYPE = simpleJDKObjectType("double");
private static final TypeMirror DOUBLE_TYPE = simpleJDKObjectType("java.lang.Double");
private static final TypeMirror CEYLON_FLOAT_TYPE = simpleCeylonObjectType("ceylon.language.Float");
private static final TypeMirror PRIM_CHAR_TYPE = simpleJDKObjectType("char");
private static final TypeMirror CHARACTER_TYPE = simpleJDKObjectType("java.lang.Character");
private static final TypeMirror CEYLON_CHARACTER_TYPE = simpleCeylonObjectType("ceylon.language.Character");
private static final TypeMirror CEYLON_ARRAY_TYPE = simpleCeylonObjectType("ceylon.language.Array");
// this one has no "_" postfix because that's how we look it up
protected static final String JAVA_LANG_ARRAYS = "java.lang.arrays";
protected static final String JAVA_LANG_BYTE_ARRAY = "java.lang.ByteArray";
protected static final String JAVA_LANG_SHORT_ARRAY = "java.lang.ShortArray";
protected static final String JAVA_LANG_INT_ARRAY = "java.lang.IntArray";
protected static final String JAVA_LANG_LONG_ARRAY = "java.lang.LongArray";
protected static final String JAVA_LANG_FLOAT_ARRAY = "java.lang.FloatArray";
protected static final String JAVA_LANG_DOUBLE_ARRAY = "java.lang.DoubleArray";
protected static final String JAVA_LANG_CHAR_ARRAY = "java.lang.CharArray";
protected static final String JAVA_LANG_BOOLEAN_ARRAY = "java.lang.BooleanArray";
protected static final String JAVA_LANG_OBJECT_ARRAY = "java.lang.ObjectArray";
// this one has the "_" postfix because that's what we translate it to
private static final String CEYLON_ARRAYS = "com.redhat.ceylon.compiler.java.language.arrays_";
private static final String CEYLON_BYTE_ARRAY = "com.redhat.ceylon.compiler.java.language.ByteArray";
private static final String CEYLON_SHORT_ARRAY = "com.redhat.ceylon.compiler.java.language.ShortArray";
private static final String CEYLON_INT_ARRAY = "com.redhat.ceylon.compiler.java.language.IntArray";
private static final String CEYLON_LONG_ARRAY = "com.redhat.ceylon.compiler.java.language.LongArray";
private static final String CEYLON_FLOAT_ARRAY = "com.redhat.ceylon.compiler.java.language.FloatArray";
private static final String CEYLON_DOUBLE_ARRAY = "com.redhat.ceylon.compiler.java.language.DoubleArray";
private static final String CEYLON_CHAR_ARRAY = "com.redhat.ceylon.compiler.java.language.CharArray";
private static final String CEYLON_BOOLEAN_ARRAY = "com.redhat.ceylon.compiler.java.language.BooleanArray";
private static final String CEYLON_OBJECT_ARRAY = "com.redhat.ceylon.compiler.java.language.ObjectArray";
private static final TypeMirror JAVA_BYTE_ARRAY_TYPE = simpleJDKObjectType("java.lang.ByteArray");
private static final TypeMirror JAVA_SHORT_ARRAY_TYPE = simpleJDKObjectType("java.lang.ShortArray");
private static final TypeMirror JAVA_INT_ARRAY_TYPE = simpleJDKObjectType("java.lang.IntArray");
private static final TypeMirror JAVA_LONG_ARRAY_TYPE = simpleJDKObjectType("java.lang.LongArray");
private static final TypeMirror JAVA_FLOAT_ARRAY_TYPE = simpleJDKObjectType("java.lang.FloatArray");
private static final TypeMirror JAVA_DOUBLE_ARRAY_TYPE = simpleJDKObjectType("java.lang.DoubleArray");
private static final TypeMirror JAVA_CHAR_ARRAY_TYPE = simpleJDKObjectType("java.lang.CharArray");
private static final TypeMirror JAVA_BOOLEAN_ARRAY_TYPE = simpleJDKObjectType("java.lang.BooleanArray");
private static final TypeMirror JAVA_OBJECT_ARRAY_TYPE = simpleJDKObjectType("java.lang.ObjectArray");
private static TypeMirror simpleJDKObjectType(String name) {
return new SimpleReflType(name, SimpleReflType.Module.JDK, TypeKind.DECLARED);
}
private static TypeMirror simpleCeylonObjectType(String name) {
return new SimpleReflType(name, SimpleReflType.Module.CEYLON, TypeKind.DECLARED);
}
protected Map<String, Declaration> declarationsByName = new HashMap<String, Declaration>();
protected Map<Package, Unit> unitsByPackage = new HashMap<Package, Unit>();
protected TypeParser typeParser;
protected Unit typeFactory;
protected final Set<String> loadedPackages = new HashSet<String>();
protected final Map<String,LazyPackage> packagesByName = new HashMap<String,LazyPackage>();
protected boolean packageDescriptorsNeedLoading = false;
protected boolean isBootstrap;
protected ModuleManager moduleManager;
protected Modules modules;
protected Map<String, ClassMirror> classMirrorCache = new HashMap<String, ClassMirror>();
protected boolean binaryCompatibilityErrorRaised = false;
protected Timer timer;
private Map<String,LazyPackage> modulelessPackages = new HashMap<String,LazyPackage>();
/**
* Loads a given package, if required. This is mostly useful for the javac reflection impl.
*
* @param the module to load the package from
* @param packageName the package name to load
* @param loadDeclarations true to load all the declarations in this package.
* @return
*/
public abstract boolean loadPackage(Module module, String packageName, boolean loadDeclarations);
/**
* Looks up a ClassMirror by name. Uses cached results, and caches the result of calling lookupNewClassMirror
* on cache misses.
*
* @param module the module in which we should find the class
* @param name the name of the Class to load
* @return a ClassMirror for the specified class, or null if not found.
*/
public synchronized final ClassMirror lookupClassMirror(Module module, String name){
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
try{
// Java array classes are not where we expect them
if (JAVA_LANG_OBJECT_ARRAY.equals(name)
|| JAVA_LANG_BOOLEAN_ARRAY.equals(name)
|| JAVA_LANG_BYTE_ARRAY.equals(name)
|| JAVA_LANG_SHORT_ARRAY.equals(name)
|| JAVA_LANG_INT_ARRAY.equals(name)
|| JAVA_LANG_LONG_ARRAY.equals(name)
|| JAVA_LANG_FLOAT_ARRAY.equals(name)
|| JAVA_LANG_DOUBLE_ARRAY.equals(name)
|| JAVA_LANG_CHAR_ARRAY.equals(name)
|| JAVA_LANG_ARRAYS.equals(name)) {
// turn them into their real class location (get rid of the "java.lang" prefix)
name = "com.redhat.ceylon.compiler.java.language" + name.substring(9);
module = getLanguageModule();
}
String cacheKey = cacheKeyByModule(module, name);
// we use containsKey to be able to cache null results
if(classMirrorCache.containsKey(cacheKey))
return classMirrorCache.get(cacheKey);
ClassMirror mirror = lookupNewClassMirror(module, name);
// we even cache null results
classMirrorCache.put(cacheKey, mirror);
return mirror;
}finally{
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
}
protected String cacheKeyByModule(Module module, String name) {
// '/' is allowed in module version but not in module or class name, so we're good
if(module.isDefault())
return module.getNameAsString() + '/' + name; // no version
return module.getNameAsString() + '/' + module.getVersion() + '/' + name;
}
protected boolean lastPartHasLowerInitial(String name) {
int index = name.lastIndexOf('.');
if (index != -1){
name = name.substring(index+1);
}
if(!name.isEmpty()){
char c = name.charAt(0);
return Util.isLowerCase(c);
}
return false;
}
/**
* Looks up a ClassMirror by name. Called by lookupClassMirror on cache misses.
*
* @param module the module in which we should find the given class
* @param name the name of the Class to load
* @return a ClassMirror for the specified class, or null if not found.
*/
protected abstract ClassMirror lookupNewClassMirror(Module module, String name);
/**
* Adds the given module to the set of modules from which we can load classes.
*
* @param module the module
* @param artifact the module's artifact, if any. Can be null.
*/
public abstract void addModuleToClassPath(Module module, ArtifactResult artifact);
/**
* Returns true if the given module has been added to this model loader's classpath.
* Defaults to true.
*/
public boolean isModuleInClassPath(Module module){
return true;
}
/**
* Returns true if the given method is overriding an inherited method (from super class or interfaces).
*/
protected abstract boolean isOverridingMethod(MethodMirror methodMirror);
/**
* Logs a warning.
*/
protected abstract void logWarning(String message);
/**
* Logs a debug message.
*/
protected abstract void logVerbose(String message);
/**
* Logs an error
*/
protected abstract void logError(String message);
public void loadStandardModules(){
// set up the type factory
Module languageModule = findOrCreateModule(CEYLON_LANGUAGE, null);
addModuleToClassPath(languageModule, null);
Package languagePackage = findOrCreatePackage(languageModule, CEYLON_LANGUAGE);
typeFactory.setPackage(languagePackage);
// make sure the jdk modules are loaded
for(String jdkModule : JDKUtils.getJDKModuleNames())
findOrCreateModule(jdkModule, JDK_MODULE_VERSION);
for(String jdkOracleModule : JDKUtils.getOracleJDKModuleNames())
findOrCreateModule(jdkOracleModule, JDK_MODULE_VERSION);
Module jdkModule = findOrCreateModule(JAVA_BASE_MODULE_NAME, JDK_MODULE_VERSION);
/*
* We start by loading java.lang and ceylon.language because we will need them no matter what.
*/
loadPackage(jdkModule, "java.lang", false);
loadPackage(languageModule, "com.redhat.ceylon.compiler.java.metadata", false);
/*
* We do not load the ceylon.language module from class files if we're bootstrapping it
*/
if(!isBootstrap){
loadPackage(languageModule, CEYLON_LANGUAGE, true);
loadPackage(languageModule, CEYLON_LANGUAGE_MODEL, true);
loadPackage(languageModule, CEYLON_LANGUAGE_MODEL_DECLARATION, true);
}
}
/**
* This is meant to be called if your subclass doesn't call loadStandardModules for whatever reason
*/
public void setupWithNoStandardModules() {
Module languageModule = modules.getLanguageModule();
if(languageModule == null)
throw new RuntimeException("Assertion failed: language module is null");
Package languagePackage = languageModule.getPackage(CEYLON_LANGUAGE);
if(languagePackage == null)
throw new RuntimeException("Assertion failed: language package is null");
typeFactory.setPackage(languagePackage);
}
enum ClassType {
ATTRIBUTE, METHOD, OBJECT, CLASS, INTERFACE;
}
private ClassMirror loadClass(Module module, String pkgName, String className) {
ClassMirror moduleClass = null;
try{
loadPackage(module, pkgName, false);
moduleClass = lookupClassMirror(module, className);
}catch(Exception x){
logVerbose("[Failed to complete class "+className+"]");
}
return moduleClass;
}
private Declaration convertNonPrimitiveTypeToDeclaration(Module moduleScope, TypeMirror type, Scope scope, DeclarationType declarationType) {
switch(type.getKind()){
case VOID:
return typeFactory.getAnythingDeclaration();
case ARRAY:
return ((Class)convertToDeclaration(getLanguageModule(), JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE));
case DECLARED:
return convertDeclaredTypeToDeclaration(moduleScope, type, declarationType);
case TYPEVAR:
return safeLookupTypeParameter(scope, type.getQualifiedName());
case WILDCARD:
return typeFactory.getNothingDeclaration();
// those can't happen
case BOOLEAN:
case BYTE:
case CHAR:
case SHORT:
case INT:
case LONG:
case FLOAT:
case DOUBLE:
// all the autoboxing should already have been done
throw new RuntimeException("Expected non-primitive type: "+type);
default:
throw new RuntimeException("Failed to handle type "+type);
}
}
private Declaration convertDeclaredTypeToDeclaration(Module moduleScope, TypeMirror type, DeclarationType declarationType) {
// SimpleReflType does not do declared class so we make an exception for it
String typeName = type.getQualifiedName();
if(type instanceof SimpleReflType){
Module module = null;
switch(((SimpleReflType) type).getModule()){
case CEYLON: module = getLanguageModule(); break;
case JDK : module = getJDKBaseModule(); break;
}
return convertToDeclaration(module, typeName, declarationType);
}
ClassMirror classMirror = type.getDeclaredClass();
Module module = findModuleForClassMirror(classMirror);
if(isImported(moduleScope, module)){
return convertToDeclaration(module, typeName, declarationType);
}else{
logVerbose("Declaration is not from an imported module: "+typeName);
return null;
}
}
protected Declaration convertToDeclaration(ClassMirror classMirror, DeclarationType declarationType) {
// avoid ignored classes
if(classMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
return null;
// avoid module and package descriptors too
if(classMirror.getAnnotation(CEYLON_MODULE_ANNOTATION) != null
|| classMirror.getAnnotation(CEYLON_PACKAGE_ANNOTATION) != null)
return null;
List<Declaration> decls = new ArrayList<Declaration>();
Module module = findModuleForClassMirror(classMirror);
boolean[] alreadyExists = new boolean[1];
Declaration decl = getOrCreateDeclaration(module, classMirror, declarationType,
decls, alreadyExists);
if (alreadyExists[0]) {
return decl;
}
// find its package
String pkgName = getPackageNameForQualifiedClassName(classMirror);
LazyPackage pkg = findOrCreatePackage(module, pkgName);
// find/make its Unit
Unit unit = getCompiledUnit(pkg, classMirror);
// set all the containers
for(Declaration d : decls){
// add it to its Unit
d.setUnit(unit);
unit.addDeclaration(d);
setContainer(classMirror, d, pkg);
}
return decl;
}
protected String getPackageNameForQualifiedClassName(ClassMirror classMirror) {
String qualifiedName = classMirror.getQualifiedName();
// Java array classes we pretend come from java.lang
if(qualifiedName.equals(CEYLON_OBJECT_ARRAY)
|| qualifiedName.equals(CEYLON_BOOLEAN_ARRAY)
|| qualifiedName.equals(CEYLON_BYTE_ARRAY)
|| qualifiedName.equals(CEYLON_SHORT_ARRAY)
|| qualifiedName.equals(CEYLON_INT_ARRAY)
|| qualifiedName.equals(CEYLON_LONG_ARRAY)
|| qualifiedName.equals(CEYLON_FLOAT_ARRAY)
|| qualifiedName.equals(CEYLON_DOUBLE_ARRAY)
|| qualifiedName.equals(CEYLON_CHAR_ARRAY)
|| qualifiedName.equals(CEYLON_ARRAYS)
)
return "java.lang";
else
return unquotePackageName(classMirror.getPackage());
}
private String unquotePackageName(PackageMirror pkg) {
return pkg.getQualifiedName().replace("$", "");
}
private void setContainer(ClassMirror classMirror, Declaration d, LazyPackage pkg) {
// add it to its package if it's not an inner class
if(!classMirror.isInnerClass() && !classMirror.isLocalClass()){
d.setContainer(pkg);
pkg.addCompiledMember(d);
DeclarationVisitor.setVisibleScope(d);
}else if(classMirror.isLocalClass()){
// set its container to the package for now, but don't add it to the package as a member because it's not
d.setContainer(pkg);
((LazyElement)d).setLocal(true);
}else if(d instanceof ClassOrInterface || d instanceof TypeAlias){
// do overloads later, since their container is their abstract superclass's container and
// we have to set that one first
if(d instanceof Class == false || !((Class)d).isOverloaded()){
ClassOrInterface container = getContainer(pkg.getModule(), classMirror);
d.setContainer(container);
// let's not trigger lazy-loading
((LazyContainer)container).addMember(d);
DeclarationVisitor.setVisibleScope(d);
// now we can do overloads
if(d instanceof Class && ((Class)d).getOverloads() != null){
for(Declaration overload : ((Class)d).getOverloads()){
overload.setContainer(container);
// let's not trigger lazy-loading
((LazyContainer)container).addMember(d);
DeclarationVisitor.setVisibleScope(overload);
}
}
}
}
}
private ClassOrInterface getContainer(Module module, ClassMirror classMirror) {
AnnotationMirror containerAnnotation = classMirror.getAnnotation(CEYLON_CONTAINER_ANNOTATION);
if(containerAnnotation != null){
TypeMirror javaClassMirror = (TypeMirror)containerAnnotation.getValue("klass");
String javaClassName = javaClassMirror.getQualifiedName();
ClassOrInterface containerDecl = (ClassOrInterface) convertToDeclaration(module, javaClassName, DeclarationType.TYPE);
if(containerDecl == null)
throw new ModelResolutionException("Failed to load outer type " + javaClassName
+ " for inner type " + classMirror.getQualifiedName().toString());
return containerDecl;
}else{
return (ClassOrInterface) convertToDeclaration(classMirror.getEnclosingClass(), DeclarationType.TYPE);
}
}
protected Declaration getOrCreateDeclaration(Module module, ClassMirror classMirror,
DeclarationType declarationType, List<Declaration> decls, boolean[] alreadyExists) {
alreadyExists[0] = false;
Declaration decl = null;
String className = classMirror.getQualifiedName();
ClassType type;
String prefix;
if(classMirror.isCeylonToplevelAttribute()){
type = ClassType.ATTRIBUTE;
prefix = "V";
}else if(classMirror.isCeylonToplevelMethod()){
type = ClassType.METHOD;
prefix = "V";
}else if(classMirror.isCeylonToplevelObject()){
type = ClassType.OBJECT;
// depends on which one we want
prefix = declarationType == DeclarationType.TYPE ? "C" : "V";
}else if(classMirror.isInterface()){
type = ClassType.INTERFACE;
prefix = "C";
}else{
type = ClassType.CLASS;
prefix = "C";
}
String key = cacheKeyByModule(module, prefix + className);
// see if we already have it
if(declarationsByName.containsKey(key)){
alreadyExists[0] = true;
return declarationsByName.get(key);
}
checkBinaryCompatibility(classMirror);
boolean isCeylon = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null;
// make it
switch(type){
case ATTRIBUTE:
decl = makeToplevelAttribute(classMirror);
setDeclarationVisibility(decl, classMirror, classMirror, true);
break;
case METHOD:
decl = makeToplevelMethod(classMirror);
setDeclarationVisibility(decl, classMirror, classMirror, true);
break;
case OBJECT:
// we first make a class
Declaration objectClassDecl = makeLazyClass(classMirror, null, null, true);
declarationsByName.put(cacheKeyByModule(module, "C"+className), objectClassDecl);
decls.add(objectClassDecl);
// then we make a value for it
Declaration objectDecl = makeToplevelAttribute(classMirror);
declarationsByName.put(cacheKeyByModule(module, "V"+className), objectDecl);
decls.add(objectDecl);
// which one did we want?
decl = declarationType == DeclarationType.TYPE ? objectClassDecl : objectDecl;
setDeclarationVisibility(objectClassDecl, classMirror, classMirror, true);
setDeclarationVisibility(objectDecl, classMirror, classMirror, true);
break;
case CLASS:
if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){
decl = makeClassAlias(classMirror);
setDeclarationVisibility(decl, classMirror, classMirror, true);
}else if(classMirror.getAnnotation(CEYLON_TYPE_ALIAS_ANNOTATION) != null){
decl = makeTypeAlias(classMirror);
setDeclarationVisibility(decl, classMirror, classMirror, true);
}else{
List<MethodMirror> constructors = getClassConstructors(classMirror);
if (!constructors.isEmpty()) {
if (constructors.size() > 1) {
decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon);
} else {
// single constructor
MethodMirror constructor = constructors.get(0);
// if the class and constructor have different visibility, we pretend there's an overload of one
// if it's a ceylon class we don't care that they don't match sometimes, like for inner classes
// where the constructor is protected because we want to use an accessor, in this case the class
// visibility is to be used
if(isCeylon || getJavaVisibility(classMirror) == getJavaVisibility(constructor)){
decl = makeLazyClass(classMirror, null, constructor, false);
setDeclarationVisibility(decl, classMirror, classMirror, isCeylon);
}else{
decl = makeOverloadedConstructor(constructors, classMirror, decls, isCeylon);
}
}
} else if(getJavaVisibility(classMirror) != JavaVisibility.PRIVATE){
Class klass = (Class)makeOverloadedConstructor(constructors, classMirror, decls, isCeylon);
decl = klass;
LazyClass subdecl = makeLazyClass(classMirror, klass, null, false);
// no visibility for subdecl (private)
subdecl.setOverloaded(true);
klass.getOverloads().add(subdecl);
decls.add(subdecl);
} else {
// private class does not need a constructor
decl = makeLazyClass(classMirror, null, null, false);
}
}
break;
case INTERFACE:
if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){
decl = makeInterfaceAlias(classMirror);
}else{
decl = makeLazyInterface(classMirror);
}
setDeclarationVisibility(decl, classMirror, classMirror, isCeylon);
break;
}
// objects have special handling above
if(type != ClassType.OBJECT){
declarationsByName.put(key, decl);
decls.add(decl);
}
return decl;
}
private Declaration makeOverloadedConstructor(List<MethodMirror> constructors, ClassMirror classMirror, List<Declaration> decls, boolean isCeylon) {
// If the class has multiple constructors we make a copy of the class
// for each one (each with it's own single constructor) and make them
// a subclass of the original
Class supercls = makeLazyClass(classMirror, null, null, false);
// the abstraction class gets the class modifiers
setDeclarationVisibility(supercls, classMirror, classMirror, isCeylon);
supercls.setAbstraction(true);
List<Declaration> overloads = new ArrayList<Declaration>(constructors.size());
// all filtering is done in getClassConstructors
for (MethodMirror constructor : constructors) {
LazyClass subdecl = makeLazyClass(classMirror, supercls, constructor, false);
// the subclasses class get the constructor modifiers
setDeclarationVisibility(subdecl, constructor, classMirror, isCeylon);
subdecl.setOverloaded(true);
overloads.add(subdecl);
decls.add(subdecl);
}
supercls.setOverloads(overloads);
return supercls;
}
private void setDeclarationVisibility(Declaration decl, AccessibleMirror mirror, ClassMirror classMirror, boolean isCeylon) {
if(isCeylon){
decl.setShared(mirror.isPublic());
}else{
decl.setShared(mirror.isPublic() || (mirror.isDefaultAccess() && classMirror.isInnerClass()) || mirror.isProtected());
decl.setPackageVisibility(mirror.isDefaultAccess());
decl.setProtectedVisibility(mirror.isProtected());
}
}
private enum JavaVisibility {
PRIVATE, PACKAGE, PROTECTED, PUBLIC;
}
private JavaVisibility getJavaVisibility(AccessibleMirror mirror) {
if(mirror.isPublic())
return JavaVisibility.PUBLIC;
if(mirror.isProtected())
return JavaVisibility.PROTECTED;
if(mirror.isDefaultAccess())
return JavaVisibility.PACKAGE;
return JavaVisibility.PRIVATE;
}
private Declaration makeClassAlias(ClassMirror classMirror) {
return new LazyClassAlias(classMirror, this);
}
private Declaration makeTypeAlias(ClassMirror classMirror) {
return new LazyTypeAlias(classMirror, this);
}
private Declaration makeInterfaceAlias(ClassMirror classMirror) {
return new LazyInterfaceAlias(classMirror, this);
}
private void checkBinaryCompatibility(ClassMirror classMirror) {
// let's not report it twice
if(binaryCompatibilityErrorRaised)
return;
AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION);
if(annotation == null)
return; // Java class, no check
Integer major = (Integer) annotation.getValue("major");
if(major == null)
major = 0;
Integer minor = (Integer) annotation.getValue("minor");
if(minor == null)
minor = 0;
if(major != Versions.JVM_BINARY_MAJOR_VERSION
|| minor != Versions.JVM_BINARY_MINOR_VERSION){
logError("Ceylon class " + classMirror.getQualifiedName() + " was compiled by an incompatible version of the Ceylon compiler"
+"\nThe class was compiled using "+major+"."+minor+"."
+"\nThis compiler supports "+Versions.JVM_BINARY_MAJOR_VERSION+"."+Versions.JVM_BINARY_MINOR_VERSION+"."
+"\nPlease try to recompile your module using a compatible compiler."
+"\nBinary compatibility will only be supported after Ceylon 1.0.");
binaryCompatibilityErrorRaised = true;
}
}
private List<MethodMirror> getClassConstructors(ClassMirror classMirror) {
LinkedList<MethodMirror> constructors = new LinkedList<MethodMirror>();
boolean isFromJDK = isFromJDK(classMirror);
for(MethodMirror methodMirror : classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(!methodMirror.isConstructor())
continue;
// FIXME: tmp hack to skip constructors that have type params as we don't handle them yet
if(!methodMirror.getTypeParameters().isEmpty())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isFromJDK
&& !methodMirror.isPublic()
// allow protected because we can subclass them, but not package-private because we can't define
// classes in the jdk packages
&& !methodMirror.isProtected())
continue;
// if we are expecting Ceylon code, check that we have enough reified type parameters
if(classMirror.getAnnotation(AbstractModelLoader.CEYLON_CEYLON_ANNOTATION) != null){
List<AnnotationMirror> tpAnnotations = getTypeParametersFromAnnotations(classMirror);
int tpCount = tpAnnotations != null ? tpAnnotations.size() : classMirror.getTypeParameters().size();
if(!checkReifiedTypeDescriptors(tpCount, classMirror, methodMirror, true))
continue;
}
constructors.add(methodMirror);
}
return constructors;
}
private boolean checkReifiedTypeDescriptors(int tpCount, ClassMirror container, MethodMirror methodMirror, boolean isConstructor) {
List<VariableMirror> params = methodMirror.getParameters();
int actualTypeDescriptorParameters = 0;
for(VariableMirror param : params){
if(param.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null && sameType(CEYLON_TYPE_DESCRIPTOR_TYPE, param.getType())){
actualTypeDescriptorParameters++;
}else
break;
}
if(tpCount != actualTypeDescriptorParameters){
if(isConstructor)
logError("Constructor for '"+container.getQualifiedName()+"' should take "+tpCount
+" reified type arguments (TypeDescriptor) but has '"+actualTypeDescriptorParameters+"': skipping constructor.");
else
logError("Method '"+container.getQualifiedName()+"."+methodMirror.getName()+"' should take "+tpCount
+" reified type arguments (TypeDescriptor) but has '"+actualTypeDescriptorParameters+"': method is invalid.");
return false;
}
return true;
}
protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) {
Unit unit = unitsByPackage.get(pkg);
if(unit == null){
unit = new Unit();
unit.setPackage(pkg);
unitsByPackage.put(pkg, unit);
}
return unit;
}
protected LazyValue makeToplevelAttribute(ClassMirror classMirror) {
LazyValue value = new LazyValue(classMirror, this);
return value;
}
protected LazyMethod makeToplevelMethod(ClassMirror classMirror) {
LazyMethod method = new LazyMethod(classMirror, this);
return method;
}
protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror constructor, boolean forTopLevelObject) {
LazyClass klass = new LazyClass(classMirror, this, superClass, constructor, forTopLevelObject);
klass.setAnonymous(classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION) != null);
klass.setAnnotation(classMirror.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null);
if(klass.isCeylon())
klass.setAbstract(classMirror.getAnnotation(CEYLON_LANGUAGE_ABSTRACT_ANNOTATION) != null
// for toplevel classes if the annotation is missing we respect the java abstract modifier
// for member classes that would be ambiguous between formal and abstract so we don't and require
// the model annotation
|| (!classMirror.isInnerClass() && !classMirror.isLocalClass() && classMirror.isAbstract()));
else
klass.setAbstract(classMirror.isAbstract());
klass.setFormal(classMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null);
klass.setDefault(classMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null);
klass.setActual(classMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null);
klass.setFinal(classMirror.isFinal());
klass.setStaticallyImportable(!klass.isCeylon() && classMirror.isStatic());
return klass;
}
protected LazyInterface makeLazyInterface(ClassMirror classMirror) {
LazyInterface iface = new LazyInterface(classMirror, this);
return iface;
}
public synchronized Declaration convertToDeclaration(Module module, String typeName, DeclarationType declarationType) {
// FIXME: this needs to move to the type parser and report warnings
//This should be done where the TypeInfo annotation is parsed
//to avoid retarded errors because of a space after a comma
typeName = typeName.trim();
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
try{
if ("ceylon.language.Nothing".equals(typeName)) {
return new NothingType(typeFactory);
} else if ("java.lang.Throwable".equals(typeName)) {
// FIXME: this being here is highly dubious
return convertToDeclaration(modules.getLanguageModule(), "ceylon.language.Exception", declarationType);
}
ClassMirror classMirror = lookupClassMirror(module, typeName);
if (classMirror == null) {
// special case when bootstrapping because we may need to pull the decl from the typechecked model
if(isBootstrap && typeName.startsWith(CEYLON_LANGUAGE+".")){
ProducedType languageType = findLanguageModuleDeclarationForBootstrap(typeName);
if(languageType != null)
return languageType.getDeclaration();
}
throw new ModelResolutionException("Failed to resolve "+typeName);
}
// we only allow source loading when it's java code we're compiling in the same go
// (well, technically before the ceylon code)
if(classMirror.isLoadedFromSource() && !classMirror.isJavaSource())
return null;
return convertToDeclaration(classMirror, declarationType);
}finally{
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
}
protected TypeParameter safeLookupTypeParameter(Scope scope, String name) {
TypeParameter param = lookupTypeParameter(scope, name);
if(param == null)
throw new ModelResolutionException("Type param "+name+" not found in "+scope);
return param;
}
private TypeParameter lookupTypeParameter(Scope scope, String name) {
if(scope instanceof Method){
Method m = (Method) scope;
for(TypeParameter param : m.getTypeParameters()){
if(param.getName().equals(name))
return param;
}
if (!m.isToplevel()) {
// look it up in its container
return lookupTypeParameter(scope.getContainer(), name);
} else {
// not found
return null;
}
}else if(scope instanceof ClassOrInterface
|| scope instanceof TypeAlias){
TypeDeclaration decl = (TypeDeclaration) scope;
for(TypeParameter param : decl.getTypeParameters()){
if(param.getName().equals(name))
return param;
}
if (!decl.isToplevel()) {
// look it up in its container
return lookupTypeParameter(scope.getContainer(), name);
} else {
// not found
return null;
}
}else
throw new ModelResolutionException("Type param "+name+" lookup not supported for scope "+scope);
}
//
// Packages
public synchronized LazyPackage findExistingPackage(Module module, String pkgName){
String quotedPkgName = Util.quoteJavaKeywords(pkgName);
LazyPackage pkg = findCachedPackage(module, quotedPkgName);
if(pkg != null)
return pkg;
// special case for the jdk module
String moduleName = module.getNameAsString();
if(AbstractModelLoader.isJDKModule(moduleName)){
if(JDKUtils.isJDKPackage(moduleName, pkgName) || JDKUtils.isOracleJDKPackage(moduleName, pkgName)){
return findOrCreatePackage(module, pkgName);
}
return null;
}
// only create it if it exists
if(loadPackage(module, pkgName, false)){
return findOrCreatePackage(module, pkgName);
}
return null;
}
private LazyPackage findCachedPackage(Module module, String quotedPkgName) {
LazyPackage pkg = packagesByName.get(cacheKeyByModule(module, quotedPkgName));
if(pkg != null){
// only return it if it matches the module we're looking for, because if it doesn't we have an issue already logged
// for a direct dependency on same module different versions logged, so no need to confuse this further
if(module != null && pkg.getModule() != null && !module.equals(pkg.getModule()))
return null;
return pkg;
}
return null;
}
public synchronized LazyPackage findOrCreatePackage(Module module, final String pkgName) {
String quotedPkgName = Util.quoteJavaKeywords(pkgName);
LazyPackage pkg = findCachedPackage(module, quotedPkgName);
if(pkg != null)
return pkg;
// try to find it from the module, perhaps it already got created and we didn't catch it
if(module instanceof LazyModule){
pkg = (LazyPackage) ((LazyModule) module).findPackageNoLazyLoading(pkgName);
}else if(module != null){
pkg = (LazyPackage) module.getDirectPackage(pkgName);
}
boolean isNew = pkg == null;
if(pkg == null){
pkg = new LazyPackage(this);
// FIXME: some refactoring needed
pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\.")));
}
packagesByName.put(cacheKeyByModule(module, quotedPkgName), pkg);
// only bind it if we already have a module
if(isNew && module != null){
pkg.setModule(module);
if(module instanceof LazyModule)
((LazyModule) module).addPackage(pkg);
else
module.getPackages().add(pkg);
}
// only load package descriptors for new packages after a certain phase
if(packageDescriptorsNeedLoading)
loadPackageDescriptor(pkg);
return pkg;
}
public synchronized void loadPackageDescriptors() {
for(Package pkg : packagesByName.values()){
loadPackageDescriptor(pkg);
}
packageDescriptorsNeedLoading = true;
}
private void loadPackageDescriptor(Package pkg) {
// Don't try to load a package descriptor for ceylon.language
// if we're bootstrapping
if (isBootstrap
&& pkg.getQualifiedNameString().startsWith("ceylon.language")) {
return;
}
// let's not load package descriptors for Java modules
if(pkg.getModule() != null
&& ((LazyModule)pkg.getModule()).isJava()){
pkg.setShared(true);
return;
}
String quotedQualifiedName = Util.quoteJavaKeywords(pkg.getQualifiedNameString());
// FIXME: not sure the toplevel package can have a package declaration
String className = quotedQualifiedName.isEmpty() ? "package" : quotedQualifiedName + ".package";
logVerbose("[Trying to look up package from "+className+"]");
Module module = pkg.getModule();
if(module == null)
throw new RuntimeException("Assertion failed: module is null for package "+pkg.getNameAsString());
ClassMirror packageClass = loadClass(module, quotedQualifiedName, className);
if(packageClass == null){
logVerbose("[Failed to complete "+className+"]");
// missing: leave it private
return;
}
// did we compile it from source or class?
if(packageClass.isLoadedFromSource()){
// must have come from source, in which case we walked it and
// loaded its values already
logVerbose("[We are compiling the package "+className+"]");
return;
}
loadCompiledPackage(packageClass, pkg);
}
private void loadCompiledPackage(ClassMirror packageClass, Package pkg) {
String name = getAnnotationStringValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "name");
Boolean shared = getAnnotationBooleanValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "shared");
// FIXME: validate the name?
if(name == null || name.isEmpty()){
logWarning("Package class "+pkg.getQualifiedNameString()+" contains no name, ignoring it");
return;
}
if(shared == null){
logWarning("Package class "+pkg.getQualifiedNameString()+" contains no shared, ignoring it");
return;
}
pkg.setShared(shared);
}
protected Module lookupModuleInternal(String packageName) {
for(Module module : modules.getListOfModules()){
// don't try the default module because it will always say yes
if(module.isDefault())
continue;
// skip modules we're not loading things from
if(module != getLanguageModule()
&& !isModuleInClassPath(module))
continue;
if(module instanceof LazyModule){
if(((LazyModule)module).containsPackage(packageName))
return module;
}else if(isSubPackage(module.getNameAsString(), packageName)){
return module;
}
}
if(JDKUtils.isJDKAnyPackage(packageName)
|| JDKUtils.isOracleJDKAnyPackage(packageName)){
String moduleName = JDKUtils.getJDKModuleNameForPackage(packageName);
return findModule(moduleName, JDK_MODULE_VERSION);
}
if(packageName.startsWith("com.redhat.ceylon.compiler.java.runtime")
|| packageName.startsWith("com.redhat.ceylon.compiler.java.language")){
return getLanguageModule();
}
return modules.getDefaultModule();
}
private boolean isSubPackage(String moduleName, String pkgName) {
return pkgName.equals(moduleName)
|| pkgName.startsWith(moduleName+".");
}
//
// Modules
/**
* Finds or creates a new module. This is mostly useful to force creation of modules such as jdk
* or ceylon.language modules.
*/
protected synchronized Module findOrCreateModule(String moduleName, String version) {
// FIXME: we don't have any version??? If not this should be private
boolean isJava = false;
boolean defaultModule = false;
// make sure it isn't loaded
Module module = getLoadedModule(moduleName);
if(module != null)
return module;
if(JDKUtils.isJDKModule(moduleName) || JDKUtils.isOracleJDKModule(moduleName)){
isJava = true;
}
java.util.List<String> moduleNameList = Arrays.asList(moduleName.split("\\."));
module = moduleManager.getOrCreateModule(moduleNameList, version);
// make sure that when we load the ceylon language module we set it to where
// the typechecker will look for it
if(moduleName.equals(CEYLON_LANGUAGE)
&& modules.getLanguageModule() == null){
modules.setLanguageModule(module);
}
// TRICKY We do this only when isJava is true to prevent resetting
// the value to false by mistake. LazyModule get's created with
// this attribute to false by default, so it should work
if (isJava && module instanceof LazyModule) {
((LazyModule)module).setJava(true);
}
// FIXME: this can't be that easy.
module.setAvailable(true);
module.setDefault(defaultModule);
return module;
}
public synchronized boolean loadCompiledModule(Module module) {
if(module.isDefault())
return false;
String pkgName = module.getNameAsString();
if(pkgName.isEmpty())
return false;
String moduleClassName = pkgName + ".module_";
logVerbose("[Trying to look up module from "+moduleClassName+"]");
ClassMirror moduleClass = loadClass(module, pkgName, moduleClassName);
if(moduleClass != null){
// load its module annotation
return loadCompiledModule(module, moduleClass, moduleClassName);
}
// give up
return false;
}
private boolean loadCompiledModule(Module module, ClassMirror moduleClass, String moduleClassName) {
String name = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "name");
String version = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "version");
if(name == null || name.isEmpty()){
logWarning("Module class "+moduleClassName+" contains no name, ignoring it");
return false;
}
if(!name.equals(module.getNameAsString())){
logWarning("Module class "+moduleClassName+" declares an invalid name: "+name+". It should be: "+module.getNameAsString());
return false;
}
if(version == null || version.isEmpty()){
logWarning("Module class "+moduleClassName+" contains no version, ignoring it");
return false;
}
if(!version.equals(module.getVersion())){
logWarning("Module class "+moduleClassName+" declares an invalid version: "+version+". It should be: "+module.getVersion());
return false;
}
int major = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "major", 0);
int minor = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "minor", 0);
module.setMajor(major);
module.setMinor(minor);
List<AnnotationMirror> imports = getAnnotationArrayValue(moduleClass, CEYLON_MODULE_ANNOTATION, "dependencies");
if(imports != null){
for (AnnotationMirror importAttribute : imports) {
String dependencyName = (String) importAttribute.getValue("name");
if (dependencyName != null) {
String dependencyVersion = (String) importAttribute.getValue("version");
Module dependency = moduleManager.getOrCreateModule(ModuleManager.splitModuleName(dependencyName), dependencyVersion);
Boolean optionalVal = (Boolean) importAttribute.getValue("optional");
Boolean exportVal = (Boolean) importAttribute.getValue("export");
ModuleImport moduleImport = moduleManager.findImport(module, dependency);
if (moduleImport == null) {
boolean optional = optionalVal != null && optionalVal;
boolean export = exportVal != null && exportVal;
moduleImport = new ModuleImport(dependency, optional, export);
module.getImports().add(moduleImport);
}
}
}
}
module.setAvailable(true);
modules.getListOfModules().add(module);
Module languageModule = modules.getLanguageModule();
module.setLanguageModule(languageModule);
if(module != languageModule){
ModuleImport moduleImport = moduleManager.findImport(module, languageModule);
if (moduleImport == null) {
moduleImport = new ModuleImport(languageModule, false, false);
module.getImports().add(moduleImport);
}
}
return true;
}
//
// Utils for loading type info from the model
@SuppressWarnings("unchecked")
private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type, String field) {
return (List<T>) getAnnotationValue(mirror, type, field);
}
@SuppressWarnings("unchecked")
private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type) {
return (List<T>) getAnnotationValue(mirror, type);
}
private String getAnnotationStringValue(AnnotatedMirror mirror, String type) {
return getAnnotationStringValue(mirror, type, "value");
}
private String getAnnotationStringValue(AnnotatedMirror mirror, String type, String field) {
return (String) getAnnotationValue(mirror, type, field);
}
private TypeMirror getAnnotationClassValue(AnnotatedMirror mirror, String type, String field) {
return (TypeMirror) getAnnotationValue(mirror, type, field);
}
private List<Short> getAnnotationShortArrayValue(AnnotatedMirror mirror, String type, String field) {
return getAnnotationArrayValue(mirror, type, field);
}
private Boolean getAnnotationBooleanValue(AnnotatedMirror mirror, String type, String field) {
return (Boolean) getAnnotationValue(mirror, type, field);
}
private int getAnnotationIntegerValue(AnnotatedMirror mirror, String type, String field, int defaultValue) {
Integer val = (Integer) getAnnotationValue(mirror, type, field);
return val != null ? val : defaultValue;
}
private List<TypeMirror> getAnnotationClassValues(AnnotationMirror annotation, String field) {
return (List<TypeMirror>)annotation.getValue(field);
}
private List<String> getAnnotationStringValues(AnnotationMirror annotation, String field) {
return (List<String>)annotation.getValue(field);
}
private List<Integer> getAnnotationIntegerValues(AnnotationMirror annotation, String field) {
return (List<Integer>)annotation.getValue(field);
}
private List<Boolean> getAnnotationBooleanValues(AnnotationMirror annotation, String field) {
return (List<Boolean>)annotation.getValue(field);
}
private List<Long> getAnnotationLongValues(AnnotationMirror annotation, String field) {
return (List<Long>)annotation.getValue(field);
}
private List<Double> getAnnotationDoubleValues(AnnotationMirror annotation, String field) {
return (List<Double>)annotation.getValue(field);
}
private List<AnnotationMirror> getAnnotationAnnoValues(AnnotationMirror annotation, String field) {
return (List<AnnotationMirror>)annotation.getValue(field);
}
private Object getAnnotationValue(AnnotatedMirror mirror, String type) {
return getAnnotationValue(mirror, type, "value");
}
private Object getAnnotationValue(AnnotatedMirror mirror, String type, String fieldName) {
AnnotationMirror annotation = mirror.getAnnotation(type);
if(annotation != null){
return annotation.getValue(fieldName);
}
return null;
}
//
// ModelCompleter
@Override
public synchronized void complete(LazyInterface iface) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
complete(iface, iface.classMirror);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
@Override
public synchronized void completeTypeParameters(LazyInterface iface) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
completeTypeParameters(iface, iface.classMirror);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
@Override
public synchronized void complete(LazyClass klass) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
complete(klass, klass.classMirror);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
@Override
public synchronized void completeTypeParameters(LazyClass klass) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
completeTypeParameters(klass, klass.classMirror);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
@Override
public synchronized void completeTypeParameters(LazyClassAlias lazyClassAlias) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
completeLazyAliasTypeParameters(lazyClassAlias, lazyClassAlias.classMirror);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
@Override
public synchronized void completeTypeParameters(LazyInterfaceAlias lazyInterfaceAlias) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
completeLazyAliasTypeParameters(lazyInterfaceAlias, lazyInterfaceAlias.classMirror);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
@Override
public synchronized void completeTypeParameters(LazyTypeAlias lazyTypeAlias) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
completeLazyAliasTypeParameters(lazyTypeAlias, lazyTypeAlias.classMirror);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
@Override
public synchronized void complete(LazyInterfaceAlias alias) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
@Override
public synchronized void complete(LazyClassAlias alias) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION);
// must be a class
Class declaration = (Class) alias.getExtendedType().getDeclaration();
// Find the instantiator method
MethodMirror instantiator = null;
ClassMirror instantiatorClass = alias.isToplevel() ? alias.classMirror : alias.classMirror.getEnclosingClass();
for (MethodMirror method : instantiatorClass.getDirectMethods()) {
// If we're finding things based on their name, shouldn't we
// we using Naming to do it?
if (method.getName().equals(alias.getName() + "$aliased$")) {
instantiator = method;
break;
}
}
// Read the parameters from the instantiator, rather than the aliased class
if (instantiator != null) {
setParameters(alias, instantiator, true, alias);
}
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
private ParameterList copyParameterList(LazyClassAlias alias, Class declaration) {
ParameterList newList = new ParameterList();
// FIXME: multiple param lists?
newList.setNamedParametersSupported(declaration.getParameterList().isNamedParametersSupported());
for(Parameter p : declaration.getParameterList().getParameters()){
// FIXME: functionalparams?
Parameter newParam = new Parameter();
MethodOrValue mov;
if (p.getModel() instanceof Value) {
Value value = new Value();
mov = value;
} else {
Method method = new Method();
mov = method;
}
mov.setContainer(alias);
mov.setUnboxed(p.getModel().getUnboxed());
mov.setUncheckedNullType(p.getModel().hasUncheckedNullType());
mov.setUnit(p.getModel().getUnit());
mov.setType(p.getModel().getProducedTypedReference(alias.getExtendedType(), Collections.<ProducedType>emptyList()).getType());
newParam.setModel(mov);
newParam.setName(p.getName());
DeclarationVisitor.setVisibleScope(mov);
newParam.setDeclaration(alias);
newParam.setSequenced(p.isSequenced());
alias.addMember(mov);
newList.getParameters().add(newParam);
}
return newList;
}
@Override
public synchronized void complete(LazyTypeAlias alias) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
completeLazyAlias(alias, alias.classMirror, CEYLON_TYPE_ALIAS_ANNOTATION);
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
private void completeLazyAliasTypeParameters(TypeDeclaration alias, ClassMirror mirror) {
// type parameters
setTypeParameters(alias, mirror);
}
private void completeLazyAlias(TypeDeclaration alias, ClassMirror mirror, String aliasAnnotationName) {
// now resolve the extended type
AnnotationMirror aliasAnnotation = mirror.getAnnotation(aliasAnnotationName);
String extendedTypeString = (String) aliasAnnotation.getValue();
ProducedType extendedType = decodeType(extendedTypeString, alias, Decl.getModuleContainer(alias), "alias target");
alias.setExtendedType(extendedType);
}
private void completeTypeParameters(ClassOrInterface klass, ClassMirror classMirror) {
setTypeParameters(klass, classMirror);
}
private void complete(ClassOrInterface klass, ClassMirror classMirror) {
Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>();
boolean isFromJDK = isFromJDK(classMirror);
boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null);
// now that everything has containers, do the inner classes
if(klass instanceof Class == false || !((Class)klass).isOverloaded()){
// this will not load inner classes of overloads, but that's fine since we want them in the
// abstracted super class (the real one)
addInnerClasses(klass, classMirror);
}
// Java classes with multiple constructors get turned into multiple Ceylon classes
// Here we get the specific constructor that was assigned to us (if any)
MethodMirror constructor = null;
if (klass instanceof LazyClass) {
constructor = ((LazyClass)klass).getConstructor();
}
// Turn a list of possibly overloaded methods into a map
// of lists that contain methods with the same name
Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>();
for(MethodMirror methodMirror : classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(methodMirror.isStaticInit())
continue;
if(isCeylon && methodMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isFromJDK && !methodMirror.isPublic())
continue;
String methodName = methodMirror.getName();
List<MethodMirror> homonyms = methods.get(methodName);
if (homonyms == null) {
homonyms = new LinkedList<MethodMirror>();
methods.put(methodName, homonyms);
}
homonyms.add(methodMirror);
}
// Add the methods
for(List<MethodMirror> methodMirrors : methods.values()){
boolean isOverloaded = methodMirrors.size() > 1;
List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null;
for (MethodMirror methodMirror : methodMirrors) {
String methodName = methodMirror.getName();
if(methodMirror.isConstructor() || isInstantiator(methodMirror)) {
break;
} else if(isGetter(methodMirror)) {
// simple attribute
addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon);
} else if(isSetter(methodMirror)) {
// We skip setters for now and handle them later
variables.put(methodMirror, methodMirrors);
} else if(isHashAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'hash' attribute from 'hashCode' method
addValue(klass, methodMirror, "hash", isCeylon);
} else if(isStringAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'string' attribute from 'toString' method
addValue(klass, methodMirror, "string", isCeylon);
- } else {
+ } else if(!methodMirror.getName().equals("hash")
+ && !methodMirror.getName().equals("string")){
// normal method
Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded);
if (isOverloaded) {
overloads.add(m);
}
}
}
if (overloads != null && !overloads.isEmpty()) {
// We create an extra "abstraction" method for overloaded methods
Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false);
abstractionMethod.setAbstraction(true);
abstractionMethod.setOverloads(overloads);
abstractionMethod.setType(new UnknownType(typeFactory).getType());
}
}
for(FieldMirror fieldMirror : classMirror.getDirectFields()){
// We skip members marked with @Ignore
if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(isCeylon && fieldMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isFromJDK && !fieldMirror.isPublic())
continue;
String name = fieldMirror.getName();
// skip the field if "we've already got one"
- boolean requireFieldPrefix = klass.getDirectMember(name, null, false) != null
+ boolean conflicts = klass.getDirectMember(name, null, false) != null
|| "equals".equals(name)
|| "string".equals(name)
|| "hash".equals(name);
- if (!requireFieldPrefix) {
+ if (!conflicts) {
addValue(klass, fieldMirror.getName(), fieldMirror, isCeylon);
- }else{
- addValue(klass, fieldMirror.getName()+"_field", fieldMirror, isCeylon);
}
}
// Having loaded methods and values, we can now set the constructor parameters
if(constructor != null
&& (!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType()))
setParameters((Class)klass, constructor, isCeylon, klass);
// Now marry-up attributes and parameters)
if (klass instanceof Class) {
for (Declaration m : klass.getMembers()) {
if (Decl.isValue(m)) {
Value v = (Value)m;
Parameter p = ((Class)klass).getParameter(v.getName());
if (p != null) {
p.setHidden(true);
}
}
}
}
// Now mark all Values for which Setters exist as variable
for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){
MethodMirror setter = setterEntry.getKey();
String name = getJavaAttributeName(setter.getName());
Declaration decl = klass.getMember(name, null, false);
boolean foundGetter = false;
// skip Java fields, which we only get if there is no getter method, in that case just add the setter method
if (decl instanceof Value && decl instanceof FieldValue == false) {
Value value = (Value)decl;
VariableMirror setterParam = setter.getParameters().get(0);
ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT,
"setter '"+setter.getName()+"'", klass);
// only add the setter if it has exactly the same type as the getter
if(paramType.isExactly(value.getType())){
foundGetter = true;
value.setVariable(true);
if(decl instanceof JavaBeanValue)
((JavaBeanValue)decl).setSetterName(setter.getName());
}else
logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method");
}
if(!foundGetter){
// it was not a setter, it was a method, let's add it as such
addMethod(klass, setter, isCeylon, false);
}
}
// In some cases, where all constructors are ignored, we can end up with no constructor, so
// pretend we have one which takes no parameters (eg. ceylon.language.String).
if(klass instanceof Class
&& !((Class) klass).isAbstraction()
&& !klass.isAnonymous()
&& ((Class) klass).getParameterList() == null){
((Class) klass).setParameterList(new ParameterList());
}
setExtendedType(klass, classMirror);
setSatisfiedTypes(klass, classMirror);
setCaseTypes(klass, classMirror);
fillRefinedDeclarations(klass);
if(isCeylon)
checkReifiedGenericsForMethods(klass, classMirror);
setAnnotations(klass, classMirror);
}
private boolean isInstantiator(MethodMirror methodMirror) {
return methodMirror.getName().endsWith("$aliased$");
}
private void checkReifiedGenericsForMethods(ClassOrInterface klass, ClassMirror classMirror) {
for(Declaration member : klass.getMembers()){
if(member instanceof JavaMethod == false)
continue;
MethodMirror mirror = ((JavaMethod)member).mirror;
if(AbstractTransformer.supportsReified(member)){
checkReifiedTypeDescriptors(mirror.getTypeParameters().size(), classMirror, mirror, false);
}
}
}
private boolean isFromJDK(ClassMirror classMirror) {
String pkgName = unquotePackageName(classMirror.getPackage());
return JDKUtils.isJDKAnyPackage(pkgName) || JDKUtils.isOracleJDKAnyPackage(pkgName);
}
private void setAnnotations(Declaration decl, AnnotatedMirror classMirror) {
List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION);
if(annotations != null) {
for(AnnotationMirror annotation : annotations){
decl.getAnnotations().add(readModelAnnotation(annotation));
}
}
// Add a ceylon deprecated("") if it's annotated with java.lang.Deprecated
// and doesn't already have the ceylon annotation
if (classMirror.getAnnotation(JAVA_DEPRECATED_ANNOTATION) != null) {
boolean hasCeylonDeprecated = false;
for(Annotation a : decl.getAnnotations()) {
if (a.getName().equals("deprecated")) {
hasCeylonDeprecated = true;
break;
}
}
if (!hasCeylonDeprecated) {
Annotation modelAnnotation = new Annotation();
modelAnnotation.setName("deprecated");
modelAnnotation.getPositionalArguments().add("");
decl.getAnnotations().add(modelAnnotation);
}
}
}
private Annotation readModelAnnotation(AnnotationMirror annotation) {
Annotation modelAnnotation = new Annotation();
modelAnnotation.setName((String) annotation.getValue());
@SuppressWarnings("unchecked")
List<String> arguments = (List<String>) annotation.getValue("arguments");
if(arguments != null){
modelAnnotation.getPositionalArguments().addAll(arguments);
}else{
@SuppressWarnings("unchecked")
List<AnnotationMirror> namedArguments = (List<AnnotationMirror>) annotation.getValue("namedArguments");
if(namedArguments != null){
for(AnnotationMirror namedArgument : namedArguments){
String argName = (String) namedArgument.getValue("name");
String argValue = (String) namedArgument.getValue("value");
modelAnnotation.getNamedArguments().put(argName, argValue);
}
}
}
return modelAnnotation;
}
private void addInnerClasses(ClassOrInterface klass, ClassMirror classMirror) {
AnnotationMirror membersAnnotation = classMirror.getAnnotation(CEYLON_MEMBERS_ANNOTATION);
if(membersAnnotation == null)
addInnerClassesFromMirror(klass, classMirror);
else
addInnerClassesFromAnnotation(klass, membersAnnotation);
}
private void addInnerClassesFromAnnotation(ClassOrInterface klass, AnnotationMirror membersAnnotation) {
List<AnnotationMirror> members = (List<AnnotationMirror>) membersAnnotation.getValue();
for(AnnotationMirror member : members){
TypeMirror javaClassMirror = (TypeMirror)member.getValue("klass");
String javaClassName = javaClassMirror.getQualifiedName();
Declaration innerDecl = convertToDeclaration(Decl.getModuleContainer(klass), javaClassName, DeclarationType.TYPE);
if(innerDecl == null)
throw new ModelResolutionException("Failed to load inner type " + javaClassName
+ " for outer type " + klass.getQualifiedNameString());
}
}
/**
* Allows subclasses to do something to the class name
*/
protected String assembleJavaClass(String javaClass, String packageName) {
return javaClass;
}
private void addInnerClassesFromMirror(ClassOrInterface klass, ClassMirror classMirror) {
boolean isJDK = isFromJDK(classMirror);
for(ClassMirror innerClass : classMirror.getDirectInnerClasses()){
// We skip members marked with @Ignore
if(innerClass.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
// We skip anonymous inner classes
if(innerClass.isAnonymous())
continue;
// We skip private classes, otherwise the JDK has a ton of unresolved things
if(isJDK && !innerClass.isPublic())
continue;
Declaration innerDecl = convertToDeclaration(innerClass, DeclarationType.TYPE);
// no need to set its container as that's now handled by convertToDeclaration
}
}
private Method addMethod(ClassOrInterface klass, MethodMirror methodMirror, boolean isCeylon, boolean isOverloaded) {
JavaMethod method = new JavaMethod(methodMirror);
String methodName = methodMirror.getName();
method.setContainer(klass);
method.setRealName(methodName);
method.setUnit(klass.getUnit());
method.setOverloaded(isOverloaded);
ProducedType type = null;
try{
setMethodOrValueFlags(klass, methodMirror, method, isCeylon);
}catch(ModelResolutionException x){
// collect an error in its type
type = logModelResolutionException(x, klass, "method '"+methodMirror.getName()+"' (checking if it is an overriding method");
}
if(methodName.equals("hash")
|| methodName.equals("string"))
method.setName(methodName+"_method");
else
method.setName(Util.strip(methodName, isCeylon, method.isShared()));
method.setDefaultedAnnotation(methodMirror.isDefault());
// type params first
setTypeParameters(method, methodMirror);
// now its parameters
if(isEqualsMethod(methodMirror))
setEqualsParameters(method, methodMirror);
else
setParameters(method, methodMirror, isCeylon, klass);
// and its return type
// do not log an additional error if we had one from checking if it was overriding
if(type == null)
type = obtainType(methodMirror.getReturnType(), methodMirror, method, Decl.getModuleContainer(method), VarianceLocation.COVARIANT,
"method '"+methodMirror.getName()+"'", klass);
method.setType(type);
method.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror));
method.setDeclaredAnything(methodMirror.isDeclaredVoid());
type.setRaw(isRaw(Decl.getModuleContainer(klass), methodMirror.getReturnType()));
markUnboxed(method, methodMirror.getReturnType());
markTypeErased(method, methodMirror, methodMirror.getReturnType());
setAnnotations(method, methodMirror);
klass.getMembers().add(method);
DeclarationVisitor.setVisibleScope(method);
return method;
}
private void fillRefinedDeclarations(ClassOrInterface klass) {
for(Declaration member : klass.getMembers()){
// do not trigger a type load (by calling isActual()) for Java inner classes since they
// can never be actual
if(member instanceof ClassOrInterface && !Decl.isCeylon((ClassOrInterface)member))
continue;
if(member.isActual()){
member.setRefinedDeclaration(findRefinedDeclaration(klass, member.getName(), getSignature(member), false));
}
}
}
private List<ProducedType> getSignature(Declaration decl) {
List<ProducedType> result = null;
if (decl instanceof Functional) {
Functional func = (Functional)decl;
if (func.getParameterLists().size() > 0) {
List<Parameter> params = func.getParameterLists().get(0).getParameters();
result = new ArrayList<ProducedType>(params.size());
for (Parameter p : params) {
result.add(p.getType());
}
}
}
return result;
}
private Declaration findRefinedDeclaration(ClassOrInterface decl, String name, List<ProducedType> signature, boolean ellipsis) {
Declaration refinedDeclaration = decl.getRefinedMember(name, signature, ellipsis);
if(refinedDeclaration == null)
throw new ModelResolutionException("Failed to find refined declaration for "+name);
return refinedDeclaration;
}
private boolean isStartOfJavaBeanPropertyName(char c){
return Character.isUpperCase(c) || c == '_';
}
private boolean isGetter(MethodMirror methodMirror) {
String name = methodMirror.getName();
boolean matchesGet = name.length() > 3 && name.startsWith("get")
&& isStartOfJavaBeanPropertyName(name.charAt(3))
&& !"getString".equals(name) && !"getHash".equals(name) && !"getEquals".equals(name);
boolean matchesIs = name.length() > 2 && name.startsWith("is")
&& isStartOfJavaBeanPropertyName(name.charAt(2))
&& !"isString".equals(name) && !"isHash".equals(name) && !"isEquals".equals(name);
boolean hasNoParams = methodMirror.getParameters().size() == 0;
boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID);
return (matchesGet || matchesIs) && hasNoParams && hasNonVoidReturn;
}
private boolean isSetter(MethodMirror methodMirror) {
String name = methodMirror.getName();
boolean matchesSet = name.length() > 3 && name.startsWith("set")
&& isStartOfJavaBeanPropertyName(name.charAt(3))
&& !"setString".equals(name) && !"setHash".equals(name) && !"setEquals".equals(name);
boolean hasOneParam = methodMirror.getParameters().size() == 1;
boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID);
return matchesSet && hasOneParam && hasVoidReturn;
}
private boolean isHashAttribute(MethodMirror methodMirror) {
String name = methodMirror.getName();
boolean matchesName = "hashCode".equals(name);
boolean hasNoParams = methodMirror.getParameters().size() == 0;
return matchesName && hasNoParams;
}
private boolean isStringAttribute(MethodMirror methodMirror) {
String name = methodMirror.getName();
boolean matchesName = "toString".equals(name);
boolean hasNoParams = methodMirror.getParameters().size() == 0;
return matchesName && hasNoParams;
}
private boolean isEqualsMethod(MethodMirror methodMirror) {
String name = methodMirror.getName();
if(!"equals".equals(name)
|| methodMirror.getParameters().size() != 1)
return false;
VariableMirror param = methodMirror.getParameters().get(0);
return sameType(param.getType(), OBJECT_TYPE);
}
private void setEqualsParameters(Method decl, MethodMirror methodMirror) {
ParameterList parameters = new ParameterList();
decl.addParameterList(parameters);
Parameter parameter = new Parameter();
Value value = new Value();
parameter.setModel(value);
value.setInitializerParameter(parameter);
value.setUnit(decl.getUnit());
value.setContainer((Scope) decl);
parameter.setName("that");
value.setName("that");
value.setType(getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, decl, VarianceLocation.INVARIANT));
parameter.setDeclaration((Declaration) decl);
parameters.getParameters().add(parameter);
}
private String getJavaAttributeName(String getterName) {
if (getterName.startsWith("get") || getterName.startsWith("set")) {
return getJavaBeanName(getterName.substring(3));
} else if (getterName.startsWith("is")) {
// Starts with "is"
return getJavaBeanName(getterName.substring(2));
} else {
throw new RuntimeException("Illegal java getter/setter name");
}
}
private String getJavaBeanName(String name) {
// See https://github.com/ceylon/ceylon-compiler/issues/340
// make it lowercase until the first non-uppercase
char[] newName = name.toCharArray();
for(int i=0;i<newName.length;i++){
char c = newName[i];
if(Character.isLowerCase(c)){
// if we had more than one upper-case, we leave the last uppercase: getURLDecoder -> urlDecoder
if(i > 1){
newName[i-1] = Character.toUpperCase(newName[i-1]);
}
break;
}
newName[i] = Character.toLowerCase(c);
}
return new String(newName);
}
private void addValue(ClassOrInterface klass, String ceylonName, FieldMirror fieldMirror, boolean isCeylon) {
// make sure it's a FieldValue so we can figure it out in the backend
Value value = new FieldValue(fieldMirror.getName());
value.setContainer(klass);
// use the name annotation if present (used by Java arrays)
String nameAnnotation = getAnnotationStringValue(fieldMirror, CEYLON_NAME_ANNOTATION);
value.setName(nameAnnotation != null ? nameAnnotation : ceylonName);
value.setUnit(klass.getUnit());
value.setShared(fieldMirror.isPublic() || fieldMirror.isProtected() || fieldMirror.isDefaultAccess());
value.setProtectedVisibility(fieldMirror.isProtected());
value.setPackageVisibility(fieldMirror.isDefaultAccess());
value.setStaticallyImportable(fieldMirror.isStatic());
// field can't be abstract or interface, so not formal
// can we override fields? good question. Not really, but from an external point of view?
// FIXME: figure this out: (default)
// FIXME: for the same reason, can it be an overriding field? (actual)
value.setVariable(!fieldMirror.isFinal());
// figure out if it's an enum subtype in a final static field
if(fieldMirror.getType().getKind() == TypeKind.DECLARED
&& fieldMirror.getType().getDeclaredClass() != null
&& fieldMirror.getType().getDeclaredClass().isEnum()
&& fieldMirror.isFinal()
&& fieldMirror.isStatic())
value.setEnumValue(true);
ProducedType type = obtainType(fieldMirror.getType(), fieldMirror, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT,
"field '"+value.getName()+"'", klass);
value.setType(type);
value.setUncheckedNullType((!isCeylon && !fieldMirror.getType().isPrimitive()) || isUncheckedNull(fieldMirror));
type.setRaw(isRaw(Decl.getModuleContainer(klass), fieldMirror.getType()));
markUnboxed(value, fieldMirror.getType());
markTypeErased(value, fieldMirror, fieldMirror.getType());
setAnnotations(value, fieldMirror);
klass.getMembers().add(value);
DeclarationVisitor.setVisibleScope(value);
}
private boolean isRaw(Module module, TypeMirror type) {
// dirty hack to get rid of bug where calling type.isRaw() on a ceylon type we are going to compile would complete() it, which
// would try to parse its file. For ceylon types we don't need the class file info we can query it
// See https://github.com/ceylon/ceylon-compiler/issues/1085
switch(type.getKind()){
case ARRAY: // arrays are never raw
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case ERROR:
case FLOAT:
case INT:
case LONG:
case NULL:
case SHORT:
case TYPEVAR:
case VOID:
case WILDCARD:
return false;
case DECLARED:
ClassMirror klass = type.getDeclaredClass();
if(klass.isJavaSource()){
// I suppose this should work
return type.isRaw();
}
List<String> path = new LinkedList<String>();
String pkgName = klass.getPackage().getQualifiedName();
String unquotedPkgName = unquotePackageName(klass.getPackage());
String qualifiedName = klass.getQualifiedName();
String relativeName = pkgName.isEmpty() ? qualifiedName : qualifiedName.substring(pkgName.length()+1);
for(String name : relativeName.split("[\\$\\.]")){
if(!name.isEmpty()){
path.add(0, klass.getName());
}
}
if(path.size() > 1){
// find the proper class mirror for the container
klass = loadClass(module, pkgName, path.get(0));
if(klass == null)
return false;
}
if(!path.isEmpty() && klass.isLoadedFromSource()){
// we need to find its model
Scope scope = packagesByName.get(cacheKeyByModule(module, unquotedPkgName));
if(scope == null)
return false;
for(String name : path){
Declaration decl = scope.getDirectMember(name, null, false);
if(decl == null)
return false;
// if we get a value, we want its type
if(Decl.isValue(decl)
&& ((Value)decl).getTypeDeclaration().getName().equals(name))
decl = ((Value)decl).getTypeDeclaration();
if(decl instanceof TypeDeclaration == false)
return false;
scope = (TypeDeclaration)decl;
}
TypeDeclaration typeDecl = (TypeDeclaration) scope;
return !typeDecl.getTypeParameters().isEmpty() && type.getTypeArguments().isEmpty();
}
try{
return type.isRaw();
}catch(Exception x){
// ignore this exception, it's likely to be due to missing module imports and an unknown type and
// it will be logged somewhere else
return false;
}
default:
return false;
}
}
private void addValue(ClassOrInterface klass, MethodMirror methodMirror, String methodName, boolean isCeylon) {
JavaBeanValue value = new JavaBeanValue();
value.setGetterName(methodMirror.getName());
value.setContainer(klass);
value.setUnit(klass.getUnit());
ProducedType type = null;
try{
setMethodOrValueFlags(klass, methodMirror, value, isCeylon);
}catch(ModelResolutionException x){
// collect an error in its type
type = logModelResolutionException(x, klass, "getter '"+methodName+"' (checking if it is an overriding method");
}
value.setName(Util.strip(methodName, isCeylon, value.isShared()));
// do not log an additional error if we had one from checking if it was overriding
if(type == null)
type = obtainType(methodMirror.getReturnType(), methodMirror, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT,
"getter '"+methodName+"'", klass);
value.setType(type);
// special case for hash attributes which we want to pretend are of type long internally
if(value.isShared() && methodName.equals("hash"))
type.setUnderlyingType("long");
value.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror));
type.setRaw(isRaw(Decl.getModuleContainer(klass), methodMirror.getReturnType()));
markUnboxed(value, methodMirror.getReturnType());
markTypeErased(value, methodMirror, methodMirror.getReturnType());
setAnnotations(value, methodMirror);
klass.getMembers().add(value);
DeclarationVisitor.setVisibleScope(value);
}
private boolean isUncheckedNull(AnnotatedMirror methodMirror) {
Boolean unchecked = getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, "uncheckedNull");
return unchecked != null && unchecked.booleanValue();
}
private void setMethodOrValueFlags(ClassOrInterface klass, MethodMirror methodMirror, MethodOrValue decl, boolean isCeylon) {
decl.setShared(methodMirror.isPublic() || methodMirror.isProtected() || methodMirror.isDefaultAccess());
decl.setProtectedVisibility(methodMirror.isProtected());
decl.setPackageVisibility(methodMirror.isDefaultAccess());
if(decl instanceof Value){
setValueTransientLateFlags((Value)decl, methodMirror, isCeylon);
}
if(// for class members we rely on abstract bit
(klass instanceof Class
&& methodMirror.isAbstract())
// Java interfaces are formal
|| (klass instanceof Interface
&& !((LazyInterface)klass).isCeylon())
// For Ceylon interfaces we rely on annotation
|| methodMirror.getAnnotation(CEYLON_LANGUAGE_FORMAL_ANNOTATION) != null) {
decl.setFormal(true);
} else {
if (// for class members we rely on final/static bits
(klass instanceof Class
&& !methodMirror.isFinal()
&& !methodMirror.isStatic())
// Java interfaces are never final
|| (klass instanceof Interface
&& !((LazyInterface)klass).isCeylon())
// For Ceylon interfaces we rely on annotation
|| methodMirror.getAnnotation(CEYLON_LANGUAGE_DEFAULT_ANNOTATION) != null){
decl.setDefault(true);
}
}
decl.setStaticallyImportable(methodMirror.isStatic());
if(isOverridingMethod(methodMirror)
// For Ceylon interfaces we rely on annotation
|| (klass instanceof LazyInterface
&& ((LazyInterface)klass).isCeylon()
&& methodMirror.getAnnotation(CEYLON_LANGUAGE_ACTUAL_ANNOTATION) != null)){
decl.setActual(true);
}
}
private void setValueTransientLateFlags(Value decl, MethodMirror methodMirror, boolean isCeylon) {
if(isCeylon)
decl.setTransient(methodMirror.getAnnotation(CEYLON_TRANSIENT_ANNOTATION) != null);
else
// all Java getters are transient, fields are not
decl.setTransient(decl instanceof FieldValue == false);
decl.setLate(methodMirror.getAnnotation(CEYLON_LANGUAGE_LATE_ANNOTATION) != null);
}
private void setExtendedType(ClassOrInterface klass, ClassMirror classMirror) {
// look at its super type
TypeMirror superClass = classMirror.getSuperclass();
ProducedType extendedType;
if(klass instanceof Interface){
// interfaces need to have their superclass set to Object
if(superClass == null || superClass.getKind() == TypeKind.NONE)
extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, klass, VarianceLocation.INVARIANT);
else
extendedType = getNonPrimitiveType(Decl.getModule(klass), superClass, klass, VarianceLocation.INVARIANT);
}else{
String className = classMirror.getQualifiedName();
String superClassName = superClass == null ? null : superClass.getQualifiedName();
if(className.equals("ceylon.language.Anything")){
// ceylon.language.Anything has no super type
extendedType = null;
}else if(className.equals("java.lang.Object")){
// we pretend its superclass is something else, but note that in theory we shouldn't
// be seeing j.l.Object at all due to unerasure
extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT);
}else{
// read it from annotation first
String annotationSuperClassName = getAnnotationStringValue(classMirror, CEYLON_CLASS_ANNOTATION, "extendsType");
if(annotationSuperClassName != null && !annotationSuperClassName.isEmpty()){
extendedType = decodeType(annotationSuperClassName, klass, Decl.getModuleContainer(klass),
"extended type");
}else{
// read it from the Java super type
// now deal with type erasure, avoid having Object as superclass
if("java.lang.Object".equals(superClassName)){
extendedType = getNonPrimitiveType(getLanguageModule(), CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT);
}else if(superClass != null){
try{
extendedType = getNonPrimitiveType(Decl.getModule(klass), superClass, klass, VarianceLocation.INVARIANT);
}catch(ModelResolutionException x){
extendedType = logModelResolutionException(x, klass, "Error while resolving extended type of "+klass.getQualifiedNameString());
}
}else{
// FIXME: should this be UnknownType?
extendedType = null;
}
}
}
}
if(extendedType != null)
klass.setExtendedType(extendedType);
}
private void setParameters(Functional decl, MethodMirror methodMirror, boolean isCeylon, Scope container) {
ParameterList parameters = new ParameterList();
parameters.setNamedParametersSupported(isCeylon);
decl.addParameterList(parameters);
int parameterCount = methodMirror.getParameters().size();
int parameterIndex = 0;
for(VariableMirror paramMirror : methodMirror.getParameters()){
// ignore some parameters
if(paramMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
boolean isLastParameter = parameterIndex == parameterCount - 1;
boolean isVariadic = isLastParameter && methodMirror.isVariadic();
String paramName = getAnnotationStringValue(paramMirror, CEYLON_NAME_ANNOTATION);
// use whatever param name we find as default
if(paramName == null)
paramName = paramMirror.getName();
Parameter parameter = new Parameter();
parameter.setName(paramName);
TypeMirror typeMirror = paramMirror.getType();
ProducedType type;
if(isVariadic){
// possibly make it optional
TypeMirror variadicType = typeMirror.getComponentType();
// we pretend it's toplevel because we want to get magic string conversion for variadic methods
type = obtainType(Decl.getModuleContainer((Scope)decl), variadicType, (Scope)decl, TypeLocation.TOPLEVEL, VarianceLocation.CONTRAVARIANT);
if(!isCeylon && !variadicType.isPrimitive()){
// Java parameters are all optional unless primitives
ProducedType optionalType = getOptionalType(type);
optionalType.setUnderlyingType(type.getUnderlyingType());
type = optionalType;
}
// turn it into a Sequential<T>
type = typeFactory.getSequentialType(type);
}else{
type = obtainType(typeMirror, paramMirror, (Scope) decl, Decl.getModuleContainer((Scope) decl), VarianceLocation.CONTRAVARIANT,
"parameter '"+paramName+"' of method '"+methodMirror.getName()+"'", (Declaration)decl);
// variadic params may technically be null in Java, but it Ceylon sequenced params may not
// so it breaks the typechecker logic for handling them, and it will always be a case of bugs
// in the java side so let's not allow this
if(!isCeylon && !typeMirror.isPrimitive()){
// Java parameters are all optional unless primitives
ProducedType optionalType = getOptionalType(type);
optionalType.setUnderlyingType(type.getUnderlyingType());
type = optionalType;
}
}
MethodOrValue value = null;
if (isCeylon && decl instanceof Class){
// For a functional parameter to a class, we can just lookup the member
value = (MethodOrValue)((Class)decl).getDirectMember(paramName, null, false);
}
if (value == null) {
// So either decl is not a Class,
// or the method or value member of decl is not shared
if (paramMirror.getAnnotation(CEYLON_FUNCTIONAL_PARAMETER_ANNOTATION) != null) {
// A functional parameter to a method
Method method = new Method();
method.setType(typeFactory.getCallableReturnType(type));
// We need to set enough of a parameter list so that the method's full type is correct
ParameterList pl = new ParameterList();
for (ProducedType pt : typeFactory.getCallableArgumentTypes(type)) {
Parameter p = new Parameter();
Value v = new Value();
v.setType(pt);
p.setModel(v);
pl.getParameters().add(p);
}
method.addParameterList(pl);
value = method;
} else {
// A value parameter to a method
value = new Value();
value.setType(type);
}
value.setContainer((Scope) decl);
DeclarationVisitor.setVisibleScope(value);
value.setUnit(((Element)decl).getUnit());
value.setName(paramName);
}
value.setInitializerParameter(parameter);
parameter.setModel(value);
if(paramMirror.getAnnotation(CEYLON_SEQUENCED_ANNOTATION) != null
|| isVariadic)
parameter.setSequenced(true);
if(paramMirror.getAnnotation(CEYLON_DEFAULTED_ANNOTATION) != null)
parameter.setDefaulted(true);
if (parameter.isSequenced() &&
typeFactory.isNonemptyIterableType(parameter.getType())) {
parameter.setAtLeastOne(true);
}
// if it's variadic, consider the array element type (T[] == T...) for boxing rules
markUnboxed(value, isVariadic ?
paramMirror.getType().getComponentType()
: paramMirror.getType());
parameter.setDeclaration((Declaration) decl);
setAnnotations(value, paramMirror);
parameters.getParameters().add(parameter);
parameterIndex++;
}
}
private ProducedType getOptionalType(ProducedType type) {
// we do not use Unit.getOptionalType because it causes lots of lazy loading that ultimately triggers the typechecker's
// infinite recursion loop
List<ProducedType> list = new ArrayList<ProducedType>(2);
list.add(typeFactory.getNullDeclaration().getType());
list.add(type);
UnionType ut = new UnionType(typeFactory);
ut.setCaseTypes(list);
return ut.getType();
}
private ProducedType logModelResolutionError(Scope container, String message) {
return logModelResolutionException((String)null, container, message);
}
private ProducedType logModelResolutionException(ModelResolutionException x, Scope container, String message) {
return logModelResolutionException(x.getMessage(), container, message);
}
private ProducedType logModelResolutionException(final String exceptionMessage, Scope container, final String message) {
final Module module = Decl.getModuleContainer(container);
Runnable errorReporter;
if(module != null && !module.isDefault()){
final StringBuilder sb = new StringBuilder();
sb.append("Error while loading the ").append(module.getNameAsString()).append("/").append(module.getVersion());
sb.append(" module:\n ");
sb.append(message);
if(exceptionMessage != null)
sb.append(":\n ").append(exceptionMessage);
errorReporter = new Runnable(){
public void run(){
moduleManager.attachErrorToOriginalModuleImport(module, sb.toString());
}
};
}else if(exceptionMessage == null){
errorReporter = new Runnable(){
public void run(){
logError(message);
}
};
}else{
errorReporter = new Runnable(){
public void run(){
logError(message+": "+exceptionMessage);
}
};
}
UnknownType ret = new UnknownType(typeFactory);
ret.setErrorReporter(errorReporter);
return ret.getType();
}
private void markTypeErased(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) {
if (getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, "erased") == Boolean.TRUE) {
decl.setTypeErased(true);
} else {
decl.setTypeErased(sameType(type, OBJECT_TYPE));
}
if(hasTypeParameterWithConstraints(type))
decl.setUntrustedType(true);
}
private boolean hasTypeParameterWithConstraints(TypeMirror type) {
switch(type.getKind()){
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FLOAT:
case INT:
case LONG:
case SHORT:
case VOID:
case WILDCARD:
return false;
case ARRAY:
return hasTypeParameterWithConstraints(type.getComponentType());
case DECLARED:
for(TypeMirror ta : type.getTypeArguments()){
if(hasTypeParameterWithConstraints(ta))
return true;
}
return false;
case TYPEVAR:
TypeParameterMirror typeParameter = type.getTypeParameter();
return typeParameter != null && hasNonErasedBounds(typeParameter);
default:
return false;
}
}
private void markUnboxed(TypedDeclaration decl, TypeMirror type) {
boolean unboxed = false;
if(type.isPrimitive()
|| type.getKind() == TypeKind.ARRAY
|| sameType(type, STRING_TYPE)
|| Util.isUnboxedVoid(decl)) {
unboxed = true;
}
decl.setUnboxed(unboxed);
}
@Override
public synchronized void complete(LazyValue value) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
try{
MethodMirror meth = null;
for (MethodMirror m : value.classMirror.getDirectMethods()) {
// Do not skip members marked with @Ignore, because the getter is supposed to be ignored
if (m.getName().equals(
Naming.getGetterName(value))
&& m.isStatic() && m.getParameters().size() == 0) {
meth = m;
}
if (m.getName().equals(
Naming.getSetterName(value))
&& m.isStatic() && m.getParameters().size() == 1) {
value.setVariable(true);
}
}
if(meth == null || meth.getReturnType() == null){
value.setType(logModelResolutionError(value.getContainer(), "Error while resolving toplevel attribute "+value.getQualifiedNameString()+": getter method missing"));
return;
}
value.setType(obtainType(meth.getReturnType(), meth, null, Decl.getModuleContainer(value.getContainer()), VarianceLocation.INVARIANT,
"toplevel attribute", value));
setValueTransientLateFlags(value, meth, true);
setAnnotations(value, meth);
markUnboxed(value, meth.getReturnType());
}finally{
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
}
@Override
public synchronized void complete(LazyMethod method) {
timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY);
try{
MethodMirror meth = null;
String lookupName = method.getName();
for(MethodMirror m : method.classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(m.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(Util.strip(m.getName()).equals(lookupName)){
meth = m;
break;
}
}
if(meth == null || meth.getReturnType() == null){
method.setType(logModelResolutionError(method.getContainer(), "Error while resolving toplevel method "+method.getQualifiedNameString()+": static method missing"));
return;
}
if(!meth.isStatic()){
method.setType(logModelResolutionError(method.getContainer(), "Error while resolving toplevel method "+method.getQualifiedNameString()+": method is not static"));
return;
}
// save the method name
method.setRealMethodName(meth.getName());
// save the method
method.setMethodMirror(meth);
// type params first
setTypeParameters(method, meth);
// now its parameters
setParameters(method, meth, true /* toplevel methods are always Ceylon */, method);
method.setType(obtainType(meth.getReturnType(), meth, method, Decl.getModuleContainer(method), VarianceLocation.COVARIANT,
"toplevel method", method));
method.setDeclaredAnything(meth.isDeclaredVoid());
markUnboxed(method, meth.getReturnType());
markTypeErased(method, meth, meth.getReturnType());
method.setAnnotation(meth.getAnnotation(CEYLON_LANGUAGE_ANNOTATION_ANNOTATION) != null);
setAnnotations(method, meth);
setAnnotationConstructor(method, meth);
}finally{
timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY);
}
}
private void setAnnotationConstructor(LazyMethod method, MethodMirror meth) {
AnnotationInvocation ai = loadAnnotationInvocation(method, method.classMirror, meth);
if (ai != null) {
loadAnnotationConstructorDefaultedParameters(method, meth, ai);
ai.setConstructorDeclaration(method);
method.setAnnotationConstructor(ai);
}
}
private AnnotationInvocation loadAnnotationInvocation(
LazyMethod method,
AnnotatedMirror annoInstMirror, MethodMirror meth) {
AnnotationInvocation ai = null;
AnnotationMirror annotationInvocationAnnotation = null;
List<AnnotationMirror> annotationTree = getAnnotationArrayValue(annoInstMirror, CEYLON_ANNOTATION_INSTANTIATION_TREE_ANNOTATION, "value");
if (annotationTree != null
&& !annotationTree.isEmpty()) {
annotationInvocationAnnotation = annotationTree.get(0);
} else {
annotationInvocationAnnotation = annoInstMirror.getAnnotation(CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION);
}
//stringValueAnnotation = annoInstMirror.getAnnotation(CEYLON_STRING_VALUE_ANNOTATION);
if (annotationInvocationAnnotation != null) {
ai = new AnnotationInvocation();
setPrimaryFromAnnotationInvocationAnnotation(annotationInvocationAnnotation, ai);
loadAnnotationInvocationArguments(new ArrayList(2), method, ai, annotationInvocationAnnotation, annotationTree, annoInstMirror);
}
return ai;
}
private void loadAnnotationInvocationArguments(
List<AnnotationFieldName> path,
LazyMethod method,
AnnotationInvocation ai, AnnotationMirror annotationInvocationAnnotation,
List<AnnotationMirror> annotationTree,
AnnotatedMirror dpm) {
List<Short> argumentCodes = (List<Short>)annotationInvocationAnnotation.getValue(CEYLON_ANNOTATION_INSTANTIATION_ARGUMENTS_MEMBER);
if(argumentCodes != null){
for (int ii = 0; ii < argumentCodes.size(); ii++) {
short code = argumentCodes.get(ii);
AnnotationArgument argument = new AnnotationArgument();
Parameter classParameter = ai.getParameters().get(ii);
argument.setParameter(classParameter);
path.add(argument);
argument.setTerm(loadAnnotationArgumentTerm(path, method, ai, classParameter, annotationTree, dpm, code));
path.remove(path.size()-1);
ai.getAnnotationArguments().add(argument);
}
}
}
public AnnotationTerm decode(Module moduleScope, List<Parameter> sourceParameters, AnnotationInvocation info,
Parameter parameter,
AnnotatedMirror dpm, List<AnnotationFieldName> path, int code) {
AnnotationTerm result;
if (code == Short.MIN_VALUE) {
return findLiteralAnnotationTerm(moduleScope, path, parameter, dpm);
} else if (code < 0) {
InvocationAnnotationTerm invocation = new InvocationAnnotationTerm();
result = invocation;
} else if (code >= 0 && code < 512) {
ParameterAnnotationTerm parameterArgument = new ParameterAnnotationTerm();
boolean spread = false;
if (code >= 256) {
spread = true;
code-=256;
}
parameterArgument.setSpread(spread);
Parameter sourceParameter = sourceParameters.get(code);
parameterArgument.setSourceParameter(sourceParameter);
//result.setTargetParameter(sourceParameter);
result = parameterArgument;
} else {
throw new RuntimeException();
}
return result;
}
private AnnotationTerm loadAnnotationArgumentTerm(
List<AnnotationFieldName> path,
LazyMethod method,
AnnotationInvocation ai, Parameter parameter,
List<AnnotationMirror> annotationTree,
AnnotatedMirror dpm,
short code) {
if (code < 0 && code != Short.MIN_VALUE) {
AnnotationMirror i = annotationTree.get(-code);
AnnotationInvocation nested = new AnnotationInvocation();
setPrimaryFromAnnotationInvocationAnnotation(i, nested);
loadAnnotationInvocationArguments(path, method, nested, i, annotationTree, dpm);
InvocationAnnotationTerm term = new InvocationAnnotationTerm();
term.setInstantiation(nested);
return term;
} else {
AnnotationTerm term = decode(Decl.getModuleContainer(method), method.getParameterLists().get(0).getParameters(), ai, parameter, dpm, path, code);
return term;
}
}
private void setPrimaryFromAnnotationInvocationAnnotation(AnnotationMirror annotationInvocationAnnotation,
AnnotationInvocation ai) {
TypeMirror annotationType = (TypeMirror)annotationInvocationAnnotation.getValue(CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION_MEMBER);
ClassMirror annotationClassMirror = annotationType.getDeclaredClass();
if (annotationClassMirror.getAnnotation(CEYLON_METHOD_ANNOTATION) != null) {
ai.setPrimary((Method)convertToDeclaration(annotationClassMirror, DeclarationType.VALUE));
} else {
ai.setPrimary((Class)convertToDeclaration(annotationClassMirror, DeclarationType.TYPE));
}
}
private void loadAnnotationConstructorDefaultedParameters(
LazyMethod method, MethodMirror meth, AnnotationInvocation ai) {
for (Parameter ctorParam : method.getParameterLists().get(0).getParameters()) {
AnnotationConstructorParameter acp = new AnnotationConstructorParameter();
acp.setParameter(ctorParam);
if (ctorParam.isDefaulted()) {
acp.setDefaultArgument(
loadAnnotationConstructorDefaultedParameter(method, meth, ctorParam, acp));
}
ai.getConstructorParameters().add(acp);
}
}
private AnnotationTerm loadAnnotationConstructorDefaultedParameter(
LazyMethod method,
MethodMirror meth,
Parameter ctorParam, AnnotationConstructorParameter acp) {
// Find the method mirror for the DPM
for (MethodMirror mm : method.classMirror.getDirectMethods()) {
if (mm.getName().equals(Naming.getDefaultedParamMethodName(method, ctorParam))) {
// Create the appropriate AnnotationTerm
if (mm.getAnnotation(CEYLON_ANNOTATION_INSTANTIATION_ANNOTATION) != null) {
// If the DPM has a @AnnotationInstantiation
// then it must be an invocation term so recurse
InvocationAnnotationTerm invocationTerm = new InvocationAnnotationTerm();
invocationTerm.setInstantiation(loadAnnotationInvocation(method, mm, meth));
return invocationTerm;
} else {
return loadLiteralAnnotationTerm(method, ctorParam, mm);
}
}
}
return null;
}
/**
* Loads a LiteralAnnotationTerm according to the presence of
* <ul>
* <li>{@code @StringValue} <li>{@code @IntegerValue} <li>etc
* </ul>
* @param ctorParam
*
*/
private LiteralAnnotationTerm loadLiteralAnnotationTerm(LazyMethod method, Parameter parameter, AnnotatedMirror mm) {
boolean singleValue = !typeFactory.isIterableType(parameter.getType())
|| typeFactory.getStringDeclaration().equals(parameter.getType().getDeclaration());
AnnotationMirror valueAnnotation = mm.getAnnotation(CEYLON_STRING_VALUE_ANNOTATION);
if (valueAnnotation != null) {
return readStringValuesAnnotation(valueAnnotation, singleValue);
}
valueAnnotation = mm.getAnnotation(CEYLON_INTEGER_VALUE_ANNOTATION);
if (valueAnnotation != null) {
return readIntegerValuesAnnotation(valueAnnotation, singleValue);
}
valueAnnotation = mm.getAnnotation(CEYLON_BOOLEAN_VALUE_ANNOTATION);
if (valueAnnotation != null) {
return readBooleanValuesAnnotation(valueAnnotation, singleValue);
}
valueAnnotation = mm.getAnnotation(CEYLON_DECLARATION_VALUE_ANNOTATION);
if (valueAnnotation != null) {
return readDeclarationValuesAnnotation(valueAnnotation, singleValue);
}
valueAnnotation = mm.getAnnotation(CEYLON_OBJECT_VALUE_ANNOTATION);
if (valueAnnotation != null) {
return readObjectValuesAnnotation(Decl.getModuleContainer(method), valueAnnotation, singleValue);
}
valueAnnotation = mm.getAnnotation(CEYLON_CHARACTER_VALUE_ANNOTATION);
if (valueAnnotation != null) {
return readCharacterValuesAnnotation(valueAnnotation, singleValue);
}
valueAnnotation = mm.getAnnotation(CEYLON_FLOAT_VALUE_ANNOTATION);
if (valueAnnotation != null) {
return readFloatValuesAnnotation(valueAnnotation, singleValue);
}
return null;
}
/**
* Searches the {@code @*Exprs} for one containing a {@code @*Value}
* whose {@code name} matches the given namePath returning the first
* match, or null.
*/
private LiteralAnnotationTerm findLiteralAnnotationTerm(Module moduleScope, List<AnnotationFieldName> namePath, Parameter parameter, AnnotatedMirror mm) {
boolean singeValue = !typeFactory.isIterableType(parameter.getType())
|| typeFactory.getStringDeclaration().equals(parameter.getType().getDeclaration());
final String name = Naming.getAnnotationFieldName(namePath);
AnnotationMirror exprsAnnotation = mm.getAnnotation(CEYLON_STRING_EXPRS_ANNOTATION);
if (exprsAnnotation != null) {
for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) {
String path = (String)valueAnnotation.getValue("name");
if (name.equals(path)) {
return readStringValuesAnnotation(valueAnnotation, singeValue);
}
}
}
exprsAnnotation = mm.getAnnotation(CEYLON_INTEGER_EXPRS_ANNOTATION);
if (exprsAnnotation != null) {
for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) {
String path = (String)valueAnnotation.getValue("name");
if (name.equals(path)) {
return readIntegerValuesAnnotation(valueAnnotation, singeValue);
}
}
}
exprsAnnotation = mm.getAnnotation(CEYLON_BOOLEAN_EXPRS_ANNOTATION);
if (exprsAnnotation != null) {
for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) {
String path = (String)valueAnnotation.getValue("name");
if (name.equals(path)) {
return readBooleanValuesAnnotation(valueAnnotation, singeValue);
}
}
}
exprsAnnotation = mm.getAnnotation(CEYLON_DECLARATION_EXPRS_ANNOTATION);
if (exprsAnnotation != null) {
for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) {
String path = (String)valueAnnotation.getValue("name");
if (name.equals(path)) {
return readDeclarationValuesAnnotation(valueAnnotation, singeValue);
}
}
}
exprsAnnotation = mm.getAnnotation(CEYLON_OBJECT_EXPRS_ANNOTATION);
if (exprsAnnotation != null) {
for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) {
String path = (String)valueAnnotation.getValue("name");
if (name.equals(path)) {
return readObjectValuesAnnotation(moduleScope, valueAnnotation, singeValue);
}
}
}
exprsAnnotation = mm.getAnnotation(CEYLON_CHARACTER_EXPRS_ANNOTATION);
if (exprsAnnotation != null) {
for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) {
String path = (String)valueAnnotation.getValue("name");
if (name.equals(path)) {
return readCharacterValuesAnnotation(valueAnnotation, singeValue);
}
}
}
exprsAnnotation = mm.getAnnotation(CEYLON_FLOAT_EXPRS_ANNOTATION);
if (exprsAnnotation != null) {
for (AnnotationMirror valueAnnotation : getAnnotationAnnoValues(exprsAnnotation, "value")) {
String path = (String)valueAnnotation.getValue("name");
if (name.equals(path)) {
return readFloatValuesAnnotation(valueAnnotation, singeValue);
}
}
}
return null;
}
private LiteralAnnotationTerm readObjectValuesAnnotation(
Module moduleScope,
AnnotationMirror valueAnnotation, boolean singleValue) {
if (singleValue) {
TypeMirror klass = getAnnotationClassValues(valueAnnotation, "value").get(0);
ProducedType type = obtainType(moduleScope, klass, null, null, null);
ObjectLiteralAnnotationTerm term = new ObjectLiteralAnnotationTerm(type);
return term;
} else {
CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(ObjectLiteralAnnotationTerm.FACTORY);
for (TypeMirror klass : getAnnotationClassValues(valueAnnotation, "value")) {
ProducedType type = obtainType(moduleScope, klass, null, null, null);
result.addElement(new ObjectLiteralAnnotationTerm(type));
}
return result;
}
}
private LiteralAnnotationTerm readStringValuesAnnotation(
AnnotationMirror valueAnnotation, boolean singleValue) {
if (singleValue) {
String value = getAnnotationStringValues(valueAnnotation, "value").get(0);
StringLiteralAnnotationTerm term = new StringLiteralAnnotationTerm(value);
return term;
} else {
CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(StringLiteralAnnotationTerm.FACTORY);
for (String value : getAnnotationStringValues(valueAnnotation, "value")) {
result.addElement(new StringLiteralAnnotationTerm(value));
}
return result;
}
}
private LiteralAnnotationTerm readIntegerValuesAnnotation(
AnnotationMirror valueAnnotation, boolean singleValue) {
if (singleValue) {
Long value = getAnnotationLongValues(valueAnnotation, "value").get(0);
IntegerLiteralAnnotationTerm term = new IntegerLiteralAnnotationTerm(value);
return term;
} else {
CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(IntegerLiteralAnnotationTerm.FACTORY);
for (Long value : getAnnotationLongValues(valueAnnotation, "value")) {
result.addElement(new IntegerLiteralAnnotationTerm(value));
}
return result;
}
}
private LiteralAnnotationTerm readCharacterValuesAnnotation(
AnnotationMirror valueAnnotation, boolean singleValue) {
if (singleValue) {
Integer value = getAnnotationIntegerValues(valueAnnotation, "value").get(0);
CharacterLiteralAnnotationTerm term = new CharacterLiteralAnnotationTerm(value);
return term;
} else {
CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(CharacterLiteralAnnotationTerm.FACTORY);
for (Integer value : getAnnotationIntegerValues(valueAnnotation, "value")) {
result.addElement(new CharacterLiteralAnnotationTerm(value));
}
return result;
}
}
private LiteralAnnotationTerm readFloatValuesAnnotation(
AnnotationMirror valueAnnotation, boolean singleValue) {
if (singleValue) {
Double value = getAnnotationDoubleValues(valueAnnotation, "value").get(0);
FloatLiteralAnnotationTerm term = new FloatLiteralAnnotationTerm(value);
return term;
} else {
CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(FloatLiteralAnnotationTerm.FACTORY);
for (Double value : getAnnotationDoubleValues(valueAnnotation, "value")) {
result.addElement(new FloatLiteralAnnotationTerm(value));
}
return result;
}
}
private LiteralAnnotationTerm readBooleanValuesAnnotation(
AnnotationMirror valueAnnotation, boolean singleValue) {
if (singleValue) {
boolean value = getAnnotationBooleanValues(valueAnnotation, "value").get(0);
BooleanLiteralAnnotationTerm term = new BooleanLiteralAnnotationTerm(value);
return term;
} else {
CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(BooleanLiteralAnnotationTerm.FACTORY);
for (Boolean value : getAnnotationBooleanValues(valueAnnotation, "value")) {
result.addElement(new BooleanLiteralAnnotationTerm(value));
}
return result;
}
}
private LiteralAnnotationTerm readDeclarationValuesAnnotation(
AnnotationMirror valueAnnotation, boolean singleValue) {
if (singleValue) {
String value = getAnnotationStringValues(valueAnnotation, "value").get(0);
DeclarationLiteralAnnotationTerm term = new DeclarationLiteralAnnotationTerm(value);
return term;
} else {
CollectionLiteralAnnotationTerm result = new CollectionLiteralAnnotationTerm(DeclarationLiteralAnnotationTerm.FACTORY);
for (String value : getAnnotationStringValues(valueAnnotation, "value")) {
result.addElement(new DeclarationLiteralAnnotationTerm(value));
}
return result;
}
}
//
// Satisfied Types
private List<String> getSatisfiedTypesFromAnnotations(AnnotatedMirror symbol) {
return getAnnotationArrayValue(symbol, CEYLON_SATISFIED_TYPES_ANNOTATION);
}
private void setSatisfiedTypes(ClassOrInterface klass, ClassMirror classMirror) {
List<String> satisfiedTypes = getSatisfiedTypesFromAnnotations(classMirror);
if(satisfiedTypes != null){
klass.getSatisfiedTypes().addAll(getTypesList(satisfiedTypes, klass, Decl.getModuleContainer(klass), "satisfied types", klass.getQualifiedNameString()));
}else{
for(TypeMirror iface : classMirror.getInterfaces()){
// ignore ReifiedType interfaces
if(sameType(iface, CEYLON_REIFIED_TYPE_TYPE))
continue;
try{
klass.getSatisfiedTypes().add(getNonPrimitiveType(Decl.getModule(klass), iface, klass, VarianceLocation.INVARIANT));
}catch(ModelResolutionException x){
String classPackageName = unquotePackageName(classMirror.getPackage());
if(JDKUtils.isJDKAnyPackage(classPackageName)){
if(iface.getKind() == TypeKind.DECLARED){
// check if it's a JDK thing
ClassMirror ifaceClass = iface.getDeclaredClass();
String ifacePackageName = unquotePackageName(ifaceClass.getPackage());
if(JDKUtils.isOracleJDKAnyPackage(ifacePackageName)){
// just log and ignore it
logMissingOracleType(iface.getQualifiedName());
continue;
}
}
}
}
}
}
}
//
// Case Types
private List<String> getCaseTypesFromAnnotations(AnnotatedMirror symbol) {
return getAnnotationArrayValue(symbol, CEYLON_CASE_TYPES_ANNOTATION);
}
private String getSelfTypeFromAnnotations(AnnotatedMirror symbol) {
return getAnnotationStringValue(symbol, CEYLON_CASE_TYPES_ANNOTATION, "of");
}
private void setCaseTypes(ClassOrInterface klass, ClassMirror classMirror) {
String selfType = getSelfTypeFromAnnotations(classMirror);
Module moduleScope = Decl.getModuleContainer(klass);
if(selfType != null && !selfType.isEmpty()){
ProducedType type = decodeType(selfType, klass, moduleScope, "self type");
if(!(type.getDeclaration() instanceof TypeParameter)){
logError("Invalid type signature for self type of "+klass.getQualifiedNameString()+": "+selfType+" is not a type parameter");
}else{
klass.setSelfType(type);
List<ProducedType> caseTypes = new LinkedList<ProducedType>();
caseTypes.add(type);
klass.setCaseTypes(caseTypes);
}
} else {
List<String> caseTypes = getCaseTypesFromAnnotations(classMirror);
if(caseTypes != null && !caseTypes.isEmpty()){
klass.setCaseTypes(getTypesList(caseTypes, klass, moduleScope, "case types", klass.getQualifiedNameString()));
}
}
}
private List<ProducedType> getTypesList(List<String> caseTypes, Scope scope, Module moduleScope, String targetType, String targetName) {
List<ProducedType> producedTypes = new LinkedList<ProducedType>();
for(String type : caseTypes){
producedTypes.add(decodeType(type, scope, moduleScope, targetType));
}
return producedTypes;
}
//
// Type parameters loading
@SuppressWarnings("unchecked")
private List<AnnotationMirror> getTypeParametersFromAnnotations(AnnotatedMirror symbol) {
return (List<AnnotationMirror>) getAnnotationValue(symbol, CEYLON_TYPE_PARAMETERS);
}
// from our annotation
@SuppressWarnings("deprecation")
private void setTypeParametersFromAnnotations(Scope scope, List<TypeParameter> params, AnnotatedMirror mirror,
List<AnnotationMirror> typeParameterAnnotations, List<TypeParameterMirror> typeParameterMirrors) {
// We must first add every type param, before we resolve the bounds, which can
// refer to type params.
String selfTypeName = getSelfTypeFromAnnotations(mirror);
int i=0;
for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){
TypeParameter param = new TypeParameter();
param.setUnit(((Element)scope).getUnit());
param.setContainer(scope);
param.setDeclaration((Declaration) scope);
// let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface
if(scope instanceof LazyContainer)
((LazyContainer)scope).addMember(param);
else // must be a method
scope.getMembers().add(param);
param.setName((String)typeParamAnnotation.getValue("value"));
param.setExtendedType(typeFactory.getAnythingDeclaration().getType());
if(i < typeParameterMirrors.size()){
TypeParameterMirror typeParameterMirror = typeParameterMirrors.get(i);
param.setNonErasedBounds(hasNonErasedBounds(typeParameterMirror));
}
String varianceName = (String) typeParamAnnotation.getValue("variance");
if(varianceName != null){
if(varianceName.equals("IN")){
param.setContravariant(true);
}else if(varianceName.equals("OUT"))
param.setCovariant(true);
}
// If this is a self type param then link it to its type's declaration
if (param.getName().equals(selfTypeName)) {
param.setSelfTypedDeclaration((TypeDeclaration)scope);
}
params.add(param);
i++;
}
Module moduleScope = Decl.getModuleContainer(scope);
// Now all type params have been set, we can resolve the references parts
Iterator<TypeParameter> paramsIterator = params.iterator();
for(AnnotationMirror typeParamAnnotation : typeParameterAnnotations){
TypeParameter param = paramsIterator.next();
@SuppressWarnings("unchecked")
List<String> satisfiesAttribute = (List<String>)typeParamAnnotation.getValue("satisfies");
setListOfTypes(param.getSatisfiedTypes(), satisfiesAttribute, scope, moduleScope,
"type parameter '"+param.getName()+"' satisfied types");
@SuppressWarnings("unchecked")
List<String> caseTypesAttribute = (List<String>)typeParamAnnotation.getValue("caseTypes");
if(caseTypesAttribute != null && !caseTypesAttribute.isEmpty())
param.setCaseTypes(new LinkedList<ProducedType>());
setListOfTypes(param.getCaseTypes(), caseTypesAttribute, scope, moduleScope,
"type parameter '"+param.getName()+"' case types");
@SuppressWarnings("unchecked")
String defaultValueAttribute = (String)typeParamAnnotation.getValue("defaultValue");
if(defaultValueAttribute != null && !defaultValueAttribute.isEmpty()){
ProducedType decodedType = decodeType(defaultValueAttribute, scope, moduleScope,
"type parameter '"+param.getName()+"' defaultValue");
param.setDefaultTypeArgument(decodedType);
param.setDefaulted(true);
}
}
}
private boolean hasNonErasedBounds(TypeParameterMirror typeParameterMirror) {
List<TypeMirror> bounds = typeParameterMirror.getBounds();
// if we have at least one bound and not a single Object one
return bounds.size() > 0
&& (bounds.size() != 1
|| !sameType(bounds.get(0), OBJECT_TYPE));
}
private void setListOfTypes(List<ProducedType> destinationTypeList, List<String> serialisedTypes, Scope scope, Module moduleScope,
String targetType) {
if(serialisedTypes != null){
for (String serialisedType : serialisedTypes) {
ProducedType decodedType = decodeType(serialisedType, scope, moduleScope, targetType);
destinationTypeList.add(decodedType);
}
}
}
// from java type info
@SuppressWarnings("deprecation")
private void setTypeParameters(Scope scope, List<TypeParameter> params, List<TypeParameterMirror> typeParameters) {
// We must first add every type param, before we resolve the bounds, which can
// refer to type params.
for(TypeParameterMirror typeParam : typeParameters){
TypeParameter param = new TypeParameter();
param.setUnit(((Element)scope).getUnit());
param.setContainer(scope);
param.setDeclaration((Declaration) scope);
// let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface
if(scope instanceof LazyContainer)
((LazyContainer)scope).addMember(param);
else // must be a method
scope.getMembers().add(param);
param.setName(typeParam.getName());
param.setExtendedType(typeFactory.getAnythingDeclaration().getType());
params.add(param);
}
// Now all type params have been set, we can resolve the references parts
Iterator<TypeParameter> paramsIterator = params.iterator();
for(TypeParameterMirror typeParam : typeParameters){
TypeParameter param = paramsIterator.next();
List<TypeMirror> bounds = typeParam.getBounds();
for(TypeMirror bound : bounds){
ProducedType boundType;
// we turn java's default upper bound java.lang.Object into ceylon.language.Object
if(sameType(bound, OBJECT_TYPE)){
// avoid adding java's default upper bound if it's just there with no meaning
if(bounds.size() == 1)
break;
boundType = getNonPrimitiveType(getLanguageModule(), CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT);
}else
boundType = getNonPrimitiveType(Decl.getModuleContainer(scope), bound, scope, VarianceLocation.INVARIANT);
param.getSatisfiedTypes().add(boundType);
}
}
}
// method
private void setTypeParameters(Method method, MethodMirror methodMirror) {
List<TypeParameter> params = new LinkedList<TypeParameter>();
method.setTypeParameters(params);
List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(methodMirror);
if(typeParameters != null) {
setTypeParametersFromAnnotations(method, params, methodMirror, typeParameters, methodMirror.getTypeParameters());
} else {
setTypeParameters(method, params, methodMirror.getTypeParameters());
}
}
// class
private void setTypeParameters(TypeDeclaration klass, ClassMirror classMirror) {
List<TypeParameter> params = new LinkedList<TypeParameter>();
klass.setTypeParameters(params);
List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(classMirror);
if(typeParameters != null) {
setTypeParametersFromAnnotations(klass, params, classMirror, typeParameters, classMirror.getTypeParameters());
} else {
setTypeParameters(klass, params, classMirror.getTypeParameters());
}
}
//
// TypeParsing and ModelLoader
private ProducedType decodeType(String value, Scope scope, Module moduleScope, String targetType) {
return decodeType(value, scope, moduleScope, targetType, null);
}
private ProducedType decodeType(String value, Scope scope, Module moduleScope, String targetType, Declaration target) {
try{
return typeParser.decodeType(value, scope, moduleScope);
}catch(TypeParserException x){
String text = formatTypeErrorMessage("Error while parsing type of", targetType, target, scope);
return logModelResolutionException(x.getMessage(), scope, text);
}catch(ModelResolutionException x){
String text = formatTypeErrorMessage("Error while resolving type of", targetType, target, scope);
return logModelResolutionException(x, scope, text);
}
}
private String formatTypeErrorMessage(String prefix, String targetType, Declaration target, Scope scope) {
String forTarget;
if(target != null)
forTarget = " for "+target.getQualifiedNameString();
else if(scope != null)
forTarget = " for "+scope.getQualifiedNameString();
else
forTarget = "";
return prefix+" "+targetType+forTarget;
}
/** Warning: only valid for toplevel types, not for type parameters */
private ProducedType obtainType(TypeMirror type, AnnotatedMirror symbol, Scope scope, Module moduleScope, VarianceLocation variance,
String targetType, Declaration target) {
String typeName = getAnnotationStringValue(symbol, CEYLON_TYPE_INFO_ANNOTATION);
if (typeName != null) {
ProducedType ret = decodeType(typeName, scope, moduleScope, targetType, target);
// even decoded types need to fit with the reality of the underlying type
ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TOPLEVEL));
return ret;
} else {
try{
return obtainType(moduleScope, type, scope, TypeLocation.TOPLEVEL, variance);
}catch(ModelResolutionException x){
String text = formatTypeErrorMessage("Error while resolving type of", targetType, target, scope);
return logModelResolutionException(x, scope, text);
}
}
}
private enum TypeLocation {
TOPLEVEL, TYPE_PARAM;
}
private enum VarianceLocation {
/**
* Used in parameter
*/
CONTRAVARIANT,
/**
* Used in method return value
*/
COVARIANT,
/**
* For field
*/
INVARIANT;
}
private String getUnderlyingType(TypeMirror type, TypeLocation location){
// don't erase to c.l.String if in a type param location
if ((sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM)
|| sameType(type, PRIM_BYTE_TYPE)
|| sameType(type, PRIM_SHORT_TYPE)
|| sameType(type, PRIM_INT_TYPE)
|| sameType(type, PRIM_FLOAT_TYPE)
|| sameType(type, PRIM_CHAR_TYPE)) {
return type.getQualifiedName();
}
return null;
}
private ProducedType obtainType(Module moduleScope, TypeMirror type, Scope scope, TypeLocation location, VarianceLocation variance) {
TypeMirror originalType = type;
// ERASURE
type = applyTypeMapping(type, location);
ProducedType ret = getNonPrimitiveType(moduleScope, type, scope, variance);
if (ret.getUnderlyingType() == null) {
ret.setUnderlyingType(getUnderlyingType(originalType, location));
}
return ret;
}
private TypeMirror applyTypeMapping(TypeMirror type, TypeLocation location) {
// don't erase to c.l.String if in a type param location
if (sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) {
return CEYLON_STRING_TYPE;
} else if (sameType(type, PRIM_BOOLEAN_TYPE)) {
return CEYLON_BOOLEAN_TYPE;
} else if (sameType(type, PRIM_BYTE_TYPE)) {
return CEYLON_INTEGER_TYPE;
} else if (sameType(type, PRIM_SHORT_TYPE)) {
return CEYLON_INTEGER_TYPE;
} else if (sameType(type, PRIM_INT_TYPE)) {
return CEYLON_INTEGER_TYPE;
} else if (sameType(type, PRIM_LONG_TYPE)) {
return CEYLON_INTEGER_TYPE;
} else if (sameType(type, PRIM_FLOAT_TYPE)) {
return CEYLON_FLOAT_TYPE;
} else if (sameType(type, PRIM_DOUBLE_TYPE)) {
return CEYLON_FLOAT_TYPE;
} else if (sameType(type, PRIM_CHAR_TYPE)) {
return CEYLON_CHARACTER_TYPE;
} else if (sameType(type, OBJECT_TYPE)) {
return CEYLON_OBJECT_TYPE;
} else if (type.getKind() == TypeKind.ARRAY) {
TypeMirror ct = type.getComponentType();
if (sameType(ct, PRIM_BOOLEAN_TYPE)) {
return JAVA_BOOLEAN_ARRAY_TYPE;
} else if (sameType(ct, PRIM_BYTE_TYPE)) {
return JAVA_BYTE_ARRAY_TYPE;
} else if (sameType(ct, PRIM_SHORT_TYPE)) {
return JAVA_SHORT_ARRAY_TYPE;
} else if (sameType(ct, PRIM_INT_TYPE)) {
return JAVA_INT_ARRAY_TYPE;
} else if (sameType(ct, PRIM_LONG_TYPE)) {
return JAVA_LONG_ARRAY_TYPE;
} else if (sameType(ct, PRIM_FLOAT_TYPE)) {
return JAVA_FLOAT_ARRAY_TYPE;
} else if (sameType(ct, PRIM_DOUBLE_TYPE)) {
return JAVA_DOUBLE_ARRAY_TYPE;
} else if (sameType(ct, PRIM_CHAR_TYPE)) {
return JAVA_CHAR_ARRAY_TYPE;
} else {
// object array
return new SimpleReflType(JAVA_LANG_OBJECT_ARRAY, SimpleReflType.Module.JDK, TypeKind.DECLARED, ct);
}
}
return type;
}
private boolean sameType(TypeMirror t1, TypeMirror t2) {
// make sure we deal with arrays which can't have a qualified name
if(t1.getKind() == TypeKind.ARRAY){
if(t2.getKind() != TypeKind.ARRAY)
return false;
return sameType(t1.getComponentType(), t2.getComponentType());
}
if(t2.getKind() == TypeKind.ARRAY)
return false;
// the rest should be OK
return t1.getQualifiedName().equals(t2.getQualifiedName());
}
@Override
public Declaration getDeclaration(Module module, String typeName, DeclarationType declarationType) {
return convertToDeclaration(module, typeName, declarationType);
}
private ProducedType getNonPrimitiveType(Module moduleScope, TypeMirror type, Scope scope, VarianceLocation variance) {
TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(moduleScope, type, scope, DeclarationType.TYPE);
if(declaration == null){
throw new ModelResolutionException("Failed to find declaration for "+type.getQualifiedName());
}
return applyTypeArguments(moduleScope, declaration, type, scope, variance, TypeMappingMode.NORMAL, null);
}
private enum TypeMappingMode {
NORMAL, GENERATOR
}
@SuppressWarnings("serial")
private static class RecursiveTypeParameterBoundException extends RuntimeException {}
private ProducedType applyTypeArguments(Module moduleScope, TypeDeclaration declaration,
TypeMirror type, Scope scope, VarianceLocation variance,
TypeMappingMode mode, Set<TypeDeclaration> rawDeclarationsSeen) {
List<TypeMirror> javacTypeArguments = type.getTypeArguments();
if(!javacTypeArguments.isEmpty()){
// detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>>
if(rawDeclarationsSeen != null && !rawDeclarationsSeen.add(declaration))
throw new RecursiveTypeParameterBoundException();
try{
List<ProducedType> typeArguments = new ArrayList<ProducedType>(javacTypeArguments.size());
for(TypeMirror typeArgument : javacTypeArguments){
// if a single type argument is a wildcard and we are in a covariant location, we erase to Object
if(typeArgument.getKind() == TypeKind.WILDCARD){
// if contravariant or if it's a ceylon type we use its bound
if(variance == VarianceLocation.CONTRAVARIANT || Decl.isCeylon(declaration)){
TypeMirror bound = typeArgument.getUpperBound();
if(bound == null)
bound = typeArgument.getLowerBound();
// if it has no bound let's take Object
if(bound == null){
// add the type arg and move to the next one
typeArguments.add(typeFactory.getObjectDeclaration().getType());
continue;
}
typeArgument = bound;
} else {
ProducedType result = typeFactory.getObjectDeclaration().getType();
result.setUnderlyingType(type.getQualifiedName());
return result;
}
}
ProducedType producedTypeArgument;
if(mode == TypeMappingMode.NORMAL)
producedTypeArgument = obtainType(moduleScope, typeArgument, scope, TypeLocation.TYPE_PARAM, variance);
else
producedTypeArgument = obtainTypeParameterBound(moduleScope, typeArgument, scope, rawDeclarationsSeen);
typeArguments.add(producedTypeArgument);
}
return declaration.getProducedType(getQualifyingType(declaration), typeArguments);
}finally{
if(rawDeclarationsSeen != null)
rawDeclarationsSeen.remove(declaration);
}
}else if(!declaration.getTypeParameters().isEmpty()){
// we have a raw type
ProducedType result;
if(variance == VarianceLocation.CONTRAVARIANT || Decl.isCeylon(declaration)){
// detect recursive bounds that we can't possibly satisfy, such as Foo<T extends Foo<T>>
if(rawDeclarationsSeen == null)
rawDeclarationsSeen = new HashSet<TypeDeclaration>();
if(!rawDeclarationsSeen.add(declaration))
throw new RecursiveTypeParameterBoundException();
try{
// generate a compatible bound for each type parameter
int count = declaration.getTypeParameters().size();
List<ProducedType> typeArguments = new ArrayList<ProducedType>(count);
for(TypeParameterMirror tp : type.getDeclaredClass().getTypeParameters()){
// FIXME: multiple bounds?
if(tp.getBounds().size() == 1){
TypeMirror bound = tp.getBounds().get(0);
typeArguments.add(obtainTypeParameterBound(moduleScope, bound, declaration, rawDeclarationsSeen));
}else
typeArguments.add(typeFactory.getObjectDeclaration().getType());
}
result = declaration.getProducedType(getQualifyingType(declaration), typeArguments);
}catch(RecursiveTypeParameterBoundException x){
// damnit, go for Object
result = typeFactory.getObjectDeclaration().getType();
}finally{
rawDeclarationsSeen.remove(declaration);
}
}else{
// covariant raw erases to Object
result = typeFactory.getObjectDeclaration().getType();
}
result.setUnderlyingType(type.getQualifiedName());
result.setRaw(true);
return result;
}
return declaration.getType();
}
private ProducedType obtainTypeParameterBound(Module moduleScope, TypeMirror type, Scope scope, Set<TypeDeclaration> rawDeclarationsSeen) {
// type variables are never mapped
if(type.getKind() == TypeKind.TYPEVAR){
TypeParameterMirror typeParameter = type.getTypeParameter();
if(!typeParameter.getBounds().isEmpty()){
IntersectionType it = new IntersectionType(typeFactory);
for(TypeMirror bound : typeParameter.getBounds()){
ProducedType boundModel = obtainTypeParameterBound(moduleScope, bound, scope, rawDeclarationsSeen);
it.getSatisfiedTypes().add(boundModel);
}
return it.getType();
}else
// no bound is Object
return typeFactory.getObjectDeclaration().getType();
}else{
TypeMirror mappedType = applyTypeMapping(type, TypeLocation.TYPE_PARAM);
TypeDeclaration declaration = (TypeDeclaration) convertNonPrimitiveTypeToDeclaration(moduleScope, mappedType, scope, DeclarationType.TYPE);
if(declaration == null){
throw new RuntimeException("Failed to find declaration for "+type);
}
ProducedType ret = applyTypeArguments(moduleScope, declaration, type, scope, VarianceLocation.CONTRAVARIANT, TypeMappingMode.GENERATOR, rawDeclarationsSeen);
if (ret.getUnderlyingType() == null) {
ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TYPE_PARAM));
}
return ret;
}
}
private ProducedType getQualifyingType(TypeDeclaration declaration) {
// As taken from ProducedType.getType():
if (declaration.isMember()) {
return((ClassOrInterface) declaration.getContainer()).getType();
}
return null;
}
@Override
public synchronized ProducedType getType(Module module, String pkgName, String name, Scope scope) {
if(scope != null){
TypeParameter typeParameter = lookupTypeParameter(scope, name);
if(typeParameter != null)
return typeParameter.getType();
}
if(!isBootstrap || !name.startsWith(CEYLON_LANGUAGE)) {
if(scope != null && pkgName != null){
Package containingPackage = Decl.getPackageContainer(scope);
Package pkg = containingPackage.getModule().getPackage(pkgName);
String relativeName = null;
String unquotedName = name.replace("$", "");
if(!pkgName.isEmpty()){
if(unquotedName.startsWith(pkgName+"."))
relativeName = unquotedName.substring(pkgName.length()+1);
// else we don't try it's not in this package
}else
relativeName = unquotedName;
if(relativeName != null && pkg != null){
Declaration declaration = pkg.getDirectMember(relativeName, null, false);
// if we get a value, we want its type
if(Decl.isValue(declaration)
&& ((Value)declaration).getTypeDeclaration().getName().equals(relativeName))
declaration = ((Value)declaration).getTypeDeclaration();
if(declaration instanceof TypeDeclaration)
return ((TypeDeclaration)declaration).getType();
// if we have something but it's not a type decl, it's a:
// - value that's not an object (why would we get its type here?)
// - method (doesn't have a type of the same name)
if(declaration != null)
return null;
}
}
Declaration declaration = convertToDeclaration(module, name, DeclarationType.TYPE);
if(declaration instanceof TypeDeclaration)
return ((TypeDeclaration)declaration).getType();
// we're looking for type declarations, so anything else doesn't work for us
return null;
}
return findLanguageModuleDeclarationForBootstrap(name);
}
private ProducedType findLanguageModuleDeclarationForBootstrap(String name) {
// make sure we don't return anything for ceylon.language
if(name.equals(CEYLON_LANGUAGE))
return null;
// we're bootstrapping ceylon.language so we need to return the ProducedTypes straight from the model we're compiling
Module languageModule = modules.getLanguageModule();
int lastDot = name.lastIndexOf(".");
if(lastDot == -1)
return null;
String pkgName = name.substring(0, lastDot);
String simpleName = name.substring(lastDot+1);
// Nothing is a special case with no real decl
if(name.equals("ceylon.language.Nothing"))
return typeFactory.getNothingDeclaration().getType();
// find the right package
Package pkg = languageModule.getDirectPackage(pkgName);
if(pkg != null){
Declaration member = pkg.getDirectMember(simpleName, null, false);
// if we get a value, we want its type
if(Decl.isValue(member)
&& ((Value)member).getTypeDeclaration().getName().equals(simpleName)){
member = ((Value)member).getTypeDeclaration();
}
if(member instanceof TypeDeclaration)
return ((TypeDeclaration)member).getType();
}
throw new ModelResolutionException("Failed to look up given type in language module while bootstrapping: "+name);
}
public synchronized void removeDeclarations(List<Declaration> declarations) {
List<String> keysToRemove = new ArrayList<String>();
// keep in sync with getOrCreateDeclaration
for (Declaration decl : declarations) {
String prefix = null, otherPrefix = null;
String fqn = decl.getQualifiedNameString().replace("::", ".");
Module module = Decl.getModuleContainer(decl.getContainer());
if(Decl.isToplevel(decl)){
if(Decl.isValue(decl)){
prefix = "V";
if(((Value)decl).getTypeDeclaration().isAnonymous())
otherPrefix = "C";
}else if(Decl.isMethod(decl))
prefix = "V";
}
if(decl instanceof ClassOrInterface){
prefix = "C";
}
// ignore declarations which we do not cache, like member method/attributes
if(prefix != null){
declarationsByName.remove(cacheKeyByModule(module, prefix + fqn));
if(otherPrefix != null)
declarationsByName.remove(cacheKeyByModule(module, otherPrefix + fqn));
}
}
for (Declaration decl : declarations) {
if (decl instanceof LazyClass || decl instanceof LazyInterface) {
Module module = Decl.getModuleContainer(decl.getContainer());
classMirrorCache.remove(cacheKeyByModule(module, decl.getQualifiedNameString().replace("::", ".")));
}
}
}
public synchronized void printStats(){
int loaded = 0;
class Stats {
int loaded, total;
}
Map<Package, Stats> loadedByPackage = new HashMap<Package, Stats>();
for(Declaration decl : declarationsByName.values()){
if(decl instanceof LazyElement){
Package pkg = getPackage(decl);
if(pkg == null){
logVerbose("[Model loader stats: declaration "+decl.getName()+" has no package. Skipping.]");
continue;
}
Stats stats = loadedByPackage.get(pkg);
if(stats == null){
stats = new Stats();
loadedByPackage.put(pkg, stats);
}
stats.total++;
if(((LazyElement)decl).isLoaded()){
loaded++;
stats.loaded++;
}
}
}
logVerbose("[Model loader: "+loaded+"(loaded)/"+declarationsByName.size()+"(total) declarations]");
for(Entry<Package, Stats> packageEntry : loadedByPackage.entrySet()){
logVerbose("[ Package "+packageEntry.getKey().getNameAsString()+": "
+packageEntry.getValue().loaded+"(loaded)/"+packageEntry.getValue().total+"(total) declarations]");
}
}
private static Package getPackage(Object decl) {
if(decl == null)
return null;
if(decl instanceof Package)
return (Package) decl;
return getPackage(((Declaration)decl).getContainer());
}
protected void logMissingOracleType(String type) {
logVerbose("Hopefully harmless completion failure in model loader: "+type
+". This is most likely when the JDK depends on Oracle private classes that we can't find."
+" As a result some model information will be incomplete.");
}
public void setupSourceFileObjects(List<?> treeHolders) {
}
public static boolean isJDKModule(String name) {
return JDKUtils.isJDKModule(name)
|| JDKUtils.isOracleJDKModule(name);
}
@Override
public Module getLoadedModule(String moduleName) {
// FIXME: version?
for(Module mod : modules.getListOfModules()){
if(mod.getNameAsString().equals(moduleName))
return mod;
}
return null;
}
public Module getLanguageModule() {
return modules.getLanguageModule();
}
public Module findModule(String name, String version){
if(name.equals(Module.DEFAULT_MODULE_NAME))
return modules.getDefaultModule();
for(Module module : modules.getListOfModules()){
if(module.getNameAsString().equals(name)
&& (version == null || module.getVersion() == null || version.equals(module.getVersion())))
return module;
}
return null;
}
public Module getJDKBaseModule() {
return findModule(JAVA_BASE_MODULE_NAME, JDK_MODULE_VERSION);
}
public Module findModuleForFile(File file){
File path = file.getParentFile();
while (path != null) {
String name = path.getPath().replaceAll("[\\\\/]", ".");
Module m = getLoadedModule(name);
if (m != null) {
return m;
}
path = path.getParentFile();
}
return modules.getDefaultModule();
}
protected abstract Module findModuleForClassMirror(ClassMirror classMirror);
protected boolean isTypeHidden(Module module, String qualifiedName){
return module.getNameAsString().equals(JAVA_BASE_MODULE_NAME)
&& qualifiedName.equals("java.lang.Object");
}
public synchronized Package findPackage(String quotedPkgName) {
String pkgName = quotedPkgName.replace("$", "");
// in theory we only have one package with the same name per module in javac
for(Package pkg : packagesByName.values()){
if(pkg.getNameAsString().equals(pkgName))
return pkg;
}
return null;
}
/**
* See explanation in cacheModulelessPackages() below. This is called by LanguageCompiler during loadCompiledModules().
*/
public synchronized LazyPackage findOrCreateModulelessPackage(String pkgName) {
LazyPackage pkg = modulelessPackages.get(pkgName);
if(pkg != null)
return pkg;
pkg = new LazyPackage(this);
// FIXME: some refactoring needed
pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\.")));
modulelessPackages.put(pkgName, pkg);
return pkg;
}
/**
* Stef: this sucks balls, but the typechecker wants Packages created before we have any Module set up, including for parsing a module
* file, and because the model loader looks up packages and caches them using their modules, we can't really have packages before we
* have modules. Rather than rewrite the typechecker, we create moduleless packages during parsing, which means they are not cached with
* their modules, and after the loadCompiledModules step above, we fix the package modules. Remains to be done is to move the packages
* created from their cache to the right per-module cache.
*/
public synchronized void cacheModulelessPackages(){
for(LazyPackage pkg : modulelessPackages.values()){
String quotedPkgName = Util.quoteJavaKeywords(pkg.getQualifiedNameString());
packagesByName.put(cacheKeyByModule(pkg.getModule(), quotedPkgName), pkg);
}
modulelessPackages.clear();
}
/**
* Stef: after a lot of attempting, I failed to make the CompilerModuleManager produce a LazyPackage when the ModuleManager.initCoreModules
* is called for the default package. Because it is called by the PhasedUnits constructor, which is called by the ModelLoader constructor,
* which means the model loader is not yet in the context, so the CompilerModuleManager can't obtain it to pass it to the LazyPackage
* constructor. A rewrite of the logic of the typechecker scanning would fix this, but at this point it's just faster to let it create
* the wrong default package and fix it before we start parsing anything.
*/
public synchronized void fixDefaultPackage() {
Module defaultModule = modules.getDefaultModule();
Package defaultPackage = defaultModule.getDirectPackage("");
if(defaultPackage instanceof LazyPackage == false){
LazyPackage newPkg = findOrCreateModulelessPackage("");
List<Package> defaultModulePackages = defaultModule.getPackages();
if(defaultModulePackages.size() != 1)
throw new RuntimeException("Assertion failed: default module has more than the default package: "+defaultModulePackages.size());
defaultModulePackages.clear();
defaultModulePackages.add(newPkg);
newPkg.setModule(defaultModule);
defaultPackage.setModule(null);
}
}
protected boolean isImported(Module moduleScope, Module importedModule) {
if(moduleScope == importedModule)
return true;
if(isImportedSpecialRules(moduleScope, importedModule))
return true;
Set<Module> visited = new HashSet<Module>();
visited.add(moduleScope);
for(ModuleImport imp : moduleScope.getImports()){
if(imp.getModule() == importedModule)
return true;
if(imp.isExport() && isImportedTransitively(imp.getModule(), importedModule, visited))
return true;
}
return false;
}
private boolean isImportedSpecialRules(Module moduleScope, Module importedModule) {
String moduleScopeName = moduleScope.getNameAsString();
String importedModuleName = importedModule.getNameAsString();
// every Java module imports the JDK
// ceylon.language imports the JDK
if((moduleScope.isJava()
|| moduleScope == getLanguageModule())
&& (JDKUtils.isJDKModule(importedModuleName)
|| JDKUtils.isOracleJDKModule(importedModuleName)))
return true;
// everyone imports the language module
if(importedModule == getLanguageModule())
return true;
if(moduleScope == getLanguageModule()){
// this really sucks, I suppose we should set that up better somewhere else
if((importedModuleName.equals("com.redhat.ceylon.compiler.java")
|| importedModuleName.equals("com.redhat.ceylon.typechecker")
|| importedModuleName.equals("com.redhat.ceylon.common")
|| importedModuleName.equals("com.redhat.ceylon.module-resolver"))
&& importedModule.getVersion().equals(Versions.CEYLON_VERSION_NUMBER))
return true;
if(importedModuleName.equals("org.jboss.modules")
&& importedModule.getVersion().equals("1.1.3.GA"))
return true;
}
return false;
}
private boolean isImportedTransitively(Module moduleScope, Module importedModule, Set<Module> visited) {
if(!visited.add(moduleScope))
return false;
for(ModuleImport imp : moduleScope.getImports()){
// only consider exported transitive deps
if(!imp.isExport())
return false;
if(imp.getModule() == importedModule)
return true;
if(isImportedSpecialRules(imp.getModule(), importedModule))
return true;
if(isImportedTransitively(imp.getModule(), importedModule, visited))
return true;
}
return false;
}
}
| false | true | private void complete(ClassOrInterface klass, ClassMirror classMirror) {
Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>();
boolean isFromJDK = isFromJDK(classMirror);
boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null);
// now that everything has containers, do the inner classes
if(klass instanceof Class == false || !((Class)klass).isOverloaded()){
// this will not load inner classes of overloads, but that's fine since we want them in the
// abstracted super class (the real one)
addInnerClasses(klass, classMirror);
}
// Java classes with multiple constructors get turned into multiple Ceylon classes
// Here we get the specific constructor that was assigned to us (if any)
MethodMirror constructor = null;
if (klass instanceof LazyClass) {
constructor = ((LazyClass)klass).getConstructor();
}
// Turn a list of possibly overloaded methods into a map
// of lists that contain methods with the same name
Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>();
for(MethodMirror methodMirror : classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(methodMirror.isStaticInit())
continue;
if(isCeylon && methodMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isFromJDK && !methodMirror.isPublic())
continue;
String methodName = methodMirror.getName();
List<MethodMirror> homonyms = methods.get(methodName);
if (homonyms == null) {
homonyms = new LinkedList<MethodMirror>();
methods.put(methodName, homonyms);
}
homonyms.add(methodMirror);
}
// Add the methods
for(List<MethodMirror> methodMirrors : methods.values()){
boolean isOverloaded = methodMirrors.size() > 1;
List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null;
for (MethodMirror methodMirror : methodMirrors) {
String methodName = methodMirror.getName();
if(methodMirror.isConstructor() || isInstantiator(methodMirror)) {
break;
} else if(isGetter(methodMirror)) {
// simple attribute
addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon);
} else if(isSetter(methodMirror)) {
// We skip setters for now and handle them later
variables.put(methodMirror, methodMirrors);
} else if(isHashAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'hash' attribute from 'hashCode' method
addValue(klass, methodMirror, "hash", isCeylon);
} else if(isStringAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'string' attribute from 'toString' method
addValue(klass, methodMirror, "string", isCeylon);
} else {
// normal method
Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded);
if (isOverloaded) {
overloads.add(m);
}
}
}
if (overloads != null && !overloads.isEmpty()) {
// We create an extra "abstraction" method for overloaded methods
Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false);
abstractionMethod.setAbstraction(true);
abstractionMethod.setOverloads(overloads);
abstractionMethod.setType(new UnknownType(typeFactory).getType());
}
}
for(FieldMirror fieldMirror : classMirror.getDirectFields()){
// We skip members marked with @Ignore
if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(isCeylon && fieldMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isFromJDK && !fieldMirror.isPublic())
continue;
String name = fieldMirror.getName();
// skip the field if "we've already got one"
boolean requireFieldPrefix = klass.getDirectMember(name, null, false) != null
|| "equals".equals(name)
|| "string".equals(name)
|| "hash".equals(name);
if (!requireFieldPrefix) {
addValue(klass, fieldMirror.getName(), fieldMirror, isCeylon);
}else{
addValue(klass, fieldMirror.getName()+"_field", fieldMirror, isCeylon);
}
}
// Having loaded methods and values, we can now set the constructor parameters
if(constructor != null
&& (!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType()))
setParameters((Class)klass, constructor, isCeylon, klass);
// Now marry-up attributes and parameters)
if (klass instanceof Class) {
for (Declaration m : klass.getMembers()) {
if (Decl.isValue(m)) {
Value v = (Value)m;
Parameter p = ((Class)klass).getParameter(v.getName());
if (p != null) {
p.setHidden(true);
}
}
}
}
// Now mark all Values for which Setters exist as variable
for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){
MethodMirror setter = setterEntry.getKey();
String name = getJavaAttributeName(setter.getName());
Declaration decl = klass.getMember(name, null, false);
boolean foundGetter = false;
// skip Java fields, which we only get if there is no getter method, in that case just add the setter method
if (decl instanceof Value && decl instanceof FieldValue == false) {
Value value = (Value)decl;
VariableMirror setterParam = setter.getParameters().get(0);
ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT,
"setter '"+setter.getName()+"'", klass);
// only add the setter if it has exactly the same type as the getter
if(paramType.isExactly(value.getType())){
foundGetter = true;
value.setVariable(true);
if(decl instanceof JavaBeanValue)
((JavaBeanValue)decl).setSetterName(setter.getName());
}else
logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method");
}
if(!foundGetter){
// it was not a setter, it was a method, let's add it as such
addMethod(klass, setter, isCeylon, false);
}
}
// In some cases, where all constructors are ignored, we can end up with no constructor, so
// pretend we have one which takes no parameters (eg. ceylon.language.String).
if(klass instanceof Class
&& !((Class) klass).isAbstraction()
&& !klass.isAnonymous()
&& ((Class) klass).getParameterList() == null){
((Class) klass).setParameterList(new ParameterList());
}
setExtendedType(klass, classMirror);
setSatisfiedTypes(klass, classMirror);
setCaseTypes(klass, classMirror);
fillRefinedDeclarations(klass);
if(isCeylon)
checkReifiedGenericsForMethods(klass, classMirror);
setAnnotations(klass, classMirror);
}
| private void complete(ClassOrInterface klass, ClassMirror classMirror) {
Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>();
boolean isFromJDK = isFromJDK(classMirror);
boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null);
// now that everything has containers, do the inner classes
if(klass instanceof Class == false || !((Class)klass).isOverloaded()){
// this will not load inner classes of overloads, but that's fine since we want them in the
// abstracted super class (the real one)
addInnerClasses(klass, classMirror);
}
// Java classes with multiple constructors get turned into multiple Ceylon classes
// Here we get the specific constructor that was assigned to us (if any)
MethodMirror constructor = null;
if (klass instanceof LazyClass) {
constructor = ((LazyClass)klass).getConstructor();
}
// Turn a list of possibly overloaded methods into a map
// of lists that contain methods with the same name
Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>();
for(MethodMirror methodMirror : classMirror.getDirectMethods()){
// We skip members marked with @Ignore
if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(methodMirror.isStaticInit())
continue;
if(isCeylon && methodMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isFromJDK && !methodMirror.isPublic())
continue;
String methodName = methodMirror.getName();
List<MethodMirror> homonyms = methods.get(methodName);
if (homonyms == null) {
homonyms = new LinkedList<MethodMirror>();
methods.put(methodName, homonyms);
}
homonyms.add(methodMirror);
}
// Add the methods
for(List<MethodMirror> methodMirrors : methods.values()){
boolean isOverloaded = methodMirrors.size() > 1;
List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null;
for (MethodMirror methodMirror : methodMirrors) {
String methodName = methodMirror.getName();
if(methodMirror.isConstructor() || isInstantiator(methodMirror)) {
break;
} else if(isGetter(methodMirror)) {
// simple attribute
addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon);
} else if(isSetter(methodMirror)) {
// We skip setters for now and handle them later
variables.put(methodMirror, methodMirrors);
} else if(isHashAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'hash' attribute from 'hashCode' method
addValue(klass, methodMirror, "hash", isCeylon);
} else if(isStringAttribute(methodMirror)) {
// ERASURE
// Un-erasing 'string' attribute from 'toString' method
addValue(klass, methodMirror, "string", isCeylon);
} else if(!methodMirror.getName().equals("hash")
&& !methodMirror.getName().equals("string")){
// normal method
Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded);
if (isOverloaded) {
overloads.add(m);
}
}
}
if (overloads != null && !overloads.isEmpty()) {
// We create an extra "abstraction" method for overloaded methods
Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false);
abstractionMethod.setAbstraction(true);
abstractionMethod.setOverloads(overloads);
abstractionMethod.setType(new UnknownType(typeFactory).getType());
}
}
for(FieldMirror fieldMirror : classMirror.getDirectFields()){
// We skip members marked with @Ignore
if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null)
continue;
if(isCeylon && fieldMirror.isStatic())
continue;
// FIXME: temporary, because some private classes from the jdk are
// referenced in private methods but not available
if(isFromJDK && !fieldMirror.isPublic())
continue;
String name = fieldMirror.getName();
// skip the field if "we've already got one"
boolean conflicts = klass.getDirectMember(name, null, false) != null
|| "equals".equals(name)
|| "string".equals(name)
|| "hash".equals(name);
if (!conflicts) {
addValue(klass, fieldMirror.getName(), fieldMirror, isCeylon);
}
}
// Having loaded methods and values, we can now set the constructor parameters
if(constructor != null
&& (!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType()))
setParameters((Class)klass, constructor, isCeylon, klass);
// Now marry-up attributes and parameters)
if (klass instanceof Class) {
for (Declaration m : klass.getMembers()) {
if (Decl.isValue(m)) {
Value v = (Value)m;
Parameter p = ((Class)klass).getParameter(v.getName());
if (p != null) {
p.setHidden(true);
}
}
}
}
// Now mark all Values for which Setters exist as variable
for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){
MethodMirror setter = setterEntry.getKey();
String name = getJavaAttributeName(setter.getName());
Declaration decl = klass.getMember(name, null, false);
boolean foundGetter = false;
// skip Java fields, which we only get if there is no getter method, in that case just add the setter method
if (decl instanceof Value && decl instanceof FieldValue == false) {
Value value = (Value)decl;
VariableMirror setterParam = setter.getParameters().get(0);
ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, Decl.getModuleContainer(klass), VarianceLocation.INVARIANT,
"setter '"+setter.getName()+"'", klass);
// only add the setter if it has exactly the same type as the getter
if(paramType.isExactly(value.getType())){
foundGetter = true;
value.setVariable(true);
if(decl instanceof JavaBeanValue)
((JavaBeanValue)decl).setSetterName(setter.getName());
}else
logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method");
}
if(!foundGetter){
// it was not a setter, it was a method, let's add it as such
addMethod(klass, setter, isCeylon, false);
}
}
// In some cases, where all constructors are ignored, we can end up with no constructor, so
// pretend we have one which takes no parameters (eg. ceylon.language.String).
if(klass instanceof Class
&& !((Class) klass).isAbstraction()
&& !klass.isAnonymous()
&& ((Class) klass).getParameterList() == null){
((Class) klass).setParameterList(new ParameterList());
}
setExtendedType(klass, classMirror);
setSatisfiedTypes(klass, classMirror);
setCaseTypes(klass, classMirror);
fillRefinedDeclarations(klass);
if(isCeylon)
checkReifiedGenericsForMethods(klass, classMirror);
setAnnotations(klass, classMirror);
}
|
diff --git a/geoserver/wms/src/main/java/org/vfny/geoserver/wms/responses/map/metatile/MetatileMapProducer.java b/geoserver/wms/src/main/java/org/vfny/geoserver/wms/responses/map/metatile/MetatileMapProducer.java
index 2eacd0489f..5dd77d46ef 100644
--- a/geoserver/wms/src/main/java/org/vfny/geoserver/wms/responses/map/metatile/MetatileMapProducer.java
+++ b/geoserver/wms/src/main/java/org/vfny/geoserver/wms/responses/map/metatile/MetatileMapProducer.java
@@ -1,248 +1,248 @@
/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.vfny.geoserver.wms.responses.map.metatile;
import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.jai.JAI;
import javax.media.jai.operator.CropDescriptor;
import org.geoserver.platform.GeoServerExtensions;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.vfny.geoserver.ServiceException;
import org.vfny.geoserver.wms.GetMapProducer;
import org.vfny.geoserver.wms.RasterMapProducer;
import org.vfny.geoserver.wms.WMSMapContext;
import org.vfny.geoserver.wms.WmsException;
import org.vfny.geoserver.wms.requests.GetMapRequest;
import org.vfny.geoserver.wms.responses.AbstractGetMapProducer;
import org.vfny.geoserver.wms.responses.DefaultRasterMapProducer;
import org.vfny.geoserver.wms.responses.map.metatile.QuickTileCache.MetaTileKey;
/**
* Wrapping map producer that performs on the fly meta tiling wrapping another
* map producer. It will first peek inside a tile cache to see if the requested
* tile has already been computed, if so, it'll encode and return that one,
* otherwise it'll build a meta tile, split it, and finally encode just the
* requested tile, putting the others in the tile cache.
*
* @author Andrea Aime - TOPP
* @author Simone Giannecchini - GeoSolutions
*/
public final class MetatileMapProducer extends AbstractGetMapProducer implements
GetMapProducer {
/** A logger for this class. */
private static final Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.vfny.geoserver.responses.wms.map.metatile");
/** Small number for double equality comparison */
public static final double EPS = 1E-6;
private GetMapRequest request;
private RasterMapProducer delegate;
private RenderedImage tile;
private static QuickTileCache tileCache;
/**
* True if the request has the tiled hint, is 256x256 image, and the raw
* delegate is a raster one
*
* @param request
* @param delegate
* @return
*/
public static boolean isRequestTiled(GetMapRequest request,
GetMapProducer delegate) {
if (!(request.isTiled() && (request.getTilesOrigin() != null)
&& (request.getWidth() == 256) && (request.getHeight() == 256) && delegate instanceof RasterMapProducer)) {
return false;
}
return true;
}
public MetatileMapProducer(GetMapRequest request, RasterMapProducer delegate) {
if(tileCache == null) {
tileCache = (QuickTileCache) GeoServerExtensions.bean("metaTileCache");
}
this.request = request;
this.delegate = delegate;
}
public void produceMap() throws WmsException {
// get the key that identifies the meta tile. The cache will make sure
// two threads asking
// for the same tile will get the same key, and thus will synchronize
// with each other
// (the first eventually builds the meta-tile, the second finds it ready
// to be used)
QuickTileCache.MetaTileKey key = tileCache.getMetaTileKey(request);
synchronized (key) {
tile = tileCache.getTile(key, request);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Looked for meta tile " + key.metaTileCoords.x
+ ", " + key.metaTileCoords.y + "in cache: "
- + ((tile == null) ? "hit!" : "miss"));
+ + ((tile != null) ? "hit!" : "miss"));
}
if (tile == null) {
// compute the meta-tile
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Building meta tile " + key.metaTileCoords.x
+ ", " + key.metaTileCoords.y);
}
// alter the map definition so that we build a meta-tile instead
// of just the tile
ReferencedEnvelope origEnv = mapContext.getAreaOfInterest();
mapContext.setAreaOfInterest(new ReferencedEnvelope(key
.getMetaTileEnvelope(), origEnv
.getCoordinateReferenceSystem()));
mapContext.setMapWidth(key.getTileSize() * key.getMetaFactor());
mapContext
.setMapHeight(key.getTileSize() * key.getMetaFactor());
// generate, split and cache
delegate.setMapContext(mapContext);
// enable meta watermarking
// enable simple watermarking
if (this.delegate instanceof DefaultRasterMapProducer)
((DefaultRasterMapProducer)this.delegate).setWmPainter(new MetatileWatermarkPainter(key, request));
delegate.produceMap();
RenderedImage metaTile = delegate.getImage();
RenderedImage[] tiles = split(key, metaTile, mapContext);
tileCache.storeTiles(key, tiles);
tile = tileCache.getTile(key, request, tiles);
}
}
}
// /**
// * Splits the tile into a set of tiles, numbered from lower right and
// going up so
// * that first row is 0,1,2,...,metaTileFactor, and so on.
// * In the case of a 3x3 meta-tile, the layout is as follows:
// * <pre>
// * 6 7 8
// * 3 4 5
// * 0 1 2
// * </pre>
// * @param key
// * @param metaTile
// * @param map
// * @return
// */
// private BufferedImage[] split(MetaTileKey key, BufferedImage metaTile,
// WMSMapContext map) {
// int metaFactor = key.getMetaFactor();
// BufferedImage[] tiles = new BufferedImage[key.getMetaFactor() *
// key.getMetaFactor()];
// int tileSize = key.getTileSize();
//
// for (int i = 0; i < metaFactor; i++) {
// for (int j = 0; j < metaFactor; j++) {
// // TODO: create child writable rasters instead of cloning the images
// using
// // graphics2d. Should be quite a bit faster and save some memory. Or
// else,
// // store meta-tiles in the cache directly, and extract children tiles
// // on demand (even simpler)
// BufferedImage tile;
//
// // keep the palette if necessary
// if (metaTile.getType() == BufferedImage.TYPE_BYTE_INDEXED) {
// tile = new BufferedImage(tileSize, tileSize,
// BufferedImage.TYPE_BYTE_INDEXED,
// (IndexColorModel) metaTile.getColorModel());
// } else if (metaTile.getType() == BufferedImage.TYPE_CUSTOM) {
// throw new RuntimeException("We don't support custom buffered image
// tiling");
// } else {
// tile = new BufferedImage(tileSize, tileSize, metaTile.getType());
// }
//
// Graphics2D g2d = (Graphics2D) tile.getGraphics();
// AffineTransform at = AffineTransform.getTranslateInstance(-j * tileSize,
// (-tileSize * (metaFactor - 1)) + (i * tileSize));
// setupBackground(g2d, map);
// g2d.drawRenderedImage(metaTile, at);
// g2d.dispose();
// tiles[(i * key.getMetaFactor()) + j] = tile;
// }
// }
//
// return tiles;
// }
/**
* Splits the tile into a set of tiles, numbered from lower right and going
* up so that first row is 0,1,2,...,metaTileFactor, and so on. In the case
* of a 3x3 meta-tile, the layout is as follows:
*
* <pre>
* 6 7 8
* 3 4 5
* 0 1 2
* </pre>
*
* @param key
* @param metaTile
* @param map
* @return
*/
private RenderedImage[] split(MetaTileKey key, RenderedImage metaTile,
WMSMapContext map) {
final int metaFactor = key.getMetaFactor();
final RenderedImage[] tiles = new RenderedImage[key.getMetaFactor()
* key.getMetaFactor()];
final int tileSize = key.getTileSize();
final RenderingHints no_cache = new RenderingHints(JAI.KEY_TILE_CACHE,
null);
for (int i = 0; i < metaFactor; i++) {
for (int j = 0; j < metaFactor; j++) {
int x = j * tileSize;
int y = (tileSize * (metaFactor - 1)) - (i * tileSize);
tile = CropDescriptor.create(metaTile, new Float(x), new Float(
y), new Float(tileSize), new Float(tileSize), no_cache);
tiles[(i * key.getMetaFactor()) + j] = tile;
}
}
return tiles;
}
/**
* Have the delegate encode the tile
*/
public void writeTo(OutputStream out) throws ServiceException, IOException {
delegate.formatImageOutputStream(tile, out);
}
public void abort() {
delegate.abort();
}
public String getContentDisposition() {
return delegate.getContentDisposition();
}
public String getContentType() throws IllegalStateException {
return delegate.getContentType();
}
}
| true | true | public void produceMap() throws WmsException {
// get the key that identifies the meta tile. The cache will make sure
// two threads asking
// for the same tile will get the same key, and thus will synchronize
// with each other
// (the first eventually builds the meta-tile, the second finds it ready
// to be used)
QuickTileCache.MetaTileKey key = tileCache.getMetaTileKey(request);
synchronized (key) {
tile = tileCache.getTile(key, request);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Looked for meta tile " + key.metaTileCoords.x
+ ", " + key.metaTileCoords.y + "in cache: "
+ ((tile == null) ? "hit!" : "miss"));
}
if (tile == null) {
// compute the meta-tile
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Building meta tile " + key.metaTileCoords.x
+ ", " + key.metaTileCoords.y);
}
// alter the map definition so that we build a meta-tile instead
// of just the tile
ReferencedEnvelope origEnv = mapContext.getAreaOfInterest();
mapContext.setAreaOfInterest(new ReferencedEnvelope(key
.getMetaTileEnvelope(), origEnv
.getCoordinateReferenceSystem()));
mapContext.setMapWidth(key.getTileSize() * key.getMetaFactor());
mapContext
.setMapHeight(key.getTileSize() * key.getMetaFactor());
// generate, split and cache
delegate.setMapContext(mapContext);
// enable meta watermarking
// enable simple watermarking
if (this.delegate instanceof DefaultRasterMapProducer)
((DefaultRasterMapProducer)this.delegate).setWmPainter(new MetatileWatermarkPainter(key, request));
delegate.produceMap();
RenderedImage metaTile = delegate.getImage();
RenderedImage[] tiles = split(key, metaTile, mapContext);
tileCache.storeTiles(key, tiles);
tile = tileCache.getTile(key, request, tiles);
}
}
}
| public void produceMap() throws WmsException {
// get the key that identifies the meta tile. The cache will make sure
// two threads asking
// for the same tile will get the same key, and thus will synchronize
// with each other
// (the first eventually builds the meta-tile, the second finds it ready
// to be used)
QuickTileCache.MetaTileKey key = tileCache.getMetaTileKey(request);
synchronized (key) {
tile = tileCache.getTile(key, request);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Looked for meta tile " + key.metaTileCoords.x
+ ", " + key.metaTileCoords.y + "in cache: "
+ ((tile != null) ? "hit!" : "miss"));
}
if (tile == null) {
// compute the meta-tile
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Building meta tile " + key.metaTileCoords.x
+ ", " + key.metaTileCoords.y);
}
// alter the map definition so that we build a meta-tile instead
// of just the tile
ReferencedEnvelope origEnv = mapContext.getAreaOfInterest();
mapContext.setAreaOfInterest(new ReferencedEnvelope(key
.getMetaTileEnvelope(), origEnv
.getCoordinateReferenceSystem()));
mapContext.setMapWidth(key.getTileSize() * key.getMetaFactor());
mapContext
.setMapHeight(key.getTileSize() * key.getMetaFactor());
// generate, split and cache
delegate.setMapContext(mapContext);
// enable meta watermarking
// enable simple watermarking
if (this.delegate instanceof DefaultRasterMapProducer)
((DefaultRasterMapProducer)this.delegate).setWmPainter(new MetatileWatermarkPainter(key, request));
delegate.produceMap();
RenderedImage metaTile = delegate.getImage();
RenderedImage[] tiles = split(key, metaTile, mapContext);
tileCache.storeTiles(key, tiles);
tile = tileCache.getTile(key, request, tiles);
}
}
}
|
diff --git a/src/main/java/com/g2one/hudson/grails/GrailsBuilder.java b/src/main/java/com/g2one/hudson/grails/GrailsBuilder.java
index 9c65255..6f0e23b 100644
--- a/src/main/java/com/g2one/hudson/grails/GrailsBuilder.java
+++ b/src/main/java/com/g2one/hudson/grails/GrailsBuilder.java
@@ -1,365 +1,365 @@
package com.g2one.hudson.grails;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.tasks.Builder;
import hudson.util.ArgumentListBuilder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.UnflaggedOption;
public class GrailsBuilder extends Builder {
private final String targets;
private final String name;
private String grailsWorkDir;
private String projectWorkDir;
private String projectBaseDir;
private String serverPort;
private String properties;
private Boolean forceUpgrade;
private Boolean nonInteractive;
private Boolean useWrapper;
private Boolean plainOutput;
private Boolean stackTrace;
private Boolean verbose;
private Boolean refreshDependencies;
@DataBoundConstructor
public GrailsBuilder(String targets, String name, String grailsWorkDir, String projectWorkDir, String projectBaseDir, String serverPort, String properties, Boolean forceUpgrade, Boolean nonInteractive, Boolean useWrapper, Boolean plainOutput, Boolean stackTrace, Boolean verbose, Boolean refreshDependencies) {
this.name = name;
this.targets = targets;
this.grailsWorkDir = grailsWorkDir;
this.projectWorkDir = projectWorkDir;
this.projectBaseDir = projectBaseDir;
this.serverPort = serverPort;
this.properties = properties;
this.forceUpgrade = forceUpgrade;
this.nonInteractive = nonInteractive;
this.useWrapper = !useWrapper;
this.plainOutput = plainOutput;
this.stackTrace = stackTrace;
this.verbose = verbose;
this.refreshDependencies = refreshDependencies;
}
public boolean getNonInteractive() {
return nonInteractive;
}
public void setNonInteractive(Boolean b) {
nonInteractive = b;
}
public boolean getForceUpgrade() {
return forceUpgrade;
}
public void setForceUpgrade(Boolean b) {
forceUpgrade = b;
}
public String getProperties() {
return properties;
}
public void setProperties(String properties) {
this.properties = properties;
}
public String getProjectBaseDir() {
return projectBaseDir;
}
public void setProjectBaseDir(String projectBaseDir) {
this.projectBaseDir = projectBaseDir;
}
public String getProjectWorkDir() {
return projectWorkDir;
}
public void setProjectWorkDir(String projectWorkDir) {
this.projectWorkDir = projectWorkDir;
}
public String getGrailsWorkDir() {
return grailsWorkDir;
}
public void setGrailsWorkDir(String grailsWorkDir) {
this.grailsWorkDir = grailsWorkDir;
}
public String getServerPort() {
return serverPort;
}
public void setServerPort(String serverPort) {
this.serverPort = serverPort;
}
public String getName() {
return name;
}
public String getTargets() {
return targets;
}
public void setUseWrapper(Boolean useWrapper) {
this.useWrapper = useWrapper;
}
public Boolean getUseWrapper() {
return useWrapper;
}
public Boolean getPlainOutput() {
return plainOutput;
}
public void setPlainOutput(Boolean plainOutput) {
this.plainOutput = plainOutput;
}
public Boolean getStackTrace() {
return stackTrace;
}
public void setStackTrace(Boolean stackTrace) {
this.stackTrace = stackTrace;
}
public Boolean getVerbose() {
return verbose;
}
public void setVerbose(Boolean verbose) {
this.verbose = verbose;
}
public Boolean getRefreshDependencies() {
return refreshDependencies;
}
public void setRefreshDependencies(Boolean refreshDependencies) {
this.refreshDependencies = refreshDependencies;
}
public GrailsInstallation getGrails() {
GrailsInstallation[] installations = Hudson.getInstance()
.getDescriptorByType(GrailsInstallation.DescriptorImpl.class)
.getInstallations();
for (GrailsInstallation i : installations) {
if (name != null && i.getName().equals(name))
return i;
}
return null;
}
private Object readResolve() {
// Default to false when loading old data to preserve previous behavior.
if (nonInteractive == null) nonInteractive = Boolean.FALSE;
if (useWrapper == null) useWrapper = Boolean.FALSE;
return this;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
readResolve();
List<String[]> targetsToRun = getTargetsToRun();
if (targetsToRun.size() > 0) {
String execName;
if (useWrapper) {
FilePath wrapper = new FilePath(getBasePath(build), launcher.isUnix() ? "grailsw" : "grailsw.bat");
execName = wrapper.getRemote();
} else {
execName = launcher.isUnix() ? "grails" : "grails.bat";
}
EnvVars env = build.getEnvironment(listener);
GrailsInstallation grailsInstallation = useWrapper ? null : getGrails();
if (grailsInstallation != null) {
grailsInstallation = grailsInstallation.forEnvironment(env)
.forNode(Computer.currentComputer().getNode(), listener);
env.put("GRAILS_HOME", grailsInstallation.getHome());
}
for (String[] targetsAndArgs : targetsToRun) {
String target = targetsAndArgs[0];
ArgumentListBuilder args = new ArgumentListBuilder();
if (grailsInstallation == null) {
args.add(execName);
} else {
File exec = grailsInstallation.getExecutable();
if (!new FilePath(launcher.getChannel(), grailsInstallation.getExecutable().getPath()).exists()) {
listener.fatalError(exec + " doesn't exist");
return false;
}
args.add(exec.getPath());
}
args.addKeyValuePairs("-D", build.getBuildVariables());
- Map sytemProperties = new HashMap();
+ Map systemProperties = new HashMap();
if (grailsWorkDir != null && !"".equals(grailsWorkDir.trim())) {
- sytemProperties.put("grails.work.dir", evalTarget(env, grailsWorkDir.trim()));
+ systemProperties.put("grails.work.dir", evalTarget(env, grailsWorkDir.trim()));
}
if (projectWorkDir != null && !"".equals(projectWorkDir.trim())) {
- sytemProperties.put("grails.project.work.dir", evalTarget(env, projectWorkDir.trim()));
+ systemProperties.put("grails.project.work.dir", evalTarget(env, projectWorkDir.trim()));
}
if (serverPort != null && !"".equals(serverPort.trim())) {
- sytemProperties.put("server.port", evalTarget(env, serverPort.trim()));
+ systemProperties.put("server.port", evalTarget(env, serverPort.trim()));
}
- if (sytemProperties.size() > 0) {
- args.addKeyValuePairs("-D", sytemProperties);
+ if (systemProperties.size() > 0) {
+ args.addKeyValuePairs("-D", systemProperties);
}
args.addKeyValuePairsFromPropertyString("-D", properties, build.getBuildVariableResolver());
args.add(target);
addArgument("--non-interactive", nonInteractive, args, env, targetsAndArgs);
addArgument("--plain-output", plainOutput, args, env, targetsAndArgs);
addArgument("--stacktrace", stackTrace, args, env, targetsAndArgs);
addArgument("--verbose", verbose, args, env, targetsAndArgs);
addArgument("--refresh-dependencies", refreshDependencies, args, env, targetsAndArgs);
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(getBasePath(build)).join();
if (r != 0) return false;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
} else {
listener.getLogger().println("Error: No Targets To Run!");
return false;
}
return true;
}
private void addArgument(String argument, Boolean option, ArgumentListBuilder args, EnvVars env, String[] targetsAndArgs) {
boolean foundArgument = false;
for (int i = 1; i < targetsAndArgs.length; i++) {
String arg = evalTarget(env, targetsAndArgs[i]);
if(argument.equals(arg)) {
foundArgument = true;
}
args.add(arg);
}
if(option != null && option && !foundArgument) {
args.add(argument);
}
}
private FilePath getBasePath(AbstractBuild<?, ?> build) {
FilePath basePath;
FilePath moduleRoot = build.getModuleRoot();
if (projectBaseDir != null && !"".equals(projectBaseDir.trim())) {
basePath = new FilePath(moduleRoot, projectBaseDir);
} else {
basePath = moduleRoot;
}
return basePath;
}
/**
* Method based on work from Kenji Nakamura
*
* @param env The enviroment vars map
* @param target The target with environment vars
* @return The target with evaluated environment vars
*/
@SuppressWarnings({"StaticMethodOnlyUsedInOneClass", "TypeMayBeWeakened"})
static String evalTarget(Map<String, String> env, String target) {
Binding binding = new Binding();
binding.setVariable("env", env);
binding.setVariable("sys", System.getProperties());
GroovyShell shell = new GroovyShell(binding);
Object result = shell.evaluate("return \"" + target + "\"");
if (result == null) {
return target;
} else {
return result.toString().trim();
}
}
protected List<String[]> getTargetsToRun() {
List<String[]> targetsToRun = new ArrayList<String[]>();
if(forceUpgrade) {
targetsToRun.add(new String[]{"upgrade", "--non-interactive"});
}
if (targets != null && targets.length() > 0) {
try {
JSAP jsap = new JSAP();
UnflaggedOption option = new UnflaggedOption("targets");
option.setGreedy(true);
jsap.registerParameter(option);
JSAPResult jsapResult = jsap.parse(this.targets);
String[] targets = jsapResult.getStringArray("targets");
for (String targetAndArgs : targets) {
String[] pieces = targetAndArgs.split(" ");
targetsToRun.add(pieces);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return targetsToRun;
}
@Extension
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends Descriptor<Builder> {
public String getDisplayName() {
return "Build With Grails";
}
@Override
public synchronized void load() {
// NOP
}
@Override
public Builder newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return req.bindJSON(clazz, formData);
}
public GrailsInstallation[] getInstallations() {
return Hudson.getInstance().getDescriptorByType(GrailsInstallation.DescriptorImpl.class).getInstallations();
}
}
}
| false | true | public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
readResolve();
List<String[]> targetsToRun = getTargetsToRun();
if (targetsToRun.size() > 0) {
String execName;
if (useWrapper) {
FilePath wrapper = new FilePath(getBasePath(build), launcher.isUnix() ? "grailsw" : "grailsw.bat");
execName = wrapper.getRemote();
} else {
execName = launcher.isUnix() ? "grails" : "grails.bat";
}
EnvVars env = build.getEnvironment(listener);
GrailsInstallation grailsInstallation = useWrapper ? null : getGrails();
if (grailsInstallation != null) {
grailsInstallation = grailsInstallation.forEnvironment(env)
.forNode(Computer.currentComputer().getNode(), listener);
env.put("GRAILS_HOME", grailsInstallation.getHome());
}
for (String[] targetsAndArgs : targetsToRun) {
String target = targetsAndArgs[0];
ArgumentListBuilder args = new ArgumentListBuilder();
if (grailsInstallation == null) {
args.add(execName);
} else {
File exec = grailsInstallation.getExecutable();
if (!new FilePath(launcher.getChannel(), grailsInstallation.getExecutable().getPath()).exists()) {
listener.fatalError(exec + " doesn't exist");
return false;
}
args.add(exec.getPath());
}
args.addKeyValuePairs("-D", build.getBuildVariables());
Map sytemProperties = new HashMap();
if (grailsWorkDir != null && !"".equals(grailsWorkDir.trim())) {
sytemProperties.put("grails.work.dir", evalTarget(env, grailsWorkDir.trim()));
}
if (projectWorkDir != null && !"".equals(projectWorkDir.trim())) {
sytemProperties.put("grails.project.work.dir", evalTarget(env, projectWorkDir.trim()));
}
if (serverPort != null && !"".equals(serverPort.trim())) {
sytemProperties.put("server.port", evalTarget(env, serverPort.trim()));
}
if (sytemProperties.size() > 0) {
args.addKeyValuePairs("-D", sytemProperties);
}
args.addKeyValuePairsFromPropertyString("-D", properties, build.getBuildVariableResolver());
args.add(target);
addArgument("--non-interactive", nonInteractive, args, env, targetsAndArgs);
addArgument("--plain-output", plainOutput, args, env, targetsAndArgs);
addArgument("--stacktrace", stackTrace, args, env, targetsAndArgs);
addArgument("--verbose", verbose, args, env, targetsAndArgs);
addArgument("--refresh-dependencies", refreshDependencies, args, env, targetsAndArgs);
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(getBasePath(build)).join();
if (r != 0) return false;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
} else {
listener.getLogger().println("Error: No Targets To Run!");
return false;
}
return true;
}
| public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
readResolve();
List<String[]> targetsToRun = getTargetsToRun();
if (targetsToRun.size() > 0) {
String execName;
if (useWrapper) {
FilePath wrapper = new FilePath(getBasePath(build), launcher.isUnix() ? "grailsw" : "grailsw.bat");
execName = wrapper.getRemote();
} else {
execName = launcher.isUnix() ? "grails" : "grails.bat";
}
EnvVars env = build.getEnvironment(listener);
GrailsInstallation grailsInstallation = useWrapper ? null : getGrails();
if (grailsInstallation != null) {
grailsInstallation = grailsInstallation.forEnvironment(env)
.forNode(Computer.currentComputer().getNode(), listener);
env.put("GRAILS_HOME", grailsInstallation.getHome());
}
for (String[] targetsAndArgs : targetsToRun) {
String target = targetsAndArgs[0];
ArgumentListBuilder args = new ArgumentListBuilder();
if (grailsInstallation == null) {
args.add(execName);
} else {
File exec = grailsInstallation.getExecutable();
if (!new FilePath(launcher.getChannel(), grailsInstallation.getExecutable().getPath()).exists()) {
listener.fatalError(exec + " doesn't exist");
return false;
}
args.add(exec.getPath());
}
args.addKeyValuePairs("-D", build.getBuildVariables());
Map systemProperties = new HashMap();
if (grailsWorkDir != null && !"".equals(grailsWorkDir.trim())) {
systemProperties.put("grails.work.dir", evalTarget(env, grailsWorkDir.trim()));
}
if (projectWorkDir != null && !"".equals(projectWorkDir.trim())) {
systemProperties.put("grails.project.work.dir", evalTarget(env, projectWorkDir.trim()));
}
if (serverPort != null && !"".equals(serverPort.trim())) {
systemProperties.put("server.port", evalTarget(env, serverPort.trim()));
}
if (systemProperties.size() > 0) {
args.addKeyValuePairs("-D", systemProperties);
}
args.addKeyValuePairsFromPropertyString("-D", properties, build.getBuildVariableResolver());
args.add(target);
addArgument("--non-interactive", nonInteractive, args, env, targetsAndArgs);
addArgument("--plain-output", plainOutput, args, env, targetsAndArgs);
addArgument("--stacktrace", stackTrace, args, env, targetsAndArgs);
addArgument("--verbose", verbose, args, env, targetsAndArgs);
addArgument("--refresh-dependencies", refreshDependencies, args, env, targetsAndArgs);
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(getBasePath(build)).join();
if (r != 0) return false;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
} else {
listener.getLogger().println("Error: No Targets To Run!");
return false;
}
return true;
}
|
diff --git a/gxt3-miglayout/src/main/java/net/miginfocom/layout/Grid.java b/gxt3-miglayout/src/main/java/net/miginfocom/layout/Grid.java
index 3fdc2ca..c8ed97a 100644
--- a/gxt3-miglayout/src/main/java/net/miginfocom/layout/Grid.java
+++ b/gxt3-miglayout/src/main/java/net/miginfocom/layout/Grid.java
@@ -1,2299 +1,2299 @@
package net.miginfocom.layout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;
/** Holds components in a grid. Does most of the logic behind the layout manager.
*/
public final class Grid
{
public static final boolean TEST_GAPS = true;
private static final Float[] GROW_100 = new Float[] {ResizeConstraint.WEIGHT_100};
private static final DimConstraint DOCK_DIM_CONSTRAINT = new DimConstraint();
static {
DOCK_DIM_CONSTRAINT.setGrowPriority(0);
}
/** This is the maximum grid position for "normal" components. Docking components use the space out to
* <code>MAX_DOCK_GRID</code> and below 0.
*/
private static final int MAX_GRID = 30000;
/** Docking components will use the grid coordinates <code>-MAX_DOCK_GRID -> 0</code> and <code>MAX_GRID -> MAX_DOCK_GRID</code>.
*/
private static final int MAX_DOCK_GRID = 32767;
/** A constraint used for gaps.
*/
private static final ResizeConstraint GAP_RC_CONST = new ResizeConstraint(200, ResizeConstraint.WEIGHT_100, 50, null);
private static final ResizeConstraint GAP_RC_CONST_PUSH = new ResizeConstraint(200, ResizeConstraint.WEIGHT_100, 50, ResizeConstraint.WEIGHT_100);
/** Used for components that doesn't have a CC set. Not that it's really really important that the CC is never changed in this Grid class.
*/
private static final CC DEF_CC = new CC();
/** The constraints. Never <code>null</code>.
*/
private final LC lc;
/** The parent that is layout out and this grid is done for. Never <code>null</code>.
*/
private final ContainerWrapper container;
/** An x, y array implemented as a sparse array to accommodate for any grid size without wasting memory (or rather 15 bit (0-MAX_GRID * 0-MAX_GRID).
*/
private final LinkedHashMap<Integer, Cell> grid = new LinkedHashMap<Integer, Cell>(); // [(y << 16) + x] -> Cell. null key for absolute positioned compwraps
private HashMap<Integer, BoundSize> wrapGapMap = null; // Row or Column index depending in the dimension that "wraps". Normally row indexes but may be column indexes if "flowy". 0 means before first row/col.
/** The size of the grid. Row count and column count.
*/
private final TreeSet<Integer> rowIndexes = new TreeSet<Integer>(), colIndexes = new TreeSet<Integer>();
/** The row and column specifications.
*/
private final AC rowConstr, colConstr;
/** The in the constructor calculated min/pref/max sizes of the rows and columns.
*/
private FlowSizeSpec colFlowSpecs = null, rowFlowSpecs = null;
/** Components that are connections in one dimension (such as baseline alignment for instance) are grouped together and stored here.
* One for each row/column.
*/
private final ArrayList<LinkedDimGroup>[] colGroupLists, rowGroupLists; //[(start)row/col number]
/** The in the constructor calculated min/pref/max size of the whole grid.
*/
private int[] width = null, height = null;
/** If debug is on contains the bounds for things to paint when calling {@link ContainerWrapper#paintDebugCell(int, int, int, int)}
*/
private ArrayList<int[]> debugRects = null; // [x, y, width, height]
/** If any of the absolute coordinates for component bounds has links the name of the target is in this Set.
* Since it requires some memory and computations this is checked at the creation so that
* the link information is only created if needed later.
* <p>
* The boolean is true for groups id:s and null for normal id:s.
*/
private HashMap<String, Boolean> linkTargetIDs = null;
private final int dockOffY, dockOffX;
private final Float[] pushXs, pushYs;
private final ArrayList<LayoutCallback> callbackList;
/** Constructor.
* @param container The container that will be laid out.
* @param lc The form flow constraints.
* @param rowConstr The rows specifications. If more cell rows are required, the last element will be used for when there is no corresponding element in this array.
* @param colConstr The columns specifications. If more cell rows are required, the last element will be used for when there is no corresponding element in this array.
* @param ccMap The map containing the parsed constraints for each child component of <code>parent</code>. Will not be altered.
* @param callbackList A list of callbacks or <code>null</code> if none. Will not be altered.
*/
public Grid(ContainerWrapper container, LC lc, AC rowConstr, AC colConstr, Map<ComponentWrapper, CC> ccMap, ArrayList<LayoutCallback> callbackList)
{
this.lc = lc;
this.rowConstr = rowConstr;
this.colConstr = colConstr;
this.container = container;
this.callbackList = callbackList;
int wrap = lc.getWrapAfter() != 0 ? lc.getWrapAfter() : (lc.isFlowX() ? colConstr : rowConstr).getConstaints().length;
final ComponentWrapper[] comps = container.getComponents();
boolean hasTagged = false; // So we do not have to sort if it will not do any good
boolean hasPushX = false, hasPushY = false;
boolean hitEndOfRow = false;
final int[] cellXY = new int[2];
final ArrayList<int[]> spannedRects = new ArrayList<int[]>(2);
final DimConstraint[] specs = (lc.isFlowX() ? rowConstr : colConstr).getConstaints();
int sizeGroupsX = 0, sizeGroupsY = 0;
int[] dockInsets = null; // top, left, bottom, right insets for docks.
LinkHandler.clearTemporaryBounds(container.getLayout());
for (int i = 0; i < comps.length;) {
ComponentWrapper comp = comps[i];
CC rootCc = getCC(comp, ccMap);
addLinkIDs(rootCc);
int hideMode = comp.isVisible() ? -1 : rootCc.getHideMode() != -1 ? rootCc.getHideMode() : lc.getHideMode();
if (hideMode == 3) { // To work with situations where there are components that does not have a layout manager, or not this one.
setLinkedBounds(comp, rootCc, comp.getX(), comp.getY(), comp.getWidth(), comp.getHeight(), rootCc.isExternal());
i++;
continue; // The "external" component should not be handled further.
}
if (rootCc.getHorizontal().getSizeGroup() != null)
sizeGroupsX++;
if (rootCc.getVertical().getSizeGroup() != null)
sizeGroupsY++;
// Special treatment of absolute positioned components.
UnitValue[] pos = getPos(comp, rootCc);
BoundSize[] cbSz = getCallbackSize(comp);
if (pos != null || rootCc.isExternal()) {
CompWrap cw = new CompWrap(comp, rootCc, hideMode, pos, cbSz);
Cell cell = grid.get(null);
if (cell == null) {
grid.put(null, new Cell(cw));
} else {
cell.compWraps.add(cw);
}
if (rootCc.isBoundsInGrid() == false || rootCc.isExternal()) {
setLinkedBounds(comp, rootCc, comp.getX(), comp.getY(), comp.getWidth(), comp.getHeight(), rootCc.isExternal());
i++;
continue;
}
}
if (rootCc.getDockSide() != -1) {
if (dockInsets == null)
dockInsets = new int[] {-MAX_DOCK_GRID, -MAX_DOCK_GRID, MAX_DOCK_GRID, MAX_DOCK_GRID};
addDockingCell(dockInsets, rootCc.getDockSide(), new CompWrap(comp, rootCc, hideMode, pos, cbSz));
i++;
continue;
}
Boolean cellFlowX = rootCc.getFlowX();
Cell cell = null;
if (rootCc.isNewline()) {
wrap(cellXY, rootCc.getNewlineGapSize());
} else if (hitEndOfRow) {
wrap(cellXY, null);
}
hitEndOfRow = false;
final boolean rowNoGrid = lc.isNoGrid() || ((DimConstraint) LayoutUtil.getIndexSafe(specs, lc.isFlowX() ? cellXY[1] : cellXY[0])).isNoGrid();
// Move to a free y, x if no absolute grid specified
int cx = rootCc.getCellX();
int cy = rootCc.getCellY();
if ((cx < 0 || cy < 0) && rowNoGrid == false && rootCc.getSkip() == 0) { // 3.7.2: If skip, don't find an empty cell first.
while (isCellFree(cellXY[1], cellXY[0], spannedRects) == false) {
if (Math.abs(increase(cellXY, 1)) >= wrap)
wrap(cellXY, null);
}
} else {
if (cx >= 0 && cy >= 0) {
if (cy >= 0) {
cellXY[0] = cx;
cellXY[1] = cy;
} else { // Only one coordinate is specified. Use the current row (flowx) or column (flowy) to fill in.
if (lc.isFlowX()) {
cellXY[0] = cx;
} else {
cellXY[1] = cx;
}
}
}
cell = getCell(cellXY[1], cellXY[0]); // Might be null
}
// Skip a number of cells. Changed for 3.6.1 to take wrap into account and thus "skip" to the next and possibly more rows.
for (int s = 0, skipCount = rootCc.getSkip(); s < skipCount; s++) {
do {
if (Math.abs(increase(cellXY, 1)) >= wrap)
wrap(cellXY, null);
} while (isCellFree(cellXY[1], cellXY[0], spannedRects) == false);
}
// If cell is not created yet, create it and set it.
if (cell == null) {
int spanx = Math.min(rowNoGrid && lc.isFlowX() ? LayoutUtil.INF : rootCc.getSpanX(), MAX_GRID - cellXY[0]);
int spany = Math.min(rowNoGrid && !lc.isFlowX() ? LayoutUtil.INF : rootCc.getSpanY(), MAX_GRID - cellXY[1]);
cell = new Cell(spanx, spany, cellFlowX != null ? cellFlowX : lc.isFlowX());
setCell(cellXY[1], cellXY[0], cell);
// Add a rectangle so we can know that spanned cells occupy more space.
if (spanx > 1 || spany > 1)
spannedRects.add(new int[] {cellXY[0], cellXY[1], spanx, spany});
}
// Add the one, or all, components that split the grid position to the same Cell.
boolean wrapHandled = false;
int splitLeft = rowNoGrid ? LayoutUtil.INF : rootCc.getSplit() - 1;
boolean splitExit = false;
final boolean spanRestOfRow = (lc.isFlowX() ? rootCc.getSpanX() : rootCc.getSpanY()) == LayoutUtil.INF;
for (; splitLeft >= 0 && i < comps.length; splitLeft--) {
ComponentWrapper compAdd = comps[i];
CC cc = getCC(compAdd, ccMap);
addLinkIDs(cc);
boolean visible = compAdd.isVisible();
hideMode = visible ? -1 : cc.getHideMode() != -1 ? cc.getHideMode() : lc.getHideMode();
if (cc.isExternal() || hideMode == 3) {
i++;
splitLeft++; // Added for 3.5.5 so that these components does not "take" a split slot.
continue; // To work with situations where there are components that does not have a layout manager, or not this one.
}
hasPushX |= (visible || hideMode > 1) && (cc.getPushX() != null);
hasPushY |= (visible || hideMode > 1) && (cc.getPushY() != null);
if (cc != rootCc) { // If not first in a cell
if (cc.isNewline() || cc.isBoundsInGrid() == false || cc.getDockSide() != -1)
break;
if (splitLeft > 0 && cc.getSkip() > 0) {
splitExit = true;
break;
}
pos = getPos(compAdd, cc);
cbSz = getCallbackSize(compAdd);
}
CompWrap cw = new CompWrap(compAdd, cc, hideMode, pos, cbSz);
cell.compWraps.add(cw);
cell.hasTagged |= cc.getTag() != null;
hasTagged |= cell.hasTagged;
if (cc != rootCc) {
if (cc.getHorizontal().getSizeGroup() != null)
sizeGroupsX++;
if (cc.getVertical().getSizeGroup() != null)
sizeGroupsY++;
}
i++;
if ((cc.isWrap() || (spanRestOfRow && splitLeft == 0))) {
if (cc.isWrap()) {
wrap(cellXY, cc.getWrapGapSize());
} else {
hitEndOfRow = true;
}
wrapHandled = true;
break;
}
}
if (wrapHandled == false && rowNoGrid == false) {
int span = lc.isFlowX() ? cell.spanx : cell.spany;
if (Math.abs((lc.isFlowX() ? cellXY[0] : cellXY[1])) + span >= wrap) {
hitEndOfRow = true;
} else {
increase(cellXY, splitExit ? span - 1 : span);
}
}
}
// If there were size groups, calculate the largest values in the groups (for min/pref/max) and enforce them on the rest in the group.
if (sizeGroupsX > 0 || sizeGroupsY > 0) {
HashMap<String, int[]> sizeGroupMapX = sizeGroupsX > 0 ? new HashMap<String, int[]>(sizeGroupsX) : null;
HashMap<String, int[]> sizeGroupMapY = sizeGroupsY > 0 ? new HashMap<String, int[]>(sizeGroupsY) : null;
ArrayList<CompWrap> sizeGroupCWs = new ArrayList<CompWrap>(Math.max(sizeGroupsX, sizeGroupsY));
for (Cell cell : grid.values()) {
for (int i = 0; i < cell.compWraps.size(); i++) {
CompWrap cw = cell.compWraps.get(i);
String sgx = cw.cc.getHorizontal().getSizeGroup();
String sgy = cw.cc.getVertical().getSizeGroup();
if (sgx != null || sgy != null) {
if (sgx != null && sizeGroupMapX != null)
addToSizeGroup(sizeGroupMapX, sgx, cw.horSizes);
if (sgy != null && sizeGroupMapY != null)
addToSizeGroup(sizeGroupMapY, sgy, cw.verSizes);
sizeGroupCWs.add(cw);
}
}
}
// Set/equalize the sizeGroups to same the values.
for (CompWrap cw : sizeGroupCWs) {
if (sizeGroupMapX != null)
cw.setSizes(sizeGroupMapX.get(cw.cc.getHorizontal().getSizeGroup()), true); // Target method handles null sizes
if (sizeGroupMapY != null)
cw.setSizes(sizeGroupMapY.get(cw.cc.getVertical().getSizeGroup()), false); // Target method handles null sizes
}
} // Component loop
// If there were size groups, calculate the largest values in the groups (for min/pref/max) and enforce them on the rest in the group.
if (sizeGroupsX > 0 || sizeGroupsY > 0) {
HashMap<String, int[]> sizeGroupMapX = sizeGroupsX > 0 ? new HashMap<String, int[]>(sizeGroupsX) : null;
HashMap<String, int[]> sizeGroupMapY = sizeGroupsY > 0 ? new HashMap<String, int[]>(sizeGroupsY) : null;
ArrayList<CompWrap> sizeGroupCWs = new ArrayList<CompWrap>(Math.max(sizeGroupsX, sizeGroupsY));
for (Cell cell : grid.values()) {
for (int i = 0; i < cell.compWraps.size(); i++) {
CompWrap cw = cell.compWraps.get(i);
String sgx = cw.cc.getHorizontal().getSizeGroup();
String sgy = cw.cc.getVertical().getSizeGroup();
if (sgx != null || sgy != null) {
if (sgx != null && sizeGroupMapX != null)
addToSizeGroup(sizeGroupMapX, sgx, cw.horSizes);
if (sgy != null && sizeGroupMapY != null)
addToSizeGroup(sizeGroupMapY, sgy, cw.verSizes);
sizeGroupCWs.add(cw);
}
}
}
// Set/equalize the sizeGroups to same the values.
for (CompWrap cw : sizeGroupCWs) {
if (sizeGroupMapX != null)
cw.setSizes(sizeGroupMapX.get(cw.cc.getHorizontal().getSizeGroup()), true); // Target method handles null sizes
if (sizeGroupMapY != null)
cw.setSizes(sizeGroupMapY.get(cw.cc.getVertical().getSizeGroup()), false); // Target method handles null sizes
}
}
if (hasTagged)
sortCellsByPlatform(grid.values(), container);
// Calculate gaps now that the cells are filled and we know all adjacent components.
boolean ltr = LayoutUtil.isLeftToRight(lc, container);
for (Cell cell : grid.values()) {
ArrayList<CompWrap> cws = cell.compWraps;
for (int i = 0, lastI = cws.size() - 1; i <= lastI; i++) {
CompWrap cw = cws.get(i);
ComponentWrapper cwBef = i > 0 ? cws.get(i - 1).comp : null;
ComponentWrapper cwAft = i < lastI ? cws.get(i + 1).comp : null;
String tag = getCC(cw.comp, ccMap).getTag();
CC ccBef = cwBef != null ? getCC(cwBef, ccMap) : null;
CC ccAft = cwAft != null ? getCC(cwAft, ccMap) : null;
cw.calcGaps(cwBef, ccBef, cwAft, ccAft, tag, cell.flowx, ltr);
}
}
dockOffX = getDockInsets(colIndexes);
dockOffY = getDockInsets(rowIndexes);
// Add synthetic indexes for empty rows and columns so they can get a size
for (int i = 0, iSz = rowConstr.getCount(); i < iSz; i++)
rowIndexes.add(i);
for (int i = 0, iSz = colConstr.getCount(); i < iSz; i++)
colIndexes.add(i);
colGroupLists = divideIntoLinkedGroups(false);
rowGroupLists = divideIntoLinkedGroups(true);
pushXs = hasPushX || lc.isFillX() ? getDefaultPushWeights(false) : null;
pushYs = hasPushY || lc.isFillY() ? getDefaultPushWeights(true) : null;
if (LayoutUtil.isDesignTime(container))
saveGrid(container, grid);
}
private static CC getCC(ComponentWrapper comp, Map<ComponentWrapper, CC> ccMap)
{
CC cc = ccMap.get(comp);
return cc != null ? cc : DEF_CC;
}
private void addLinkIDs(CC cc)
{
String[] linkIDs = cc.getLinkTargets();
for (String linkID : linkIDs) {
if (linkTargetIDs == null)
linkTargetIDs = new HashMap<String, Boolean>();
linkTargetIDs.put(linkID, null);
}
}
/** If the container (parent) that this grid is laying out has changed its bounds, call this method to
* clear any cached values.
*/
public void invalidateContainerSize()
{
colFlowSpecs = null;
}
/** Does the actual layout. Uses many values calculated in the constructor.
* @param bounds The bounds to layout against. Normally that of the parent. [x, y, width, height].
* @param alignX The alignment for the x-axis.
* @param alignY The alignment for the y-axis.
* @param debug If debug information should be saved in {@link #debugRects}.
* @param checkPrefChange If a check should be done to see if the setting of any new bounds changes the preferred size
* of a component.
* @return If the layout has probably changed the preferred size and there is need for a new layout (normally only SWT).
*/
public boolean layout(int[] bounds, UnitValue alignX, UnitValue alignY, boolean debug, boolean checkPrefChange)
{
if (debug)
debugRects = new ArrayList<int[]>();
checkSizeCalcs();
resetLinkValues(true, true);
layoutInOneDim(bounds[2], alignX, false, pushXs);
layoutInOneDim(bounds[3], alignY, true, pushYs);
HashMap<String, Integer> endGrpXMap = null, endGrpYMap = null;
int compCount = container.getComponentCount();
// Transfer the calculated bound from the ComponentWrappers to the actual Components.
boolean layoutAgain = false;
if (compCount > 0) {
for (int j = 0; j < (linkTargetIDs != null ? 2 : 1); j++) { // First do the calculations (maybe more than once) then set the bounds when done
boolean doAgain;
int count = 0;
do {
doAgain = false;
for (Cell cell : grid.values()) {
ArrayList<CompWrap> compWraps = cell.compWraps;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
if (j == 0) {
doAgain |= doAbsoluteCorrections(cw, bounds);
if (doAgain == false) { // If we are going to do this again, do not bother this time around
if (cw.cc.getHorizontal().getEndGroup() != null)
endGrpXMap = addToEndGroup(endGrpXMap, cw.cc.getHorizontal().getEndGroup(), cw.x + cw.w);
if (cw.cc.getVertical().getEndGroup() != null)
endGrpYMap = addToEndGroup(endGrpYMap, cw.cc.getVertical().getEndGroup(), cw.y + cw.h);
}
// @since 3.7.2 Needed or absolute "pos" pointing to "visual" or "container" didn't work if
// their bounds changed during the layout cycle. At least not in SWT.
if (linkTargetIDs != null && (linkTargetIDs.containsKey("visual") || linkTargetIDs.containsKey("container")))
layoutAgain = true;
}
if (linkTargetIDs == null || j == 1) {
if (cw.cc.getHorizontal().getEndGroup() != null)
cw.w = endGrpXMap.get(cw.cc.getHorizontal().getEndGroup()) - cw.x;
if (cw.cc.getVertical().getEndGroup() != null)
cw.h = endGrpYMap.get(cw.cc.getVertical().getEndGroup()) - cw.y;
cw.x += bounds[0];
cw.y += bounds[1];
layoutAgain |= cw.transferBounds(checkPrefChange && !layoutAgain);
if (callbackList != null) {
for (LayoutCallback callback : callbackList)
callback.correctBounds(cw.comp);
}
}
}
}
clearGroupLinkBounds();
if (++count > ((compCount << 3) + 10)) {
System.err.println("Unstable cyclic dependency in absolute linked values!");
break;
}
} while (doAgain);
}
}
// Add debug shapes for the "cells". Use the CompWraps as base for inding the cells.
if (debug) {
for (Cell cell : grid.values()) {
ArrayList<CompWrap> compWraps = cell.compWraps;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
LinkedDimGroup hGrp = getGroupContaining(colGroupLists, cw);
LinkedDimGroup vGrp = getGroupContaining(rowGroupLists, cw);
if (hGrp != null && vGrp != null)
debugRects.add(new int[]{hGrp.lStart + bounds[0] - (hGrp.fromEnd ? hGrp.lSize : 0), vGrp.lStart + bounds[1] - (vGrp.fromEnd ? vGrp.lSize : 0), hGrp.lSize, vGrp.lSize});
}
}
}
return layoutAgain;
}
public void paintDebug()
{
if (debugRects != null) {
container.paintDebugOutline();
ArrayList<int[]> painted = new ArrayList<int[]>();
for (int i = 0, iSz = debugRects.size(); i < iSz; i++) {
int[] r = debugRects.get(i);
if (painted.contains(r) == false) {
container.paintDebugCell(r[0], r[1], r[2], r[3]);
painted.add(r);
}
}
for (Cell cell : grid.values()) {
ArrayList<CompWrap> compWraps = cell.compWraps;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++)
compWraps.get(i).comp.paintDebugOutline();
}
}
}
public ContainerWrapper getContainer()
{
return container;
}
public final int[] getWidth()
{
checkSizeCalcs();
int[] res = new int[width.length];
System.arraycopy(width, 0, res, 0, width.length);
return res;
}
public final int[] getHeight()
{
checkSizeCalcs();
int[] res = new int[height.length];
System.arraycopy(height, 0, res, 0, height.length);
return res;
}
private void checkSizeCalcs()
{
if (colFlowSpecs == null) {
colFlowSpecs = calcRowsOrColsSizes(true);
rowFlowSpecs = calcRowsOrColsSizes(false);
width = getMinPrefMaxSumSize(true);
height = getMinPrefMaxSumSize(false);
if (linkTargetIDs == null) {
resetLinkValues(false, true);
} else {
// This call makes some components flicker on SWT. They get their bounds changed twice since
// the change might affect the absolute size adjustment below. There's no way around this that
// I know of.
layout(new int[4], null, null, false, false);
resetLinkValues(false, false);
}
adjustSizeForAbsolute(true);
adjustSizeForAbsolute(false);
}
}
private UnitValue[] getPos(ComponentWrapper cw, CC cc)
{
UnitValue[] cbPos = null;
if (callbackList != null) {
for (int i = 0; i < callbackList.size() && cbPos == null; i++)
cbPos = callbackList.get(i).getPosition(cw); // NOT a copy!
}
// If one is null, return the other (which many also be null)
UnitValue[] ccPos = cc.getPos(); // A copy!!
if (cbPos == null || ccPos == null)
return cbPos != null ? cbPos : ccPos;
// Merge
for (int i = 0; i < 4; i++) {
UnitValue cbUv = cbPos[i];
if (cbUv != null)
ccPos[i] = cbUv;
}
return ccPos;
}
private BoundSize[] getCallbackSize(ComponentWrapper cw)
{
if (callbackList != null) {
for (LayoutCallback callback : callbackList) {
BoundSize[] bs = callback.getSize(cw); // NOT a copy!
if (bs != null)
return bs;
}
}
return null;
}
private static int getDockInsets(TreeSet<Integer> set)
{
int c = 0;
for (Integer i : set) {
if (i < -MAX_GRID) {
c++;
} else {
break; // Since they are sorted we can break
}
}
return c;
}
/**
* @param cw Never <code>null</code>.
* @param cc Never <code>null</code>.
* @param external The bounds should be stored even if they are not in {@link #linkTargetIDs}.
* @return If a change has been made.
*/
private boolean setLinkedBounds(ComponentWrapper cw, CC cc, int x, int y, int w, int h, boolean external)
{
String id = cc.getId() != null ? cc.getId() : cw.getLinkId();
if (id == null)
return false;
String gid = null;
int grIx = id.indexOf('.');
if (grIx != -1 ) {
gid = id.substring(0, grIx);
id = id.substring(grIx + 1);
}
Object lay = container.getLayout();
boolean changed = false;
if (external || (linkTargetIDs != null && linkTargetIDs.containsKey(id)))
changed = LinkHandler.setBounds(lay, id, x, y, w, h, !external, false);
if (gid != null && (external || (linkTargetIDs != null && linkTargetIDs.containsKey(gid)))) {
if (linkTargetIDs == null)
linkTargetIDs = new HashMap<String, Boolean>(4);
linkTargetIDs.put(gid, Boolean.TRUE);
changed |= LinkHandler.setBounds(lay, gid, x, y, w, h, !external, true);
}
return changed;
}
/** Go to next cell.
* @param p The point to increase
* @param cnt How many cells to advance.
* @return The new value in the "incresing" dimension.
*/
private int increase(int[] p, int cnt)
{
return lc.isFlowX() ? (p[0] += cnt) : (p[1] += cnt);
}
/** Wraps to the next row or column depending on if horizontal flow or vertical flow is used.
* @param cellXY The point to wrap and thus set either x or y to 0 and increase the other one.
* @param gapSize The gaps size specified in a "wrap XXX" or "newline XXX" or <code>null</code> if none.
*/
private void wrap(int[] cellXY, BoundSize gapSize)
{
boolean flowx = lc.isFlowX();
cellXY[0] = flowx ? 0 : cellXY[0] + 1;
cellXY[1] = flowx ? cellXY[1] + 1 : 0;
if (gapSize != null) {
if (wrapGapMap == null)
wrapGapMap = new HashMap<Integer, BoundSize>(8);
wrapGapMap.put(cellXY[flowx ? 1 : 0], gapSize);
}
// add the row/column so that the gap in the last row/col will not be removed.
if (flowx) {
rowIndexes.add(cellXY[1]);
} else {
colIndexes.add(cellXY[0]);
}
}
/** Sort components (normally buttons in a button bar) so they appear in the correct order.
* @param cells The cells to sort.
* @param parent The parent.
*/
private static void sortCellsByPlatform(Collection<Cell> cells, ContainerWrapper parent)
{
String order = PlatformDefaults.getButtonOrder();
String orderLo = order.toLowerCase();
int unrelSize = PlatformDefaults.convertToPixels(1, "u", true, 0, parent, null);
if (unrelSize == UnitConverter.UNABLE)
throw new IllegalArgumentException("'unrelated' not recognized by PlatformDefaults!");
int[] gapUnrel = new int[] {unrelSize, unrelSize, LayoutUtil.NOT_SET};
int[] flGap = new int[] {0, 0, LayoutUtil.NOT_SET};
for (Cell cell : cells) {
if (cell.hasTagged == false)
continue;
CompWrap prevCW = null;
boolean nextUnrel = false;
boolean nextPush = false;
ArrayList<CompWrap> sortedList = new ArrayList<CompWrap>(cell.compWraps.size());
for (int i = 0, iSz = orderLo.length(); i < iSz; i++) {
char c = orderLo.charAt(i);
if (c == '+' || c == '_') {
nextUnrel = true;
if (c == '+')
nextPush = true;
} else {
String tag = PlatformDefaults.getTagForChar(c);
if (tag != null) {
for (int j = 0, jSz = cell.compWraps.size(); j < jSz; j++) {
CompWrap cw = cell.compWraps.get(j);
if (tag.equals(cw.cc.getTag())) {
if (Character.isUpperCase(order.charAt(i))) {
int min = PlatformDefaults.getMinimumButtonWidth().getPixels(0, parent, cw.comp);
if (min > cw.horSizes[LayoutUtil.MIN])
cw.horSizes[LayoutUtil.MIN] = min;
correctMinMax(cw.horSizes);
}
sortedList.add(cw);
if (nextUnrel) {
(prevCW != null ? prevCW : cw).mergeGapSizes(gapUnrel, cell.flowx, prevCW == null);
if (nextPush) {
cw.forcedPushGaps = 1;
nextUnrel = false;
nextPush = false;
}
}
// "unknown" components will always get an Unrelated gap.
if (c == 'u')
nextUnrel = true;
prevCW = cw;
}
}
}
}
}
// If we have a gap that was supposed to push but no more components was found to but the "gap before" then compensate.
if (sortedList.size() > 0) {
CompWrap cw = sortedList.get(sortedList.size() - 1);
if (nextUnrel) {
cw.mergeGapSizes(gapUnrel, cell.flowx, false);
if (nextPush)
cw.forcedPushGaps |= 2;
}
// Remove first and last gap if not set explicitly.
if (cw.cc.getHorizontal().getGapAfter() == null)
cw.setGaps(flGap, 3);
cw = sortedList.get(0);
if (cw.cc.getHorizontal().getGapBefore() == null)
cw.setGaps(flGap, 1);
}
// Exchange the unsorted CompWraps for the sorted one.
if (cell.compWraps.size() == sortedList.size()) {
cell.compWraps.clear();
} else {
cell.compWraps.removeAll(sortedList);
}
cell.compWraps.addAll(sortedList);
}
}
private Float[] getDefaultPushWeights(boolean isRows)
{
ArrayList<LinkedDimGroup>[] groupLists = isRows ? rowGroupLists : colGroupLists;
Float[] pushWeightArr = GROW_100; // Only create specific if any of the components have grow.
for (int i = 0, ix = 1; i < groupLists.length; i++, ix += 2) {
ArrayList<LinkedDimGroup> grps = groupLists[i];
Float rowPushWeight = null;
for (LinkedDimGroup grp : grps) {
for (int c = 0; c < grp._compWraps.size(); c++) {
CompWrap cw = grp._compWraps.get(c);
int hideMode = cw.comp.isVisible() ? -1 : cw.cc.getHideMode() != -1 ? cw.cc.getHideMode() : lc.getHideMode();
Float pushWeight = hideMode < 2 ? (isRows ? cw.cc.getPushY() : cw.cc.getPushX()) : null;
if (rowPushWeight == null || (pushWeight != null && pushWeight.floatValue() > rowPushWeight.floatValue()))
rowPushWeight = pushWeight;
}
}
if (rowPushWeight != null) {
if (pushWeightArr == GROW_100)
pushWeightArr = new Float[(groupLists.length << 1) + 1];
pushWeightArr[ix] = rowPushWeight;
}
}
return pushWeightArr;
}
private void clearGroupLinkBounds()
{
if (linkTargetIDs == null)
return;
for (Map.Entry<String, Boolean> o : linkTargetIDs.entrySet()) {
if (o.getValue() == Boolean.TRUE)
LinkHandler.clearBounds(container.getLayout(), o.getKey());
}
}
private void resetLinkValues(boolean parentSize, boolean compLinks)
{
Object lay = container.getLayout();
if (compLinks)
LinkHandler.clearTemporaryBounds(lay);
boolean defIns = !hasDocks();
int parW = parentSize ? lc.getWidth().constrain(container.getWidth(), getParentSize(container, true), container) : 0;
int parH = parentSize ? lc.getHeight().constrain(container.getHeight(), getParentSize(container, false), container) : 0;
int insX = LayoutUtil.getInsets(lc, 0, defIns).getPixels(0, container, null);
int insY = LayoutUtil.getInsets(lc, 1, defIns).getPixels(0, container, null);
int visW = parW - insX - LayoutUtil.getInsets(lc, 2, defIns).getPixels(0, container, null);
int visH = parH - insY - LayoutUtil.getInsets(lc, 3, defIns).getPixels(0, container, null);
LinkHandler.setBounds(lay, "visual", insX, insY, visW, visH, true, false);
LinkHandler.setBounds(lay, "container", 0, 0, parW, parH, true, false);
}
/** Returns the {@link net.miginfocom.layout.Grid.LinkedDimGroup} that has the {@link net.miginfocom.layout.Grid.CompWrap}
* <code>cw</code>.
* @param groupLists The lists to search in.
* @param cw The component wrap to find.
* @return The linked group or <code>null</code> if none had the component wrap.
*/
private static LinkedDimGroup getGroupContaining(ArrayList<LinkedDimGroup>[] groupLists, CompWrap cw)
{
for (ArrayList<LinkedDimGroup> groups : groupLists) {
for (int j = 0, jSz = groups.size(); j < jSz; j++) {
ArrayList<CompWrap> cwList = groups.get(j)._compWraps;
for (int k = 0, kSz = cwList.size(); k < kSz; k++) {
if (cwList.get(k) == cw)
return groups.get(j);
}
}
}
return null;
}
private boolean doAbsoluteCorrections(CompWrap cw, int[] bounds)
{
boolean changed = false;
int[] stSz = getAbsoluteDimBounds(cw, bounds[2], true);
if (stSz != null)
cw.setDimBounds(stSz[0], stSz[1], true);
stSz = getAbsoluteDimBounds(cw, bounds[3], false);
if (stSz != null)
cw.setDimBounds(stSz[0], stSz[1], false);
// If there is a link id, store the new bounds.
if (linkTargetIDs != null)
changed = setLinkedBounds(cw.comp, cw.cc, cw.x, cw.y, cw.w, cw.h, false);
return changed;
}
private void adjustSizeForAbsolute(boolean isHor)
{
int[] curSizes = isHor ? width : height;
Cell absCell = grid.get(null);
if (absCell == null || absCell.compWraps.size() == 0)
return;
ArrayList<CompWrap> cws = absCell.compWraps;
int maxEnd = 0;
for (int j = 0, cwSz = absCell.compWraps.size(); j < cwSz + 3; j++) { // "Do Again" max absCell.compWraps.size() + 3 times.
boolean doAgain = false;
for (int i = 0; i < cwSz; i++) {
CompWrap cw = cws.get(i);
int[] stSz = getAbsoluteDimBounds(cw, 0, isHor);
int end = stSz[0] + stSz[1];
if (maxEnd < end)
maxEnd = end;
// If there is a link id, store the new bounds.
if (linkTargetIDs != null)
doAgain |= setLinkedBounds(cw.comp, cw.cc, stSz[0], stSz[0], stSz[1], stSz[1], false);
}
if (doAgain == false)
break;
// We need to check this again since the coords may be smaller this round.
maxEnd = 0;
clearGroupLinkBounds();
}
maxEnd += LayoutUtil.getInsets(lc, isHor ? 3 : 2, !hasDocks()).getPixels(0, container, null);
if (curSizes[LayoutUtil.MIN] < maxEnd)
curSizes[LayoutUtil.MIN] = maxEnd;
if (curSizes[LayoutUtil.PREF] < maxEnd)
curSizes[LayoutUtil.PREF] = maxEnd;
}
private int[] getAbsoluteDimBounds(CompWrap cw, int refSize, boolean isHor)
{
if (cw.cc.isExternal()) {
if (isHor) {
return new int[] {cw.comp.getX(), cw.comp.getWidth()};
} else {
return new int[] {cw.comp.getY(), cw.comp.getHeight()};
}
}
int[] plafPad = lc.isVisualPadding() ? cw.comp.getVisualPadding() : null;
UnitValue[] pad = cw.cc.getPadding();
// If no changes do not create a lot of objects
if (cw.pos == null && plafPad == null && pad == null)
return null;
// Set start
int st = isHor ? cw.x : cw.y;
int sz = isHor ? cw.w : cw.h;
// If absolute, use those coordinates instead.
if (cw.pos != null) {
UnitValue stUV = cw.pos != null ? cw.pos[isHor ? 0 : 1] : null;
UnitValue endUV = cw.pos != null ? cw.pos[isHor ? 2 : 3] : null;
int minSz = cw.getSize(LayoutUtil.MIN, isHor);
int maxSz = cw.getSize(LayoutUtil.MAX, isHor);
sz = Math.min(Math.max(cw.getSize(LayoutUtil.PREF, isHor), minSz), maxSz);
if (stUV != null) {
st = stUV.getPixels(stUV.getUnit() == UnitValue.ALIGN ? sz : refSize, container, cw.comp);
if (endUV != null) // if (endUV == null && cw.cc.isBoundsIsGrid() == true)
sz = Math.min(Math.max((isHor ? (cw.x + cw.w) : (cw.y + cw.h)) - st, minSz), maxSz);
}
if (endUV != null) {
if (stUV != null) { // if (stUV != null || cw.cc.isBoundsIsGrid()) {
sz = Math.min(Math.max(endUV.getPixels(refSize, container, cw.comp) - st, minSz), maxSz);
} else {
st = endUV.getPixels(refSize, container, cw.comp) - sz;
}
}
}
// If constraint has padding -> correct the start/size
if (pad != null) {
UnitValue uv = pad[isHor ? 1 : 0];
int p = uv != null ? uv.getPixels(refSize, container, cw.comp) : 0;
st += p;
uv = pad[isHor ? 3 : 2];
sz += -p + (uv != null ? uv.getPixels(refSize, container, cw.comp) : 0);
}
// If the plaf converter has padding -> correct the start/size
if (plafPad != null) {
int p = plafPad[isHor ? 1 : 0];
st += p;
sz += -p + (plafPad[isHor ? 3 : 2]);
}
return new int[] {st, sz};
}
private void layoutInOneDim(int refSize, UnitValue align, boolean isRows, Float[] defaultPushWeights)
{
boolean fromEnd = !(isRows ? lc.isTopToBottom() : LayoutUtil.isLeftToRight(lc, container));
DimConstraint[] primDCs = (isRows ? rowConstr : colConstr).getConstaints();
FlowSizeSpec fss = isRows ? rowFlowSpecs : colFlowSpecs;
ArrayList<LinkedDimGroup>[] rowCols = isRows ? rowGroupLists : colGroupLists;
int[] rowColSizes = LayoutUtil.calculateSerial(fss.sizes, fss.resConstsInclGaps, defaultPushWeights, LayoutUtil.PREF, refSize);
if (LayoutUtil.isDesignTime(container)) {
TreeSet<Integer> indexes = isRows ? rowIndexes : colIndexes;
int[] ixArr = new int[indexes.size()];
int ix = 0;
for (Integer i : indexes)
ixArr[ix++] = i;
putSizesAndIndexes(container.getComponent(), rowColSizes, ixArr, isRows);
}
int curPos = align != null ? align.getPixels(refSize - LayoutUtil.sum(rowColSizes), container, null) : 0;
if (fromEnd)
curPos = refSize - curPos;
for (int i = 0 ; i < rowCols.length; i++) {
ArrayList<LinkedDimGroup> linkedGroups = rowCols[i];
int scIx = i - (isRows ? dockOffY : dockOffX);
int bIx = i << 1;
int bIx2 = bIx + 1;
curPos += (fromEnd ? -rowColSizes[bIx] : rowColSizes[bIx]);
DimConstraint primDC = scIx >= 0 ? primDCs[scIx >= primDCs.length ? primDCs.length - 1 : scIx] : DOCK_DIM_CONSTRAINT;
int rowSize = rowColSizes[bIx2];
for (LinkedDimGroup group : linkedGroups) {
int groupSize = rowSize;
if (group.span > 1)
groupSize = LayoutUtil.sum(rowColSizes, bIx2, Math.min((group.span << 1) - 1, rowColSizes.length - bIx2 - 1));
group.layout(primDC, curPos, groupSize, group.span);
}
curPos += (fromEnd ? -rowSize : rowSize);
}
}
private static void addToSizeGroup(HashMap<String, int[]> sizeGroups, String sizeGroup, int[] size)
{
int[] sgSize = sizeGroups.get(sizeGroup);
if (sgSize == null) {
sizeGroups.put(sizeGroup, new int[] {size[LayoutUtil.MIN], size[LayoutUtil.PREF], size[LayoutUtil.MAX]});
} else {
sgSize[LayoutUtil.MIN] = Math.max(size[LayoutUtil.MIN], sgSize[LayoutUtil.MIN]);
sgSize[LayoutUtil.PREF] = Math.max(size[LayoutUtil.PREF], sgSize[LayoutUtil.PREF]);
sgSize[LayoutUtil.MAX] = Math.min(size[LayoutUtil.MAX], sgSize[LayoutUtil.MAX]);
}
}
private static HashMap<String, Integer> addToEndGroup(HashMap<String, Integer> endGroups, String endGroup, int end)
{
if (endGroup != null) {
if (endGroups == null)
endGroups = new HashMap<String, Integer>(2);
Integer oldEnd = endGroups.get(endGroup);
if (oldEnd == null || end > oldEnd)
endGroups.put(endGroup, end);
}
return endGroups;
}
/** Calculates Min, Preferred and Max size for the columns OR rows.
* @param isHor If it is the horizontal dimension to calculate.
* @return The sizes in a {@link net.miginfocom.layout.Grid.FlowSizeSpec}.
*/
private FlowSizeSpec calcRowsOrColsSizes(boolean isHor)
{
ArrayList<LinkedDimGroup>[] groupsLists = isHor ? colGroupLists : rowGroupLists;
Float[] defPush = isHor ? pushXs : pushYs;
int refSize = isHor ? container.getWidth() : container.getHeight();
BoundSize cSz = isHor ? lc.getWidth() : lc.getHeight();
if (cSz.isUnset() == false)
refSize = cSz.constrain(refSize, getParentSize(container, isHor), container);
DimConstraint[] primDCs = (isHor? colConstr : rowConstr).getConstaints();
TreeSet<Integer> primIndexes = isHor ? colIndexes : rowIndexes;
int[][] rowColBoundSizes = new int[primIndexes.size()][];
HashMap<String, int[]> sizeGroupMap = new HashMap<String, int[]>(2);
DimConstraint[] allDCs = new DimConstraint[primIndexes.size()];
Iterator<Integer> primIt = primIndexes.iterator();
for (int r = 0; r < rowColBoundSizes.length; r++) {
int cellIx = primIt.next();
int[] rowColSizes = new int[3];
if (cellIx >= -MAX_GRID && cellIx <= MAX_GRID) { // If not dock cell
allDCs[r] = primDCs[cellIx >= primDCs.length ? primDCs.length - 1 : cellIx];
} else {
allDCs[r] = DOCK_DIM_CONSTRAINT;
}
ArrayList<LinkedDimGroup> groups = groupsLists[r];
int[] groupSizes = new int[] {
getTotalGroupsSizeParallel(groups, LayoutUtil.MIN, false),
getTotalGroupsSizeParallel(groups, LayoutUtil.PREF, false),
LayoutUtil.INF};
correctMinMax(groupSizes);
BoundSize dimSize = allDCs[r].getSize();
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.MAX; sType++) {
int rowColSize = groupSizes[sType];
UnitValue uv = dimSize.getSize(sType);
if (uv != null) {
// If the size of the column is a link to some other size, use that instead
int unit = uv.getUnit();
if (unit == UnitValue.PREF_SIZE) {
rowColSize = groupSizes[LayoutUtil.PREF];
} else if (unit == UnitValue.MIN_SIZE) {
rowColSize = groupSizes[LayoutUtil.MIN];
} else if (unit == UnitValue.MAX_SIZE) {
rowColSize = groupSizes[LayoutUtil.MAX];
} else {
rowColSize = uv.getPixels(refSize, container, null);
}
} else if (cellIx >= -MAX_GRID && cellIx <= MAX_GRID && rowColSize == 0) {
rowColSize = LayoutUtil.isDesignTime(container) ? LayoutUtil.getDesignTimeEmptySize() : 0; // Empty rows with no size set gets XX pixels if design time
}
rowColSizes[sType] = rowColSize;
}
correctMinMax(rowColSizes);
addToSizeGroup(sizeGroupMap, allDCs[r].getSizeGroup(), rowColSizes);
rowColBoundSizes[r] = rowColSizes;
}
// Set/equalize the size groups to same the values.
if (sizeGroupMap.size() > 0) {
for (int r = 0; r < rowColBoundSizes.length; r++) {
if (allDCs[r].getSizeGroup() != null)
rowColBoundSizes[r] = sizeGroupMap.get(allDCs[r].getSizeGroup());
}
}
// Add the gaps
ResizeConstraint[] resConstrs = getRowResizeConstraints(allDCs);
boolean[] fillInPushGaps = new boolean[allDCs.length + 1];
int[][] gapSizes = getRowGaps(allDCs, refSize, isHor, fillInPushGaps);
FlowSizeSpec fss = mergeSizesGapsAndResConstrs(resConstrs, fillInPushGaps, rowColBoundSizes, gapSizes);
// Spanning components are not handled yet. Check and adjust the multi-row min/pref they enforce.
adjustMinPrefForSpanningComps(allDCs, defPush, fss, groupsLists);
return fss;
}
private static int getParentSize(ComponentWrapper cw, boolean isHor)
{
ComponentWrapper p = cw.getParent();
return p != null ? (isHor ? cw.getWidth() : cw.getHeight()) : 0;
}
private int[] getMinPrefMaxSumSize(boolean isHor)
{
int[][] sizes = isHor ? colFlowSpecs.sizes : rowFlowSpecs.sizes;
int[] retSizes = new int[3];
BoundSize sz = isHor ? lc.getWidth() : lc.getHeight();
for (int i = 0; i < sizes.length; i++) {
if (sizes[i] != null) {
int[] size = sizes[i];
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.MAX; sType++) {
if (sz.getSize(sType) != null) {
if (i == 0)
retSizes[sType] = sz.getSize(sType).getPixels(getParentSize(container, isHor), container, null);
} else {
int s = size[sType];
if (s != LayoutUtil.NOT_SET) {
if (sType == LayoutUtil.PREF) {
int bnd = size[LayoutUtil.MAX];
if (bnd != LayoutUtil.NOT_SET && bnd < s)
s = bnd;
bnd = size[LayoutUtil.MIN];
if (bnd > s) // Includes s == LayoutUtil.NOT_SET since < 0.
s = bnd;
}
retSizes[sType] += s; // MAX compensated below.
}
// So that MAX is always correct.
if (size[LayoutUtil.MAX] == LayoutUtil.NOT_SET || retSizes[LayoutUtil.MAX] > LayoutUtil.INF)
retSizes[LayoutUtil.MAX] = LayoutUtil.INF;
}
}
}
}
correctMinMax(retSizes);
return retSizes;
}
private static ResizeConstraint[] getRowResizeConstraints(DimConstraint[] specs)
{
ResizeConstraint[] resConsts = new ResizeConstraint[specs.length];
for (int i = 0; i < resConsts.length; i++)
resConsts[i] = specs[i].resize;
return resConsts;
}
private static ResizeConstraint[] getComponentResizeConstraints(ArrayList<CompWrap> compWraps, boolean isHor)
{
ResizeConstraint[] resConsts = new ResizeConstraint[compWraps.size()];
for (int i = 0; i < resConsts.length; i++) {
CC fc = compWraps.get(i).cc;
resConsts[i] = fc.getDimConstraint(isHor).resize;
// Always grow docking components in the correct dimension.
int dock = fc.getDockSide();
if (isHor ? (dock == 0 || dock == 2) : (dock == 1 || dock == 3)) {
ResizeConstraint dc = resConsts[i];
resConsts[i] = new ResizeConstraint(dc.shrinkPrio, dc.shrink, dc.growPrio, ResizeConstraint.WEIGHT_100);
}
}
return resConsts;
}
private static boolean[] getComponentGapPush(ArrayList<CompWrap> compWraps, boolean isHor)
{
// Make one element bigger and or the after gap with the next before gap.
boolean[] barr = new boolean[compWraps.size() + 1];
for (int i = 0; i < barr.length; i++) {
boolean push = i > 0 && compWraps.get(i - 1).isPushGap(isHor, false);
if (push == false && i < (barr.length - 1))
push = compWraps.get(i).isPushGap(isHor, true);
barr[i] = push;
}
return barr;
}
/** Returns the row gaps in pixel sizes. One more than there are <code>specs</code> sent in.
* @param specs
* @param refSize
* @param isHor
* @param fillInPushGaps If the gaps are pushing. <b>NOTE!</b> this argument will be filled in and thus changed!
* @return The row gaps in pixel sizes. One more than there are <code>specs</code> sent in.
*/
private int[][] getRowGaps(DimConstraint[] specs, int refSize, boolean isHor, boolean[] fillInPushGaps)
{
BoundSize defGap = isHor ? lc.getGridGapX() : lc.getGridGapY();
if (defGap == null)
defGap = isHor ? PlatformDefaults.getGridGapX() : PlatformDefaults.getGridGapY();
int[] defGapArr = defGap.getPixelSizes(refSize, container, null);
boolean defIns = !hasDocks();
UnitValue firstGap = LayoutUtil.getInsets(lc, isHor ? 1 : 0, defIns);
UnitValue lastGap = LayoutUtil.getInsets(lc, isHor ? 3 : 2, defIns);
int[][] retValues = new int[specs.length + 1][];
for (int i = 0, wgIx = 0; i < retValues.length; i++) {
DimConstraint specBefore = i > 0 ? specs[i - 1] : null;
DimConstraint specAfter = i < specs.length ? specs[i] : null;
// No gap if between docking components.
boolean edgeBefore = (specBefore == DOCK_DIM_CONSTRAINT || specBefore == null);
boolean edgeAfter = (specAfter == DOCK_DIM_CONSTRAINT || specAfter == null);
if (edgeBefore && edgeAfter)
continue;
BoundSize wrapGapSize = (wrapGapMap == null || isHor == lc.isFlowX() ? null : wrapGapMap.get(Integer.valueOf(wgIx++)));
if (wrapGapSize == null) {
int[] gapBefore = specBefore != null ? specBefore.getRowGaps(container, null, refSize, false) : null;
int[] gapAfter = specAfter != null ? specAfter.getRowGaps(container, null, refSize, true) : null;
if (edgeBefore && gapAfter == null && firstGap != null) {
int bef = firstGap.getPixels(refSize, container, null);
retValues[i] = new int[] {bef, bef, bef};
} else if (edgeAfter && gapBefore == null && firstGap != null) {
int aft = lastGap.getPixels(refSize, container, null);
retValues[i] = new int[] {aft, aft, aft};
} else {
retValues[i] = gapAfter != gapBefore ? mergeSizes(gapAfter, gapBefore) : new int[] {defGapArr[0], defGapArr[1], defGapArr[2]};
}
if (specBefore != null && specBefore.isGapAfterPush() || specAfter != null && specAfter.isGapBeforePush())
fillInPushGaps[i] = true;
} else {
if (wrapGapSize.isUnset()) {
retValues[i] = new int[] {defGapArr[0], defGapArr[1], defGapArr[2]};
} else {
retValues[i] = wrapGapSize.getPixelSizes(refSize, container, null);
}
fillInPushGaps[i] = wrapGapSize.getGapPush();
}
}
return retValues;
}
private static int[][] getGaps(ArrayList<CompWrap> compWraps, boolean isHor)
{
int compCount = compWraps.size();
int[][] retValues = new int[compCount + 1][];
retValues[0] = compWraps.get(0).getGaps(isHor, true);
for (int i = 0; i < compCount; i++) {
int[] gap1 = compWraps.get(i).getGaps(isHor, false);
int[] gap2 = i < compCount - 1 ? compWraps.get(i + 1).getGaps(isHor, true) : null;
retValues[i + 1] = mergeSizes(gap1, gap2);
}
return retValues;
}
private boolean hasDocks()
{
return (dockOffX > 0 || dockOffY > 0 || rowIndexes.last() > MAX_GRID || colIndexes.last() > MAX_GRID);
}
/** Adjust min/pref size for columns(or rows) that has components that spans multiple columns (or rows).
* @param specs The specs for the columns or rows. Last index will be used if <code>count</code> is greater than this array's length.
* @param defPush The default grow weight if the specs does not have anyone that will grow. Comes from "push" in the CC.
* @param fss
* @param groupsLists
*/
private void adjustMinPrefForSpanningComps(DimConstraint[] specs, Float[] defPush, FlowSizeSpec fss, ArrayList<LinkedDimGroup>[] groupsLists)
{
for (int r = groupsLists.length - 1; r >= 0; r--) { // Since 3.7.3 Iterate from end to start. Will solve some multiple spanning components hard to solve problems.
ArrayList<LinkedDimGroup> groups = groupsLists[r];
for (LinkedDimGroup group : groups) {
if (group.span == 1)
continue;
int[] sizes = group.getMinPrefMax();
for (int s = LayoutUtil.MIN; s <= LayoutUtil.PREF; s++) {
int cSize = sizes[s];
if (cSize == LayoutUtil.NOT_SET)
continue;
int rowSize = 0;
int sIx = (r << 1) + 1;
int len = Math.min((group.span << 1), fss.sizes.length - sIx) - 1;
for (int j = sIx; j < sIx + len; j++) {
int sz = fss.sizes[j][s];
if (sz != LayoutUtil.NOT_SET)
rowSize += sz;
}
if (rowSize < cSize && len > 0) {
for (int eagerness = 0, newRowSize = 0; eagerness < 4 && newRowSize < cSize; eagerness++)
newRowSize = fss.expandSizes(specs, defPush, cSize, sIx, len, s, eagerness);
}
}
}
}
}
/** For one dimension divide the component wraps into logical groups. One group for component wraps that share a common something,
* line the property to layout by base line.
* @param isRows If rows, and not columns, are to be divided.
* @return One <code>ArrayList<LinkedDimGroup></code> for every row/column.
*/
private ArrayList<LinkedDimGroup>[] divideIntoLinkedGroups(boolean isRows)
{
boolean fromEnd = !(isRows ? lc.isTopToBottom() : LayoutUtil.isLeftToRight(lc, container));
TreeSet<Integer> primIndexes = isRows ? rowIndexes : colIndexes;
TreeSet<Integer> secIndexes = isRows ? colIndexes : rowIndexes;
DimConstraint[] primDCs = (isRows ? rowConstr : colConstr).getConstaints();
@SuppressWarnings("unchecked")
ArrayList<LinkedDimGroup>[] groupLists = new ArrayList[primIndexes.size()];
int gIx = 0;
for (int i : primIndexes) {
DimConstraint dc;
if (i >= -MAX_GRID && i <= MAX_GRID) { // If not dock cell
dc = primDCs[i >= primDCs.length ? primDCs.length - 1 : i];
} else {
dc = DOCK_DIM_CONSTRAINT;
}
ArrayList<LinkedDimGroup> groupList = new ArrayList<LinkedDimGroup>(2);
groupLists[gIx++] = groupList;
for (Integer ix : secIndexes) {
Cell cell = isRows ? getCell(i, ix) : getCell(ix, i);
if (cell == null || cell.compWraps.size() == 0)
continue;
int span = (isRows ? cell.spany : cell.spanx);
if (span > 1)
span = convertSpanToSparseGrid(i, span, primIndexes);
boolean isPar = (cell.flowx == isRows);
if ((isPar == false && cell.compWraps.size() > 1) || span > 1) {
int linkType = isPar ? LinkedDimGroup.TYPE_PARALLEL : LinkedDimGroup.TYPE_SERIAL;
LinkedDimGroup lg = new LinkedDimGroup("p," + ix, span, linkType, !isRows, fromEnd);
lg.setCompWraps(cell.compWraps);
groupList.add(lg);
} else {
for (int cwIx = 0; cwIx < cell.compWraps.size(); cwIx++) {
CompWrap cw = cell.compWraps.get(cwIx);
boolean rowBaselineAlign = (isRows && lc.isTopToBottom() && dc.getAlignOrDefault(!isRows) == UnitValue.BASELINE_IDENTITY); // Disable baseline for bottomToTop since I can not verify it working.
boolean isBaseline = isRows && cw.isBaselineAlign(rowBaselineAlign);
String linkCtx = isBaseline ? "baseline" : null;
// Find a group with same link context and put it in that group.
boolean foundList = false;
for (int glIx = 0, lastGl = groupList.size() - 1; glIx <= lastGl; glIx++) {
LinkedDimGroup group = groupList.get(glIx);
if (group.linkCtx == linkCtx || linkCtx != null && linkCtx.equals(group.linkCtx)) {
group.addCompWrap(cw);
foundList = true;
break;
}
}
// If none found and at last add a new group.
if (foundList == false) {
int linkType = isBaseline ? LinkedDimGroup.TYPE_BASELINE : LinkedDimGroup.TYPE_PARALLEL;
LinkedDimGroup lg = new LinkedDimGroup(linkCtx, 1, linkType, !isRows, fromEnd);
lg.addCompWrap(cw);
groupList.add(lg);
}
}
}
}
}
return groupLists;
}
/** Spanning is specified in the uncompressed grid number. They can for instance be more than 60000 for the outer
* edge dock grid cells. When the grid is compressed and indexed after only the cells that area occupied the span
* is erratic. This method use the row/col indexes and corrects the span to be correct for the compressed grid.
* @param span The span un the uncompressed grid. <code>LayoutUtil.INF</code> will be interpreted to span the rest
* of the column/row excluding the surrounding docking components.
* @param indexes The indexes in the correct dimension.
* @return The converted span.
*/
private static int convertSpanToSparseGrid(int curIx, int span, TreeSet<Integer> indexes)
{
int lastIx = curIx + span;
int retSpan = 1;
for (Integer ix : indexes) {
if (ix <= curIx)
continue; // We have not arrived to the correct index yet
if (ix >= lastIx)
break;
retSpan++;
}
return retSpan;
}
private boolean isCellFree(int r, int c, ArrayList<int[]> occupiedRects)
{
if (getCell(r, c) != null)
return false;
for (int[] rect : occupiedRects) {
if (rect[0] <= c && rect[1] <= r && rect[0] + rect[2] > c && rect[1] + rect[3] > r)
return false;
}
return true;
}
private Cell getCell(int r, int c)
{
return grid.get(Integer.valueOf((r << 16) + c));
}
private void setCell(int r, int c, Cell cell)
{
if (c < 0 || r < 0)
throw new IllegalArgumentException("Cell position cannot be negative. row: " + r + ", col: " + c);
if (c > MAX_GRID || r > MAX_GRID)
throw new IllegalArgumentException("Cell position out of bounds. Out of cells. row: " + r + ", col: " + c);
rowIndexes.add(r);
colIndexes.add(c);
grid.put((r << 16) + c, cell);
}
/** Adds a docking cell. That cell is outside the normal cell indexes.
* @param dockInsets The current dock insets. Will be updated!
* @param side top == 0, left == 1, bottom = 2, right = 3.
* @param cw The compwrap to put in a cell and add.
*/
private void addDockingCell(int[] dockInsets, int side, CompWrap cw)
{
int r, c, spanx = 1, spany = 1;
switch (side) {
case 0:
case 2:
r = side == 0 ? dockInsets[0]++ : dockInsets[2]--;
c = dockInsets[1];
spanx = dockInsets[3] - dockInsets[1] + 1; // The +1 is for cell 0.
colIndexes.add(dockInsets[3]); // Make sure there is a receiving cell
break;
case 1:
case 3:
c = side == 1 ? dockInsets[1]++ : dockInsets[3]--;
r = dockInsets[0];
spany = dockInsets[2] - dockInsets[0] + 1; // The +1 is for cell 0.
rowIndexes.add(dockInsets[2]); // Make sure there is a receiving cell
break;
default:
throw new IllegalArgumentException("Internal error 123.");
}
rowIndexes.add(r);
colIndexes.add(c);
grid.put((r << 16) + c, new Cell(cw, spanx, spany, spanx > 1));
}
/** A simple representation of a cell in the grid. Contains a number of component wraps, if they span more than one cell.
*/
private static class Cell
{
private final int spanx, spany;
private final boolean flowx;
private final ArrayList<CompWrap> compWraps = new ArrayList<CompWrap>(1);
private boolean hasTagged = false; // If one or more components have styles and need to be checked by the component sorter
private Cell(CompWrap cw)
{
this(cw, 1, 1, true);
}
private Cell(int spanx, int spany, boolean flowx)
{
this(null, spanx, spany, flowx);
}
private Cell(CompWrap cw, int spanx, int spany, boolean flowx)
{
if (cw != null)
compWraps.add(cw);
this.spanx = spanx;
this.spany = spany;
this.flowx = flowx;
}
}
/** A number of component wraps that share a layout "something" <b>in one dimension</b>
*/
private static class LinkedDimGroup
{
private static final int TYPE_SERIAL = 0;
private static final int TYPE_PARALLEL = 1;
private static final int TYPE_BASELINE = 2;
private final String linkCtx;
private final int span;
private final int linkType;
private final boolean isHor, fromEnd;
private ArrayList<CompWrap> _compWraps = new ArrayList<CompWrap>(4);
private int[] sizes = null;
private int lStart = 0, lSize = 0; // Currently mostly for debug painting
private LinkedDimGroup(String linkCtx, int span, int linkType, boolean isHor, boolean fromEnd)
{
this.linkCtx = linkCtx;
this.span = span;
this.linkType = linkType;
this.isHor = isHor;
this.fromEnd = fromEnd;
}
private void addCompWrap(CompWrap cw)
{
_compWraps.add(cw);
sizes = null;
}
private void setCompWraps(ArrayList<CompWrap> cws)
{
if (_compWraps != cws) {
_compWraps = cws;
sizes = null;
}
}
private void layout(DimConstraint dc, int start, int size, int spanCount)
{
lStart = start;
lSize = size;
if (_compWraps.size() == 0)
return;
ContainerWrapper parent = _compWraps.get(0).comp.getParent();
if (linkType == TYPE_PARALLEL) {
layoutParallel(parent, _compWraps, dc, start, size, isHor, fromEnd);
} else if (linkType == TYPE_BASELINE) {
layoutBaseline(parent, _compWraps, dc, start, size, LayoutUtil.PREF, spanCount);
} else {
layoutSerial(parent, _compWraps, dc, start, size, isHor, spanCount, fromEnd);
}
}
/** Returns the min/pref/max sizes for this cell. Returned array <b>must not be altered</b>
* @return A shared min/pref/max array of sizes. Always of length 3 and never <code>null</code>. Will always be of type STATIC and PIXEL.
*/
private int[] getMinPrefMax()
{
if (sizes == null && _compWraps.size() > 0) {
sizes = new int[3];
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.PREF; sType++) {
if (linkType == TYPE_PARALLEL) {
sizes[sType] = getTotalSizeParallel(_compWraps, sType, isHor);
} else if (linkType == TYPE_BASELINE) {
int[] aboveBelow = getBaselineAboveBelow(_compWraps, sType, false);
sizes[sType] = aboveBelow[0] + aboveBelow[1];
} else {
sizes[sType] = getTotalSizeSerial(_compWraps, sType, isHor);
}
}
sizes[LayoutUtil.MAX] = LayoutUtil.INF;
}
return sizes;
}
}
/** Wraps a {@link java.awt.Component} together with its constraint. Caches a lot of information about the component so
* for instance not the preferred size has to be calculated more than once.
*/
private final static class CompWrap
{
private final ComponentWrapper comp;
private final CC cc;
private final UnitValue[] pos;
private int[][] gaps; // [top,left(actually before),bottom,right(actually after)][min,pref,max]
private final int[] horSizes = new int[3];
private final int[] verSizes = new int[3];
private int x = LayoutUtil.NOT_SET, y = LayoutUtil.NOT_SET, w = LayoutUtil.NOT_SET, h = LayoutUtil.NOT_SET;
private int forcedPushGaps = 0; // 1 == before, 2 = after. Bitwise.
private CompWrap(ComponentWrapper c, CC cc, int eHideMode, UnitValue[] pos, BoundSize[] callbackSz)
{
this.comp = c;
this.cc = cc;
this.pos = pos;
if (eHideMode <= 0) {
BoundSize hBS = (callbackSz != null && callbackSz[0] != null) ? callbackSz[0] : cc.getHorizontal().getSize();
BoundSize vBS = (callbackSz != null && callbackSz[1] != null) ? callbackSz[1] : cc.getVertical().getSize();
int wHint = -1, hHint = -1; // Added for v3.7
if (comp.getWidth() > 0 && comp.getHeight() > 0) {
hHint = comp.getHeight();
wHint = comp.getWidth();
}
for (int i = LayoutUtil.MIN; i <= LayoutUtil.MAX; i++) {
- horSizes[i] = getSize(hBS, i, true, hHint);
- verSizes[i] = getSize(vBS, i, false, wHint > 0 ? wHint : horSizes[i]);
+ horSizes[i] = getSize(hBS, i, true, wHint);
+ verSizes[i] = getSize(vBS, i, false, hHint > 0 ? hHint : horSizes[i]);
}
correctMinMax(horSizes);
correctMinMax(verSizes);
}
if (eHideMode > 1) {
gaps = new int[4][];
for (int i = 0; i < gaps.length; i++)
gaps[i] = new int[3];
}
}
private int getSize(BoundSize uvs, int sizeType, boolean isHor, int sizeHint)
{
if (uvs == null || uvs.getSize(sizeType) == null) {
switch(sizeType) {
case LayoutUtil.MIN:
return isHor ? comp.getMinimumWidth(sizeHint) : comp.getMinimumHeight(sizeHint);
case LayoutUtil.PREF:
return isHor ? comp.getPreferredWidth(sizeHint) : comp.getPreferredHeight(sizeHint);
default:
return isHor ? comp.getMaximumWidth(sizeHint) : comp.getMaximumHeight(sizeHint);
}
}
ContainerWrapper par = comp.getParent();
return uvs.getSize(sizeType).getPixels(isHor ? par.getWidth() : par.getHeight(), par, comp);
}
private void calcGaps(ComponentWrapper before, CC befCC, ComponentWrapper after, CC aftCC, String tag, boolean flowX, boolean isLTR)
{
ContainerWrapper par = comp.getParent();
int parW = par.getWidth();
int parH = par.getHeight();
BoundSize befGap = before != null ? (flowX ? befCC.getHorizontal() : befCC.getVertical()).getGapAfter() : null;
BoundSize aftGap = after != null ? (flowX ? aftCC.getHorizontal() : aftCC.getVertical()).getGapBefore() : null;
mergeGapSizes(cc.getVertical().getComponentGaps(par, comp, befGap, (flowX ? null : before), tag, parH, 0, isLTR), false, true);
mergeGapSizes(cc.getHorizontal().getComponentGaps(par, comp, befGap, (flowX ? before : null), tag, parW, 1, isLTR), true, true);
mergeGapSizes(cc.getVertical().getComponentGaps(par, comp, aftGap, (flowX ? null : after), tag, parH, 2, isLTR), false, false);
mergeGapSizes(cc.getHorizontal().getComponentGaps(par, comp, aftGap, (flowX ? after : null), tag, parW, 3, isLTR), true, false);
}
private void setDimBounds(int start, int size, boolean isHor)
{
if (isHor) {
x = start;
w = size;
} else {
y = start;
h = size;
}
}
private boolean isPushGap(boolean isHor, boolean isBefore)
{
if (isHor && ((isBefore ? 1 : 2) & forcedPushGaps) != 0)
return true; // Forced
DimConstraint dc = cc.getDimConstraint(isHor);
BoundSize s = isBefore ? dc.getGapBefore() : dc.getGapAfter();
return s != null && s.getGapPush();
}
/**
* @return If the preferred size have changed because of the new bounds.
*/
private boolean transferBounds(boolean checkPrefChange)
{
comp.setBounds(x, y, w, h);
if (checkPrefChange && w != horSizes[LayoutUtil.PREF]) {
BoundSize vSz = cc.getVertical().getSize();
if (vSz.getPreferred() == null) {
if (comp.getPreferredHeight(-1) != verSizes[LayoutUtil.PREF])
return true;
}
}
return false;
}
private void setSizes(int[] sizes, boolean isHor)
{
if (sizes == null)
return;
int[] s = isHor ? horSizes : verSizes;
s[LayoutUtil.MIN] = sizes[LayoutUtil.MIN];
s[LayoutUtil.PREF] = sizes[LayoutUtil.PREF];
s[LayoutUtil.MAX] = sizes[LayoutUtil.MAX];
}
private void setGaps(int[] minPrefMax, int ix)
{
if (gaps == null)
gaps = new int[][] {null, null, null, null};
gaps[ix] = minPrefMax;
}
private void mergeGapSizes(int[] sizes, boolean isHor, boolean isTL)
{
if (gaps == null)
gaps = new int[][] {null, null, null, null};
if (sizes == null)
return;
int gapIX = getGapIx(isHor, isTL);
int[] oldGaps = gaps[gapIX];
if (oldGaps == null) {
oldGaps = new int[] {0, 0, LayoutUtil.INF};
gaps[gapIX] = oldGaps;
}
oldGaps[LayoutUtil.MIN] = Math.max(sizes[LayoutUtil.MIN], oldGaps[LayoutUtil.MIN]);
oldGaps[LayoutUtil.PREF] = Math.max(sizes[LayoutUtil.PREF], oldGaps[LayoutUtil.PREF]);
oldGaps[LayoutUtil.MAX] = Math.min(sizes[LayoutUtil.MAX], oldGaps[LayoutUtil.MAX]);
}
private int getGapIx(boolean isHor, boolean isTL)
{
return isHor ? (isTL ? 1 : 3) : (isTL ? 0 : 2);
}
private int getSizeInclGaps(int sizeType, boolean isHor)
{
return filter(sizeType, getGapBefore(sizeType, isHor) + getSize(sizeType, isHor) + getGapAfter(sizeType, isHor));
}
private int getSize(int sizeType, boolean isHor)
{
return filter(sizeType, isHor ? horSizes[sizeType] : verSizes[sizeType]);
}
private int getGapBefore(int sizeType, boolean isHor)
{
int[] gaps = getGaps(isHor, true);
return gaps != null ? filter(sizeType, gaps[sizeType]) : 0;
}
private int getGapAfter(int sizeType, boolean isHor)
{
int[] gaps = getGaps(isHor, false);
return gaps != null ? filter(sizeType, gaps[sizeType]) : 0;
}
private int[] getGaps(boolean isHor, boolean isTL)
{
return gaps[getGapIx(isHor, isTL)];
}
private int filter(int sizeType, int size)
{
if (size == LayoutUtil.NOT_SET)
return sizeType != LayoutUtil.MAX ? 0 : LayoutUtil.INF;
return constrainSize(size);
}
private boolean isBaselineAlign(boolean defValue)
{
Float g = cc.getVertical().getGrow();
if (g != null && g.intValue() != 0)
return false;
UnitValue al = cc.getVertical().getAlign();
return (al != null ? al == UnitValue.BASELINE_IDENTITY : defValue) && comp.hasBaseline();
}
private int getBaseline(int sizeType)
{
return comp.getBaseline(getSize(sizeType, true), getSize(sizeType, false));
}
}
//***************************************************************************************
//* Helper Methods
//***************************************************************************************
private static void layoutBaseline(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, int sizeType, int spanCount)
{
int[] aboveBelow = getBaselineAboveBelow(compWraps, sizeType, true);
int blRowSize = aboveBelow[0] + aboveBelow[1];
CC cc = compWraps.get(0).cc;
// Align for the whole baseline component array
UnitValue align = cc.getVertical().getAlign();
if (spanCount == 1 && align == null)
align = dc.getAlignOrDefault(false);
if (align == UnitValue.BASELINE_IDENTITY)
align = UnitValue.CENTER;
int offset = start + aboveBelow[0] + (align != null ? Math.max(0, align.getPixels(size - blRowSize, parent, null)) : 0);
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
cw.y += offset;
if (cw.y + cw.h > start + size)
cw.h = start + size - cw.y;
}
}
private static void layoutSerial(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, boolean isHor, int spanCount, boolean fromEnd)
{
FlowSizeSpec fss = mergeSizesGapsAndResConstrs(
getComponentResizeConstraints(compWraps, isHor),
getComponentGapPush(compWraps, isHor),
getComponentSizes(compWraps, isHor),
getGaps(compWraps, isHor));
Float[] pushW = dc.isFill() ? GROW_100 : null;
int[] sizes = LayoutUtil.calculateSerial(fss.sizes, fss.resConstsInclGaps, pushW, LayoutUtil.PREF, size);
setCompWrapBounds(parent, sizes, compWraps, dc.getAlignOrDefault(isHor), start, size, isHor, fromEnd);
}
private static void setCompWrapBounds(ContainerWrapper parent, int[] allSizes, ArrayList<CompWrap> compWraps, UnitValue rowAlign, int start, int size, boolean isHor, boolean fromEnd)
{
int totSize = LayoutUtil.sum(allSizes);
CC cc = compWraps.get(0).cc;
UnitValue align = correctAlign(cc, rowAlign, isHor, fromEnd);
int cSt = start;
int slack = size - totSize;
if (slack > 0 && align != null) {
int al = Math.min(slack, Math.max(0, align.getPixels(slack, parent, null)));
cSt += (fromEnd ? -al : al);
}
for (int i = 0, bIx = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
if (fromEnd ) {
cSt -= allSizes[bIx++];
cw.setDimBounds(cSt - allSizes[bIx], allSizes[bIx], isHor);
cSt -= allSizes[bIx++];
} else {
cSt += allSizes[bIx++];
cw.setDimBounds(cSt, allSizes[bIx], isHor);
cSt += allSizes[bIx++];
}
}
}
private static void layoutParallel(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, boolean isHor, boolean fromEnd)
{
int[][] sizes = new int[compWraps.size()][]; // [compIx][gapBef,compSize,gapAft]
for (int i = 0; i < sizes.length; i++) {
CompWrap cw = compWraps.get(i);
DimConstraint cDc = cw.cc.getDimConstraint(isHor);
ResizeConstraint[] resConstr = new ResizeConstraint[] {
cw.isPushGap(isHor, true) ? GAP_RC_CONST_PUSH : GAP_RC_CONST,
cDc.resize,
cw.isPushGap(isHor, false) ? GAP_RC_CONST_PUSH : GAP_RC_CONST,
};
int[][] sz = new int[][] {
cw.getGaps(isHor, true), (isHor ? cw.horSizes : cw.verSizes), cw.getGaps(isHor, false)
};
Float[] pushW = dc.isFill() ? GROW_100 : null;
sizes[i] = LayoutUtil.calculateSerial(sz, resConstr, pushW, LayoutUtil.PREF, size);
}
UnitValue rowAlign = dc.getAlignOrDefault(isHor);
setCompWrapBounds(parent, sizes, compWraps, rowAlign, start, size, isHor, fromEnd);
}
private static void setCompWrapBounds(ContainerWrapper parent, int[][] sizes, ArrayList<CompWrap> compWraps, UnitValue rowAlign, int start, int size, boolean isHor, boolean fromEnd)
{
for (int i = 0; i < sizes.length; i++) {
CompWrap cw = compWraps.get(i);
UnitValue align = correctAlign(cw.cc, rowAlign, isHor, fromEnd);
int[] cSizes = sizes[i];
int gapBef = cSizes[0];
int cSize = cSizes[1]; // No Math.min(size, cSizes[1]) here!
int gapAft = cSizes[2];
int cSt = fromEnd ? start - gapBef : start + gapBef;
int slack = size - cSize - gapBef - gapAft;
if (slack > 0 && align != null) {
int al = Math.min(slack, Math.max(0, align.getPixels(slack, parent, null)));
cSt += (fromEnd ? -al : al);
}
cw.setDimBounds(fromEnd ? cSt - cSize : cSt, cSize, isHor);
}
}
private static UnitValue correctAlign(CC cc, UnitValue rowAlign, boolean isHor, boolean fromEnd)
{
UnitValue align = (isHor ? cc.getHorizontal() : cc.getVertical()).getAlign();
if (align == null)
align = rowAlign;
if (align == UnitValue.BASELINE_IDENTITY)
align = UnitValue.CENTER;
if (fromEnd) {
if (align == UnitValue.LEFT)
align = UnitValue.RIGHT;
else if (align == UnitValue.RIGHT)
align = UnitValue.LEFT;
}
return align;
}
private static int[] getBaselineAboveBelow(ArrayList<CompWrap> compWraps, int sType, boolean centerBaseline)
{
int maxAbove = Short.MIN_VALUE;
int maxBelow = Short.MIN_VALUE;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
int height = cw.getSize(sType, false);
if (height >= LayoutUtil.INF)
return new int[] {LayoutUtil.INF / 2, LayoutUtil.INF / 2};
int baseline = cw.getBaseline(sType);
int above = baseline + cw.getGapBefore(sType, false);
maxAbove = Math.max(above, maxAbove);
maxBelow = Math.max(height - baseline + cw.getGapAfter(sType, false), maxBelow);
if (centerBaseline)
cw.setDimBounds(-baseline, height, false);
}
return new int[] {maxAbove, maxBelow};
}
private static int getTotalSizeParallel(ArrayList<CompWrap> compWraps, int sType, boolean isHor)
{
int size = sType == LayoutUtil.MAX ? LayoutUtil.INF : 0;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
int cwSize = cw.getSizeInclGaps(sType, isHor);
if (cwSize >= LayoutUtil.INF)
return LayoutUtil.INF;
if (sType == LayoutUtil.MAX ? cwSize < size : cwSize > size)
size = cwSize;
}
return constrainSize(size);
}
private static int getTotalSizeSerial(ArrayList<CompWrap> compWraps, int sType, boolean isHor)
{
int totSize = 0;
for (int i = 0, iSz = compWraps.size(), lastGapAfter = 0; i < iSz; i++) {
CompWrap wrap = compWraps.get(i);
int gapBef = wrap.getGapBefore(sType, isHor);
if (gapBef > lastGapAfter)
totSize += gapBef - lastGapAfter;
totSize += wrap.getSize(sType, isHor);
totSize += (lastGapAfter = wrap.getGapAfter(sType, isHor));
if (totSize >= LayoutUtil.INF)
return LayoutUtil.INF;
}
return constrainSize(totSize);
}
private static int getTotalGroupsSizeParallel(ArrayList<LinkedDimGroup> groups, int sType, boolean countSpanning)
{
int size = sType == LayoutUtil.MAX ? LayoutUtil.INF : 0;
for (int i = 0, iSz = groups.size(); i < iSz; i++) {
LinkedDimGroup group = groups.get(i);
if (countSpanning || group.span == 1) {
int grpSize = group.getMinPrefMax()[sType];
if (grpSize >= LayoutUtil.INF)
return LayoutUtil.INF;
if (sType == LayoutUtil.MAX ? grpSize < size : grpSize > size)
size = grpSize;
}
}
return constrainSize(size);
}
/**
* @param compWraps
* @param isHor
* @return Might contain LayoutUtil.NOT_SET
*/
private static int[][] getComponentSizes(ArrayList<CompWrap> compWraps, boolean isHor)
{
int[][] compSizes = new int[compWraps.size()][];
for (int i = 0; i < compSizes.length; i++) {
CompWrap cw = compWraps.get(i);
compSizes[i] = isHor ? cw.horSizes : cw.verSizes;
}
return compSizes;
}
/** Merges sizes and gaps together with Resize Constraints. For gaps {@link #GAP_RC_CONST} is used.
* @param resConstr One resize constriant for every row/component. Can be lesser in length and the last element should be used for missing elements.
* @param gapPush If the corresponding gap should be considered pushing and thus want to take free space if left over. Should be one more than resConstrs!
* @param minPrefMaxSizes The sizes (min/pref/max) for every row/component.
* @param gapSizes The gaps before and after each row/component packed in one double sized array.
* @return A holder for the merged values.
*/
private static FlowSizeSpec mergeSizesGapsAndResConstrs(ResizeConstraint[] resConstr, boolean[] gapPush, int[][] minPrefMaxSizes, int[][] gapSizes)
{
int[][] sizes = new int[(minPrefMaxSizes.length << 1) + 1][]; // Make room for gaps around.
ResizeConstraint[] resConstsInclGaps = new ResizeConstraint[sizes.length];
sizes[0] = gapSizes[0];
for (int i = 0, crIx = 1; i < minPrefMaxSizes.length; i++, crIx += 2) {
// Component bounds and constraints
resConstsInclGaps[crIx] = resConstr[i];
sizes[crIx] = minPrefMaxSizes[i];
sizes[crIx + 1] = gapSizes[i + 1];
if (sizes[crIx - 1] != null)
resConstsInclGaps[crIx - 1] = gapPush[i < gapPush.length ? i : gapPush.length - 1] ? GAP_RC_CONST_PUSH : GAP_RC_CONST;
if (i == (minPrefMaxSizes.length - 1) && sizes[crIx + 1] != null)
resConstsInclGaps[crIx + 1] = gapPush[(i + 1) < gapPush.length ? (i + 1) : gapPush.length - 1] ? GAP_RC_CONST_PUSH : GAP_RC_CONST;
}
// Check for null and set it to 0, 0, 0.
for (int i = 0; i < sizes.length; i++) {
if (sizes[i] == null)
sizes[i] = new int[3];
}
return new FlowSizeSpec(sizes, resConstsInclGaps);
}
private static int[] mergeSizes(int[] oldValues, int[] newValues)
{
if (oldValues == null)
return newValues;
if (newValues == null)
return oldValues;
int[] ret = new int[oldValues.length];
for (int i = 0; i < ret.length; i++)
ret[i] = mergeSizes(oldValues[i], newValues[i], true);
return ret;
}
private static int mergeSizes(int oldValue, int newValue, boolean toMax)
{
if (oldValue == LayoutUtil.NOT_SET || oldValue == newValue)
return newValue;
if (newValue == LayoutUtil.NOT_SET)
return oldValue;
return toMax != oldValue > newValue ? newValue : oldValue;
}
private static int constrainSize(int s)
{
return s > 0 ? (s < LayoutUtil.INF ? s : LayoutUtil.INF) : 0;
}
private static void correctMinMax(int s[])
{
if (s[LayoutUtil.MIN] > s[LayoutUtil.MAX])
s[LayoutUtil.MIN] = s[LayoutUtil.MAX]; // Since MAX is almost always explicitly set use that
if (s[LayoutUtil.PREF] < s[LayoutUtil.MIN])
s[LayoutUtil.PREF] = s[LayoutUtil.MIN];
if (s[LayoutUtil.PREF] > s[LayoutUtil.MAX])
s[LayoutUtil.PREF] = s[LayoutUtil.MAX];
}
private static final class FlowSizeSpec
{
private final int[][] sizes; // [row/col index][min, pref, max]
private final ResizeConstraint[] resConstsInclGaps; // [row/col index]
private FlowSizeSpec(int[][] sizes, ResizeConstraint[] resConstsInclGaps)
{
this.sizes = sizes;
this.resConstsInclGaps = resConstsInclGaps;
}
/**
* @param specs The specs for the columns or rows. Last index will be used of <code>fromIx + len</code> is greater than this array's length.
* @param targetSize The size to try to meet.
* @param defGrow The default grow weight if the specs does not have anyone that will grow. Comes from "push" in the CC.
* @param fromIx
* @param len
* @param sizeType
* @param eagerness How eager the algorithm should be to try to expand the sizes.
* <ul>
* <li>0 - Grow only rows/columns which have the <code>sizeType</code> set to be the containing components AND which has a grow weight > 0.
* <li>1 - Grow only rows/columns which have the <code>sizeType</code> set to be the containing components AND which has a grow weight > 0 OR unspecified.
* <li>2 - Grow all rows/columns that have a grow weight > 0.
* <li>3 - Grow all rows/columns that have a grow weight > 0 OR unspecified.
* </ul>
* @return The new size.
*/
private int expandSizes(DimConstraint[] specs, Float[] defGrow, int targetSize, int fromIx, int len, int sizeType, int eagerness)
{
ResizeConstraint[] resConstr = new ResizeConstraint[len];
int[][] sizesToExpand = new int[len][];
for (int i = 0; i < len; i++) {
int[] minPrefMax = sizes[i + fromIx];
sizesToExpand[i] = new int[] {minPrefMax[sizeType], minPrefMax[LayoutUtil.PREF], minPrefMax[LayoutUtil.MAX]};
if (eagerness <= 1 && i % 2 == 0) { // (i % 2 == 0) means only odd indexes, which is only rows/col indexes and not gaps.
int cIx = (i + fromIx - 1) >> 1;
DimConstraint spec = (DimConstraint) LayoutUtil.getIndexSafe(specs, cIx);
BoundSize sz = spec.getSize();
if ( (sizeType == LayoutUtil.MIN && sz.getMin() != null && sz.getMin().getUnit() != UnitValue.MIN_SIZE) ||
(sizeType == LayoutUtil.PREF && sz.getPreferred() != null && sz.getPreferred().getUnit() != UnitValue.PREF_SIZE)) {
continue;
}
}
resConstr[i] = (ResizeConstraint) LayoutUtil.getIndexSafe(resConstsInclGaps, i + fromIx);
}
Float[] growW = (eagerness == 1 || eagerness == 3) ? extractSubArray(specs, defGrow, fromIx, len): null;
int[] newSizes = LayoutUtil.calculateSerial(sizesToExpand, resConstr, growW, LayoutUtil.PREF, targetSize);
int newSize = 0;
for (int i = 0; i < len; i++) {
int s = newSizes[i];
sizes[i + fromIx][sizeType] = s;
newSize += s;
}
return newSize;
}
}
private static Float[] extractSubArray(DimConstraint[] specs, Float[] arr, int ix, int len)
{
if (arr == null || arr.length < ix + len) {
Float[] growLastArr = new Float[len];
// Handle a group where some rows (first one/few and/or last one/few) are docks.
for (int i = ix + len - 1; i >= 0; i -= 2) {
int specIx = (i >> 1);
if (specs[specIx] != DOCK_DIM_CONSTRAINT) {
growLastArr[i - ix] = ResizeConstraint.WEIGHT_100;
return growLastArr;
}
}
return growLastArr;
}
Float[] newArr = new Float[len];
for (int i = 0; i < len; i++)
newArr[i] = arr[ix + i];
return newArr;
}
private static synchronized void putSizesAndIndexes(Object parComp, int[] sizes, int[] ixArr, boolean isRows)
{
}
static synchronized int[][] getSizesAndIndexes(Object parComp, boolean isRows)
{
return null;
}
private static synchronized void saveGrid(ComponentWrapper parComp, LinkedHashMap<Integer, Cell> grid)
{
}
static synchronized HashMap<Object, int[]> getGridPositions(Object parComp)
{
return null;
}
}
| true | true | private int[] getAbsoluteDimBounds(CompWrap cw, int refSize, boolean isHor)
{
if (cw.cc.isExternal()) {
if (isHor) {
return new int[] {cw.comp.getX(), cw.comp.getWidth()};
} else {
return new int[] {cw.comp.getY(), cw.comp.getHeight()};
}
}
int[] plafPad = lc.isVisualPadding() ? cw.comp.getVisualPadding() : null;
UnitValue[] pad = cw.cc.getPadding();
// If no changes do not create a lot of objects
if (cw.pos == null && plafPad == null && pad == null)
return null;
// Set start
int st = isHor ? cw.x : cw.y;
int sz = isHor ? cw.w : cw.h;
// If absolute, use those coordinates instead.
if (cw.pos != null) {
UnitValue stUV = cw.pos != null ? cw.pos[isHor ? 0 : 1] : null;
UnitValue endUV = cw.pos != null ? cw.pos[isHor ? 2 : 3] : null;
int minSz = cw.getSize(LayoutUtil.MIN, isHor);
int maxSz = cw.getSize(LayoutUtil.MAX, isHor);
sz = Math.min(Math.max(cw.getSize(LayoutUtil.PREF, isHor), minSz), maxSz);
if (stUV != null) {
st = stUV.getPixels(stUV.getUnit() == UnitValue.ALIGN ? sz : refSize, container, cw.comp);
if (endUV != null) // if (endUV == null && cw.cc.isBoundsIsGrid() == true)
sz = Math.min(Math.max((isHor ? (cw.x + cw.w) : (cw.y + cw.h)) - st, minSz), maxSz);
}
if (endUV != null) {
if (stUV != null) { // if (stUV != null || cw.cc.isBoundsIsGrid()) {
sz = Math.min(Math.max(endUV.getPixels(refSize, container, cw.comp) - st, minSz), maxSz);
} else {
st = endUV.getPixels(refSize, container, cw.comp) - sz;
}
}
}
// If constraint has padding -> correct the start/size
if (pad != null) {
UnitValue uv = pad[isHor ? 1 : 0];
int p = uv != null ? uv.getPixels(refSize, container, cw.comp) : 0;
st += p;
uv = pad[isHor ? 3 : 2];
sz += -p + (uv != null ? uv.getPixels(refSize, container, cw.comp) : 0);
}
// If the plaf converter has padding -> correct the start/size
if (plafPad != null) {
int p = plafPad[isHor ? 1 : 0];
st += p;
sz += -p + (plafPad[isHor ? 3 : 2]);
}
return new int[] {st, sz};
}
private void layoutInOneDim(int refSize, UnitValue align, boolean isRows, Float[] defaultPushWeights)
{
boolean fromEnd = !(isRows ? lc.isTopToBottom() : LayoutUtil.isLeftToRight(lc, container));
DimConstraint[] primDCs = (isRows ? rowConstr : colConstr).getConstaints();
FlowSizeSpec fss = isRows ? rowFlowSpecs : colFlowSpecs;
ArrayList<LinkedDimGroup>[] rowCols = isRows ? rowGroupLists : colGroupLists;
int[] rowColSizes = LayoutUtil.calculateSerial(fss.sizes, fss.resConstsInclGaps, defaultPushWeights, LayoutUtil.PREF, refSize);
if (LayoutUtil.isDesignTime(container)) {
TreeSet<Integer> indexes = isRows ? rowIndexes : colIndexes;
int[] ixArr = new int[indexes.size()];
int ix = 0;
for (Integer i : indexes)
ixArr[ix++] = i;
putSizesAndIndexes(container.getComponent(), rowColSizes, ixArr, isRows);
}
int curPos = align != null ? align.getPixels(refSize - LayoutUtil.sum(rowColSizes), container, null) : 0;
if (fromEnd)
curPos = refSize - curPos;
for (int i = 0 ; i < rowCols.length; i++) {
ArrayList<LinkedDimGroup> linkedGroups = rowCols[i];
int scIx = i - (isRows ? dockOffY : dockOffX);
int bIx = i << 1;
int bIx2 = bIx + 1;
curPos += (fromEnd ? -rowColSizes[bIx] : rowColSizes[bIx]);
DimConstraint primDC = scIx >= 0 ? primDCs[scIx >= primDCs.length ? primDCs.length - 1 : scIx] : DOCK_DIM_CONSTRAINT;
int rowSize = rowColSizes[bIx2];
for (LinkedDimGroup group : linkedGroups) {
int groupSize = rowSize;
if (group.span > 1)
groupSize = LayoutUtil.sum(rowColSizes, bIx2, Math.min((group.span << 1) - 1, rowColSizes.length - bIx2 - 1));
group.layout(primDC, curPos, groupSize, group.span);
}
curPos += (fromEnd ? -rowSize : rowSize);
}
}
private static void addToSizeGroup(HashMap<String, int[]> sizeGroups, String sizeGroup, int[] size)
{
int[] sgSize = sizeGroups.get(sizeGroup);
if (sgSize == null) {
sizeGroups.put(sizeGroup, new int[] {size[LayoutUtil.MIN], size[LayoutUtil.PREF], size[LayoutUtil.MAX]});
} else {
sgSize[LayoutUtil.MIN] = Math.max(size[LayoutUtil.MIN], sgSize[LayoutUtil.MIN]);
sgSize[LayoutUtil.PREF] = Math.max(size[LayoutUtil.PREF], sgSize[LayoutUtil.PREF]);
sgSize[LayoutUtil.MAX] = Math.min(size[LayoutUtil.MAX], sgSize[LayoutUtil.MAX]);
}
}
private static HashMap<String, Integer> addToEndGroup(HashMap<String, Integer> endGroups, String endGroup, int end)
{
if (endGroup != null) {
if (endGroups == null)
endGroups = new HashMap<String, Integer>(2);
Integer oldEnd = endGroups.get(endGroup);
if (oldEnd == null || end > oldEnd)
endGroups.put(endGroup, end);
}
return endGroups;
}
/** Calculates Min, Preferred and Max size for the columns OR rows.
* @param isHor If it is the horizontal dimension to calculate.
* @return The sizes in a {@link net.miginfocom.layout.Grid.FlowSizeSpec}.
*/
private FlowSizeSpec calcRowsOrColsSizes(boolean isHor)
{
ArrayList<LinkedDimGroup>[] groupsLists = isHor ? colGroupLists : rowGroupLists;
Float[] defPush = isHor ? pushXs : pushYs;
int refSize = isHor ? container.getWidth() : container.getHeight();
BoundSize cSz = isHor ? lc.getWidth() : lc.getHeight();
if (cSz.isUnset() == false)
refSize = cSz.constrain(refSize, getParentSize(container, isHor), container);
DimConstraint[] primDCs = (isHor? colConstr : rowConstr).getConstaints();
TreeSet<Integer> primIndexes = isHor ? colIndexes : rowIndexes;
int[][] rowColBoundSizes = new int[primIndexes.size()][];
HashMap<String, int[]> sizeGroupMap = new HashMap<String, int[]>(2);
DimConstraint[] allDCs = new DimConstraint[primIndexes.size()];
Iterator<Integer> primIt = primIndexes.iterator();
for (int r = 0; r < rowColBoundSizes.length; r++) {
int cellIx = primIt.next();
int[] rowColSizes = new int[3];
if (cellIx >= -MAX_GRID && cellIx <= MAX_GRID) { // If not dock cell
allDCs[r] = primDCs[cellIx >= primDCs.length ? primDCs.length - 1 : cellIx];
} else {
allDCs[r] = DOCK_DIM_CONSTRAINT;
}
ArrayList<LinkedDimGroup> groups = groupsLists[r];
int[] groupSizes = new int[] {
getTotalGroupsSizeParallel(groups, LayoutUtil.MIN, false),
getTotalGroupsSizeParallel(groups, LayoutUtil.PREF, false),
LayoutUtil.INF};
correctMinMax(groupSizes);
BoundSize dimSize = allDCs[r].getSize();
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.MAX; sType++) {
int rowColSize = groupSizes[sType];
UnitValue uv = dimSize.getSize(sType);
if (uv != null) {
// If the size of the column is a link to some other size, use that instead
int unit = uv.getUnit();
if (unit == UnitValue.PREF_SIZE) {
rowColSize = groupSizes[LayoutUtil.PREF];
} else if (unit == UnitValue.MIN_SIZE) {
rowColSize = groupSizes[LayoutUtil.MIN];
} else if (unit == UnitValue.MAX_SIZE) {
rowColSize = groupSizes[LayoutUtil.MAX];
} else {
rowColSize = uv.getPixels(refSize, container, null);
}
} else if (cellIx >= -MAX_GRID && cellIx <= MAX_GRID && rowColSize == 0) {
rowColSize = LayoutUtil.isDesignTime(container) ? LayoutUtil.getDesignTimeEmptySize() : 0; // Empty rows with no size set gets XX pixels if design time
}
rowColSizes[sType] = rowColSize;
}
correctMinMax(rowColSizes);
addToSizeGroup(sizeGroupMap, allDCs[r].getSizeGroup(), rowColSizes);
rowColBoundSizes[r] = rowColSizes;
}
// Set/equalize the size groups to same the values.
if (sizeGroupMap.size() > 0) {
for (int r = 0; r < rowColBoundSizes.length; r++) {
if (allDCs[r].getSizeGroup() != null)
rowColBoundSizes[r] = sizeGroupMap.get(allDCs[r].getSizeGroup());
}
}
// Add the gaps
ResizeConstraint[] resConstrs = getRowResizeConstraints(allDCs);
boolean[] fillInPushGaps = new boolean[allDCs.length + 1];
int[][] gapSizes = getRowGaps(allDCs, refSize, isHor, fillInPushGaps);
FlowSizeSpec fss = mergeSizesGapsAndResConstrs(resConstrs, fillInPushGaps, rowColBoundSizes, gapSizes);
// Spanning components are not handled yet. Check and adjust the multi-row min/pref they enforce.
adjustMinPrefForSpanningComps(allDCs, defPush, fss, groupsLists);
return fss;
}
private static int getParentSize(ComponentWrapper cw, boolean isHor)
{
ComponentWrapper p = cw.getParent();
return p != null ? (isHor ? cw.getWidth() : cw.getHeight()) : 0;
}
private int[] getMinPrefMaxSumSize(boolean isHor)
{
int[][] sizes = isHor ? colFlowSpecs.sizes : rowFlowSpecs.sizes;
int[] retSizes = new int[3];
BoundSize sz = isHor ? lc.getWidth() : lc.getHeight();
for (int i = 0; i < sizes.length; i++) {
if (sizes[i] != null) {
int[] size = sizes[i];
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.MAX; sType++) {
if (sz.getSize(sType) != null) {
if (i == 0)
retSizes[sType] = sz.getSize(sType).getPixels(getParentSize(container, isHor), container, null);
} else {
int s = size[sType];
if (s != LayoutUtil.NOT_SET) {
if (sType == LayoutUtil.PREF) {
int bnd = size[LayoutUtil.MAX];
if (bnd != LayoutUtil.NOT_SET && bnd < s)
s = bnd;
bnd = size[LayoutUtil.MIN];
if (bnd > s) // Includes s == LayoutUtil.NOT_SET since < 0.
s = bnd;
}
retSizes[sType] += s; // MAX compensated below.
}
// So that MAX is always correct.
if (size[LayoutUtil.MAX] == LayoutUtil.NOT_SET || retSizes[LayoutUtil.MAX] > LayoutUtil.INF)
retSizes[LayoutUtil.MAX] = LayoutUtil.INF;
}
}
}
}
correctMinMax(retSizes);
return retSizes;
}
private static ResizeConstraint[] getRowResizeConstraints(DimConstraint[] specs)
{
ResizeConstraint[] resConsts = new ResizeConstraint[specs.length];
for (int i = 0; i < resConsts.length; i++)
resConsts[i] = specs[i].resize;
return resConsts;
}
private static ResizeConstraint[] getComponentResizeConstraints(ArrayList<CompWrap> compWraps, boolean isHor)
{
ResizeConstraint[] resConsts = new ResizeConstraint[compWraps.size()];
for (int i = 0; i < resConsts.length; i++) {
CC fc = compWraps.get(i).cc;
resConsts[i] = fc.getDimConstraint(isHor).resize;
// Always grow docking components in the correct dimension.
int dock = fc.getDockSide();
if (isHor ? (dock == 0 || dock == 2) : (dock == 1 || dock == 3)) {
ResizeConstraint dc = resConsts[i];
resConsts[i] = new ResizeConstraint(dc.shrinkPrio, dc.shrink, dc.growPrio, ResizeConstraint.WEIGHT_100);
}
}
return resConsts;
}
private static boolean[] getComponentGapPush(ArrayList<CompWrap> compWraps, boolean isHor)
{
// Make one element bigger and or the after gap with the next before gap.
boolean[] barr = new boolean[compWraps.size() + 1];
for (int i = 0; i < barr.length; i++) {
boolean push = i > 0 && compWraps.get(i - 1).isPushGap(isHor, false);
if (push == false && i < (barr.length - 1))
push = compWraps.get(i).isPushGap(isHor, true);
barr[i] = push;
}
return barr;
}
/** Returns the row gaps in pixel sizes. One more than there are <code>specs</code> sent in.
* @param specs
* @param refSize
* @param isHor
* @param fillInPushGaps If the gaps are pushing. <b>NOTE!</b> this argument will be filled in and thus changed!
* @return The row gaps in pixel sizes. One more than there are <code>specs</code> sent in.
*/
private int[][] getRowGaps(DimConstraint[] specs, int refSize, boolean isHor, boolean[] fillInPushGaps)
{
BoundSize defGap = isHor ? lc.getGridGapX() : lc.getGridGapY();
if (defGap == null)
defGap = isHor ? PlatformDefaults.getGridGapX() : PlatformDefaults.getGridGapY();
int[] defGapArr = defGap.getPixelSizes(refSize, container, null);
boolean defIns = !hasDocks();
UnitValue firstGap = LayoutUtil.getInsets(lc, isHor ? 1 : 0, defIns);
UnitValue lastGap = LayoutUtil.getInsets(lc, isHor ? 3 : 2, defIns);
int[][] retValues = new int[specs.length + 1][];
for (int i = 0, wgIx = 0; i < retValues.length; i++) {
DimConstraint specBefore = i > 0 ? specs[i - 1] : null;
DimConstraint specAfter = i < specs.length ? specs[i] : null;
// No gap if between docking components.
boolean edgeBefore = (specBefore == DOCK_DIM_CONSTRAINT || specBefore == null);
boolean edgeAfter = (specAfter == DOCK_DIM_CONSTRAINT || specAfter == null);
if (edgeBefore && edgeAfter)
continue;
BoundSize wrapGapSize = (wrapGapMap == null || isHor == lc.isFlowX() ? null : wrapGapMap.get(Integer.valueOf(wgIx++)));
if (wrapGapSize == null) {
int[] gapBefore = specBefore != null ? specBefore.getRowGaps(container, null, refSize, false) : null;
int[] gapAfter = specAfter != null ? specAfter.getRowGaps(container, null, refSize, true) : null;
if (edgeBefore && gapAfter == null && firstGap != null) {
int bef = firstGap.getPixels(refSize, container, null);
retValues[i] = new int[] {bef, bef, bef};
} else if (edgeAfter && gapBefore == null && firstGap != null) {
int aft = lastGap.getPixels(refSize, container, null);
retValues[i] = new int[] {aft, aft, aft};
} else {
retValues[i] = gapAfter != gapBefore ? mergeSizes(gapAfter, gapBefore) : new int[] {defGapArr[0], defGapArr[1], defGapArr[2]};
}
if (specBefore != null && specBefore.isGapAfterPush() || specAfter != null && specAfter.isGapBeforePush())
fillInPushGaps[i] = true;
} else {
if (wrapGapSize.isUnset()) {
retValues[i] = new int[] {defGapArr[0], defGapArr[1], defGapArr[2]};
} else {
retValues[i] = wrapGapSize.getPixelSizes(refSize, container, null);
}
fillInPushGaps[i] = wrapGapSize.getGapPush();
}
}
return retValues;
}
private static int[][] getGaps(ArrayList<CompWrap> compWraps, boolean isHor)
{
int compCount = compWraps.size();
int[][] retValues = new int[compCount + 1][];
retValues[0] = compWraps.get(0).getGaps(isHor, true);
for (int i = 0; i < compCount; i++) {
int[] gap1 = compWraps.get(i).getGaps(isHor, false);
int[] gap2 = i < compCount - 1 ? compWraps.get(i + 1).getGaps(isHor, true) : null;
retValues[i + 1] = mergeSizes(gap1, gap2);
}
return retValues;
}
private boolean hasDocks()
{
return (dockOffX > 0 || dockOffY > 0 || rowIndexes.last() > MAX_GRID || colIndexes.last() > MAX_GRID);
}
/** Adjust min/pref size for columns(or rows) that has components that spans multiple columns (or rows).
* @param specs The specs for the columns or rows. Last index will be used if <code>count</code> is greater than this array's length.
* @param defPush The default grow weight if the specs does not have anyone that will grow. Comes from "push" in the CC.
* @param fss
* @param groupsLists
*/
private void adjustMinPrefForSpanningComps(DimConstraint[] specs, Float[] defPush, FlowSizeSpec fss, ArrayList<LinkedDimGroup>[] groupsLists)
{
for (int r = groupsLists.length - 1; r >= 0; r--) { // Since 3.7.3 Iterate from end to start. Will solve some multiple spanning components hard to solve problems.
ArrayList<LinkedDimGroup> groups = groupsLists[r];
for (LinkedDimGroup group : groups) {
if (group.span == 1)
continue;
int[] sizes = group.getMinPrefMax();
for (int s = LayoutUtil.MIN; s <= LayoutUtil.PREF; s++) {
int cSize = sizes[s];
if (cSize == LayoutUtil.NOT_SET)
continue;
int rowSize = 0;
int sIx = (r << 1) + 1;
int len = Math.min((group.span << 1), fss.sizes.length - sIx) - 1;
for (int j = sIx; j < sIx + len; j++) {
int sz = fss.sizes[j][s];
if (sz != LayoutUtil.NOT_SET)
rowSize += sz;
}
if (rowSize < cSize && len > 0) {
for (int eagerness = 0, newRowSize = 0; eagerness < 4 && newRowSize < cSize; eagerness++)
newRowSize = fss.expandSizes(specs, defPush, cSize, sIx, len, s, eagerness);
}
}
}
}
}
/** For one dimension divide the component wraps into logical groups. One group for component wraps that share a common something,
* line the property to layout by base line.
* @param isRows If rows, and not columns, are to be divided.
* @return One <code>ArrayList<LinkedDimGroup></code> for every row/column.
*/
private ArrayList<LinkedDimGroup>[] divideIntoLinkedGroups(boolean isRows)
{
boolean fromEnd = !(isRows ? lc.isTopToBottom() : LayoutUtil.isLeftToRight(lc, container));
TreeSet<Integer> primIndexes = isRows ? rowIndexes : colIndexes;
TreeSet<Integer> secIndexes = isRows ? colIndexes : rowIndexes;
DimConstraint[] primDCs = (isRows ? rowConstr : colConstr).getConstaints();
@SuppressWarnings("unchecked")
ArrayList<LinkedDimGroup>[] groupLists = new ArrayList[primIndexes.size()];
int gIx = 0;
for (int i : primIndexes) {
DimConstraint dc;
if (i >= -MAX_GRID && i <= MAX_GRID) { // If not dock cell
dc = primDCs[i >= primDCs.length ? primDCs.length - 1 : i];
} else {
dc = DOCK_DIM_CONSTRAINT;
}
ArrayList<LinkedDimGroup> groupList = new ArrayList<LinkedDimGroup>(2);
groupLists[gIx++] = groupList;
for (Integer ix : secIndexes) {
Cell cell = isRows ? getCell(i, ix) : getCell(ix, i);
if (cell == null || cell.compWraps.size() == 0)
continue;
int span = (isRows ? cell.spany : cell.spanx);
if (span > 1)
span = convertSpanToSparseGrid(i, span, primIndexes);
boolean isPar = (cell.flowx == isRows);
if ((isPar == false && cell.compWraps.size() > 1) || span > 1) {
int linkType = isPar ? LinkedDimGroup.TYPE_PARALLEL : LinkedDimGroup.TYPE_SERIAL;
LinkedDimGroup lg = new LinkedDimGroup("p," + ix, span, linkType, !isRows, fromEnd);
lg.setCompWraps(cell.compWraps);
groupList.add(lg);
} else {
for (int cwIx = 0; cwIx < cell.compWraps.size(); cwIx++) {
CompWrap cw = cell.compWraps.get(cwIx);
boolean rowBaselineAlign = (isRows && lc.isTopToBottom() && dc.getAlignOrDefault(!isRows) == UnitValue.BASELINE_IDENTITY); // Disable baseline for bottomToTop since I can not verify it working.
boolean isBaseline = isRows && cw.isBaselineAlign(rowBaselineAlign);
String linkCtx = isBaseline ? "baseline" : null;
// Find a group with same link context and put it in that group.
boolean foundList = false;
for (int glIx = 0, lastGl = groupList.size() - 1; glIx <= lastGl; glIx++) {
LinkedDimGroup group = groupList.get(glIx);
if (group.linkCtx == linkCtx || linkCtx != null && linkCtx.equals(group.linkCtx)) {
group.addCompWrap(cw);
foundList = true;
break;
}
}
// If none found and at last add a new group.
if (foundList == false) {
int linkType = isBaseline ? LinkedDimGroup.TYPE_BASELINE : LinkedDimGroup.TYPE_PARALLEL;
LinkedDimGroup lg = new LinkedDimGroup(linkCtx, 1, linkType, !isRows, fromEnd);
lg.addCompWrap(cw);
groupList.add(lg);
}
}
}
}
}
return groupLists;
}
/** Spanning is specified in the uncompressed grid number. They can for instance be more than 60000 for the outer
* edge dock grid cells. When the grid is compressed and indexed after only the cells that area occupied the span
* is erratic. This method use the row/col indexes and corrects the span to be correct for the compressed grid.
* @param span The span un the uncompressed grid. <code>LayoutUtil.INF</code> will be interpreted to span the rest
* of the column/row excluding the surrounding docking components.
* @param indexes The indexes in the correct dimension.
* @return The converted span.
*/
private static int convertSpanToSparseGrid(int curIx, int span, TreeSet<Integer> indexes)
{
int lastIx = curIx + span;
int retSpan = 1;
for (Integer ix : indexes) {
if (ix <= curIx)
continue; // We have not arrived to the correct index yet
if (ix >= lastIx)
break;
retSpan++;
}
return retSpan;
}
private boolean isCellFree(int r, int c, ArrayList<int[]> occupiedRects)
{
if (getCell(r, c) != null)
return false;
for (int[] rect : occupiedRects) {
if (rect[0] <= c && rect[1] <= r && rect[0] + rect[2] > c && rect[1] + rect[3] > r)
return false;
}
return true;
}
private Cell getCell(int r, int c)
{
return grid.get(Integer.valueOf((r << 16) + c));
}
private void setCell(int r, int c, Cell cell)
{
if (c < 0 || r < 0)
throw new IllegalArgumentException("Cell position cannot be negative. row: " + r + ", col: " + c);
if (c > MAX_GRID || r > MAX_GRID)
throw new IllegalArgumentException("Cell position out of bounds. Out of cells. row: " + r + ", col: " + c);
rowIndexes.add(r);
colIndexes.add(c);
grid.put((r << 16) + c, cell);
}
/** Adds a docking cell. That cell is outside the normal cell indexes.
* @param dockInsets The current dock insets. Will be updated!
* @param side top == 0, left == 1, bottom = 2, right = 3.
* @param cw The compwrap to put in a cell and add.
*/
private void addDockingCell(int[] dockInsets, int side, CompWrap cw)
{
int r, c, spanx = 1, spany = 1;
switch (side) {
case 0:
case 2:
r = side == 0 ? dockInsets[0]++ : dockInsets[2]--;
c = dockInsets[1];
spanx = dockInsets[3] - dockInsets[1] + 1; // The +1 is for cell 0.
colIndexes.add(dockInsets[3]); // Make sure there is a receiving cell
break;
case 1:
case 3:
c = side == 1 ? dockInsets[1]++ : dockInsets[3]--;
r = dockInsets[0];
spany = dockInsets[2] - dockInsets[0] + 1; // The +1 is for cell 0.
rowIndexes.add(dockInsets[2]); // Make sure there is a receiving cell
break;
default:
throw new IllegalArgumentException("Internal error 123.");
}
rowIndexes.add(r);
colIndexes.add(c);
grid.put((r << 16) + c, new Cell(cw, spanx, spany, spanx > 1));
}
/** A simple representation of a cell in the grid. Contains a number of component wraps, if they span more than one cell.
*/
private static class Cell
{
private final int spanx, spany;
private final boolean flowx;
private final ArrayList<CompWrap> compWraps = new ArrayList<CompWrap>(1);
private boolean hasTagged = false; // If one or more components have styles and need to be checked by the component sorter
private Cell(CompWrap cw)
{
this(cw, 1, 1, true);
}
private Cell(int spanx, int spany, boolean flowx)
{
this(null, spanx, spany, flowx);
}
private Cell(CompWrap cw, int spanx, int spany, boolean flowx)
{
if (cw != null)
compWraps.add(cw);
this.spanx = spanx;
this.spany = spany;
this.flowx = flowx;
}
}
/** A number of component wraps that share a layout "something" <b>in one dimension</b>
*/
private static class LinkedDimGroup
{
private static final int TYPE_SERIAL = 0;
private static final int TYPE_PARALLEL = 1;
private static final int TYPE_BASELINE = 2;
private final String linkCtx;
private final int span;
private final int linkType;
private final boolean isHor, fromEnd;
private ArrayList<CompWrap> _compWraps = new ArrayList<CompWrap>(4);
private int[] sizes = null;
private int lStart = 0, lSize = 0; // Currently mostly for debug painting
private LinkedDimGroup(String linkCtx, int span, int linkType, boolean isHor, boolean fromEnd)
{
this.linkCtx = linkCtx;
this.span = span;
this.linkType = linkType;
this.isHor = isHor;
this.fromEnd = fromEnd;
}
private void addCompWrap(CompWrap cw)
{
_compWraps.add(cw);
sizes = null;
}
private void setCompWraps(ArrayList<CompWrap> cws)
{
if (_compWraps != cws) {
_compWraps = cws;
sizes = null;
}
}
private void layout(DimConstraint dc, int start, int size, int spanCount)
{
lStart = start;
lSize = size;
if (_compWraps.size() == 0)
return;
ContainerWrapper parent = _compWraps.get(0).comp.getParent();
if (linkType == TYPE_PARALLEL) {
layoutParallel(parent, _compWraps, dc, start, size, isHor, fromEnd);
} else if (linkType == TYPE_BASELINE) {
layoutBaseline(parent, _compWraps, dc, start, size, LayoutUtil.PREF, spanCount);
} else {
layoutSerial(parent, _compWraps, dc, start, size, isHor, spanCount, fromEnd);
}
}
/** Returns the min/pref/max sizes for this cell. Returned array <b>must not be altered</b>
* @return A shared min/pref/max array of sizes. Always of length 3 and never <code>null</code>. Will always be of type STATIC and PIXEL.
*/
private int[] getMinPrefMax()
{
if (sizes == null && _compWraps.size() > 0) {
sizes = new int[3];
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.PREF; sType++) {
if (linkType == TYPE_PARALLEL) {
sizes[sType] = getTotalSizeParallel(_compWraps, sType, isHor);
} else if (linkType == TYPE_BASELINE) {
int[] aboveBelow = getBaselineAboveBelow(_compWraps, sType, false);
sizes[sType] = aboveBelow[0] + aboveBelow[1];
} else {
sizes[sType] = getTotalSizeSerial(_compWraps, sType, isHor);
}
}
sizes[LayoutUtil.MAX] = LayoutUtil.INF;
}
return sizes;
}
}
/** Wraps a {@link java.awt.Component} together with its constraint. Caches a lot of information about the component so
* for instance not the preferred size has to be calculated more than once.
*/
private final static class CompWrap
{
private final ComponentWrapper comp;
private final CC cc;
private final UnitValue[] pos;
private int[][] gaps; // [top,left(actually before),bottom,right(actually after)][min,pref,max]
private final int[] horSizes = new int[3];
private final int[] verSizes = new int[3];
private int x = LayoutUtil.NOT_SET, y = LayoutUtil.NOT_SET, w = LayoutUtil.NOT_SET, h = LayoutUtil.NOT_SET;
private int forcedPushGaps = 0; // 1 == before, 2 = after. Bitwise.
private CompWrap(ComponentWrapper c, CC cc, int eHideMode, UnitValue[] pos, BoundSize[] callbackSz)
{
this.comp = c;
this.cc = cc;
this.pos = pos;
if (eHideMode <= 0) {
BoundSize hBS = (callbackSz != null && callbackSz[0] != null) ? callbackSz[0] : cc.getHorizontal().getSize();
BoundSize vBS = (callbackSz != null && callbackSz[1] != null) ? callbackSz[1] : cc.getVertical().getSize();
int wHint = -1, hHint = -1; // Added for v3.7
if (comp.getWidth() > 0 && comp.getHeight() > 0) {
hHint = comp.getHeight();
wHint = comp.getWidth();
}
for (int i = LayoutUtil.MIN; i <= LayoutUtil.MAX; i++) {
horSizes[i] = getSize(hBS, i, true, hHint);
verSizes[i] = getSize(vBS, i, false, wHint > 0 ? wHint : horSizes[i]);
}
correctMinMax(horSizes);
correctMinMax(verSizes);
}
if (eHideMode > 1) {
gaps = new int[4][];
for (int i = 0; i < gaps.length; i++)
gaps[i] = new int[3];
}
}
private int getSize(BoundSize uvs, int sizeType, boolean isHor, int sizeHint)
{
if (uvs == null || uvs.getSize(sizeType) == null) {
switch(sizeType) {
case LayoutUtil.MIN:
return isHor ? comp.getMinimumWidth(sizeHint) : comp.getMinimumHeight(sizeHint);
case LayoutUtil.PREF:
return isHor ? comp.getPreferredWidth(sizeHint) : comp.getPreferredHeight(sizeHint);
default:
return isHor ? comp.getMaximumWidth(sizeHint) : comp.getMaximumHeight(sizeHint);
}
}
ContainerWrapper par = comp.getParent();
return uvs.getSize(sizeType).getPixels(isHor ? par.getWidth() : par.getHeight(), par, comp);
}
private void calcGaps(ComponentWrapper before, CC befCC, ComponentWrapper after, CC aftCC, String tag, boolean flowX, boolean isLTR)
{
ContainerWrapper par = comp.getParent();
int parW = par.getWidth();
int parH = par.getHeight();
BoundSize befGap = before != null ? (flowX ? befCC.getHorizontal() : befCC.getVertical()).getGapAfter() : null;
BoundSize aftGap = after != null ? (flowX ? aftCC.getHorizontal() : aftCC.getVertical()).getGapBefore() : null;
mergeGapSizes(cc.getVertical().getComponentGaps(par, comp, befGap, (flowX ? null : before), tag, parH, 0, isLTR), false, true);
mergeGapSizes(cc.getHorizontal().getComponentGaps(par, comp, befGap, (flowX ? before : null), tag, parW, 1, isLTR), true, true);
mergeGapSizes(cc.getVertical().getComponentGaps(par, comp, aftGap, (flowX ? null : after), tag, parH, 2, isLTR), false, false);
mergeGapSizes(cc.getHorizontal().getComponentGaps(par, comp, aftGap, (flowX ? after : null), tag, parW, 3, isLTR), true, false);
}
private void setDimBounds(int start, int size, boolean isHor)
{
if (isHor) {
x = start;
w = size;
} else {
y = start;
h = size;
}
}
private boolean isPushGap(boolean isHor, boolean isBefore)
{
if (isHor && ((isBefore ? 1 : 2) & forcedPushGaps) != 0)
return true; // Forced
DimConstraint dc = cc.getDimConstraint(isHor);
BoundSize s = isBefore ? dc.getGapBefore() : dc.getGapAfter();
return s != null && s.getGapPush();
}
/**
* @return If the preferred size have changed because of the new bounds.
*/
private boolean transferBounds(boolean checkPrefChange)
{
comp.setBounds(x, y, w, h);
if (checkPrefChange && w != horSizes[LayoutUtil.PREF]) {
BoundSize vSz = cc.getVertical().getSize();
if (vSz.getPreferred() == null) {
if (comp.getPreferredHeight(-1) != verSizes[LayoutUtil.PREF])
return true;
}
}
return false;
}
private void setSizes(int[] sizes, boolean isHor)
{
if (sizes == null)
return;
int[] s = isHor ? horSizes : verSizes;
s[LayoutUtil.MIN] = sizes[LayoutUtil.MIN];
s[LayoutUtil.PREF] = sizes[LayoutUtil.PREF];
s[LayoutUtil.MAX] = sizes[LayoutUtil.MAX];
}
private void setGaps(int[] minPrefMax, int ix)
{
if (gaps == null)
gaps = new int[][] {null, null, null, null};
gaps[ix] = minPrefMax;
}
private void mergeGapSizes(int[] sizes, boolean isHor, boolean isTL)
{
if (gaps == null)
gaps = new int[][] {null, null, null, null};
if (sizes == null)
return;
int gapIX = getGapIx(isHor, isTL);
int[] oldGaps = gaps[gapIX];
if (oldGaps == null) {
oldGaps = new int[] {0, 0, LayoutUtil.INF};
gaps[gapIX] = oldGaps;
}
oldGaps[LayoutUtil.MIN] = Math.max(sizes[LayoutUtil.MIN], oldGaps[LayoutUtil.MIN]);
oldGaps[LayoutUtil.PREF] = Math.max(sizes[LayoutUtil.PREF], oldGaps[LayoutUtil.PREF]);
oldGaps[LayoutUtil.MAX] = Math.min(sizes[LayoutUtil.MAX], oldGaps[LayoutUtil.MAX]);
}
private int getGapIx(boolean isHor, boolean isTL)
{
return isHor ? (isTL ? 1 : 3) : (isTL ? 0 : 2);
}
private int getSizeInclGaps(int sizeType, boolean isHor)
{
return filter(sizeType, getGapBefore(sizeType, isHor) + getSize(sizeType, isHor) + getGapAfter(sizeType, isHor));
}
private int getSize(int sizeType, boolean isHor)
{
return filter(sizeType, isHor ? horSizes[sizeType] : verSizes[sizeType]);
}
private int getGapBefore(int sizeType, boolean isHor)
{
int[] gaps = getGaps(isHor, true);
return gaps != null ? filter(sizeType, gaps[sizeType]) : 0;
}
private int getGapAfter(int sizeType, boolean isHor)
{
int[] gaps = getGaps(isHor, false);
return gaps != null ? filter(sizeType, gaps[sizeType]) : 0;
}
private int[] getGaps(boolean isHor, boolean isTL)
{
return gaps[getGapIx(isHor, isTL)];
}
private int filter(int sizeType, int size)
{
if (size == LayoutUtil.NOT_SET)
return sizeType != LayoutUtil.MAX ? 0 : LayoutUtil.INF;
return constrainSize(size);
}
private boolean isBaselineAlign(boolean defValue)
{
Float g = cc.getVertical().getGrow();
if (g != null && g.intValue() != 0)
return false;
UnitValue al = cc.getVertical().getAlign();
return (al != null ? al == UnitValue.BASELINE_IDENTITY : defValue) && comp.hasBaseline();
}
private int getBaseline(int sizeType)
{
return comp.getBaseline(getSize(sizeType, true), getSize(sizeType, false));
}
}
//***************************************************************************************
//* Helper Methods
//***************************************************************************************
private static void layoutBaseline(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, int sizeType, int spanCount)
{
int[] aboveBelow = getBaselineAboveBelow(compWraps, sizeType, true);
int blRowSize = aboveBelow[0] + aboveBelow[1];
CC cc = compWraps.get(0).cc;
// Align for the whole baseline component array
UnitValue align = cc.getVertical().getAlign();
if (spanCount == 1 && align == null)
align = dc.getAlignOrDefault(false);
if (align == UnitValue.BASELINE_IDENTITY)
align = UnitValue.CENTER;
int offset = start + aboveBelow[0] + (align != null ? Math.max(0, align.getPixels(size - blRowSize, parent, null)) : 0);
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
cw.y += offset;
if (cw.y + cw.h > start + size)
cw.h = start + size - cw.y;
}
}
private static void layoutSerial(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, boolean isHor, int spanCount, boolean fromEnd)
{
FlowSizeSpec fss = mergeSizesGapsAndResConstrs(
getComponentResizeConstraints(compWraps, isHor),
getComponentGapPush(compWraps, isHor),
getComponentSizes(compWraps, isHor),
getGaps(compWraps, isHor));
Float[] pushW = dc.isFill() ? GROW_100 : null;
int[] sizes = LayoutUtil.calculateSerial(fss.sizes, fss.resConstsInclGaps, pushW, LayoutUtil.PREF, size);
setCompWrapBounds(parent, sizes, compWraps, dc.getAlignOrDefault(isHor), start, size, isHor, fromEnd);
}
private static void setCompWrapBounds(ContainerWrapper parent, int[] allSizes, ArrayList<CompWrap> compWraps, UnitValue rowAlign, int start, int size, boolean isHor, boolean fromEnd)
{
int totSize = LayoutUtil.sum(allSizes);
CC cc = compWraps.get(0).cc;
UnitValue align = correctAlign(cc, rowAlign, isHor, fromEnd);
int cSt = start;
int slack = size - totSize;
if (slack > 0 && align != null) {
int al = Math.min(slack, Math.max(0, align.getPixels(slack, parent, null)));
cSt += (fromEnd ? -al : al);
}
for (int i = 0, bIx = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
if (fromEnd ) {
cSt -= allSizes[bIx++];
cw.setDimBounds(cSt - allSizes[bIx], allSizes[bIx], isHor);
cSt -= allSizes[bIx++];
} else {
cSt += allSizes[bIx++];
cw.setDimBounds(cSt, allSizes[bIx], isHor);
cSt += allSizes[bIx++];
}
}
}
private static void layoutParallel(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, boolean isHor, boolean fromEnd)
{
int[][] sizes = new int[compWraps.size()][]; // [compIx][gapBef,compSize,gapAft]
for (int i = 0; i < sizes.length; i++) {
CompWrap cw = compWraps.get(i);
DimConstraint cDc = cw.cc.getDimConstraint(isHor);
ResizeConstraint[] resConstr = new ResizeConstraint[] {
cw.isPushGap(isHor, true) ? GAP_RC_CONST_PUSH : GAP_RC_CONST,
cDc.resize,
cw.isPushGap(isHor, false) ? GAP_RC_CONST_PUSH : GAP_RC_CONST,
};
int[][] sz = new int[][] {
cw.getGaps(isHor, true), (isHor ? cw.horSizes : cw.verSizes), cw.getGaps(isHor, false)
};
Float[] pushW = dc.isFill() ? GROW_100 : null;
sizes[i] = LayoutUtil.calculateSerial(sz, resConstr, pushW, LayoutUtil.PREF, size);
}
UnitValue rowAlign = dc.getAlignOrDefault(isHor);
setCompWrapBounds(parent, sizes, compWraps, rowAlign, start, size, isHor, fromEnd);
}
private static void setCompWrapBounds(ContainerWrapper parent, int[][] sizes, ArrayList<CompWrap> compWraps, UnitValue rowAlign, int start, int size, boolean isHor, boolean fromEnd)
{
for (int i = 0; i < sizes.length; i++) {
CompWrap cw = compWraps.get(i);
UnitValue align = correctAlign(cw.cc, rowAlign, isHor, fromEnd);
int[] cSizes = sizes[i];
int gapBef = cSizes[0];
int cSize = cSizes[1]; // No Math.min(size, cSizes[1]) here!
int gapAft = cSizes[2];
int cSt = fromEnd ? start - gapBef : start + gapBef;
int slack = size - cSize - gapBef - gapAft;
if (slack > 0 && align != null) {
int al = Math.min(slack, Math.max(0, align.getPixels(slack, parent, null)));
cSt += (fromEnd ? -al : al);
}
cw.setDimBounds(fromEnd ? cSt - cSize : cSt, cSize, isHor);
}
}
private static UnitValue correctAlign(CC cc, UnitValue rowAlign, boolean isHor, boolean fromEnd)
{
UnitValue align = (isHor ? cc.getHorizontal() : cc.getVertical()).getAlign();
if (align == null)
align = rowAlign;
if (align == UnitValue.BASELINE_IDENTITY)
align = UnitValue.CENTER;
if (fromEnd) {
if (align == UnitValue.LEFT)
align = UnitValue.RIGHT;
else if (align == UnitValue.RIGHT)
align = UnitValue.LEFT;
}
return align;
}
private static int[] getBaselineAboveBelow(ArrayList<CompWrap> compWraps, int sType, boolean centerBaseline)
{
int maxAbove = Short.MIN_VALUE;
int maxBelow = Short.MIN_VALUE;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
int height = cw.getSize(sType, false);
if (height >= LayoutUtil.INF)
return new int[] {LayoutUtil.INF / 2, LayoutUtil.INF / 2};
int baseline = cw.getBaseline(sType);
int above = baseline + cw.getGapBefore(sType, false);
maxAbove = Math.max(above, maxAbove);
maxBelow = Math.max(height - baseline + cw.getGapAfter(sType, false), maxBelow);
if (centerBaseline)
cw.setDimBounds(-baseline, height, false);
}
return new int[] {maxAbove, maxBelow};
}
private static int getTotalSizeParallel(ArrayList<CompWrap> compWraps, int sType, boolean isHor)
{
int size = sType == LayoutUtil.MAX ? LayoutUtil.INF : 0;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
int cwSize = cw.getSizeInclGaps(sType, isHor);
if (cwSize >= LayoutUtil.INF)
return LayoutUtil.INF;
if (sType == LayoutUtil.MAX ? cwSize < size : cwSize > size)
size = cwSize;
}
return constrainSize(size);
}
private static int getTotalSizeSerial(ArrayList<CompWrap> compWraps, int sType, boolean isHor)
{
int totSize = 0;
for (int i = 0, iSz = compWraps.size(), lastGapAfter = 0; i < iSz; i++) {
CompWrap wrap = compWraps.get(i);
int gapBef = wrap.getGapBefore(sType, isHor);
if (gapBef > lastGapAfter)
totSize += gapBef - lastGapAfter;
totSize += wrap.getSize(sType, isHor);
totSize += (lastGapAfter = wrap.getGapAfter(sType, isHor));
if (totSize >= LayoutUtil.INF)
return LayoutUtil.INF;
}
return constrainSize(totSize);
}
private static int getTotalGroupsSizeParallel(ArrayList<LinkedDimGroup> groups, int sType, boolean countSpanning)
{
int size = sType == LayoutUtil.MAX ? LayoutUtil.INF : 0;
for (int i = 0, iSz = groups.size(); i < iSz; i++) {
LinkedDimGroup group = groups.get(i);
if (countSpanning || group.span == 1) {
int grpSize = group.getMinPrefMax()[sType];
if (grpSize >= LayoutUtil.INF)
return LayoutUtil.INF;
if (sType == LayoutUtil.MAX ? grpSize < size : grpSize > size)
size = grpSize;
}
}
return constrainSize(size);
}
/**
* @param compWraps
* @param isHor
* @return Might contain LayoutUtil.NOT_SET
*/
private static int[][] getComponentSizes(ArrayList<CompWrap> compWraps, boolean isHor)
{
int[][] compSizes = new int[compWraps.size()][];
for (int i = 0; i < compSizes.length; i++) {
CompWrap cw = compWraps.get(i);
compSizes[i] = isHor ? cw.horSizes : cw.verSizes;
}
return compSizes;
}
/** Merges sizes and gaps together with Resize Constraints. For gaps {@link #GAP_RC_CONST} is used.
* @param resConstr One resize constriant for every row/component. Can be lesser in length and the last element should be used for missing elements.
* @param gapPush If the corresponding gap should be considered pushing and thus want to take free space if left over. Should be one more than resConstrs!
* @param minPrefMaxSizes The sizes (min/pref/max) for every row/component.
* @param gapSizes The gaps before and after each row/component packed in one double sized array.
* @return A holder for the merged values.
*/
private static FlowSizeSpec mergeSizesGapsAndResConstrs(ResizeConstraint[] resConstr, boolean[] gapPush, int[][] minPrefMaxSizes, int[][] gapSizes)
{
int[][] sizes = new int[(minPrefMaxSizes.length << 1) + 1][]; // Make room for gaps around.
ResizeConstraint[] resConstsInclGaps = new ResizeConstraint[sizes.length];
sizes[0] = gapSizes[0];
for (int i = 0, crIx = 1; i < minPrefMaxSizes.length; i++, crIx += 2) {
// Component bounds and constraints
resConstsInclGaps[crIx] = resConstr[i];
sizes[crIx] = minPrefMaxSizes[i];
sizes[crIx + 1] = gapSizes[i + 1];
if (sizes[crIx - 1] != null)
resConstsInclGaps[crIx - 1] = gapPush[i < gapPush.length ? i : gapPush.length - 1] ? GAP_RC_CONST_PUSH : GAP_RC_CONST;
if (i == (minPrefMaxSizes.length - 1) && sizes[crIx + 1] != null)
resConstsInclGaps[crIx + 1] = gapPush[(i + 1) < gapPush.length ? (i + 1) : gapPush.length - 1] ? GAP_RC_CONST_PUSH : GAP_RC_CONST;
}
// Check for null and set it to 0, 0, 0.
for (int i = 0; i < sizes.length; i++) {
if (sizes[i] == null)
sizes[i] = new int[3];
}
return new FlowSizeSpec(sizes, resConstsInclGaps);
}
private static int[] mergeSizes(int[] oldValues, int[] newValues)
{
if (oldValues == null)
return newValues;
if (newValues == null)
return oldValues;
int[] ret = new int[oldValues.length];
for (int i = 0; i < ret.length; i++)
ret[i] = mergeSizes(oldValues[i], newValues[i], true);
return ret;
}
private static int mergeSizes(int oldValue, int newValue, boolean toMax)
{
if (oldValue == LayoutUtil.NOT_SET || oldValue == newValue)
return newValue;
if (newValue == LayoutUtil.NOT_SET)
return oldValue;
return toMax != oldValue > newValue ? newValue : oldValue;
}
private static int constrainSize(int s)
{
return s > 0 ? (s < LayoutUtil.INF ? s : LayoutUtil.INF) : 0;
}
private static void correctMinMax(int s[])
{
if (s[LayoutUtil.MIN] > s[LayoutUtil.MAX])
s[LayoutUtil.MIN] = s[LayoutUtil.MAX]; // Since MAX is almost always explicitly set use that
if (s[LayoutUtil.PREF] < s[LayoutUtil.MIN])
s[LayoutUtil.PREF] = s[LayoutUtil.MIN];
if (s[LayoutUtil.PREF] > s[LayoutUtil.MAX])
s[LayoutUtil.PREF] = s[LayoutUtil.MAX];
}
private static final class FlowSizeSpec
{
private final int[][] sizes; // [row/col index][min, pref, max]
private final ResizeConstraint[] resConstsInclGaps; // [row/col index]
private FlowSizeSpec(int[][] sizes, ResizeConstraint[] resConstsInclGaps)
{
this.sizes = sizes;
this.resConstsInclGaps = resConstsInclGaps;
}
/**
* @param specs The specs for the columns or rows. Last index will be used of <code>fromIx + len</code> is greater than this array's length.
* @param targetSize The size to try to meet.
* @param defGrow The default grow weight if the specs does not have anyone that will grow. Comes from "push" in the CC.
* @param fromIx
* @param len
* @param sizeType
* @param eagerness How eager the algorithm should be to try to expand the sizes.
* <ul>
* <li>0 - Grow only rows/columns which have the <code>sizeType</code> set to be the containing components AND which has a grow weight > 0.
* <li>1 - Grow only rows/columns which have the <code>sizeType</code> set to be the containing components AND which has a grow weight > 0 OR unspecified.
* <li>2 - Grow all rows/columns that have a grow weight > 0.
* <li>3 - Grow all rows/columns that have a grow weight > 0 OR unspecified.
* </ul>
* @return The new size.
*/
private int expandSizes(DimConstraint[] specs, Float[] defGrow, int targetSize, int fromIx, int len, int sizeType, int eagerness)
{
ResizeConstraint[] resConstr = new ResizeConstraint[len];
int[][] sizesToExpand = new int[len][];
for (int i = 0; i < len; i++) {
int[] minPrefMax = sizes[i + fromIx];
sizesToExpand[i] = new int[] {minPrefMax[sizeType], minPrefMax[LayoutUtil.PREF], minPrefMax[LayoutUtil.MAX]};
if (eagerness <= 1 && i % 2 == 0) { // (i % 2 == 0) means only odd indexes, which is only rows/col indexes and not gaps.
int cIx = (i + fromIx - 1) >> 1;
DimConstraint spec = (DimConstraint) LayoutUtil.getIndexSafe(specs, cIx);
BoundSize sz = spec.getSize();
if ( (sizeType == LayoutUtil.MIN && sz.getMin() != null && sz.getMin().getUnit() != UnitValue.MIN_SIZE) ||
(sizeType == LayoutUtil.PREF && sz.getPreferred() != null && sz.getPreferred().getUnit() != UnitValue.PREF_SIZE)) {
continue;
}
}
resConstr[i] = (ResizeConstraint) LayoutUtil.getIndexSafe(resConstsInclGaps, i + fromIx);
}
Float[] growW = (eagerness == 1 || eagerness == 3) ? extractSubArray(specs, defGrow, fromIx, len): null;
int[] newSizes = LayoutUtil.calculateSerial(sizesToExpand, resConstr, growW, LayoutUtil.PREF, targetSize);
int newSize = 0;
for (int i = 0; i < len; i++) {
int s = newSizes[i];
sizes[i + fromIx][sizeType] = s;
newSize += s;
}
return newSize;
}
}
private static Float[] extractSubArray(DimConstraint[] specs, Float[] arr, int ix, int len)
{
if (arr == null || arr.length < ix + len) {
Float[] growLastArr = new Float[len];
// Handle a group where some rows (first one/few and/or last one/few) are docks.
for (int i = ix + len - 1; i >= 0; i -= 2) {
int specIx = (i >> 1);
if (specs[specIx] != DOCK_DIM_CONSTRAINT) {
growLastArr[i - ix] = ResizeConstraint.WEIGHT_100;
return growLastArr;
}
}
return growLastArr;
}
Float[] newArr = new Float[len];
for (int i = 0; i < len; i++)
newArr[i] = arr[ix + i];
return newArr;
}
private static synchronized void putSizesAndIndexes(Object parComp, int[] sizes, int[] ixArr, boolean isRows)
{
}
static synchronized int[][] getSizesAndIndexes(Object parComp, boolean isRows)
{
return null;
}
private static synchronized void saveGrid(ComponentWrapper parComp, LinkedHashMap<Integer, Cell> grid)
{
}
static synchronized HashMap<Object, int[]> getGridPositions(Object parComp)
{
return null;
}
}
| private int[] getAbsoluteDimBounds(CompWrap cw, int refSize, boolean isHor)
{
if (cw.cc.isExternal()) {
if (isHor) {
return new int[] {cw.comp.getX(), cw.comp.getWidth()};
} else {
return new int[] {cw.comp.getY(), cw.comp.getHeight()};
}
}
int[] plafPad = lc.isVisualPadding() ? cw.comp.getVisualPadding() : null;
UnitValue[] pad = cw.cc.getPadding();
// If no changes do not create a lot of objects
if (cw.pos == null && plafPad == null && pad == null)
return null;
// Set start
int st = isHor ? cw.x : cw.y;
int sz = isHor ? cw.w : cw.h;
// If absolute, use those coordinates instead.
if (cw.pos != null) {
UnitValue stUV = cw.pos != null ? cw.pos[isHor ? 0 : 1] : null;
UnitValue endUV = cw.pos != null ? cw.pos[isHor ? 2 : 3] : null;
int minSz = cw.getSize(LayoutUtil.MIN, isHor);
int maxSz = cw.getSize(LayoutUtil.MAX, isHor);
sz = Math.min(Math.max(cw.getSize(LayoutUtil.PREF, isHor), minSz), maxSz);
if (stUV != null) {
st = stUV.getPixels(stUV.getUnit() == UnitValue.ALIGN ? sz : refSize, container, cw.comp);
if (endUV != null) // if (endUV == null && cw.cc.isBoundsIsGrid() == true)
sz = Math.min(Math.max((isHor ? (cw.x + cw.w) : (cw.y + cw.h)) - st, minSz), maxSz);
}
if (endUV != null) {
if (stUV != null) { // if (stUV != null || cw.cc.isBoundsIsGrid()) {
sz = Math.min(Math.max(endUV.getPixels(refSize, container, cw.comp) - st, minSz), maxSz);
} else {
st = endUV.getPixels(refSize, container, cw.comp) - sz;
}
}
}
// If constraint has padding -> correct the start/size
if (pad != null) {
UnitValue uv = pad[isHor ? 1 : 0];
int p = uv != null ? uv.getPixels(refSize, container, cw.comp) : 0;
st += p;
uv = pad[isHor ? 3 : 2];
sz += -p + (uv != null ? uv.getPixels(refSize, container, cw.comp) : 0);
}
// If the plaf converter has padding -> correct the start/size
if (plafPad != null) {
int p = plafPad[isHor ? 1 : 0];
st += p;
sz += -p + (plafPad[isHor ? 3 : 2]);
}
return new int[] {st, sz};
}
private void layoutInOneDim(int refSize, UnitValue align, boolean isRows, Float[] defaultPushWeights)
{
boolean fromEnd = !(isRows ? lc.isTopToBottom() : LayoutUtil.isLeftToRight(lc, container));
DimConstraint[] primDCs = (isRows ? rowConstr : colConstr).getConstaints();
FlowSizeSpec fss = isRows ? rowFlowSpecs : colFlowSpecs;
ArrayList<LinkedDimGroup>[] rowCols = isRows ? rowGroupLists : colGroupLists;
int[] rowColSizes = LayoutUtil.calculateSerial(fss.sizes, fss.resConstsInclGaps, defaultPushWeights, LayoutUtil.PREF, refSize);
if (LayoutUtil.isDesignTime(container)) {
TreeSet<Integer> indexes = isRows ? rowIndexes : colIndexes;
int[] ixArr = new int[indexes.size()];
int ix = 0;
for (Integer i : indexes)
ixArr[ix++] = i;
putSizesAndIndexes(container.getComponent(), rowColSizes, ixArr, isRows);
}
int curPos = align != null ? align.getPixels(refSize - LayoutUtil.sum(rowColSizes), container, null) : 0;
if (fromEnd)
curPos = refSize - curPos;
for (int i = 0 ; i < rowCols.length; i++) {
ArrayList<LinkedDimGroup> linkedGroups = rowCols[i];
int scIx = i - (isRows ? dockOffY : dockOffX);
int bIx = i << 1;
int bIx2 = bIx + 1;
curPos += (fromEnd ? -rowColSizes[bIx] : rowColSizes[bIx]);
DimConstraint primDC = scIx >= 0 ? primDCs[scIx >= primDCs.length ? primDCs.length - 1 : scIx] : DOCK_DIM_CONSTRAINT;
int rowSize = rowColSizes[bIx2];
for (LinkedDimGroup group : linkedGroups) {
int groupSize = rowSize;
if (group.span > 1)
groupSize = LayoutUtil.sum(rowColSizes, bIx2, Math.min((group.span << 1) - 1, rowColSizes.length - bIx2 - 1));
group.layout(primDC, curPos, groupSize, group.span);
}
curPos += (fromEnd ? -rowSize : rowSize);
}
}
private static void addToSizeGroup(HashMap<String, int[]> sizeGroups, String sizeGroup, int[] size)
{
int[] sgSize = sizeGroups.get(sizeGroup);
if (sgSize == null) {
sizeGroups.put(sizeGroup, new int[] {size[LayoutUtil.MIN], size[LayoutUtil.PREF], size[LayoutUtil.MAX]});
} else {
sgSize[LayoutUtil.MIN] = Math.max(size[LayoutUtil.MIN], sgSize[LayoutUtil.MIN]);
sgSize[LayoutUtil.PREF] = Math.max(size[LayoutUtil.PREF], sgSize[LayoutUtil.PREF]);
sgSize[LayoutUtil.MAX] = Math.min(size[LayoutUtil.MAX], sgSize[LayoutUtil.MAX]);
}
}
private static HashMap<String, Integer> addToEndGroup(HashMap<String, Integer> endGroups, String endGroup, int end)
{
if (endGroup != null) {
if (endGroups == null)
endGroups = new HashMap<String, Integer>(2);
Integer oldEnd = endGroups.get(endGroup);
if (oldEnd == null || end > oldEnd)
endGroups.put(endGroup, end);
}
return endGroups;
}
/** Calculates Min, Preferred and Max size for the columns OR rows.
* @param isHor If it is the horizontal dimension to calculate.
* @return The sizes in a {@link net.miginfocom.layout.Grid.FlowSizeSpec}.
*/
private FlowSizeSpec calcRowsOrColsSizes(boolean isHor)
{
ArrayList<LinkedDimGroup>[] groupsLists = isHor ? colGroupLists : rowGroupLists;
Float[] defPush = isHor ? pushXs : pushYs;
int refSize = isHor ? container.getWidth() : container.getHeight();
BoundSize cSz = isHor ? lc.getWidth() : lc.getHeight();
if (cSz.isUnset() == false)
refSize = cSz.constrain(refSize, getParentSize(container, isHor), container);
DimConstraint[] primDCs = (isHor? colConstr : rowConstr).getConstaints();
TreeSet<Integer> primIndexes = isHor ? colIndexes : rowIndexes;
int[][] rowColBoundSizes = new int[primIndexes.size()][];
HashMap<String, int[]> sizeGroupMap = new HashMap<String, int[]>(2);
DimConstraint[] allDCs = new DimConstraint[primIndexes.size()];
Iterator<Integer> primIt = primIndexes.iterator();
for (int r = 0; r < rowColBoundSizes.length; r++) {
int cellIx = primIt.next();
int[] rowColSizes = new int[3];
if (cellIx >= -MAX_GRID && cellIx <= MAX_GRID) { // If not dock cell
allDCs[r] = primDCs[cellIx >= primDCs.length ? primDCs.length - 1 : cellIx];
} else {
allDCs[r] = DOCK_DIM_CONSTRAINT;
}
ArrayList<LinkedDimGroup> groups = groupsLists[r];
int[] groupSizes = new int[] {
getTotalGroupsSizeParallel(groups, LayoutUtil.MIN, false),
getTotalGroupsSizeParallel(groups, LayoutUtil.PREF, false),
LayoutUtil.INF};
correctMinMax(groupSizes);
BoundSize dimSize = allDCs[r].getSize();
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.MAX; sType++) {
int rowColSize = groupSizes[sType];
UnitValue uv = dimSize.getSize(sType);
if (uv != null) {
// If the size of the column is a link to some other size, use that instead
int unit = uv.getUnit();
if (unit == UnitValue.PREF_SIZE) {
rowColSize = groupSizes[LayoutUtil.PREF];
} else if (unit == UnitValue.MIN_SIZE) {
rowColSize = groupSizes[LayoutUtil.MIN];
} else if (unit == UnitValue.MAX_SIZE) {
rowColSize = groupSizes[LayoutUtil.MAX];
} else {
rowColSize = uv.getPixels(refSize, container, null);
}
} else if (cellIx >= -MAX_GRID && cellIx <= MAX_GRID && rowColSize == 0) {
rowColSize = LayoutUtil.isDesignTime(container) ? LayoutUtil.getDesignTimeEmptySize() : 0; // Empty rows with no size set gets XX pixels if design time
}
rowColSizes[sType] = rowColSize;
}
correctMinMax(rowColSizes);
addToSizeGroup(sizeGroupMap, allDCs[r].getSizeGroup(), rowColSizes);
rowColBoundSizes[r] = rowColSizes;
}
// Set/equalize the size groups to same the values.
if (sizeGroupMap.size() > 0) {
for (int r = 0; r < rowColBoundSizes.length; r++) {
if (allDCs[r].getSizeGroup() != null)
rowColBoundSizes[r] = sizeGroupMap.get(allDCs[r].getSizeGroup());
}
}
// Add the gaps
ResizeConstraint[] resConstrs = getRowResizeConstraints(allDCs);
boolean[] fillInPushGaps = new boolean[allDCs.length + 1];
int[][] gapSizes = getRowGaps(allDCs, refSize, isHor, fillInPushGaps);
FlowSizeSpec fss = mergeSizesGapsAndResConstrs(resConstrs, fillInPushGaps, rowColBoundSizes, gapSizes);
// Spanning components are not handled yet. Check and adjust the multi-row min/pref they enforce.
adjustMinPrefForSpanningComps(allDCs, defPush, fss, groupsLists);
return fss;
}
private static int getParentSize(ComponentWrapper cw, boolean isHor)
{
ComponentWrapper p = cw.getParent();
return p != null ? (isHor ? cw.getWidth() : cw.getHeight()) : 0;
}
private int[] getMinPrefMaxSumSize(boolean isHor)
{
int[][] sizes = isHor ? colFlowSpecs.sizes : rowFlowSpecs.sizes;
int[] retSizes = new int[3];
BoundSize sz = isHor ? lc.getWidth() : lc.getHeight();
for (int i = 0; i < sizes.length; i++) {
if (sizes[i] != null) {
int[] size = sizes[i];
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.MAX; sType++) {
if (sz.getSize(sType) != null) {
if (i == 0)
retSizes[sType] = sz.getSize(sType).getPixels(getParentSize(container, isHor), container, null);
} else {
int s = size[sType];
if (s != LayoutUtil.NOT_SET) {
if (sType == LayoutUtil.PREF) {
int bnd = size[LayoutUtil.MAX];
if (bnd != LayoutUtil.NOT_SET && bnd < s)
s = bnd;
bnd = size[LayoutUtil.MIN];
if (bnd > s) // Includes s == LayoutUtil.NOT_SET since < 0.
s = bnd;
}
retSizes[sType] += s; // MAX compensated below.
}
// So that MAX is always correct.
if (size[LayoutUtil.MAX] == LayoutUtil.NOT_SET || retSizes[LayoutUtil.MAX] > LayoutUtil.INF)
retSizes[LayoutUtil.MAX] = LayoutUtil.INF;
}
}
}
}
correctMinMax(retSizes);
return retSizes;
}
private static ResizeConstraint[] getRowResizeConstraints(DimConstraint[] specs)
{
ResizeConstraint[] resConsts = new ResizeConstraint[specs.length];
for (int i = 0; i < resConsts.length; i++)
resConsts[i] = specs[i].resize;
return resConsts;
}
private static ResizeConstraint[] getComponentResizeConstraints(ArrayList<CompWrap> compWraps, boolean isHor)
{
ResizeConstraint[] resConsts = new ResizeConstraint[compWraps.size()];
for (int i = 0; i < resConsts.length; i++) {
CC fc = compWraps.get(i).cc;
resConsts[i] = fc.getDimConstraint(isHor).resize;
// Always grow docking components in the correct dimension.
int dock = fc.getDockSide();
if (isHor ? (dock == 0 || dock == 2) : (dock == 1 || dock == 3)) {
ResizeConstraint dc = resConsts[i];
resConsts[i] = new ResizeConstraint(dc.shrinkPrio, dc.shrink, dc.growPrio, ResizeConstraint.WEIGHT_100);
}
}
return resConsts;
}
private static boolean[] getComponentGapPush(ArrayList<CompWrap> compWraps, boolean isHor)
{
// Make one element bigger and or the after gap with the next before gap.
boolean[] barr = new boolean[compWraps.size() + 1];
for (int i = 0; i < barr.length; i++) {
boolean push = i > 0 && compWraps.get(i - 1).isPushGap(isHor, false);
if (push == false && i < (barr.length - 1))
push = compWraps.get(i).isPushGap(isHor, true);
barr[i] = push;
}
return barr;
}
/** Returns the row gaps in pixel sizes. One more than there are <code>specs</code> sent in.
* @param specs
* @param refSize
* @param isHor
* @param fillInPushGaps If the gaps are pushing. <b>NOTE!</b> this argument will be filled in and thus changed!
* @return The row gaps in pixel sizes. One more than there are <code>specs</code> sent in.
*/
private int[][] getRowGaps(DimConstraint[] specs, int refSize, boolean isHor, boolean[] fillInPushGaps)
{
BoundSize defGap = isHor ? lc.getGridGapX() : lc.getGridGapY();
if (defGap == null)
defGap = isHor ? PlatformDefaults.getGridGapX() : PlatformDefaults.getGridGapY();
int[] defGapArr = defGap.getPixelSizes(refSize, container, null);
boolean defIns = !hasDocks();
UnitValue firstGap = LayoutUtil.getInsets(lc, isHor ? 1 : 0, defIns);
UnitValue lastGap = LayoutUtil.getInsets(lc, isHor ? 3 : 2, defIns);
int[][] retValues = new int[specs.length + 1][];
for (int i = 0, wgIx = 0; i < retValues.length; i++) {
DimConstraint specBefore = i > 0 ? specs[i - 1] : null;
DimConstraint specAfter = i < specs.length ? specs[i] : null;
// No gap if between docking components.
boolean edgeBefore = (specBefore == DOCK_DIM_CONSTRAINT || specBefore == null);
boolean edgeAfter = (specAfter == DOCK_DIM_CONSTRAINT || specAfter == null);
if (edgeBefore && edgeAfter)
continue;
BoundSize wrapGapSize = (wrapGapMap == null || isHor == lc.isFlowX() ? null : wrapGapMap.get(Integer.valueOf(wgIx++)));
if (wrapGapSize == null) {
int[] gapBefore = specBefore != null ? specBefore.getRowGaps(container, null, refSize, false) : null;
int[] gapAfter = specAfter != null ? specAfter.getRowGaps(container, null, refSize, true) : null;
if (edgeBefore && gapAfter == null && firstGap != null) {
int bef = firstGap.getPixels(refSize, container, null);
retValues[i] = new int[] {bef, bef, bef};
} else if (edgeAfter && gapBefore == null && firstGap != null) {
int aft = lastGap.getPixels(refSize, container, null);
retValues[i] = new int[] {aft, aft, aft};
} else {
retValues[i] = gapAfter != gapBefore ? mergeSizes(gapAfter, gapBefore) : new int[] {defGapArr[0], defGapArr[1], defGapArr[2]};
}
if (specBefore != null && specBefore.isGapAfterPush() || specAfter != null && specAfter.isGapBeforePush())
fillInPushGaps[i] = true;
} else {
if (wrapGapSize.isUnset()) {
retValues[i] = new int[] {defGapArr[0], defGapArr[1], defGapArr[2]};
} else {
retValues[i] = wrapGapSize.getPixelSizes(refSize, container, null);
}
fillInPushGaps[i] = wrapGapSize.getGapPush();
}
}
return retValues;
}
private static int[][] getGaps(ArrayList<CompWrap> compWraps, boolean isHor)
{
int compCount = compWraps.size();
int[][] retValues = new int[compCount + 1][];
retValues[0] = compWraps.get(0).getGaps(isHor, true);
for (int i = 0; i < compCount; i++) {
int[] gap1 = compWraps.get(i).getGaps(isHor, false);
int[] gap2 = i < compCount - 1 ? compWraps.get(i + 1).getGaps(isHor, true) : null;
retValues[i + 1] = mergeSizes(gap1, gap2);
}
return retValues;
}
private boolean hasDocks()
{
return (dockOffX > 0 || dockOffY > 0 || rowIndexes.last() > MAX_GRID || colIndexes.last() > MAX_GRID);
}
/** Adjust min/pref size for columns(or rows) that has components that spans multiple columns (or rows).
* @param specs The specs for the columns or rows. Last index will be used if <code>count</code> is greater than this array's length.
* @param defPush The default grow weight if the specs does not have anyone that will grow. Comes from "push" in the CC.
* @param fss
* @param groupsLists
*/
private void adjustMinPrefForSpanningComps(DimConstraint[] specs, Float[] defPush, FlowSizeSpec fss, ArrayList<LinkedDimGroup>[] groupsLists)
{
for (int r = groupsLists.length - 1; r >= 0; r--) { // Since 3.7.3 Iterate from end to start. Will solve some multiple spanning components hard to solve problems.
ArrayList<LinkedDimGroup> groups = groupsLists[r];
for (LinkedDimGroup group : groups) {
if (group.span == 1)
continue;
int[] sizes = group.getMinPrefMax();
for (int s = LayoutUtil.MIN; s <= LayoutUtil.PREF; s++) {
int cSize = sizes[s];
if (cSize == LayoutUtil.NOT_SET)
continue;
int rowSize = 0;
int sIx = (r << 1) + 1;
int len = Math.min((group.span << 1), fss.sizes.length - sIx) - 1;
for (int j = sIx; j < sIx + len; j++) {
int sz = fss.sizes[j][s];
if (sz != LayoutUtil.NOT_SET)
rowSize += sz;
}
if (rowSize < cSize && len > 0) {
for (int eagerness = 0, newRowSize = 0; eagerness < 4 && newRowSize < cSize; eagerness++)
newRowSize = fss.expandSizes(specs, defPush, cSize, sIx, len, s, eagerness);
}
}
}
}
}
/** For one dimension divide the component wraps into logical groups. One group for component wraps that share a common something,
* line the property to layout by base line.
* @param isRows If rows, and not columns, are to be divided.
* @return One <code>ArrayList<LinkedDimGroup></code> for every row/column.
*/
private ArrayList<LinkedDimGroup>[] divideIntoLinkedGroups(boolean isRows)
{
boolean fromEnd = !(isRows ? lc.isTopToBottom() : LayoutUtil.isLeftToRight(lc, container));
TreeSet<Integer> primIndexes = isRows ? rowIndexes : colIndexes;
TreeSet<Integer> secIndexes = isRows ? colIndexes : rowIndexes;
DimConstraint[] primDCs = (isRows ? rowConstr : colConstr).getConstaints();
@SuppressWarnings("unchecked")
ArrayList<LinkedDimGroup>[] groupLists = new ArrayList[primIndexes.size()];
int gIx = 0;
for (int i : primIndexes) {
DimConstraint dc;
if (i >= -MAX_GRID && i <= MAX_GRID) { // If not dock cell
dc = primDCs[i >= primDCs.length ? primDCs.length - 1 : i];
} else {
dc = DOCK_DIM_CONSTRAINT;
}
ArrayList<LinkedDimGroup> groupList = new ArrayList<LinkedDimGroup>(2);
groupLists[gIx++] = groupList;
for (Integer ix : secIndexes) {
Cell cell = isRows ? getCell(i, ix) : getCell(ix, i);
if (cell == null || cell.compWraps.size() == 0)
continue;
int span = (isRows ? cell.spany : cell.spanx);
if (span > 1)
span = convertSpanToSparseGrid(i, span, primIndexes);
boolean isPar = (cell.flowx == isRows);
if ((isPar == false && cell.compWraps.size() > 1) || span > 1) {
int linkType = isPar ? LinkedDimGroup.TYPE_PARALLEL : LinkedDimGroup.TYPE_SERIAL;
LinkedDimGroup lg = new LinkedDimGroup("p," + ix, span, linkType, !isRows, fromEnd);
lg.setCompWraps(cell.compWraps);
groupList.add(lg);
} else {
for (int cwIx = 0; cwIx < cell.compWraps.size(); cwIx++) {
CompWrap cw = cell.compWraps.get(cwIx);
boolean rowBaselineAlign = (isRows && lc.isTopToBottom() && dc.getAlignOrDefault(!isRows) == UnitValue.BASELINE_IDENTITY); // Disable baseline for bottomToTop since I can not verify it working.
boolean isBaseline = isRows && cw.isBaselineAlign(rowBaselineAlign);
String linkCtx = isBaseline ? "baseline" : null;
// Find a group with same link context and put it in that group.
boolean foundList = false;
for (int glIx = 0, lastGl = groupList.size() - 1; glIx <= lastGl; glIx++) {
LinkedDimGroup group = groupList.get(glIx);
if (group.linkCtx == linkCtx || linkCtx != null && linkCtx.equals(group.linkCtx)) {
group.addCompWrap(cw);
foundList = true;
break;
}
}
// If none found and at last add a new group.
if (foundList == false) {
int linkType = isBaseline ? LinkedDimGroup.TYPE_BASELINE : LinkedDimGroup.TYPE_PARALLEL;
LinkedDimGroup lg = new LinkedDimGroup(linkCtx, 1, linkType, !isRows, fromEnd);
lg.addCompWrap(cw);
groupList.add(lg);
}
}
}
}
}
return groupLists;
}
/** Spanning is specified in the uncompressed grid number. They can for instance be more than 60000 for the outer
* edge dock grid cells. When the grid is compressed and indexed after only the cells that area occupied the span
* is erratic. This method use the row/col indexes and corrects the span to be correct for the compressed grid.
* @param span The span un the uncompressed grid. <code>LayoutUtil.INF</code> will be interpreted to span the rest
* of the column/row excluding the surrounding docking components.
* @param indexes The indexes in the correct dimension.
* @return The converted span.
*/
private static int convertSpanToSparseGrid(int curIx, int span, TreeSet<Integer> indexes)
{
int lastIx = curIx + span;
int retSpan = 1;
for (Integer ix : indexes) {
if (ix <= curIx)
continue; // We have not arrived to the correct index yet
if (ix >= lastIx)
break;
retSpan++;
}
return retSpan;
}
private boolean isCellFree(int r, int c, ArrayList<int[]> occupiedRects)
{
if (getCell(r, c) != null)
return false;
for (int[] rect : occupiedRects) {
if (rect[0] <= c && rect[1] <= r && rect[0] + rect[2] > c && rect[1] + rect[3] > r)
return false;
}
return true;
}
private Cell getCell(int r, int c)
{
return grid.get(Integer.valueOf((r << 16) + c));
}
private void setCell(int r, int c, Cell cell)
{
if (c < 0 || r < 0)
throw new IllegalArgumentException("Cell position cannot be negative. row: " + r + ", col: " + c);
if (c > MAX_GRID || r > MAX_GRID)
throw new IllegalArgumentException("Cell position out of bounds. Out of cells. row: " + r + ", col: " + c);
rowIndexes.add(r);
colIndexes.add(c);
grid.put((r << 16) + c, cell);
}
/** Adds a docking cell. That cell is outside the normal cell indexes.
* @param dockInsets The current dock insets. Will be updated!
* @param side top == 0, left == 1, bottom = 2, right = 3.
* @param cw The compwrap to put in a cell and add.
*/
private void addDockingCell(int[] dockInsets, int side, CompWrap cw)
{
int r, c, spanx = 1, spany = 1;
switch (side) {
case 0:
case 2:
r = side == 0 ? dockInsets[0]++ : dockInsets[2]--;
c = dockInsets[1];
spanx = dockInsets[3] - dockInsets[1] + 1; // The +1 is for cell 0.
colIndexes.add(dockInsets[3]); // Make sure there is a receiving cell
break;
case 1:
case 3:
c = side == 1 ? dockInsets[1]++ : dockInsets[3]--;
r = dockInsets[0];
spany = dockInsets[2] - dockInsets[0] + 1; // The +1 is for cell 0.
rowIndexes.add(dockInsets[2]); // Make sure there is a receiving cell
break;
default:
throw new IllegalArgumentException("Internal error 123.");
}
rowIndexes.add(r);
colIndexes.add(c);
grid.put((r << 16) + c, new Cell(cw, spanx, spany, spanx > 1));
}
/** A simple representation of a cell in the grid. Contains a number of component wraps, if they span more than one cell.
*/
private static class Cell
{
private final int spanx, spany;
private final boolean flowx;
private final ArrayList<CompWrap> compWraps = new ArrayList<CompWrap>(1);
private boolean hasTagged = false; // If one or more components have styles and need to be checked by the component sorter
private Cell(CompWrap cw)
{
this(cw, 1, 1, true);
}
private Cell(int spanx, int spany, boolean flowx)
{
this(null, spanx, spany, flowx);
}
private Cell(CompWrap cw, int spanx, int spany, boolean flowx)
{
if (cw != null)
compWraps.add(cw);
this.spanx = spanx;
this.spany = spany;
this.flowx = flowx;
}
}
/** A number of component wraps that share a layout "something" <b>in one dimension</b>
*/
private static class LinkedDimGroup
{
private static final int TYPE_SERIAL = 0;
private static final int TYPE_PARALLEL = 1;
private static final int TYPE_BASELINE = 2;
private final String linkCtx;
private final int span;
private final int linkType;
private final boolean isHor, fromEnd;
private ArrayList<CompWrap> _compWraps = new ArrayList<CompWrap>(4);
private int[] sizes = null;
private int lStart = 0, lSize = 0; // Currently mostly for debug painting
private LinkedDimGroup(String linkCtx, int span, int linkType, boolean isHor, boolean fromEnd)
{
this.linkCtx = linkCtx;
this.span = span;
this.linkType = linkType;
this.isHor = isHor;
this.fromEnd = fromEnd;
}
private void addCompWrap(CompWrap cw)
{
_compWraps.add(cw);
sizes = null;
}
private void setCompWraps(ArrayList<CompWrap> cws)
{
if (_compWraps != cws) {
_compWraps = cws;
sizes = null;
}
}
private void layout(DimConstraint dc, int start, int size, int spanCount)
{
lStart = start;
lSize = size;
if (_compWraps.size() == 0)
return;
ContainerWrapper parent = _compWraps.get(0).comp.getParent();
if (linkType == TYPE_PARALLEL) {
layoutParallel(parent, _compWraps, dc, start, size, isHor, fromEnd);
} else if (linkType == TYPE_BASELINE) {
layoutBaseline(parent, _compWraps, dc, start, size, LayoutUtil.PREF, spanCount);
} else {
layoutSerial(parent, _compWraps, dc, start, size, isHor, spanCount, fromEnd);
}
}
/** Returns the min/pref/max sizes for this cell. Returned array <b>must not be altered</b>
* @return A shared min/pref/max array of sizes. Always of length 3 and never <code>null</code>. Will always be of type STATIC and PIXEL.
*/
private int[] getMinPrefMax()
{
if (sizes == null && _compWraps.size() > 0) {
sizes = new int[3];
for (int sType = LayoutUtil.MIN; sType <= LayoutUtil.PREF; sType++) {
if (linkType == TYPE_PARALLEL) {
sizes[sType] = getTotalSizeParallel(_compWraps, sType, isHor);
} else if (linkType == TYPE_BASELINE) {
int[] aboveBelow = getBaselineAboveBelow(_compWraps, sType, false);
sizes[sType] = aboveBelow[0] + aboveBelow[1];
} else {
sizes[sType] = getTotalSizeSerial(_compWraps, sType, isHor);
}
}
sizes[LayoutUtil.MAX] = LayoutUtil.INF;
}
return sizes;
}
}
/** Wraps a {@link java.awt.Component} together with its constraint. Caches a lot of information about the component so
* for instance not the preferred size has to be calculated more than once.
*/
private final static class CompWrap
{
private final ComponentWrapper comp;
private final CC cc;
private final UnitValue[] pos;
private int[][] gaps; // [top,left(actually before),bottom,right(actually after)][min,pref,max]
private final int[] horSizes = new int[3];
private final int[] verSizes = new int[3];
private int x = LayoutUtil.NOT_SET, y = LayoutUtil.NOT_SET, w = LayoutUtil.NOT_SET, h = LayoutUtil.NOT_SET;
private int forcedPushGaps = 0; // 1 == before, 2 = after. Bitwise.
private CompWrap(ComponentWrapper c, CC cc, int eHideMode, UnitValue[] pos, BoundSize[] callbackSz)
{
this.comp = c;
this.cc = cc;
this.pos = pos;
if (eHideMode <= 0) {
BoundSize hBS = (callbackSz != null && callbackSz[0] != null) ? callbackSz[0] : cc.getHorizontal().getSize();
BoundSize vBS = (callbackSz != null && callbackSz[1] != null) ? callbackSz[1] : cc.getVertical().getSize();
int wHint = -1, hHint = -1; // Added for v3.7
if (comp.getWidth() > 0 && comp.getHeight() > 0) {
hHint = comp.getHeight();
wHint = comp.getWidth();
}
for (int i = LayoutUtil.MIN; i <= LayoutUtil.MAX; i++) {
horSizes[i] = getSize(hBS, i, true, wHint);
verSizes[i] = getSize(vBS, i, false, hHint > 0 ? hHint : horSizes[i]);
}
correctMinMax(horSizes);
correctMinMax(verSizes);
}
if (eHideMode > 1) {
gaps = new int[4][];
for (int i = 0; i < gaps.length; i++)
gaps[i] = new int[3];
}
}
private int getSize(BoundSize uvs, int sizeType, boolean isHor, int sizeHint)
{
if (uvs == null || uvs.getSize(sizeType) == null) {
switch(sizeType) {
case LayoutUtil.MIN:
return isHor ? comp.getMinimumWidth(sizeHint) : comp.getMinimumHeight(sizeHint);
case LayoutUtil.PREF:
return isHor ? comp.getPreferredWidth(sizeHint) : comp.getPreferredHeight(sizeHint);
default:
return isHor ? comp.getMaximumWidth(sizeHint) : comp.getMaximumHeight(sizeHint);
}
}
ContainerWrapper par = comp.getParent();
return uvs.getSize(sizeType).getPixels(isHor ? par.getWidth() : par.getHeight(), par, comp);
}
private void calcGaps(ComponentWrapper before, CC befCC, ComponentWrapper after, CC aftCC, String tag, boolean flowX, boolean isLTR)
{
ContainerWrapper par = comp.getParent();
int parW = par.getWidth();
int parH = par.getHeight();
BoundSize befGap = before != null ? (flowX ? befCC.getHorizontal() : befCC.getVertical()).getGapAfter() : null;
BoundSize aftGap = after != null ? (flowX ? aftCC.getHorizontal() : aftCC.getVertical()).getGapBefore() : null;
mergeGapSizes(cc.getVertical().getComponentGaps(par, comp, befGap, (flowX ? null : before), tag, parH, 0, isLTR), false, true);
mergeGapSizes(cc.getHorizontal().getComponentGaps(par, comp, befGap, (flowX ? before : null), tag, parW, 1, isLTR), true, true);
mergeGapSizes(cc.getVertical().getComponentGaps(par, comp, aftGap, (flowX ? null : after), tag, parH, 2, isLTR), false, false);
mergeGapSizes(cc.getHorizontal().getComponentGaps(par, comp, aftGap, (flowX ? after : null), tag, parW, 3, isLTR), true, false);
}
private void setDimBounds(int start, int size, boolean isHor)
{
if (isHor) {
x = start;
w = size;
} else {
y = start;
h = size;
}
}
private boolean isPushGap(boolean isHor, boolean isBefore)
{
if (isHor && ((isBefore ? 1 : 2) & forcedPushGaps) != 0)
return true; // Forced
DimConstraint dc = cc.getDimConstraint(isHor);
BoundSize s = isBefore ? dc.getGapBefore() : dc.getGapAfter();
return s != null && s.getGapPush();
}
/**
* @return If the preferred size have changed because of the new bounds.
*/
private boolean transferBounds(boolean checkPrefChange)
{
comp.setBounds(x, y, w, h);
if (checkPrefChange && w != horSizes[LayoutUtil.PREF]) {
BoundSize vSz = cc.getVertical().getSize();
if (vSz.getPreferred() == null) {
if (comp.getPreferredHeight(-1) != verSizes[LayoutUtil.PREF])
return true;
}
}
return false;
}
private void setSizes(int[] sizes, boolean isHor)
{
if (sizes == null)
return;
int[] s = isHor ? horSizes : verSizes;
s[LayoutUtil.MIN] = sizes[LayoutUtil.MIN];
s[LayoutUtil.PREF] = sizes[LayoutUtil.PREF];
s[LayoutUtil.MAX] = sizes[LayoutUtil.MAX];
}
private void setGaps(int[] minPrefMax, int ix)
{
if (gaps == null)
gaps = new int[][] {null, null, null, null};
gaps[ix] = minPrefMax;
}
private void mergeGapSizes(int[] sizes, boolean isHor, boolean isTL)
{
if (gaps == null)
gaps = new int[][] {null, null, null, null};
if (sizes == null)
return;
int gapIX = getGapIx(isHor, isTL);
int[] oldGaps = gaps[gapIX];
if (oldGaps == null) {
oldGaps = new int[] {0, 0, LayoutUtil.INF};
gaps[gapIX] = oldGaps;
}
oldGaps[LayoutUtil.MIN] = Math.max(sizes[LayoutUtil.MIN], oldGaps[LayoutUtil.MIN]);
oldGaps[LayoutUtil.PREF] = Math.max(sizes[LayoutUtil.PREF], oldGaps[LayoutUtil.PREF]);
oldGaps[LayoutUtil.MAX] = Math.min(sizes[LayoutUtil.MAX], oldGaps[LayoutUtil.MAX]);
}
private int getGapIx(boolean isHor, boolean isTL)
{
return isHor ? (isTL ? 1 : 3) : (isTL ? 0 : 2);
}
private int getSizeInclGaps(int sizeType, boolean isHor)
{
return filter(sizeType, getGapBefore(sizeType, isHor) + getSize(sizeType, isHor) + getGapAfter(sizeType, isHor));
}
private int getSize(int sizeType, boolean isHor)
{
return filter(sizeType, isHor ? horSizes[sizeType] : verSizes[sizeType]);
}
private int getGapBefore(int sizeType, boolean isHor)
{
int[] gaps = getGaps(isHor, true);
return gaps != null ? filter(sizeType, gaps[sizeType]) : 0;
}
private int getGapAfter(int sizeType, boolean isHor)
{
int[] gaps = getGaps(isHor, false);
return gaps != null ? filter(sizeType, gaps[sizeType]) : 0;
}
private int[] getGaps(boolean isHor, boolean isTL)
{
return gaps[getGapIx(isHor, isTL)];
}
private int filter(int sizeType, int size)
{
if (size == LayoutUtil.NOT_SET)
return sizeType != LayoutUtil.MAX ? 0 : LayoutUtil.INF;
return constrainSize(size);
}
private boolean isBaselineAlign(boolean defValue)
{
Float g = cc.getVertical().getGrow();
if (g != null && g.intValue() != 0)
return false;
UnitValue al = cc.getVertical().getAlign();
return (al != null ? al == UnitValue.BASELINE_IDENTITY : defValue) && comp.hasBaseline();
}
private int getBaseline(int sizeType)
{
return comp.getBaseline(getSize(sizeType, true), getSize(sizeType, false));
}
}
//***************************************************************************************
//* Helper Methods
//***************************************************************************************
private static void layoutBaseline(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, int sizeType, int spanCount)
{
int[] aboveBelow = getBaselineAboveBelow(compWraps, sizeType, true);
int blRowSize = aboveBelow[0] + aboveBelow[1];
CC cc = compWraps.get(0).cc;
// Align for the whole baseline component array
UnitValue align = cc.getVertical().getAlign();
if (spanCount == 1 && align == null)
align = dc.getAlignOrDefault(false);
if (align == UnitValue.BASELINE_IDENTITY)
align = UnitValue.CENTER;
int offset = start + aboveBelow[0] + (align != null ? Math.max(0, align.getPixels(size - blRowSize, parent, null)) : 0);
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
cw.y += offset;
if (cw.y + cw.h > start + size)
cw.h = start + size - cw.y;
}
}
private static void layoutSerial(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, boolean isHor, int spanCount, boolean fromEnd)
{
FlowSizeSpec fss = mergeSizesGapsAndResConstrs(
getComponentResizeConstraints(compWraps, isHor),
getComponentGapPush(compWraps, isHor),
getComponentSizes(compWraps, isHor),
getGaps(compWraps, isHor));
Float[] pushW = dc.isFill() ? GROW_100 : null;
int[] sizes = LayoutUtil.calculateSerial(fss.sizes, fss.resConstsInclGaps, pushW, LayoutUtil.PREF, size);
setCompWrapBounds(parent, sizes, compWraps, dc.getAlignOrDefault(isHor), start, size, isHor, fromEnd);
}
private static void setCompWrapBounds(ContainerWrapper parent, int[] allSizes, ArrayList<CompWrap> compWraps, UnitValue rowAlign, int start, int size, boolean isHor, boolean fromEnd)
{
int totSize = LayoutUtil.sum(allSizes);
CC cc = compWraps.get(0).cc;
UnitValue align = correctAlign(cc, rowAlign, isHor, fromEnd);
int cSt = start;
int slack = size - totSize;
if (slack > 0 && align != null) {
int al = Math.min(slack, Math.max(0, align.getPixels(slack, parent, null)));
cSt += (fromEnd ? -al : al);
}
for (int i = 0, bIx = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
if (fromEnd ) {
cSt -= allSizes[bIx++];
cw.setDimBounds(cSt - allSizes[bIx], allSizes[bIx], isHor);
cSt -= allSizes[bIx++];
} else {
cSt += allSizes[bIx++];
cw.setDimBounds(cSt, allSizes[bIx], isHor);
cSt += allSizes[bIx++];
}
}
}
private static void layoutParallel(ContainerWrapper parent, ArrayList<CompWrap> compWraps, DimConstraint dc, int start, int size, boolean isHor, boolean fromEnd)
{
int[][] sizes = new int[compWraps.size()][]; // [compIx][gapBef,compSize,gapAft]
for (int i = 0; i < sizes.length; i++) {
CompWrap cw = compWraps.get(i);
DimConstraint cDc = cw.cc.getDimConstraint(isHor);
ResizeConstraint[] resConstr = new ResizeConstraint[] {
cw.isPushGap(isHor, true) ? GAP_RC_CONST_PUSH : GAP_RC_CONST,
cDc.resize,
cw.isPushGap(isHor, false) ? GAP_RC_CONST_PUSH : GAP_RC_CONST,
};
int[][] sz = new int[][] {
cw.getGaps(isHor, true), (isHor ? cw.horSizes : cw.verSizes), cw.getGaps(isHor, false)
};
Float[] pushW = dc.isFill() ? GROW_100 : null;
sizes[i] = LayoutUtil.calculateSerial(sz, resConstr, pushW, LayoutUtil.PREF, size);
}
UnitValue rowAlign = dc.getAlignOrDefault(isHor);
setCompWrapBounds(parent, sizes, compWraps, rowAlign, start, size, isHor, fromEnd);
}
private static void setCompWrapBounds(ContainerWrapper parent, int[][] sizes, ArrayList<CompWrap> compWraps, UnitValue rowAlign, int start, int size, boolean isHor, boolean fromEnd)
{
for (int i = 0; i < sizes.length; i++) {
CompWrap cw = compWraps.get(i);
UnitValue align = correctAlign(cw.cc, rowAlign, isHor, fromEnd);
int[] cSizes = sizes[i];
int gapBef = cSizes[0];
int cSize = cSizes[1]; // No Math.min(size, cSizes[1]) here!
int gapAft = cSizes[2];
int cSt = fromEnd ? start - gapBef : start + gapBef;
int slack = size - cSize - gapBef - gapAft;
if (slack > 0 && align != null) {
int al = Math.min(slack, Math.max(0, align.getPixels(slack, parent, null)));
cSt += (fromEnd ? -al : al);
}
cw.setDimBounds(fromEnd ? cSt - cSize : cSt, cSize, isHor);
}
}
private static UnitValue correctAlign(CC cc, UnitValue rowAlign, boolean isHor, boolean fromEnd)
{
UnitValue align = (isHor ? cc.getHorizontal() : cc.getVertical()).getAlign();
if (align == null)
align = rowAlign;
if (align == UnitValue.BASELINE_IDENTITY)
align = UnitValue.CENTER;
if (fromEnd) {
if (align == UnitValue.LEFT)
align = UnitValue.RIGHT;
else if (align == UnitValue.RIGHT)
align = UnitValue.LEFT;
}
return align;
}
private static int[] getBaselineAboveBelow(ArrayList<CompWrap> compWraps, int sType, boolean centerBaseline)
{
int maxAbove = Short.MIN_VALUE;
int maxBelow = Short.MIN_VALUE;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
int height = cw.getSize(sType, false);
if (height >= LayoutUtil.INF)
return new int[] {LayoutUtil.INF / 2, LayoutUtil.INF / 2};
int baseline = cw.getBaseline(sType);
int above = baseline + cw.getGapBefore(sType, false);
maxAbove = Math.max(above, maxAbove);
maxBelow = Math.max(height - baseline + cw.getGapAfter(sType, false), maxBelow);
if (centerBaseline)
cw.setDimBounds(-baseline, height, false);
}
return new int[] {maxAbove, maxBelow};
}
private static int getTotalSizeParallel(ArrayList<CompWrap> compWraps, int sType, boolean isHor)
{
int size = sType == LayoutUtil.MAX ? LayoutUtil.INF : 0;
for (int i = 0, iSz = compWraps.size(); i < iSz; i++) {
CompWrap cw = compWraps.get(i);
int cwSize = cw.getSizeInclGaps(sType, isHor);
if (cwSize >= LayoutUtil.INF)
return LayoutUtil.INF;
if (sType == LayoutUtil.MAX ? cwSize < size : cwSize > size)
size = cwSize;
}
return constrainSize(size);
}
private static int getTotalSizeSerial(ArrayList<CompWrap> compWraps, int sType, boolean isHor)
{
int totSize = 0;
for (int i = 0, iSz = compWraps.size(), lastGapAfter = 0; i < iSz; i++) {
CompWrap wrap = compWraps.get(i);
int gapBef = wrap.getGapBefore(sType, isHor);
if (gapBef > lastGapAfter)
totSize += gapBef - lastGapAfter;
totSize += wrap.getSize(sType, isHor);
totSize += (lastGapAfter = wrap.getGapAfter(sType, isHor));
if (totSize >= LayoutUtil.INF)
return LayoutUtil.INF;
}
return constrainSize(totSize);
}
private static int getTotalGroupsSizeParallel(ArrayList<LinkedDimGroup> groups, int sType, boolean countSpanning)
{
int size = sType == LayoutUtil.MAX ? LayoutUtil.INF : 0;
for (int i = 0, iSz = groups.size(); i < iSz; i++) {
LinkedDimGroup group = groups.get(i);
if (countSpanning || group.span == 1) {
int grpSize = group.getMinPrefMax()[sType];
if (grpSize >= LayoutUtil.INF)
return LayoutUtil.INF;
if (sType == LayoutUtil.MAX ? grpSize < size : grpSize > size)
size = grpSize;
}
}
return constrainSize(size);
}
/**
* @param compWraps
* @param isHor
* @return Might contain LayoutUtil.NOT_SET
*/
private static int[][] getComponentSizes(ArrayList<CompWrap> compWraps, boolean isHor)
{
int[][] compSizes = new int[compWraps.size()][];
for (int i = 0; i < compSizes.length; i++) {
CompWrap cw = compWraps.get(i);
compSizes[i] = isHor ? cw.horSizes : cw.verSizes;
}
return compSizes;
}
/** Merges sizes and gaps together with Resize Constraints. For gaps {@link #GAP_RC_CONST} is used.
* @param resConstr One resize constriant for every row/component. Can be lesser in length and the last element should be used for missing elements.
* @param gapPush If the corresponding gap should be considered pushing and thus want to take free space if left over. Should be one more than resConstrs!
* @param minPrefMaxSizes The sizes (min/pref/max) for every row/component.
* @param gapSizes The gaps before and after each row/component packed in one double sized array.
* @return A holder for the merged values.
*/
private static FlowSizeSpec mergeSizesGapsAndResConstrs(ResizeConstraint[] resConstr, boolean[] gapPush, int[][] minPrefMaxSizes, int[][] gapSizes)
{
int[][] sizes = new int[(minPrefMaxSizes.length << 1) + 1][]; // Make room for gaps around.
ResizeConstraint[] resConstsInclGaps = new ResizeConstraint[sizes.length];
sizes[0] = gapSizes[0];
for (int i = 0, crIx = 1; i < minPrefMaxSizes.length; i++, crIx += 2) {
// Component bounds and constraints
resConstsInclGaps[crIx] = resConstr[i];
sizes[crIx] = minPrefMaxSizes[i];
sizes[crIx + 1] = gapSizes[i + 1];
if (sizes[crIx - 1] != null)
resConstsInclGaps[crIx - 1] = gapPush[i < gapPush.length ? i : gapPush.length - 1] ? GAP_RC_CONST_PUSH : GAP_RC_CONST;
if (i == (minPrefMaxSizes.length - 1) && sizes[crIx + 1] != null)
resConstsInclGaps[crIx + 1] = gapPush[(i + 1) < gapPush.length ? (i + 1) : gapPush.length - 1] ? GAP_RC_CONST_PUSH : GAP_RC_CONST;
}
// Check for null and set it to 0, 0, 0.
for (int i = 0; i < sizes.length; i++) {
if (sizes[i] == null)
sizes[i] = new int[3];
}
return new FlowSizeSpec(sizes, resConstsInclGaps);
}
private static int[] mergeSizes(int[] oldValues, int[] newValues)
{
if (oldValues == null)
return newValues;
if (newValues == null)
return oldValues;
int[] ret = new int[oldValues.length];
for (int i = 0; i < ret.length; i++)
ret[i] = mergeSizes(oldValues[i], newValues[i], true);
return ret;
}
private static int mergeSizes(int oldValue, int newValue, boolean toMax)
{
if (oldValue == LayoutUtil.NOT_SET || oldValue == newValue)
return newValue;
if (newValue == LayoutUtil.NOT_SET)
return oldValue;
return toMax != oldValue > newValue ? newValue : oldValue;
}
private static int constrainSize(int s)
{
return s > 0 ? (s < LayoutUtil.INF ? s : LayoutUtil.INF) : 0;
}
private static void correctMinMax(int s[])
{
if (s[LayoutUtil.MIN] > s[LayoutUtil.MAX])
s[LayoutUtil.MIN] = s[LayoutUtil.MAX]; // Since MAX is almost always explicitly set use that
if (s[LayoutUtil.PREF] < s[LayoutUtil.MIN])
s[LayoutUtil.PREF] = s[LayoutUtil.MIN];
if (s[LayoutUtil.PREF] > s[LayoutUtil.MAX])
s[LayoutUtil.PREF] = s[LayoutUtil.MAX];
}
private static final class FlowSizeSpec
{
private final int[][] sizes; // [row/col index][min, pref, max]
private final ResizeConstraint[] resConstsInclGaps; // [row/col index]
private FlowSizeSpec(int[][] sizes, ResizeConstraint[] resConstsInclGaps)
{
this.sizes = sizes;
this.resConstsInclGaps = resConstsInclGaps;
}
/**
* @param specs The specs for the columns or rows. Last index will be used of <code>fromIx + len</code> is greater than this array's length.
* @param targetSize The size to try to meet.
* @param defGrow The default grow weight if the specs does not have anyone that will grow. Comes from "push" in the CC.
* @param fromIx
* @param len
* @param sizeType
* @param eagerness How eager the algorithm should be to try to expand the sizes.
* <ul>
* <li>0 - Grow only rows/columns which have the <code>sizeType</code> set to be the containing components AND which has a grow weight > 0.
* <li>1 - Grow only rows/columns which have the <code>sizeType</code> set to be the containing components AND which has a grow weight > 0 OR unspecified.
* <li>2 - Grow all rows/columns that have a grow weight > 0.
* <li>3 - Grow all rows/columns that have a grow weight > 0 OR unspecified.
* </ul>
* @return The new size.
*/
private int expandSizes(DimConstraint[] specs, Float[] defGrow, int targetSize, int fromIx, int len, int sizeType, int eagerness)
{
ResizeConstraint[] resConstr = new ResizeConstraint[len];
int[][] sizesToExpand = new int[len][];
for (int i = 0; i < len; i++) {
int[] minPrefMax = sizes[i + fromIx];
sizesToExpand[i] = new int[] {minPrefMax[sizeType], minPrefMax[LayoutUtil.PREF], minPrefMax[LayoutUtil.MAX]};
if (eagerness <= 1 && i % 2 == 0) { // (i % 2 == 0) means only odd indexes, which is only rows/col indexes and not gaps.
int cIx = (i + fromIx - 1) >> 1;
DimConstraint spec = (DimConstraint) LayoutUtil.getIndexSafe(specs, cIx);
BoundSize sz = spec.getSize();
if ( (sizeType == LayoutUtil.MIN && sz.getMin() != null && sz.getMin().getUnit() != UnitValue.MIN_SIZE) ||
(sizeType == LayoutUtil.PREF && sz.getPreferred() != null && sz.getPreferred().getUnit() != UnitValue.PREF_SIZE)) {
continue;
}
}
resConstr[i] = (ResizeConstraint) LayoutUtil.getIndexSafe(resConstsInclGaps, i + fromIx);
}
Float[] growW = (eagerness == 1 || eagerness == 3) ? extractSubArray(specs, defGrow, fromIx, len): null;
int[] newSizes = LayoutUtil.calculateSerial(sizesToExpand, resConstr, growW, LayoutUtil.PREF, targetSize);
int newSize = 0;
for (int i = 0; i < len; i++) {
int s = newSizes[i];
sizes[i + fromIx][sizeType] = s;
newSize += s;
}
return newSize;
}
}
private static Float[] extractSubArray(DimConstraint[] specs, Float[] arr, int ix, int len)
{
if (arr == null || arr.length < ix + len) {
Float[] growLastArr = new Float[len];
// Handle a group where some rows (first one/few and/or last one/few) are docks.
for (int i = ix + len - 1; i >= 0; i -= 2) {
int specIx = (i >> 1);
if (specs[specIx] != DOCK_DIM_CONSTRAINT) {
growLastArr[i - ix] = ResizeConstraint.WEIGHT_100;
return growLastArr;
}
}
return growLastArr;
}
Float[] newArr = new Float[len];
for (int i = 0; i < len; i++)
newArr[i] = arr[ix + i];
return newArr;
}
private static synchronized void putSizesAndIndexes(Object parComp, int[] sizes, int[] ixArr, boolean isRows)
{
}
static synchronized int[][] getSizesAndIndexes(Object parComp, boolean isRows)
{
return null;
}
private static synchronized void saveGrid(ComponentWrapper parComp, LinkedHashMap<Integer, Cell> grid)
{
}
static synchronized HashMap<Object, int[]> getGridPositions(Object parComp)
{
return null;
}
}
|
diff --git a/src/core/java/org/wyona/yanel/core/ResourceConfiguration.java b/src/core/java/org/wyona/yanel/core/ResourceConfiguration.java
index cf38bcd8b..6a4350457 100644
--- a/src/core/java/org/wyona/yanel/core/ResourceConfiguration.java
+++ b/src/core/java/org/wyona/yanel/core/ResourceConfiguration.java
@@ -1,195 +1,194 @@
/*
* Copyright 2007 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.core;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationUtil;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.log4j.Category;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Abstraction of a resource configuration.
*/
public class ResourceConfiguration {
private Category log = Category.getInstance(ResourceConfiguration.class);
protected Map properties;
protected String name;
protected String namespace;
private String encoding = null;
Configuration config;
/**
*
*/
public ResourceConfiguration(InputStream in) throws Exception {
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(true);
config = builder.build(in);
Configuration rtiConfig = config.getChild("rti");
name = rtiConfig.getAttribute("name");
namespace = rtiConfig.getAttribute("namespace");
log.debug("Universal Name: " + getUniversalName());
Configuration encodingConfig = config.getChild("encoding", false);
if (encodingConfig != null) encoding = encodingConfig.getValue();
// TODO: Read properties and set this.properties
}
/**
* Create a resource from scratch
* @param name Resource Type Name
* @param namespace Resource Type Namespace
*/
public ResourceConfiguration(String name, String namespace, Map properties) {
this.name = name;
this.namespace = namespace;
if (properties == null) {
this.properties = new HashMap();
} else {
this.properties = properties;
}
}
/**
* Get universal name of resource type
*/
public String getUniversalName() {
return "<{" + namespace + "}" + name + "/>";
}
/**
* Get resource type name
*/
public String getName() {
return name;
}
/**
* Get resource type namespace
*/
public String getNamespace() {
return namespace;
}
/**
* Get encoding respectively charset
*/
public String getEncoding() {
return encoding;
}
/**
* @param key
* @return value for this key or null if no value exists for this key.
*/
public String getProperty(String key) throws Exception {
//return (String)properties.get(key);
if (config != null) {
Configuration[] props = config.getChildren("property");
for (int i = 0; i < props.length; i++) {
if (props[i].getAttribute("name") != null && props[i].getAttribute("name").equals(key)) return props[i].getAttribute("value");
}
}
return null;
}
/**
* Check if property exists
*/
public boolean containsKey(String key) throws Exception {
//return properties.containsKey(key);
if (config != null) {
Configuration[] props = config.getChildren("property");
for (int i = 0; i < props.length; i++) {
if (props[i].getAttribute("name") != null && props[i].getAttribute("name").equals(key)) return true;
}
}
return false;
}
/**
* Get yanel:custom-config
*/
public org.w3c.dom.Document getCustomConfiguration() {
Configuration customConfig = config.getChild("custom-config");
if (customConfig != null) {
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation();
org.w3c.dom.DocumentType doctype = null;
doc = impl.createDocument(customConfig.getNamespace(), customConfig.getName(), doctype);
Configuration[] children = customConfig.getChildren();
if (children.length > 0) {
Element rootElement = doc.getDocumentElement();
for (int i = 0; i < children.length; i++) {
- log.error("DEBUG: child: " + children[i].getName());
rootElement.appendChild(createElement(children[i], doc));
}
}
} catch(Exception e) {
log.error(e.getMessage(), e);
}
return doc;
// TODO: ConfigurationUtil doesn't seem to work properly
/*
org.w3c.dom.Element element = ConfigurationUtil.toElement(customConfig);
log.error("DEBUG: element: " + element.getLocalName());
org.w3c.dom.Document doc = element.getOwnerDocument();
org.w3c.dom.Element rootElement = doc.getDocumentElement();
rootElement.appendChild(element);
return doc;
*/
} else {
log.warn("No custom configuration: " + getUniversalName());
}
return null;
}
/**
*
*/
private Element createElement(Configuration config, Document doc) throws Exception {
Element element = doc.createElementNS(config.getNamespace(), config.getName());
String[] attrs = config.getAttributeNames();
for (int i = 0; i < attrs.length; i++) {
element.setAttributeNS(config.getNamespace(), attrs[i], config.getAttribute(attrs[i]));
}
Configuration[] children = config.getChildren();
if (children.length > 0) {
for (int i = 0; i < children.length; i++) {
element.appendChild(createElement(children[i], doc));
}
}
return element;
}
}
| true | true | public org.w3c.dom.Document getCustomConfiguration() {
Configuration customConfig = config.getChild("custom-config");
if (customConfig != null) {
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation();
org.w3c.dom.DocumentType doctype = null;
doc = impl.createDocument(customConfig.getNamespace(), customConfig.getName(), doctype);
Configuration[] children = customConfig.getChildren();
if (children.length > 0) {
Element rootElement = doc.getDocumentElement();
for (int i = 0; i < children.length; i++) {
log.error("DEBUG: child: " + children[i].getName());
rootElement.appendChild(createElement(children[i], doc));
}
}
} catch(Exception e) {
log.error(e.getMessage(), e);
}
return doc;
// TODO: ConfigurationUtil doesn't seem to work properly
/*
org.w3c.dom.Element element = ConfigurationUtil.toElement(customConfig);
log.error("DEBUG: element: " + element.getLocalName());
org.w3c.dom.Document doc = element.getOwnerDocument();
org.w3c.dom.Element rootElement = doc.getDocumentElement();
rootElement.appendChild(element);
return doc;
*/
} else {
log.warn("No custom configuration: " + getUniversalName());
}
return null;
}
| public org.w3c.dom.Document getCustomConfiguration() {
Configuration customConfig = config.getChild("custom-config");
if (customConfig != null) {
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation();
org.w3c.dom.DocumentType doctype = null;
doc = impl.createDocument(customConfig.getNamespace(), customConfig.getName(), doctype);
Configuration[] children = customConfig.getChildren();
if (children.length > 0) {
Element rootElement = doc.getDocumentElement();
for (int i = 0; i < children.length; i++) {
rootElement.appendChild(createElement(children[i], doc));
}
}
} catch(Exception e) {
log.error(e.getMessage(), e);
}
return doc;
// TODO: ConfigurationUtil doesn't seem to work properly
/*
org.w3c.dom.Element element = ConfigurationUtil.toElement(customConfig);
log.error("DEBUG: element: " + element.getLocalName());
org.w3c.dom.Document doc = element.getOwnerDocument();
org.w3c.dom.Element rootElement = doc.getDocumentElement();
rootElement.appendChild(element);
return doc;
*/
} else {
log.warn("No custom configuration: " + getUniversalName());
}
return null;
}
|
diff --git a/src/vooga/rts/gui/menus/gamesubmenus/InfoSubMenu.java b/src/vooga/rts/gui/menus/gamesubmenus/InfoSubMenu.java
index dc0c2700..562d8d2c 100755
--- a/src/vooga/rts/gui/menus/gamesubmenus/InfoSubMenu.java
+++ b/src/vooga/rts/gui/menus/gamesubmenus/InfoSubMenu.java
@@ -1,64 +1,64 @@
package vooga.rts.gui.menus.gamesubmenus;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.util.Observable;
import vooga.rts.gamedesign.sprite.gamesprites.interactive.InteractiveEntity;
import vooga.rts.gui.Button;
import vooga.rts.gui.Window;
import util.Location;
public class InfoSubMenu extends SubMenu {
public InfoSubMenu (String image, Dimension size, Location pos) {
super(image, size, pos);
}
@Override
public void paint (Graphics2D pen) {
super.paint(pen);
pen.setFont(new Font("Arial", Font.PLAIN, 24));
try {
if (mySelectedEntity != null) {
if (mySelectedEntity.getInfo() != null) {
pen.setColor(Color.WHITE);
pen.drawString(mySelectedEntity.getInfo().getName(), (int) 280,
(int) Window.D_Y - 90);
pen.setFont(new Font("Arial", Font.PLAIN, 20));
pen.setColor(Color.GRAY);
pen.drawString(mySelectedEntity.getInfo().getDescription(), (int) 280,
(int) Window.D_Y - 65);
- if (mySelectedEntity.getInfo().getButtonImage() != null) {
+ if (mySelectedEntity.getInfo().getButtonImage() != null) {
pen.drawImage(mySelectedEntity.getInfo().getButtonImage(), (int) 220,
- (int) Window.D_Y - 90, null);
+ (int) Window.D_Y - 90, 50, 50, null);
}
}
}
}
catch (NullPointerException np) {
// catch weird error
}
}
@Override
public void processClick (int x, int y) {
// TODO Auto-generated method stub
}
@Override
public void processHover (int x, int y) {
// TODO Auto-generated method stub
}
@Override
public void update (Observable o, Object arg) {
// TODO Auto-generated method stub
}
}
| false | true | public void paint (Graphics2D pen) {
super.paint(pen);
pen.setFont(new Font("Arial", Font.PLAIN, 24));
try {
if (mySelectedEntity != null) {
if (mySelectedEntity.getInfo() != null) {
pen.setColor(Color.WHITE);
pen.drawString(mySelectedEntity.getInfo().getName(), (int) 280,
(int) Window.D_Y - 90);
pen.setFont(new Font("Arial", Font.PLAIN, 20));
pen.setColor(Color.GRAY);
pen.drawString(mySelectedEntity.getInfo().getDescription(), (int) 280,
(int) Window.D_Y - 65);
if (mySelectedEntity.getInfo().getButtonImage() != null) {
pen.drawImage(mySelectedEntity.getInfo().getButtonImage(), (int) 220,
(int) Window.D_Y - 90, null);
}
}
}
}
catch (NullPointerException np) {
// catch weird error
}
}
| public void paint (Graphics2D pen) {
super.paint(pen);
pen.setFont(new Font("Arial", Font.PLAIN, 24));
try {
if (mySelectedEntity != null) {
if (mySelectedEntity.getInfo() != null) {
pen.setColor(Color.WHITE);
pen.drawString(mySelectedEntity.getInfo().getName(), (int) 280,
(int) Window.D_Y - 90);
pen.setFont(new Font("Arial", Font.PLAIN, 20));
pen.setColor(Color.GRAY);
pen.drawString(mySelectedEntity.getInfo().getDescription(), (int) 280,
(int) Window.D_Y - 65);
if (mySelectedEntity.getInfo().getButtonImage() != null) {
pen.drawImage(mySelectedEntity.getInfo().getButtonImage(), (int) 220,
(int) Window.D_Y - 90, 50, 50, null);
}
}
}
}
catch (NullPointerException np) {
// catch weird error
}
}
|
diff --git a/microemulator/src/com/barteo/emulator/device/j2se/J2SEDevice.java b/microemulator/src/com/barteo/emulator/device/j2se/J2SEDevice.java
index dee95908..c92095e2 100644
--- a/microemulator/src/com/barteo/emulator/device/j2se/J2SEDevice.java
+++ b/microemulator/src/com/barteo/emulator/device/j2se/J2SEDevice.java
@@ -1,497 +1,499 @@
/*
* MicroEmulator
* Copyright (C) 2002 Bartek Teodorczyk <[email protected]>
*
* 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.barteo.emulator.device.j2se;
import java.awt.Color;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.lcdui.Canvas;
import com.barteo.emulator.EmulatorContext;
import com.barteo.emulator.device.Device;
import com.barteo.emulator.device.DeviceDisplay;
import com.barteo.emulator.device.FontManager;
import com.barteo.emulator.device.InputMethod;
import com.sixlegs.image.png.PngImage;
import nanoxml.XMLElement;
import nanoxml.XMLParseException;
public class J2SEDevice implements Device
{
private J2SEDeviceDisplay deviceDisplay;
private FontManager fontManager = null;
private InputMethod inputMethod = null;
private Vector buttons;
private Vector softButtons;
private Image normalImage;
private Image overImage;
private Image pressedImage;
public J2SEDevice()
{
}
public void init(EmulatorContext context)
{
// Here should be device.xml but Netscape security manager doesn't accept this extension
init(context, "/com/barteo/emulator/device/device.txt");
}
public void init(EmulatorContext context, String config)
{
deviceDisplay = new J2SEDeviceDisplay(context);
buttons = new Vector();
softButtons = new Vector();
loadConfig(config);
}
public javax.microedition.lcdui.Image createImage(int width, int height)
{
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException();
}
return new MutableImage(width, height);
}
public javax.microedition.lcdui.Image createImage(String name)
throws IOException
{
return new ImmutableImage(getImage(name));
}
public javax.microedition.lcdui.Image createImage(byte[] imageData, int imageOffset, int imageLength)
{
ByteArrayInputStream is = new ByteArrayInputStream(imageData, imageOffset, imageLength);
return new ImmutableImage(getImage(is));
}
public DeviceDisplay getDeviceDisplay()
{
return deviceDisplay;
}
public FontManager getFontManager()
{
if (fontManager == null) {
fontManager = new J2SEFontManager();
}
return fontManager;
}
public InputMethod getInputMethod()
{
if (inputMethod == null) {
inputMethod = new J2SEInputMethod();
}
return inputMethod;
}
public int getGameAction(int keyCode)
{
switch (keyCode) {
case KeyEvent.VK_UP:
return Canvas.UP;
case KeyEvent.VK_DOWN:
return Canvas.DOWN;
case KeyEvent.VK_LEFT:
return Canvas.LEFT;
case KeyEvent.VK_RIGHT:
return Canvas.RIGHT;
case KeyEvent.VK_ENTER:
return Canvas.FIRE;
case KeyEvent.VK_A:
return Canvas.GAME_A;
case KeyEvent.VK_B:
return Canvas.GAME_B;
case KeyEvent.VK_C:
return Canvas.GAME_C;
case KeyEvent.VK_D:
return Canvas.GAME_D;
case KeyEvent.VK_0:
case KeyEvent.VK_1:
case KeyEvent.VK_2:
case KeyEvent.VK_3:
case KeyEvent.VK_4:
case KeyEvent.VK_5:
case KeyEvent.VK_6:
case KeyEvent.VK_7:
case KeyEvent.VK_8:
case KeyEvent.VK_9:
int rval = Canvas.KEY_NUM0 + (keyCode-KeyEvent.VK_0);
return rval;
case KeyEvent.VK_MULTIPLY:
return Canvas.KEY_STAR;
case KeyEvent.VK_NUMBER_SIGN:
return Canvas.KEY_POUND;
default:
return 0;
}
}
public int getKeyCode(int gameAction)
{
switch (gameAction) {
case Canvas.UP:
return KeyEvent.VK_UP;
case Canvas.DOWN:
return KeyEvent.VK_DOWN;
case Canvas.LEFT:
return KeyEvent.VK_LEFT;
case Canvas.RIGHT:
return KeyEvent.VK_RIGHT;
case Canvas.FIRE:
return KeyEvent.VK_ENTER;
case Canvas.GAME_A:
return KeyEvent.VK_A;
case Canvas.GAME_B:
return KeyEvent.VK_B;
case Canvas.GAME_C:
return KeyEvent.VK_C;
case Canvas.GAME_D:
return KeyEvent.VK_D;
case Canvas.KEY_NUM0:
case Canvas.KEY_NUM1:
case Canvas.KEY_NUM2:
case Canvas.KEY_NUM3:
case Canvas.KEY_NUM4:
case Canvas.KEY_NUM5:
case Canvas.KEY_NUM6:
case Canvas.KEY_NUM7:
case Canvas.KEY_NUM8:
case Canvas.KEY_NUM9:
int rval = KeyEvent.VK_0 + (gameAction-Canvas.KEY_NUM0);
return rval;
case Canvas.KEY_POUND:
return KeyEvent.VK_NUMBER_SIGN;
case Canvas.KEY_STAR:
return KeyEvent.VK_MULTIPLY;
default:
return 0;
}
}
public Vector getSoftButtons()
{
return softButtons;
}
public Image getNormalImage()
{
return normalImage;
}
public Image getOverImage()
{
return overImage;
}
public Image getPressedImage()
{
return pressedImage;
}
public boolean hasPointerMotionEvents()
{
return false;
}
public boolean hasPointerEvents()
{
return false;
}
public boolean hasRepeatEvents()
{
return false;
}
public Vector getButtons()
{
return buttons;
}
public void loadConfig(String config)
{
String xml = "";
InputStream dis = new BufferedInputStream(getClass().getResourceAsStream(config));
try {
while (dis.available() > 0) {
byte[] b = new byte[dis.available()];
- dis.read(b);
+ if (dis.read(b) == -1) {
+ break;
+ }
xml += new String(b);
}
} catch (Exception ex) {
System.out.println("Cannot find com.barteo.emulator.device.device.txt definition file");
return;
}
XMLElement doc = new XMLElement();
try {
doc.parseString(xml);
} catch (XMLParseException ex) {
System.err.println(ex);
return;
}
for (Enumeration e = doc.enumerateChildren(); e.hasMoreElements(); ) {
XMLElement tmp = (XMLElement) e.nextElement();
if (tmp.getName().equals("img")) {
try {
if (tmp.getStringAttribute("name").equals("normal")) {
normalImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("over")) {
overImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("pressed")) {
pressedImage = getSystemImage(tmp.getStringAttribute("src"));
}
} catch (IOException ex) {
System.out.println("Cannot load " + tmp.getStringAttribute("src"));
return;
}
} else if (tmp.getName().equals("display")) {
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("numcolors")) {
deviceDisplay.numColors = Integer.parseInt(tmp_display.getContent());
} else if (tmp_display.getName().equals("iscolor")) {
deviceDisplay.isColor = parseBoolean(tmp_display.getContent());
} else if (tmp_display.getName().equals("background")) {
deviceDisplay.backgroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("foreground")) {
deviceDisplay.foregroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("rectangle")) {
deviceDisplay.displayRectangle = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("paintable")) {
deviceDisplay.displayPaintable = getRectangle(tmp_display);
}
}
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("img")) {
if (tmp_display.getStringAttribute("name").equals("up")) {
deviceDisplay.upImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("down")) {
deviceDisplay.downImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("mode")) {
if (tmp_display.getStringAttribute("type").equals("123")) {
deviceDisplay.mode123Image = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("abc")) {
deviceDisplay.modeAbcLowerImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("ABC")) {
deviceDisplay.modeAbcUpperImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
}
}
}
}
} else if (tmp.getName().equals("keyboard")) {
for (Enumeration e_keyboard = tmp.enumerateChildren(); e_keyboard.hasMoreElements(); ) {
XMLElement tmp_keyboard = (XMLElement) e_keyboard.nextElement();
if (tmp_keyboard.getName().equals("button")) {
Rectangle rectangle = null;
Vector stringArray = new Vector();
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("chars")) {
for (Enumeration e_chars = tmp_button.enumerateChildren(); e_chars.hasMoreElements(); ) {
XMLElement tmp_chars = (XMLElement) e_chars.nextElement();
if (tmp_chars.getName().equals("char")) {
stringArray.addElement(tmp_chars.getContent());
}
}
} else if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
}
}
char[] charArray = new char[stringArray.size()];
for (int i = 0; i < stringArray.size(); i++) {
String str = (String) stringArray.elementAt(i);
if (str.length() > 0) {
charArray[i] = str.charAt(0);
} else {
charArray[i] = ' ';
}
}
buttons.addElement(new J2SEButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), charArray));
} else if (tmp_keyboard.getName().equals("softbutton")) {
Vector commands = new Vector();
Rectangle rectangle = null, paintable = null;
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("paintable")) {
paintable = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("command")) {
commands.addElement(tmp_button.getContent());
}
}
String tmp_str = tmp_keyboard.getStringAttribute("menuactivate");
boolean menuactivate = false;
if (tmp_str != null && tmp_str.equals("true")) {
menuactivate = true;
}
J2SESoftButton button = new J2SESoftButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), paintable,
tmp_keyboard.getStringAttribute("alignment"), commands, menuactivate);
buttons.addElement(button);
softButtons.addElement(button);
}
}
}
}
}
private XMLElement getElement(XMLElement source, String name)
{
for (Enumeration e_content = source.enumerateChildren(); e_content.hasMoreElements(); ) {
XMLElement tmp_content = (XMLElement) e_content.nextElement();
if (tmp_content.getName().equals(name)) {
return tmp_content;
}
}
return null;
}
private Rectangle getRectangle(XMLElement source)
{
Rectangle rect = new Rectangle();
for (Enumeration e_rectangle = source.enumerateChildren(); e_rectangle.hasMoreElements(); ) {
XMLElement tmp_rectangle = (XMLElement) e_rectangle.nextElement();
if (tmp_rectangle.getName().equals("x")) {
rect.x = Integer.parseInt(tmp_rectangle.getContent());
} else if (tmp_rectangle.getName().equals("y")) {
rect.y = Integer.parseInt(tmp_rectangle.getContent());
} else if (tmp_rectangle.getName().equals("width")) {
rect.width = Integer.parseInt(tmp_rectangle.getContent());
} else if (tmp_rectangle.getName().equals("height")) {
rect.height = Integer.parseInt(tmp_rectangle.getContent());
}
}
return rect;
}
private boolean parseBoolean(String value)
{
if (value.toLowerCase().equals(new String("true").toLowerCase())) {
return true;
} else {
return false;
}
}
private Image getSystemImage(String str)
throws IOException
{
InputStream is;
is = getClass().getResourceAsStream(str);
if (is == null) {
throw new IOException();
}
PngImage png = new PngImage(is);
return Toolkit.getDefaultToolkit().createImage(png);
}
private Image getImage(String str)
{
InputStream is = deviceDisplay.getEmulatorContext().getClassLoader().getResourceAsStream(str);
return getImage(is);
}
private Image getImage(InputStream is)
{
ImageFilter filter = null;
PngImage png = new PngImage(is);
if (getDeviceDisplay().isColor()) {
filter = new RGBImageFilter();
} else {
if (getDeviceDisplay().numColors() == 2) {
filter = new BWImageFilter();
} else {
filter = new GrayImageFilter();
}
}
FilteredImageSource imageSource = new FilteredImageSource(png, filter);
return Toolkit.getDefaultToolkit().createImage(imageSource);
}
}
| true | true | public void loadConfig(String config)
{
String xml = "";
InputStream dis = new BufferedInputStream(getClass().getResourceAsStream(config));
try {
while (dis.available() > 0) {
byte[] b = new byte[dis.available()];
dis.read(b);
xml += new String(b);
}
} catch (Exception ex) {
System.out.println("Cannot find com.barteo.emulator.device.device.txt definition file");
return;
}
XMLElement doc = new XMLElement();
try {
doc.parseString(xml);
} catch (XMLParseException ex) {
System.err.println(ex);
return;
}
for (Enumeration e = doc.enumerateChildren(); e.hasMoreElements(); ) {
XMLElement tmp = (XMLElement) e.nextElement();
if (tmp.getName().equals("img")) {
try {
if (tmp.getStringAttribute("name").equals("normal")) {
normalImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("over")) {
overImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("pressed")) {
pressedImage = getSystemImage(tmp.getStringAttribute("src"));
}
} catch (IOException ex) {
System.out.println("Cannot load " + tmp.getStringAttribute("src"));
return;
}
} else if (tmp.getName().equals("display")) {
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("numcolors")) {
deviceDisplay.numColors = Integer.parseInt(tmp_display.getContent());
} else if (tmp_display.getName().equals("iscolor")) {
deviceDisplay.isColor = parseBoolean(tmp_display.getContent());
} else if (tmp_display.getName().equals("background")) {
deviceDisplay.backgroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("foreground")) {
deviceDisplay.foregroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("rectangle")) {
deviceDisplay.displayRectangle = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("paintable")) {
deviceDisplay.displayPaintable = getRectangle(tmp_display);
}
}
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("img")) {
if (tmp_display.getStringAttribute("name").equals("up")) {
deviceDisplay.upImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("down")) {
deviceDisplay.downImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("mode")) {
if (tmp_display.getStringAttribute("type").equals("123")) {
deviceDisplay.mode123Image = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("abc")) {
deviceDisplay.modeAbcLowerImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("ABC")) {
deviceDisplay.modeAbcUpperImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
}
}
}
}
} else if (tmp.getName().equals("keyboard")) {
for (Enumeration e_keyboard = tmp.enumerateChildren(); e_keyboard.hasMoreElements(); ) {
XMLElement tmp_keyboard = (XMLElement) e_keyboard.nextElement();
if (tmp_keyboard.getName().equals("button")) {
Rectangle rectangle = null;
Vector stringArray = new Vector();
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("chars")) {
for (Enumeration e_chars = tmp_button.enumerateChildren(); e_chars.hasMoreElements(); ) {
XMLElement tmp_chars = (XMLElement) e_chars.nextElement();
if (tmp_chars.getName().equals("char")) {
stringArray.addElement(tmp_chars.getContent());
}
}
} else if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
}
}
char[] charArray = new char[stringArray.size()];
for (int i = 0; i < stringArray.size(); i++) {
String str = (String) stringArray.elementAt(i);
if (str.length() > 0) {
charArray[i] = str.charAt(0);
} else {
charArray[i] = ' ';
}
}
buttons.addElement(new J2SEButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), charArray));
} else if (tmp_keyboard.getName().equals("softbutton")) {
Vector commands = new Vector();
Rectangle rectangle = null, paintable = null;
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("paintable")) {
paintable = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("command")) {
commands.addElement(tmp_button.getContent());
}
}
String tmp_str = tmp_keyboard.getStringAttribute("menuactivate");
boolean menuactivate = false;
if (tmp_str != null && tmp_str.equals("true")) {
menuactivate = true;
}
J2SESoftButton button = new J2SESoftButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), paintable,
tmp_keyboard.getStringAttribute("alignment"), commands, menuactivate);
buttons.addElement(button);
softButtons.addElement(button);
}
}
}
}
}
| public void loadConfig(String config)
{
String xml = "";
InputStream dis = new BufferedInputStream(getClass().getResourceAsStream(config));
try {
while (dis.available() > 0) {
byte[] b = new byte[dis.available()];
if (dis.read(b) == -1) {
break;
}
xml += new String(b);
}
} catch (Exception ex) {
System.out.println("Cannot find com.barteo.emulator.device.device.txt definition file");
return;
}
XMLElement doc = new XMLElement();
try {
doc.parseString(xml);
} catch (XMLParseException ex) {
System.err.println(ex);
return;
}
for (Enumeration e = doc.enumerateChildren(); e.hasMoreElements(); ) {
XMLElement tmp = (XMLElement) e.nextElement();
if (tmp.getName().equals("img")) {
try {
if (tmp.getStringAttribute("name").equals("normal")) {
normalImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("over")) {
overImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("pressed")) {
pressedImage = getSystemImage(tmp.getStringAttribute("src"));
}
} catch (IOException ex) {
System.out.println("Cannot load " + tmp.getStringAttribute("src"));
return;
}
} else if (tmp.getName().equals("display")) {
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("numcolors")) {
deviceDisplay.numColors = Integer.parseInt(tmp_display.getContent());
} else if (tmp_display.getName().equals("iscolor")) {
deviceDisplay.isColor = parseBoolean(tmp_display.getContent());
} else if (tmp_display.getName().equals("background")) {
deviceDisplay.backgroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("foreground")) {
deviceDisplay.foregroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("rectangle")) {
deviceDisplay.displayRectangle = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("paintable")) {
deviceDisplay.displayPaintable = getRectangle(tmp_display);
}
}
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("img")) {
if (tmp_display.getStringAttribute("name").equals("up")) {
deviceDisplay.upImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("down")) {
deviceDisplay.downImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("mode")) {
if (tmp_display.getStringAttribute("type").equals("123")) {
deviceDisplay.mode123Image = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("abc")) {
deviceDisplay.modeAbcLowerImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("ABC")) {
deviceDisplay.modeAbcUpperImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
}
}
}
}
} else if (tmp.getName().equals("keyboard")) {
for (Enumeration e_keyboard = tmp.enumerateChildren(); e_keyboard.hasMoreElements(); ) {
XMLElement tmp_keyboard = (XMLElement) e_keyboard.nextElement();
if (tmp_keyboard.getName().equals("button")) {
Rectangle rectangle = null;
Vector stringArray = new Vector();
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("chars")) {
for (Enumeration e_chars = tmp_button.enumerateChildren(); e_chars.hasMoreElements(); ) {
XMLElement tmp_chars = (XMLElement) e_chars.nextElement();
if (tmp_chars.getName().equals("char")) {
stringArray.addElement(tmp_chars.getContent());
}
}
} else if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
}
}
char[] charArray = new char[stringArray.size()];
for (int i = 0; i < stringArray.size(); i++) {
String str = (String) stringArray.elementAt(i);
if (str.length() > 0) {
charArray[i] = str.charAt(0);
} else {
charArray[i] = ' ';
}
}
buttons.addElement(new J2SEButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), charArray));
} else if (tmp_keyboard.getName().equals("softbutton")) {
Vector commands = new Vector();
Rectangle rectangle = null, paintable = null;
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("paintable")) {
paintable = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("command")) {
commands.addElement(tmp_button.getContent());
}
}
String tmp_str = tmp_keyboard.getStringAttribute("menuactivate");
boolean menuactivate = false;
if (tmp_str != null && tmp_str.equals("true")) {
menuactivate = true;
}
J2SESoftButton button = new J2SESoftButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), paintable,
tmp_keyboard.getStringAttribute("alignment"), commands, menuactivate);
buttons.addElement(button);
softButtons.addElement(button);
}
}
}
}
}
|
diff --git a/src/swarm/Hitbox.java b/src/swarm/Hitbox.java
index de782df..725fbea 100644
--- a/src/swarm/Hitbox.java
+++ b/src/swarm/Hitbox.java
@@ -1,60 +1,60 @@
package swarm;
public class Hitbox{
private int width;
private int height;
private int x;
private int y;
public Hitbox(int x, int y, int width, int height)
{
setWidth(width);
setHeight(height);
setX(x);
setY(y);
}
public boolean checkCollision(Hitbox box)
{
if(box==null)
return false;
if((box.x > x && box.x < x + width) ||(box.x + box.width > x && box.x + box.width < x + width)){
- if((box.y > y && box.y < y + height) || (box.y+box.height > y && box.height<box.y+box.height)){
+ if((box.y > y && box.y < y + height) ||(box.y + box.height > y && box.y + box.height < y + height)){
return true;
}
}
return false;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
| true | true | public boolean checkCollision(Hitbox box)
{
if(box==null)
return false;
if((box.x > x && box.x < x + width) ||(box.x + box.width > x && box.x + box.width < x + width)){
if((box.y > y && box.y < y + height) || (box.y+box.height > y && box.height<box.y+box.height)){
return true;
}
}
return false;
}
| public boolean checkCollision(Hitbox box)
{
if(box==null)
return false;
if((box.x > x && box.x < x + width) ||(box.x + box.width > x && box.x + box.width < x + width)){
if((box.y > y && box.y < y + height) ||(box.y + box.height > y && box.y + box.height < y + height)){
return true;
}
}
return false;
}
|
diff --git a/forms/src/org/riotfamily/forms/element/core/ImageUpload.java b/forms/src/org/riotfamily/forms/element/core/ImageUpload.java
index 3d4ba7bf3..d7225e834 100755
--- a/forms/src/org/riotfamily/forms/element/core/ImageUpload.java
+++ b/forms/src/org/riotfamily/forms/element/core/ImageUpload.java
@@ -1,402 +1,400 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Riot.
*
* The Initial Developer of the Original Code is
* Neteye GmbH.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Felix Gnass [fgnass at neteye dot de]
*
* ***** END LICENSE BLOCK ***** */
package org.riotfamily.forms.element.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.SocketException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.devlib.schmidt.imageinfo.ImageInfo;
import org.riotfamily.common.markup.Html;
import org.riotfamily.common.markup.TagWriter;
import org.riotfamily.common.web.util.ServletUtils;
import org.riotfamily.forms.Element;
import org.riotfamily.forms.bind.EditorBinder;
import org.riotfamily.forms.element.ContentElement;
import org.riotfamily.forms.element.DHTMLElement;
import org.riotfamily.forms.element.support.AbstractElement;
import org.riotfamily.forms.element.support.image.ImageCropper;
import org.riotfamily.forms.error.ErrorUtils;
import org.riotfamily.forms.resource.Resources;
import org.riotfamily.forms.resource.ScriptResource;
import org.riotfamily.forms.resource.ScriptSequence;
import org.riotfamily.forms.support.TemplateUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.ServletRequestUtils;
/**
* Specialized FileUpload element for image uploads.
*/
public class ImageUpload extends FileUpload {
private int[] widths;
private int[] heights;
private int minWidth;
private int maxWidth;
private int minHeight;
private int maxHeight;
private String validFormats = "GIF,JPEG,PNG";
private String widthProperty;
private String heightProperty;
private ImageInfo info;
private ImageCropper cropper;
private boolean crop = true;
private File originalFile;
private File croppedFile;
public ImageUpload() {
addResource(new ScriptSequence(new ScriptResource[] {
Resources.PROTOTYPE,
Resources.SCRIPTACULOUS_SLIDER,
new ScriptResource("riot-js/image-cropper.js", "Cropper")
}));
}
protected Element createPreviewElement() {
return new PreviewElement();
}
public void setCropper(ImageCropper cropper) {
this.cropper = cropper;
}
public void setCrop(boolean crop) {
this.crop = crop;
}
public void setWidths(int[] widths) {
this.widths = widths;
if (widths != null) {
int min = Integer.MAX_VALUE;
int max = 0;
for (int i = 0; i < widths.length; i++) {
min = Math.min(min, widths[i]);
max = Math.max(max, widths[i]);
}
setMinWidth(min);
setMaxWidth(max);
}
}
public void setWidth(int width) {
setWidths(new int[] { width });
}
public void setHeights(int[] heights) {
this.heights = heights;
if (heights != null) {
int min = Integer.MAX_VALUE;
int max = 0;
for (int i = 0; i < heights.length; i++) {
min = Math.min(min, heights[i]);
max = Math.max(max, heights[i]);
}
setMinHeight(min);
setMaxHeight(max);
}
}
public void setHeight(int height) {
setHeights(new int[] {height});
}
public void setMinWidth(int minWidth) {
this.minWidth = minWidth;
}
public void setMaxWidth(int maxWidth) {
this.maxWidth = maxWidth;
}
public void setMinHeight(int minHeight) {
this.minHeight = minHeight;
}
public void setMaxHeight(int maxHeight) {
this.maxHeight = maxHeight;
}
public void setValidFormats(String validFormats) {
this.validFormats = validFormats;
}
public String getHeightProperty() {
return this.heightProperty;
}
public void setHeightProperty(String heightProperty) {
this.heightProperty = heightProperty;
}
public String getWidthProperty() {
return this.widthProperty;
}
public void setWidthProperty(String widthProperty) {
this.widthProperty = widthProperty;
}
public boolean isPreviewAvailable() {
return true;
}
protected void cropImage(int width, int height, int x, int y,
int scaledWidth) throws IOException {
if (croppedFile == null) {
croppedFile = File.createTempFile("000", ".tmp");
}
if (originalFile == null) {
originalFile = getFile();
}
cropper.cropImage(originalFile, croppedFile, width, height, x, y,
scaledWidth);
setFile(croppedFile);
}
protected void afterFileUploaded() {
originalFile = getFile();
}
protected void undoCrop() {
setFile(originalFile);
}
protected void destroy() {
super.destroy();
if (croppedFile != null && !croppedFile.equals(getReturnedFile())) {
croppedFile.delete();
}
}
protected void validateFile(File file) {
try {
info = new ImageInfo();
info.setInput(new FileInputStream(file));
info.check();
log.debug(info.getFormatName() + " Size: "
+ info.getWidth() + "x" + info.getHeight());
if (validFormats != null) {
if (validFormats.indexOf(info.getFormatName()) == -1) {
ErrorUtils.reject(this, "image.invalidFormat",
new Object[] { validFormats, info.getFormatName() });
}
}
int imageHeight = info.getHeight();
int imageWidth = info.getWidth();
if (widths != null) {
boolean match = false;
for (int i = 0; i < widths.length; i++) {
if (imageWidth == widths[i]) {
match = true;
break;
}
}
if (!match) {
ErrorUtils.reject(this, "image.size.mismatch");
+ return;
}
}
- else {
- if (imageWidth < minWidth || (maxWidth > 0 && imageWidth > maxWidth)) {
- ErrorUtils.reject(this, "image.size.mismatch");
- }
+ else if (imageWidth < minWidth || (maxWidth > 0 && imageWidth > maxWidth)) {
+ ErrorUtils.reject(this, "image.size.mismatch");
+ return;
}
if (heights != null) {
boolean match = false;
for (int i = 0; i < heights.length; i++) {
if (imageHeight == heights[i]) {
match = true;
break;
}
}
if (!match) {
ErrorUtils.reject(this, "image.size.mismatch");
}
}
- else {
- if (imageHeight < minHeight || (maxHeight > 0 && imageHeight > maxHeight)) {
- ErrorUtils.reject(this, "image.size.mismatch");
- }
+ else if (imageHeight < minHeight || (maxHeight > 0 && imageHeight > maxHeight)) {
+ ErrorUtils.reject(this, "image.size.mismatch");
}
}
catch (IOException e) {
}
}
public Object getValue() {
if (info != null) {
EditorBinder editorBinder = getEditorBinding().getEditorBinder();
if (widthProperty != null) {
editorBinder.setPropertyValue(widthProperty,
new Integer(info.getWidth()));
}
if (heightProperty != null) {
editorBinder.setPropertyValue(heightProperty,
new Integer(info.getHeight()));
}
}
return super.getValue();
}
public class PreviewElement extends AbstractElement
implements ContentElement, DHTMLElement {
protected void renderInternal(PrintWriter writer) {
int w = maxWidth > 0 ? maxWidth : 150;
int h = (maxHeight > 0 ? maxHeight : 100) + 50;
new TagWriter(writer).start(Html.DIV)
.attribute(Html.COMMON_ID, getId())
.attribute(Html.COMMON_STYLE,
"width:" + w + "px;height:" + h + "px").end();
}
private int getIntParameter(HttpServletRequest request, String name) {
return ServletRequestUtils.getIntParameter(request, name, 0);
}
public void handleContentRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (isPresent()) {
if ("crop".equals(request.getParameter("action"))) {
cropImage(
getIntParameter(request, "width"),
getIntParameter(request, "height"),
getIntParameter(request, "x"),
getIntParameter(request, "y"),
getIntParameter(request, "scaledWidth"));
response.getWriter().print(getCroppedImageUrl());
}
else if ("undo".equals(request.getParameter("action"))) {
undoCrop();
}
else {
ServletUtils.setNoCacheHeaders(response);
response.setHeader("Content-Type", getContentType());
response.setContentLength(getSize().intValue());
try {
//TODO Check if file exists
FileCopyUtils.copy(new FileInputStream(getFile()),
response.getOutputStream());
}
catch (IOException e) {
// Ignore exceptions caused by client abortion:
if (!SocketException.class.isInstance(e.getCause())) {
throw e;
}
}
}
}
else {
response.sendError(HttpServletResponse.SC_NO_CONTENT);
}
}
public String getImageUrl() {
if (isPresent()) {
return getFormContext().getContentUrl(this)
+ "&time=" + System.currentTimeMillis();
}
return null;
}
public String getCropUrl() {
if (cropper != null && crop) {
return getFormContext().getContentUrl(this) + "&action=crop";
}
return null;
}
public String getUndoUrl() {
if (cropper != null && crop) {
return getFormContext().getContentUrl(this) + "&action=undo";
}
return null;
}
public String getCroppedImageUrl() {
return getFormContext().getContentUrl(this)
+ "&cropped=true&time=" + System.currentTimeMillis();
}
public String getInitScript() {
return TemplateUtils.getInitScript(this);
}
public String getPrecondition() {
return "Cropper";
}
public int getMinWidth() {
return minWidth;
}
public int getMaxWidth() {
return maxWidth;
}
public int getMinHeight() {
return minHeight;
}
public int getMaxHeight() {
return maxHeight;
}
public int[] getWidths() {
return widths;
}
public int[] getHeights() {
return heights;
}
}
}
| false | true | protected void validateFile(File file) {
try {
info = new ImageInfo();
info.setInput(new FileInputStream(file));
info.check();
log.debug(info.getFormatName() + " Size: "
+ info.getWidth() + "x" + info.getHeight());
if (validFormats != null) {
if (validFormats.indexOf(info.getFormatName()) == -1) {
ErrorUtils.reject(this, "image.invalidFormat",
new Object[] { validFormats, info.getFormatName() });
}
}
int imageHeight = info.getHeight();
int imageWidth = info.getWidth();
if (widths != null) {
boolean match = false;
for (int i = 0; i < widths.length; i++) {
if (imageWidth == widths[i]) {
match = true;
break;
}
}
if (!match) {
ErrorUtils.reject(this, "image.size.mismatch");
}
}
else {
if (imageWidth < minWidth || (maxWidth > 0 && imageWidth > maxWidth)) {
ErrorUtils.reject(this, "image.size.mismatch");
}
}
if (heights != null) {
boolean match = false;
for (int i = 0; i < heights.length; i++) {
if (imageHeight == heights[i]) {
match = true;
break;
}
}
if (!match) {
ErrorUtils.reject(this, "image.size.mismatch");
}
}
else {
if (imageHeight < minHeight || (maxHeight > 0 && imageHeight > maxHeight)) {
ErrorUtils.reject(this, "image.size.mismatch");
}
}
}
catch (IOException e) {
}
}
| protected void validateFile(File file) {
try {
info = new ImageInfo();
info.setInput(new FileInputStream(file));
info.check();
log.debug(info.getFormatName() + " Size: "
+ info.getWidth() + "x" + info.getHeight());
if (validFormats != null) {
if (validFormats.indexOf(info.getFormatName()) == -1) {
ErrorUtils.reject(this, "image.invalidFormat",
new Object[] { validFormats, info.getFormatName() });
}
}
int imageHeight = info.getHeight();
int imageWidth = info.getWidth();
if (widths != null) {
boolean match = false;
for (int i = 0; i < widths.length; i++) {
if (imageWidth == widths[i]) {
match = true;
break;
}
}
if (!match) {
ErrorUtils.reject(this, "image.size.mismatch");
return;
}
}
else if (imageWidth < minWidth || (maxWidth > 0 && imageWidth > maxWidth)) {
ErrorUtils.reject(this, "image.size.mismatch");
return;
}
if (heights != null) {
boolean match = false;
for (int i = 0; i < heights.length; i++) {
if (imageHeight == heights[i]) {
match = true;
break;
}
}
if (!match) {
ErrorUtils.reject(this, "image.size.mismatch");
}
}
else if (imageHeight < minHeight || (maxHeight > 0 && imageHeight > maxHeight)) {
ErrorUtils.reject(this, "image.size.mismatch");
}
}
catch (IOException e) {
}
}
|
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCRegistry.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCRegistry.java
index 4d7d842f0..1d21e2b88 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCRegistry.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCRegistry.java
@@ -1,284 +1,287 @@
/*
* 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.openjpa.enhance;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.ReferenceMap;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashSet;
import org.apache.openjpa.util.UserException;
/**
* Tracks registered persistence-capable classes.
*
* @since 0.4.0
* @author Abe White
*/
public class PCRegistry {
// DO NOT ADD ADDITIONAL DEPENDENCIES TO THIS CLASS
private static final Localizer _loc = Localizer.forPackage(PCRegistry.class);
// map of persistent classes to meta structures; weak so the VM can GC classes
private static final Map<Class<?>,Meta> _metas = new ConcurrentReferenceHashMap(ReferenceMap.WEAK,
ReferenceMap.HARD);
// register class listeners
// Weak reference prevents OutOfMemeoryError as described in OPENJPA-2042
private static final Collection<RegisterClassListener> _listeners =
new ConcurrentReferenceHashSet<RegisterClassListener>(
ConcurrentReferenceHashSet.WEAK);
/**
* Register a {@link RegisterClassListener}.
*/
public static void addRegisterClassListener(RegisterClassListener rcl) {
if (rcl == null)
return;
// we have to be positive that every listener gets notified for
// every class, so lots of locking
synchronized (_listeners) {
_listeners.add(rcl);
}
synchronized (_metas) {
for (Class<?> cls : _metas.keySet())
rcl.register(cls);
}
}
/**
* Removes a {@link RegisterClassListener}.
*/
public static boolean removeRegisterClassListener(RegisterClassListener rcl) {
synchronized (_listeners) {
return _listeners.remove(rcl);
}
}
/**
* Get the field names for a <code>PersistenceCapable</code> class.
*/
public static String[] getFieldNames(Class<?> pcClass) {
Meta meta = getMeta(pcClass);
return meta.fieldNames;
}
/**
* Get the field types for a <code>PersistenceCapable</code> class.
*/
public static Class<?>[] getFieldTypes(Class<?> pcClass) {
Meta meta = getMeta(pcClass);
return meta.fieldTypes;
}
/**
* Return the persistent superclass for a <code>PersistenceCapable</code>
* class, or null if none. The superclass may or may not implement
* {@link PersistenceCapable}, depending on the access type of the class.
*/
public static Class<?> getPersistentSuperclass(Class<?> pcClass) {
Meta meta = getMeta(pcClass);
return meta.pcSuper;
}
/**
* Create a new instance of the class and assign its state manager.
* The new instance has its flags set to <code>LOAD_REQUIRED</code>.
*/
public static PersistenceCapable newInstance(Class<?> pcClass, StateManager sm, boolean clear) {
Meta meta = getMeta(pcClass);
return (meta.pc == null) ? null : meta.pc.pcNewInstance(sm, clear);
}
/**
* Create a new instance of the class and assign its state manager and oid.
* The new instance has its flags set to <code>LOAD_REQUIRED</code>.
*/
public static PersistenceCapable newInstance(Class<?> pcClass, StateManager sm, Object oid, boolean clear) {
Meta meta = getMeta(pcClass);
return (meta.pc == null) ? null : meta.pc.pcNewInstance(sm, oid, clear);
}
/**
* Return the persistence-capable type for <code>type</code>. This might
* be a generated subclass of <code>type</code>.
*
* @since 1.1.0
*/
public static Class<?> getPCType(Class<?> type) {
Meta meta = getMeta(type);
return (meta.pc == null) ? null : meta.pc.getClass();
}
/**
* Create a new identity object for the given
* <code>PersistenceCapable</code> class.
*/
public static Object newObjectId(Class<?> pcClass) {
Meta meta = getMeta(pcClass);
return (meta.pc == null) ? null : meta.pc.pcNewObjectIdInstance();
}
/**
* Create a new identity object for the given
* <code>PersistenceCapable</code> class, using the <code>String</code>
* form of the constructor.
*/
public static Object newObjectId(Class<?> pcClass, String str) {
Meta meta = getMeta(pcClass);
return (meta.pc == null) ? null : meta.pc.pcNewObjectIdInstance(str);
}
/**
* Return the alias for the given type.
*/
public static String getTypeAlias(Class<?> pcClass) {
return getMeta(pcClass).alias;
}
/**
* Copy fields from an outside source to the key fields in the identity
* object.
*/
public static void copyKeyFieldsToObjectId(Class<?> pcClass, FieldSupplier fm, Object oid) {
Meta meta = getMeta(pcClass);
if (meta.pc == null)
throw new UserException(_loc.get("copy-no-id", pcClass));
meta.pc.pcCopyKeyFieldsToObjectId(fm, oid);
}
/**
* Copy fields to an outside source from the key fields in the identity
* object.
*/
public static void copyKeyFieldsFromObjectId(Class<?> pcClass, FieldConsumer fm, Object oid) {
Meta meta = getMeta(pcClass);
if (meta.pc == null)
throw new UserException(_loc.get("copy-no-id", pcClass));
meta.pc.pcCopyKeyFieldsFromObjectId(fm, oid);
}
/**
* Register metadata by class.
*
* @param fieldTypes managed field types
* @param fieldFlags managed field flags
* @param sup the most immediate persistent superclass
* @param pcClass the <code>PersistenceCapable</code> class
* @param fieldNames managed field names
* @param alias the class alias
* @param pc an instance of the class, if not abstract
*/
public static void register(Class<?> pcClass, String[] fieldNames, Class<?>[] fieldTypes, byte[] fieldFlags,
Class<?> sup, String alias, PersistenceCapable pc) {
if (pcClass == null)
throw new NullPointerException();
// we have to be positive that every listener gets notified for
// every class, so lots of locking
Meta meta = new Meta(pc, fieldNames, fieldTypes, sup, alias);
synchronized (_metas) {
_metas.put(pcClass, meta);
}
synchronized (_listeners) {
- for (RegisterClassListener r : _listeners)
- r.register(pcClass);
+ for (RegisterClassListener r : _listeners){
+ if (r != null) {
+ r.register(pcClass);
+ }
+ }
}
}
/**
* De-Register all metadata associated with the given ClassLoader.
* Allows ClassLoaders to be garbage collected.
*
* @param cl the ClassLoader
*/
public static void deRegister(ClassLoader cl) {
synchronized (_metas) {
for (Class<?> pcClass : _metas.keySet()) {
if (pcClass.getClassLoader() == cl) {
_metas.remove(pcClass);
}
}
}
}
/**
* Returns a collection of class objects of the registered
* persistence-capable classes.
*/
public static Collection<Class<?>> getRegisteredTypes() {
return Collections.unmodifiableCollection(_metas.keySet());
}
/**
* Returns <code>true</code> if the given class is already registered.
*/
public static boolean isRegistered(Class<?> cls) {
return _metas.containsKey(cls);
}
/**
* Look up the metadata for a <code>PersistenceCapable</code> class.
*/
private static Meta getMeta(Class<?> pcClass) {
Meta ret = (Meta) _metas.get(pcClass);
if (ret == null)
throw new IllegalStateException(_loc.get("no-meta", pcClass).
getMessage());
return ret;
}
/**
* Listener for persistent class registration events.
*/
public static interface RegisterClassListener {
public void register(Class<?> cls);
}
/**
* This is a helper class to manage metadata per persistence-capable class.
*/
private static class Meta {
public final PersistenceCapable pc;
public final String[] fieldNames;
public final Class<?>[] fieldTypes;
public final Class<?> pcSuper;
public final String alias;
public Meta(PersistenceCapable pc, String[] fieldNames,
Class<?>[] fieldTypes, Class<?> pcSuper, String alias) {
this.pc = pc;
this.fieldNames = fieldNames;
this.fieldTypes = fieldTypes;
this.pcSuper = pcSuper;
this.alias = alias;
}
}
}
| true | true | public static void register(Class<?> pcClass, String[] fieldNames, Class<?>[] fieldTypes, byte[] fieldFlags,
Class<?> sup, String alias, PersistenceCapable pc) {
if (pcClass == null)
throw new NullPointerException();
// we have to be positive that every listener gets notified for
// every class, so lots of locking
Meta meta = new Meta(pc, fieldNames, fieldTypes, sup, alias);
synchronized (_metas) {
_metas.put(pcClass, meta);
}
synchronized (_listeners) {
for (RegisterClassListener r : _listeners)
r.register(pcClass);
}
}
| public static void register(Class<?> pcClass, String[] fieldNames, Class<?>[] fieldTypes, byte[] fieldFlags,
Class<?> sup, String alias, PersistenceCapable pc) {
if (pcClass == null)
throw new NullPointerException();
// we have to be positive that every listener gets notified for
// every class, so lots of locking
Meta meta = new Meta(pc, fieldNames, fieldTypes, sup, alias);
synchronized (_metas) {
_metas.put(pcClass, meta);
}
synchronized (_listeners) {
for (RegisterClassListener r : _listeners){
if (r != null) {
r.register(pcClass);
}
}
}
}
|
diff --git a/manual-layout-impl/src/main/java/org/cytoscape/view/manual/internal/control/actions/align/HAlignLeft.java b/manual-layout-impl/src/main/java/org/cytoscape/view/manual/internal/control/actions/align/HAlignLeft.java
index c776fc057..1b2bcd5d2 100644
--- a/manual-layout-impl/src/main/java/org/cytoscape/view/manual/internal/control/actions/align/HAlignLeft.java
+++ b/manual-layout-impl/src/main/java/org/cytoscape/view/manual/internal/control/actions/align/HAlignLeft.java
@@ -1,62 +1,62 @@
package org.cytoscape.view.manual.internal.control.actions.align;
/*
* #%L
* Cytoscape Manual Layout Impl (manual-layout-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2013 The Cytoscape Consortium
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import javax.swing.Icon;
import org.cytoscape.view.manual.internal.control.actions.AbstractControlAction;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.model.CyNode;
import org.cytoscape.view.model.View;
import org.cytoscape.view.presentation.property.BasicVisualLexicon;
/**
*
*/
public class HAlignLeft extends AbstractControlAction {
private static final long serialVersionUID = 6744254664976466345L;
public HAlignLeft(Icon i,CyApplicationManager appMgr) {
super("",i,appMgr);
}
protected void control(List<View<CyNode>> nodes) {
for ( View<CyNode> n : nodes ) {
- double w = n.getVisualProperty(BasicVisualLexicon.NODE_X_LOCATION) / 2;
+ double w = n.getVisualProperty(BasicVisualLexicon.NODE_WIDTH) / 2;
n.setVisualProperty(BasicVisualLexicon.NODE_X_LOCATION, X_min + w);
}
}
protected double getX(View<CyNode> n) {
double x = n.getVisualProperty(BasicVisualLexicon.NODE_X_LOCATION);
double w = n.getVisualProperty(BasicVisualLexicon.NODE_WIDTH) / 2;
return x - w;
}
}
| true | true | protected void control(List<View<CyNode>> nodes) {
for ( View<CyNode> n : nodes ) {
double w = n.getVisualProperty(BasicVisualLexicon.NODE_X_LOCATION) / 2;
n.setVisualProperty(BasicVisualLexicon.NODE_X_LOCATION, X_min + w);
}
}
| protected void control(List<View<CyNode>> nodes) {
for ( View<CyNode> n : nodes ) {
double w = n.getVisualProperty(BasicVisualLexicon.NODE_WIDTH) / 2;
n.setVisualProperty(BasicVisualLexicon.NODE_X_LOCATION, X_min + w);
}
}
|
diff --git a/ide/eclipse/appfactory/org.wso2.developerstudio.appfactory.core/src/org/wso2/developerstudio/appfactory/core/model/AppListModel.java b/ide/eclipse/appfactory/org.wso2.developerstudio.appfactory.core/src/org/wso2/developerstudio/appfactory/core/model/AppListModel.java
index 29a93d373..f783fea28 100644
--- a/ide/eclipse/appfactory/org.wso2.developerstudio.appfactory.core/src/org/wso2/developerstudio/appfactory/core/model/AppListModel.java
+++ b/ide/eclipse/appfactory/org.wso2.developerstudio.appfactory.core/src/org/wso2/developerstudio/appfactory/core/model/AppListModel.java
@@ -1,267 +1,268 @@
/*
* Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.appfactory.core.model;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.http.HttpResponse;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.wso2.developerstudio.appfactory.core.Activator;
import org.wso2.developerstudio.appfactory.core.authentication.Authenticator;
import org.wso2.developerstudio.appfactory.core.client.HttpsJaggeryClient;
import org.wso2.developerstudio.appfactory.core.client.RssClient;
import org.wso2.developerstudio.appfactory.core.jag.api.JagApiProperties;
import org.wso2.developerstudio.appfactory.core.model.AppVersionInfo;
import org.wso2.developerstudio.appfactory.core.model.ApplicationInfo;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class AppListModel {
private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID);
public List<ApplicationInfo> getCategories(List<ApplicationInfo> apps) {
// TODO can do changes to default model
for (ApplicationInfo applicationInfo : apps) {
/*Currently API doesn't provide the app owner information*/
applicationInfo.setApplicationOwner(Authenticator.getInstance().getCredentials().getUser());
}
return apps;
}
public boolean setversionInfo(ApplicationInfo applicationInfo) {
String respond = "";
/* Getting version information */
Map<String, String> params = new HashMap<String, String>();
params.put("action", JagApiProperties.App_NIFO_ACTION);
params.put("stageName", "Development");
params.put("userName", Authenticator.getInstance().getCredentials()
.getUser());
params.put("applicationKey", applicationInfo.getKey());
respond = HttpsJaggeryClient.httpPost(JagApiProperties.getAppInfoUrl(),
params);
if ("false".equals(respond)) {
return false;
} else {
JsonElement jelement = new JsonParser().parse(respond);
JsonElement jsonElement = jelement.getAsJsonArray().get(0)
.getAsJsonObject().get("versions");
JsonArray infoArray = jsonElement.getAsJsonArray();
ArrayList<AppVersionInfo> appVersionList = new ArrayList<AppVersionInfo>();
for (JsonElement jsonElement2 : infoArray) {
JsonObject asJsonObject = jsonElement2.getAsJsonObject();
Gson gson = new Gson();
AppVersionInfo version = gson.fromJson(asJsonObject,
AppVersionInfo.class);
version.setAppName(applicationInfo.getKey());
version.setLocalRepo(applicationInfo.getLocalrepoLocation());
appVersionList.add(version);
}
applicationInfo.setAppVersionList(appVersionList);
return true;
}
}
public boolean setRoleInfomation(ApplicationInfo applicationInfo) {
String respond;
Map<String, String> params;
JsonElement jelement;
params = new HashMap<String, String>();
params.put("action", JagApiProperties.App_USERS_ROLES_ACTION);
params.put("applicationKey", applicationInfo.getKey());
respond = HttpsJaggeryClient.httpPost(
JagApiProperties.getAppUserRolesUrlS(), params);
if ("false".equals(respond)) {
return false;
} else {
jelement = new JsonParser().parse(respond);
JsonArray infoArray2 = jelement.getAsJsonArray();
ArrayList<AppUserInfo> appUserList = new ArrayList<AppUserInfo>();
for (JsonElement jsonElement3 : infoArray2) {
JsonObject asJsonObject = jsonElement3.getAsJsonObject();
Gson gson = new Gson();
AppUserInfo user = gson.fromJson(asJsonObject, AppUserInfo.class);
appUserList.add(user);
}
applicationInfo.setApplicationDevelopers(appUserList);
return true;
}
}
public boolean setDSInfomation(ApplicationInfo applicationInfo) {
String respond;
Map<String, String> params;
params = new HashMap<String, String>();
params.put("action", JagApiProperties.App_DS_INFO_ACTION);
params.put("stage", "Development");
respond = HttpsJaggeryClient.httpPost(
JagApiProperties.getAppDsInfoUrl(), params);
if ("false".equals(respond)) {
return false;
} else {
RssClient.getDBinfo("reloadAllDataSources", respond);
String dsinfo = RssClient.getDBinfo("getAllDataSources", respond);
if (dsinfo == null) {
return false;
}
try {
List<DataSource> dsModels = new ArrayList<DataSource>();
InputStream is = new ByteArrayInputStream(dsinfo.getBytes());
SOAPMessage msg = MessageFactory.newInstance().createMessage(null, is);
SOAPBody soapBody = msg.getSOAPBody();
SOAPElement allDataSources = (SOAPElement) soapBody.getFirstChild();
@SuppressWarnings("unchecked")
Iterator<SOAPElement> dsList = allDataSources.getChildElements();
while (dsList.hasNext()) {
- SOAPElement isactive = (SOAPElement) dsList.next().getLastChild().getLastChild();
+ SOAPElement element = dsList.next();
+ SOAPElement isactive = (SOAPElement) element.getLastChild().getLastChild();
if ("ACTIVE".equalsIgnoreCase(isactive.getValue())) {
try {
DataSource dsModel = new DataSource();
- SOAPElement reInfo = (SOAPElement) dsList.next();
- SOAPElement dsMetaInfo = (SOAPElement)reInfo.getFirstChild();
+ //SOAPElement reInfo = (SOAPElement) element;
+ SOAPElement dsMetaInfo = (SOAPElement)element.getFirstChild();
SOAPElement dsName = (SOAPElement) dsMetaInfo
.getElementsByTagNameNS( "http://services.core.ndatasource.carbon.wso2.org/xsd",
"name").item(0);
dsModel.setName(dsName.getValue());
SOAPElement dsDefinition = (SOAPElement) dsMetaInfo.getFirstChild();
SOAPElement dsType = (SOAPElement) dsDefinition
.getElementsByTagNameNS(
"http://services.core.ndatasource.carbon.wso2.org/xsd",
"type").item(0);
dsModel.setType(dsType.getValue());
SOAPElement dsXMLConfiguration = (SOAPElement) dsDefinition
.getFirstChild();
Map<String, String> dbconfig = new HashMap<String, String>();
String xmlSource = dsXMLConfiguration.getValue();
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory
.newDocumentBuilder();
Document doc = builder.parse(new InputSource(
new StringReader(xmlSource)));
Node firstChild = doc.getFirstChild();
NodeList childNodes = firstChild.getChildNodes();
for (int temp = 0; temp < childNodes.getLength(); temp++) {
Node nNode = childNodes.item(temp);
Element eElement = (Element) nNode;
dbconfig.put(eElement.getNodeName(),
eElement.getTextContent());
}
dsModel.setConfig(dbconfig);
dsModels.add(dsModel);
} catch (Exception e) {
log.error("DataSource Response msg processing error",e);
}
}
}
applicationInfo.setDatasources(dsModels);
} catch (IOException e) {
return false;
} catch (SOAPException e) {
return false;
}
}
return true;
}
public boolean setDBInfomation(ApplicationInfo applicationInfo) {
String respond;
Map<String, String> params;
JsonElement jelement;
params = new HashMap<String, String>();
params.put("action", JagApiProperties.App_DB_INFO_ACTION);
params.put("applicationKey", applicationInfo.getKey());
respond = HttpsJaggeryClient.httpPost(
JagApiProperties.getAppUserDbInfoUrl(), params);
if ("false".equals(respond)) {
return false;
} else {
jelement = new JsonParser().parse(respond);
JsonArray infoArray2 = jelement.getAsJsonArray();
ArrayList<AppDBinfo> appDbList = new ArrayList<AppDBinfo>();
for (JsonElement jsonElement3 : infoArray2) {
JsonObject asJsonObject = jsonElement3.getAsJsonObject();
String stage = asJsonObject.get("stage").getAsString();
if("Development".equals(stage)){
AppDBinfo appDBinfo = new AppDBinfo();
JsonArray dbArray = asJsonObject.get("dbs").getAsJsonArray();
List<Map<String,String>> dbs = new ArrayList<Map<String,String>>();
for (JsonElement jsonElement : dbArray) {
HashMap<String, String> dbInfo = new HashMap<String, String>();
dbInfo.put("dbName",jsonElement.getAsJsonObject().get("dbName").getAsString());
dbInfo.put("url",jsonElement.getAsJsonObject().get("url").getAsString());
dbs.add(dbInfo);
}
appDBinfo.setDbs(dbs);
JsonArray dbusers = asJsonObject.get("users").getAsJsonArray();
List<String> usr = new ArrayList<String>();
for (JsonElement jsonElement : dbusers) {
usr.add(jsonElement.getAsJsonObject().get("name").getAsString());
}
appDBinfo.setUsr(usr);
JsonArray dbtemplates = asJsonObject.get("templates").getAsJsonArray();
List<String> temple = new ArrayList<String>();
for (JsonElement jsonElement : dbtemplates) {
temple.add(jsonElement.getAsJsonObject().get("name").getAsString());
}
appDBinfo.setUsr(temple);
appDbList.add(appDBinfo);
}
}
applicationInfo.setDatabases(appDbList);
return true;
}
}
}
| false | true | public boolean setDSInfomation(ApplicationInfo applicationInfo) {
String respond;
Map<String, String> params;
params = new HashMap<String, String>();
params.put("action", JagApiProperties.App_DS_INFO_ACTION);
params.put("stage", "Development");
respond = HttpsJaggeryClient.httpPost(
JagApiProperties.getAppDsInfoUrl(), params);
if ("false".equals(respond)) {
return false;
} else {
RssClient.getDBinfo("reloadAllDataSources", respond);
String dsinfo = RssClient.getDBinfo("getAllDataSources", respond);
if (dsinfo == null) {
return false;
}
try {
List<DataSource> dsModels = new ArrayList<DataSource>();
InputStream is = new ByteArrayInputStream(dsinfo.getBytes());
SOAPMessage msg = MessageFactory.newInstance().createMessage(null, is);
SOAPBody soapBody = msg.getSOAPBody();
SOAPElement allDataSources = (SOAPElement) soapBody.getFirstChild();
@SuppressWarnings("unchecked")
Iterator<SOAPElement> dsList = allDataSources.getChildElements();
while (dsList.hasNext()) {
SOAPElement isactive = (SOAPElement) dsList.next().getLastChild().getLastChild();
if ("ACTIVE".equalsIgnoreCase(isactive.getValue())) {
try {
DataSource dsModel = new DataSource();
SOAPElement reInfo = (SOAPElement) dsList.next();
SOAPElement dsMetaInfo = (SOAPElement)reInfo.getFirstChild();
SOAPElement dsName = (SOAPElement) dsMetaInfo
.getElementsByTagNameNS( "http://services.core.ndatasource.carbon.wso2.org/xsd",
"name").item(0);
dsModel.setName(dsName.getValue());
SOAPElement dsDefinition = (SOAPElement) dsMetaInfo.getFirstChild();
SOAPElement dsType = (SOAPElement) dsDefinition
.getElementsByTagNameNS(
"http://services.core.ndatasource.carbon.wso2.org/xsd",
"type").item(0);
dsModel.setType(dsType.getValue());
SOAPElement dsXMLConfiguration = (SOAPElement) dsDefinition
.getFirstChild();
Map<String, String> dbconfig = new HashMap<String, String>();
String xmlSource = dsXMLConfiguration.getValue();
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory
.newDocumentBuilder();
Document doc = builder.parse(new InputSource(
new StringReader(xmlSource)));
Node firstChild = doc.getFirstChild();
NodeList childNodes = firstChild.getChildNodes();
for (int temp = 0; temp < childNodes.getLength(); temp++) {
Node nNode = childNodes.item(temp);
Element eElement = (Element) nNode;
dbconfig.put(eElement.getNodeName(),
eElement.getTextContent());
}
dsModel.setConfig(dbconfig);
dsModels.add(dsModel);
} catch (Exception e) {
log.error("DataSource Response msg processing error",e);
}
}
}
applicationInfo.setDatasources(dsModels);
} catch (IOException e) {
return false;
} catch (SOAPException e) {
return false;
}
}
return true;
}
| public boolean setDSInfomation(ApplicationInfo applicationInfo) {
String respond;
Map<String, String> params;
params = new HashMap<String, String>();
params.put("action", JagApiProperties.App_DS_INFO_ACTION);
params.put("stage", "Development");
respond = HttpsJaggeryClient.httpPost(
JagApiProperties.getAppDsInfoUrl(), params);
if ("false".equals(respond)) {
return false;
} else {
RssClient.getDBinfo("reloadAllDataSources", respond);
String dsinfo = RssClient.getDBinfo("getAllDataSources", respond);
if (dsinfo == null) {
return false;
}
try {
List<DataSource> dsModels = new ArrayList<DataSource>();
InputStream is = new ByteArrayInputStream(dsinfo.getBytes());
SOAPMessage msg = MessageFactory.newInstance().createMessage(null, is);
SOAPBody soapBody = msg.getSOAPBody();
SOAPElement allDataSources = (SOAPElement) soapBody.getFirstChild();
@SuppressWarnings("unchecked")
Iterator<SOAPElement> dsList = allDataSources.getChildElements();
while (dsList.hasNext()) {
SOAPElement element = dsList.next();
SOAPElement isactive = (SOAPElement) element.getLastChild().getLastChild();
if ("ACTIVE".equalsIgnoreCase(isactive.getValue())) {
try {
DataSource dsModel = new DataSource();
//SOAPElement reInfo = (SOAPElement) element;
SOAPElement dsMetaInfo = (SOAPElement)element.getFirstChild();
SOAPElement dsName = (SOAPElement) dsMetaInfo
.getElementsByTagNameNS( "http://services.core.ndatasource.carbon.wso2.org/xsd",
"name").item(0);
dsModel.setName(dsName.getValue());
SOAPElement dsDefinition = (SOAPElement) dsMetaInfo.getFirstChild();
SOAPElement dsType = (SOAPElement) dsDefinition
.getElementsByTagNameNS(
"http://services.core.ndatasource.carbon.wso2.org/xsd",
"type").item(0);
dsModel.setType(dsType.getValue());
SOAPElement dsXMLConfiguration = (SOAPElement) dsDefinition
.getFirstChild();
Map<String, String> dbconfig = new HashMap<String, String>();
String xmlSource = dsXMLConfiguration.getValue();
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory
.newDocumentBuilder();
Document doc = builder.parse(new InputSource(
new StringReader(xmlSource)));
Node firstChild = doc.getFirstChild();
NodeList childNodes = firstChild.getChildNodes();
for (int temp = 0; temp < childNodes.getLength(); temp++) {
Node nNode = childNodes.item(temp);
Element eElement = (Element) nNode;
dbconfig.put(eElement.getNodeName(),
eElement.getTextContent());
}
dsModel.setConfig(dbconfig);
dsModels.add(dsModel);
} catch (Exception e) {
log.error("DataSource Response msg processing error",e);
}
}
}
applicationInfo.setDatasources(dsModels);
} catch (IOException e) {
return false;
} catch (SOAPException e) {
return false;
}
}
return true;
}
|
diff --git a/modules/logger/src/main/java/org/novelang/logger/ConsoleLogger.java b/modules/logger/src/main/java/org/novelang/logger/ConsoleLogger.java
index 88ed7aa4..9ee15128 100644
--- a/modules/logger/src/main/java/org/novelang/logger/ConsoleLogger.java
+++ b/modules/logger/src/main/java/org/novelang/logger/ConsoleLogger.java
@@ -1,65 +1,65 @@
/*
* Copyright (C) 2008 Laurent Caillette
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.novelang.logger;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* A simplistic implementation.
*
* @author Laurent Caillette
*/
public final class ConsoleLogger extends AbstractLogger {
private ConsoleLogger() { }
public static final ConsoleLogger INSTANCE = new ConsoleLogger() ;
@Override
protected void log( final Level level, final String message, final Throwable throwable ) {
final String stackTrace ;
if( throwable == null ) {
stackTrace = "" ;
} else {
final StringWriter stringWriter = new StringWriter() ;
throwable.printStackTrace( new PrintWriter( stringWriter ) ) ;
stackTrace = stringWriter.toString() ;
}
- System.err.println( "[" + level + "] " + ( message == null ? "" : message ) + stackTrace ) ;
+ System.out.println( "[" + level + "] " + ( message == null ? "" : message ) + stackTrace ) ;
}
@Override
public String getName() {
return getClass().getSimpleName() ;
}
@Override
public boolean isTraceEnabled() {
return false ;
}
@Override
public boolean isDebugEnabled() {
return false ;
}
@Override
public boolean isInfoEnabled() {
return true ;
}
}
| true | true | protected void log( final Level level, final String message, final Throwable throwable ) {
final String stackTrace ;
if( throwable == null ) {
stackTrace = "" ;
} else {
final StringWriter stringWriter = new StringWriter() ;
throwable.printStackTrace( new PrintWriter( stringWriter ) ) ;
stackTrace = stringWriter.toString() ;
}
System.err.println( "[" + level + "] " + ( message == null ? "" : message ) + stackTrace ) ;
}
| protected void log( final Level level, final String message, final Throwable throwable ) {
final String stackTrace ;
if( throwable == null ) {
stackTrace = "" ;
} else {
final StringWriter stringWriter = new StringWriter() ;
throwable.printStackTrace( new PrintWriter( stringWriter ) ) ;
stackTrace = stringWriter.toString() ;
}
System.out.println( "[" + level + "] " + ( message == null ? "" : message ) + stackTrace ) ;
}
|
diff --git a/mes-plugins/mes-plugins-operational-tasks-for-orders/src/main/java/com/qcadoo/mes/operationalTasksForOrders/hooks/OrderHooksOTFO.java b/mes-plugins/mes-plugins-operational-tasks-for-orders/src/main/java/com/qcadoo/mes/operationalTasksForOrders/hooks/OrderHooksOTFO.java
index c8fb79697e..ca454ad657 100644
--- a/mes-plugins/mes-plugins-operational-tasks-for-orders/src/main/java/com/qcadoo/mes/operationalTasksForOrders/hooks/OrderHooksOTFO.java
+++ b/mes-plugins/mes-plugins-operational-tasks-for-orders/src/main/java/com/qcadoo/mes/operationalTasksForOrders/hooks/OrderHooksOTFO.java
@@ -1,45 +1,46 @@
package com.qcadoo.mes.operationalTasksForOrders.hooks;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qcadoo.mes.operationalTasks.constants.OperationalTasksConstants;
import com.qcadoo.mes.operationalTasks.constants.OperationalTasksFields;
import com.qcadoo.mes.orders.constants.OrderFields;
import com.qcadoo.model.api.DataDefinition;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.search.SearchRestrictions;
@Service
public class OrderHooksOTFO {
@Autowired
private DataDefinitionService dataDefinitionService;
public void changedProductionLine(final DataDefinition dataDefinition, final Entity entity) {
if (entity.getId() == null) {
return;
}
Entity order = dataDefinition.get(entity.getId());
Entity productionLine = entity.getBelongsToField(OrderFields.PRODUCTION_LINE);
Entity orderProductionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE);
- if ((orderProductionLine != null && productionLine == null) || (orderProductionLine == null && productionLine != null)
- || (!orderProductionLine.equals(productionLine))) {
+ if ((orderProductionLine == null && productionLine == null) || orderProductionLine.equals(productionLine)) {
+ return;
+ } else {
changedProductionLineInOperationalTasks(order, productionLine);
}
}
private void changedProductionLineInOperationalTasks(final Entity order, final Entity productionLine) {
DataDefinition operationalTasksDD = dataDefinitionService.get(OperationalTasksConstants.PLUGIN_IDENTIFIER,
OperationalTasksConstants.MODEL_OPERATIONAL_TASK);
List<Entity> operationalTasksList = operationalTasksDD.find().add(SearchRestrictions.belongsTo("order", order)).list()
.getEntities();
for (Entity operationalTask : operationalTasksList) {
operationalTask.setField(OperationalTasksFields.PRODUCTION_LINE, productionLine);
operationalTasksDD.save(operationalTask);
}
}
}
| true | true | public void changedProductionLine(final DataDefinition dataDefinition, final Entity entity) {
if (entity.getId() == null) {
return;
}
Entity order = dataDefinition.get(entity.getId());
Entity productionLine = entity.getBelongsToField(OrderFields.PRODUCTION_LINE);
Entity orderProductionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE);
if ((orderProductionLine != null && productionLine == null) || (orderProductionLine == null && productionLine != null)
|| (!orderProductionLine.equals(productionLine))) {
changedProductionLineInOperationalTasks(order, productionLine);
}
}
| public void changedProductionLine(final DataDefinition dataDefinition, final Entity entity) {
if (entity.getId() == null) {
return;
}
Entity order = dataDefinition.get(entity.getId());
Entity productionLine = entity.getBelongsToField(OrderFields.PRODUCTION_LINE);
Entity orderProductionLine = order.getBelongsToField(OrderFields.PRODUCTION_LINE);
if ((orderProductionLine == null && productionLine == null) || orderProductionLine.equals(productionLine)) {
return;
} else {
changedProductionLineInOperationalTasks(order, productionLine);
}
}
|
diff --git a/clients/java/src/test/java/com/thoughtworks/selenium/ClientDriverSuite.java b/clients/java/src/test/java/com/thoughtworks/selenium/ClientDriverSuite.java
index cd28a72b..925aad3d 100644
--- a/clients/java/src/test/java/com/thoughtworks/selenium/ClientDriverSuite.java
+++ b/clients/java/src/test/java/com/thoughtworks/selenium/ClientDriverSuite.java
@@ -1,111 +1,111 @@
/*
* Created on Feb 25, 2006
*
*/
package com.thoughtworks.selenium;
import junit.extensions.*;
import junit.framework.*;
import org.openqa.selenium.server.*;
import com.thoughtworks.selenium.corebased.*;
/** The wrapper test suite for these tests, which spawns an in-process Selenium Server
* for simple integration testing.
*
* <p>Normally, users should start the Selenium Server
* out-of-process, and just leave it up and running, available for the tests to use.
* But, if you like, you can do what we do here and start a Selenium Server before
* launching the tests.</p>
*
* <p>Note that we don't recommend starting and stopping the
* entire server during each test's setUp and tearDown for these Integration tests;
* it shouldn't be necessary, and doing so may conceal bugs in the server.</p>
*
*
* @author Dan Fabulich
*
*/
public class ClientDriverSuite extends TestSuite{
/** Construct a test suite containing the other integration tests,
* wrapping them up in a TestSetup object that will launch the Selenium
* Server in-proc.
* @return a test suite containing tests to run
*/
public static Test suite() {
try {
ClientDriverSuite supersuite = new ClientDriverSuite();
ClientDriverSuite suite = new ClientDriverSuite();
suite.addTest(I18nTest.suite());
- suite.addTestSuite(ApacheMyFacesSuggestTest.class);
+ //suite.addTestSuite(ApacheMyFacesSuggestTest.class); disabled pending DOJO combobox trouble issue resolution
suite.addTestSuite(RealDealIntegrationTest.class);
suite.addTestSuite(TestErrorChecking.class);
suite.addTestSuite(TestJavascriptParameters.class);
suite.addTestSuite(TestClick.class);
suite.addTestSuite(TestCheckUncheck.class);
suite.addTestSuite(TestClick.class);
suite.addTestSuite(TestXPathLocators.class);
suite.addTestSuite(TestClickJavascriptHref.class);
suite.addTestSuite(TestCommandError.class);
suite.addTestSuite(TestComments.class);
suite.addTestSuite(TestFailingAssert.class);
suite.addTestSuite(TestFailingVerifications.class);
suite.addTestSuite(TestFocusOnBlur.class);
//suite.addTestSuite(TestGoBack.class); pending http://jira.openqa.org/browse/SRC-52
suite.addTestSuite(TestImplicitLocators.class);
suite.addTestSuite(TestLocators.class);
suite.addTestSuite(TestOpen.class);
suite.addTestSuite(TestPatternMatching.class);
suite.addTestSuite(TestPause.class);
suite.addTestSuite(TestStore.class);
suite.addTestSuite(TestSubmit.class);
suite.addTestSuite(TestType.class);
suite.addTestSuite(TestVerifications.class);
ClientDriverTestSetup setup = new ClientDriverTestSetup(suite);
supersuite.addTest(setup);
return supersuite;
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
}
/** A TestSetup decorator that runs a super setUp and tearDown at the
* beginning and end of the entire run: in this case, we use it to
* startup and shutdown the in-process Selenium Server.
*
*
* @author danielf
*
*/
static class ClientDriverTestSetup extends TestSetup {
SeleniumServer server;
public ClientDriverTestSetup(Test test) {
super(test);
}
public void setUp() throws Exception {
try {
server = new SeleniumServer(SeleniumServer.DEFAULT_PORT);
System.out.println("Starting the Selenium Server as part of global setup...");
server.start();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public void tearDown() throws Exception {
try {
server.stop();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
}
| true | true | public static Test suite() {
try {
ClientDriverSuite supersuite = new ClientDriverSuite();
ClientDriverSuite suite = new ClientDriverSuite();
suite.addTest(I18nTest.suite());
suite.addTestSuite(ApacheMyFacesSuggestTest.class);
suite.addTestSuite(RealDealIntegrationTest.class);
suite.addTestSuite(TestErrorChecking.class);
suite.addTestSuite(TestJavascriptParameters.class);
suite.addTestSuite(TestClick.class);
suite.addTestSuite(TestCheckUncheck.class);
suite.addTestSuite(TestClick.class);
suite.addTestSuite(TestXPathLocators.class);
suite.addTestSuite(TestClickJavascriptHref.class);
suite.addTestSuite(TestCommandError.class);
suite.addTestSuite(TestComments.class);
suite.addTestSuite(TestFailingAssert.class);
suite.addTestSuite(TestFailingVerifications.class);
suite.addTestSuite(TestFocusOnBlur.class);
//suite.addTestSuite(TestGoBack.class); pending http://jira.openqa.org/browse/SRC-52
suite.addTestSuite(TestImplicitLocators.class);
suite.addTestSuite(TestLocators.class);
suite.addTestSuite(TestOpen.class);
suite.addTestSuite(TestPatternMatching.class);
suite.addTestSuite(TestPause.class);
suite.addTestSuite(TestStore.class);
suite.addTestSuite(TestSubmit.class);
suite.addTestSuite(TestType.class);
suite.addTestSuite(TestVerifications.class);
ClientDriverTestSetup setup = new ClientDriverTestSetup(suite);
supersuite.addTest(setup);
return supersuite;
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
}
| public static Test suite() {
try {
ClientDriverSuite supersuite = new ClientDriverSuite();
ClientDriverSuite suite = new ClientDriverSuite();
suite.addTest(I18nTest.suite());
//suite.addTestSuite(ApacheMyFacesSuggestTest.class); disabled pending DOJO combobox trouble issue resolution
suite.addTestSuite(RealDealIntegrationTest.class);
suite.addTestSuite(TestErrorChecking.class);
suite.addTestSuite(TestJavascriptParameters.class);
suite.addTestSuite(TestClick.class);
suite.addTestSuite(TestCheckUncheck.class);
suite.addTestSuite(TestClick.class);
suite.addTestSuite(TestXPathLocators.class);
suite.addTestSuite(TestClickJavascriptHref.class);
suite.addTestSuite(TestCommandError.class);
suite.addTestSuite(TestComments.class);
suite.addTestSuite(TestFailingAssert.class);
suite.addTestSuite(TestFailingVerifications.class);
suite.addTestSuite(TestFocusOnBlur.class);
//suite.addTestSuite(TestGoBack.class); pending http://jira.openqa.org/browse/SRC-52
suite.addTestSuite(TestImplicitLocators.class);
suite.addTestSuite(TestLocators.class);
suite.addTestSuite(TestOpen.class);
suite.addTestSuite(TestPatternMatching.class);
suite.addTestSuite(TestPause.class);
suite.addTestSuite(TestStore.class);
suite.addTestSuite(TestSubmit.class);
suite.addTestSuite(TestType.class);
suite.addTestSuite(TestVerifications.class);
ClientDriverTestSetup setup = new ClientDriverTestSetup(suite);
supersuite.addTest(setup);
return supersuite;
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
}
|
diff --git a/workspace/org.grammaticalframework.eclipse/src/org/grammaticalframework/eclipse/builder/GFBuilder.java b/workspace/org.grammaticalframework.eclipse/src/org/grammaticalframework/eclipse/builder/GFBuilder.java
index 1a5d810c..31c7daac 100644
--- a/workspace/org.grammaticalframework.eclipse/src/org/grammaticalframework/eclipse/builder/GFBuilder.java
+++ b/workspace/org.grammaticalframework.eclipse/src/org/grammaticalframework/eclipse/builder/GFBuilder.java
@@ -1,297 +1,297 @@
package org.grammaticalframework.eclipse.builder;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.grammaticalframework.eclipse.GFPreferences;
/**
* Custom GF builder, yeah!
* Some refs..
* http://wiki.eclipse.org/FAQ_How_do_I_implement_an_incremental_project_builder%3F
* http://www.eclipse.org/articles/Article-Builders/builders.html
*
* TODO Adding of markers to files
* TODO Should this class actually be moved to the UI plugin?
* TODO Support for monitor, when building takes a long time (progress, cancellation)
*
* @author John J. Camilleri
*
*/
public class GFBuilder extends IncrementalProjectBuilder {
public static final String BUILDER_ID = "org.grammaticalframework.eclipse.ui.build.GFBuilderID"; //$NON-NLS-1$
public static final String BUILD_FOLDER = ".gfbuild"; //$NON-NLS-1$
public static final Boolean USE_INDIVIDUAL_FOLDERS = false;
private String gfPath;
private String defaultGFPath = "/home/john/.cabal/bin/gf"; // TODO hardcoded just for testing!
private boolean showDebug = false;
private void log(String msg) {
if (showDebug)
System.out.println(msg);
}
@Override
protected IProject[] build(int kind, Map<String, String> args, IProgressMonitor monitor) throws CoreException {
// Get some prefs
IPreferencesService prefs = Platform.getPreferencesService();
showDebug = prefs.getBoolean(GFPreferences.QUALIFIER, GFPreferences.SHOW_DEBUG, true, null);
gfPath = prefs.getString(GFPreferences.QUALIFIER, GFPreferences.GF_BIN_PATH, defaultGFPath, null);
if (gfPath == null || gfPath.trim().isEmpty()) {
log("Error during build: GF path not specified.");
return null;
}
if (kind == IncrementalProjectBuilder.FULL_BUILD) {
fullBuild(monitor);
} else {
IResourceDelta delta = getDelta(getProject());
if (delta == null) {
fullBuild(monitor);
} else {
incrementalBuild(delta, monitor);
}
}
return null;
}
private void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) {
log("Incremental build on " + delta);
try {
delta.accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta) {
IResource resource = delta.getResource();
int kind = delta.getKind();
if (kind == IResourceDelta.ADDED || kind == IResourceDelta.CHANGED) {
if (shouldBuild(resource)) {
if (USE_INDIVIDUAL_FOLDERS) {
cleanFile((IFile) resource);
}
if (buildFile((IFile) resource)) {
log(" + " + delta.getResource().getRawLocation());
} else {
log(" > Failed: " + delta.getResource().getRawLocation());
}
}
}
return true; // visit children too
}
});
getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
} catch (CoreException e) {
e.printStackTrace();
}
}
private void fullBuild(IProgressMonitor monitor) throws CoreException {
log("Full build on " + getProject().getName());
recursiveDispatcher(getProject().members(), new CallableOnResource() {
public void call(IResource resource) {
if (shouldBuild(resource)) {
if (buildFile((IFile) resource)) {
log(" + " + resource.getName());
} else {
log(" > Failed: " + resource.getName());
}
}
}
});
getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
@Override
protected void clean(final IProgressMonitor monitor) throws CoreException {
IPreferencesService prefs = Platform.getPreferencesService();
showDebug = prefs.getBoolean(GFPreferences.QUALIFIER, GFPreferences.SHOW_DEBUG, true, null);
log("Clean " + getProject().getName());
// TODO Delete markers with getProject().deleteMarkers()
recursiveDispatcher(getProject().members(), new CallableOnResource() {
public void call(IResource resource) {
if (resource.getType() == IResource.FILE && resource.getFileExtension().equals("gfh")) {
try {
resource.delete(true, monitor);
log(" - " + resource.getName());
} catch (CoreException e) {
log(" > Failed: " + resource.getName());
e.printStackTrace();
}
}
}
});
}
/**
* For recursively applying a function to an IResource
*
*/
interface CallableOnResource {
public void call(IResource resource);
}
private void recursiveDispatcher(IResource[] res, CallableOnResource func) {
try {
for (IResource r : res) {
if (r.getType() == IResource.FOLDER) {
recursiveDispatcher(((IFolder)r).members(), func);
} else {
func.call(r);
}
}
} catch (CoreException e) {
e.printStackTrace();
}
}
/**
* Determine if a resource should be built, based on its properties
* @param resource
* @return
*/
private boolean shouldBuild(IResource resource) {
return resource.getType() == IResource.FILE && resource.getFileExtension().equals("gf");
}
private String getBuildDirectory(IFile file) {
String filename = file.getName();
if (USE_INDIVIDUAL_FOLDERS) {
return file.getRawLocation().removeLastSegments(1).toOSString()
+ java.io.File.separator
+ BUILD_FOLDER
+ java.io.File.separator
+ filename
+ java.io.File.separator;
} else {
return file.getRawLocation().removeLastSegments(1).toOSString()
+ java.io.File.separator
+ BUILD_FOLDER
+ java.io.File.separator;
}
}
/**
* For a single .gf file, compile it with GF and run "ss -strip -save" to
* capture all the GF headers in the build subfolder.
*
* TODO Share a single process for the whole build cycle to save on overheads
* @param file
*/
private boolean buildFile(IFile file) {
/*
* We want to compile each source file in .gf with these commands:
* i --retain HelloEng.gf
* ss -strip -save
*
* Shell command: echo "ss -strip -save" | gf -retain HelloEng.gf
*/
String filename = file.getName();
String buildDir = getBuildDirectory(file);
ArrayList<String> command = new ArrayList<String>();
command.add(gfPath);
command.add("--retain");
if (USE_INDIVIDUAL_FOLDERS) {
command.add(String.format("..%1$s..%1$s%2$s", java.io.File.separator, filename));
} else {
command.add(".." + java.io.File.separator + filename);
}
try {
// Check the build directory and try to create it
File buildDirFile = new File(buildDir);
if (!buildDirFile.exists()) {
buildDirFile.mkdir();
}
// Piece together our GF process
ProcessBuilder b = new ProcessBuilder(command);
b.directory(buildDirFile);
// b.redirectErrorStream(true);
Process process = b.start();
// Feed it our commands, then quit
BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
processInput.write("ss -strip -save");
processInput.newLine();
processInput.flush();
processInput.write("quit");
processInput.newLine();
processInput.flush();
// BufferedReader processError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String err_str;
// while ((err_str = processError.readLine()) != null) {
-// System.out.println(err_str);
+// log(err_str);
// }
BufferedReader processOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String out_str;
while ((out_str = processOutput.readLine()) != null) {
- System.out.println(out_str);
+ log(out_str);
}
// Tidy up
processInput.close();
// processOutput.close();
process.waitFor();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
/**
* Clean all the files in the build directory for a given file
*
* @param file
* @return
*/
private void cleanFile(IFile file) {
log(" Cleaning build directory for " + file.getName());
String buildDir = getBuildDirectory(file);
// Check the build directory and try to create it
File buildDirFile = new File(buildDir);
if (buildDirFile.exists()) {
File[] files = buildDirFile.listFiles();
for (File f : files) {
try {
f.delete();
log(" - " + f.getName());
} catch (Exception _) {
log(" > Failed: " + f.getName());
}
}
}
}
}
| false | true | private boolean buildFile(IFile file) {
/*
* We want to compile each source file in .gf with these commands:
* i --retain HelloEng.gf
* ss -strip -save
*
* Shell command: echo "ss -strip -save" | gf -retain HelloEng.gf
*/
String filename = file.getName();
String buildDir = getBuildDirectory(file);
ArrayList<String> command = new ArrayList<String>();
command.add(gfPath);
command.add("--retain");
if (USE_INDIVIDUAL_FOLDERS) {
command.add(String.format("..%1$s..%1$s%2$s", java.io.File.separator, filename));
} else {
command.add(".." + java.io.File.separator + filename);
}
try {
// Check the build directory and try to create it
File buildDirFile = new File(buildDir);
if (!buildDirFile.exists()) {
buildDirFile.mkdir();
}
// Piece together our GF process
ProcessBuilder b = new ProcessBuilder(command);
b.directory(buildDirFile);
// b.redirectErrorStream(true);
Process process = b.start();
// Feed it our commands, then quit
BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
processInput.write("ss -strip -save");
processInput.newLine();
processInput.flush();
processInput.write("quit");
processInput.newLine();
processInput.flush();
// BufferedReader processError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String err_str;
// while ((err_str = processError.readLine()) != null) {
// System.out.println(err_str);
// }
BufferedReader processOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String out_str;
while ((out_str = processOutput.readLine()) != null) {
System.out.println(out_str);
}
// Tidy up
processInput.close();
// processOutput.close();
process.waitFor();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
| private boolean buildFile(IFile file) {
/*
* We want to compile each source file in .gf with these commands:
* i --retain HelloEng.gf
* ss -strip -save
*
* Shell command: echo "ss -strip -save" | gf -retain HelloEng.gf
*/
String filename = file.getName();
String buildDir = getBuildDirectory(file);
ArrayList<String> command = new ArrayList<String>();
command.add(gfPath);
command.add("--retain");
if (USE_INDIVIDUAL_FOLDERS) {
command.add(String.format("..%1$s..%1$s%2$s", java.io.File.separator, filename));
} else {
command.add(".." + java.io.File.separator + filename);
}
try {
// Check the build directory and try to create it
File buildDirFile = new File(buildDir);
if (!buildDirFile.exists()) {
buildDirFile.mkdir();
}
// Piece together our GF process
ProcessBuilder b = new ProcessBuilder(command);
b.directory(buildDirFile);
// b.redirectErrorStream(true);
Process process = b.start();
// Feed it our commands, then quit
BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
processInput.write("ss -strip -save");
processInput.newLine();
processInput.flush();
processInput.write("quit");
processInput.newLine();
processInput.flush();
// BufferedReader processError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String err_str;
// while ((err_str = processError.readLine()) != null) {
// log(err_str);
// }
BufferedReader processOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String out_str;
while ((out_str = processOutput.readLine()) != null) {
log(out_str);
}
// Tidy up
processInput.close();
// processOutput.close();
process.waitFor();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
|
diff --git a/src/me/ThaH3lper/com/SkillsCollection/SkillShootProjectile.java b/src/me/ThaH3lper/com/SkillsCollection/SkillShootProjectile.java
index 4adc8c4..5e89022 100644
--- a/src/me/ThaH3lper/com/SkillsCollection/SkillShootProjectile.java
+++ b/src/me/ThaH3lper/com/SkillsCollection/SkillShootProjectile.java
@@ -1,68 +1,67 @@
package me.ThaH3lper.com.SkillsCollection;
import me.ThaH3lper.com.EpicBoss;
import me.ThaH3lper.com.Skills.SkillHandler;
import org.bukkit.Effect;
import org.bukkit.craftbukkit.v1_6_R3.CraftWorld;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Egg;
import org.bukkit.entity.EnderPearl;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Snowball;
import org.bukkit.metadata.FixedMetadataValue;
public class SkillShootProjectile {
// Shoots a projectile
// projectile type:damage:velocity
// type can be arrow, snowball, egg, or enderpearl
public static void ExecuteShoot(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))
{
String projectileType = data[0];
int damage = Integer.parseInt(data[1]);
float velocity = Float.parseFloat(data[2]);
Projectile projectile;
if (projectileType.equalsIgnoreCase("arrow")) {
projectile = l.launchProjectile(Arrow.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("snowball")) {
projectile = l.launchProjectile(Snowball.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("egg")) {
projectile = l.launchProjectile(Egg.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("enderpearl")) {
projectile = l.launchProjectile(EnderPearl.class);
((CraftWorld) l.getLocation().getWorld()).getHandle().makeSound(l.getLocation().getX(), l.getLocation().getY(), l.getLocation().getZ(), "mob.endermen.portal", 1, (float)0.5);
} else {
projectile = l.launchProjectile(Arrow.class);
}
projectile.setVelocity(l.getLocation().getDirection().multiply(velocity));
projectile.setBounce(false);
projectile.setShooter(l);
projectile.setMetadata("EpicBossProjectile", new FixedMetadataValue(EpicBoss.plugin, new ProjectileData(damage)));
- EpicBoss.plugin.logger.info("Projectile Fired!");
}
}
}
public static class ProjectileData {
public int damage;
public ProjectileData(int damage) {
this.damage = damage;
}
}
}
| true | true | public static void ExecuteShoot(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))
{
String projectileType = data[0];
int damage = Integer.parseInt(data[1]);
float velocity = Float.parseFloat(data[2]);
Projectile projectile;
if (projectileType.equalsIgnoreCase("arrow")) {
projectile = l.launchProjectile(Arrow.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("snowball")) {
projectile = l.launchProjectile(Snowball.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("egg")) {
projectile = l.launchProjectile(Egg.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("enderpearl")) {
projectile = l.launchProjectile(EnderPearl.class);
((CraftWorld) l.getLocation().getWorld()).getHandle().makeSound(l.getLocation().getX(), l.getLocation().getY(), l.getLocation().getZ(), "mob.endermen.portal", 1, (float)0.5);
} else {
projectile = l.launchProjectile(Arrow.class);
}
projectile.setVelocity(l.getLocation().getDirection().multiply(velocity));
projectile.setBounce(false);
projectile.setShooter(l);
projectile.setMetadata("EpicBossProjectile", new FixedMetadataValue(EpicBoss.plugin, new ProjectileData(damage)));
EpicBoss.plugin.logger.info("Projectile Fired!");
}
}
}
| public static void ExecuteShoot(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))
{
String projectileType = data[0];
int damage = Integer.parseInt(data[1]);
float velocity = Float.parseFloat(data[2]);
Projectile projectile;
if (projectileType.equalsIgnoreCase("arrow")) {
projectile = l.launchProjectile(Arrow.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("snowball")) {
projectile = l.launchProjectile(Snowball.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("egg")) {
projectile = l.launchProjectile(Egg.class);
l.getWorld().playEffect(l.getLocation(), Effect.BOW_FIRE, 0);
} else if (projectileType.equalsIgnoreCase("enderpearl")) {
projectile = l.launchProjectile(EnderPearl.class);
((CraftWorld) l.getLocation().getWorld()).getHandle().makeSound(l.getLocation().getX(), l.getLocation().getY(), l.getLocation().getZ(), "mob.endermen.portal", 1, (float)0.5);
} else {
projectile = l.launchProjectile(Arrow.class);
}
projectile.setVelocity(l.getLocation().getDirection().multiply(velocity));
projectile.setBounce(false);
projectile.setShooter(l);
projectile.setMetadata("EpicBossProjectile", new FixedMetadataValue(EpicBoss.plugin, new ProjectileData(damage)));
}
}
}
|
diff --git a/src/net/slipcor/pvparena/managers/SpawnManager.java b/src/net/slipcor/pvparena/managers/SpawnManager.java
index f8eaedec..2019de96 100644
--- a/src/net/slipcor/pvparena/managers/SpawnManager.java
+++ b/src/net/slipcor/pvparena/managers/SpawnManager.java
@@ -1,335 +1,335 @@
package net.slipcor.pvparena.managers;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import net.slipcor.pvparena.PVPArena;
import net.slipcor.pvparena.arena.Arena;
import net.slipcor.pvparena.arena.ArenaPlayer;
import net.slipcor.pvparena.arena.ArenaTeam;
import net.slipcor.pvparena.classes.PABlockLocation;
import net.slipcor.pvparena.classes.PALocation;
import net.slipcor.pvparena.core.Config;
import net.slipcor.pvparena.core.Debug;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
* <pre>Spawn Manager class</pre>
*
* Provides static methods to manage Spawns
*
* @author slipcor
*
* @version v0.9.1
*/
public class SpawnManager {
private static Debug db = new Debug(27);
public static HashSet<PABlockLocation> getBlocks(Arena arena, String sTeam) {
db.i("reading blocks of arena " + arena + " (" + sTeam + ")");
HashSet<PABlockLocation> result = new HashSet<PABlockLocation>();
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (sTeam.equals("flags")) {
if (!name.startsWith("flag")) {
continue;
}
} else if (name.endsWith("flag")) {
String sName = sTeam.replace("flag", "");
db.i("checking if " + name + " starts with " + sName);
if (!name.startsWith(sName)) {
continue;
}
} else if (sTeam.equals("free")) {
if (!name.startsWith("spawn")) {
continue;
}
} else if (name.contains("lounge")) {
continue;
} else if (sTeam.endsWith("flag") || sTeam.endsWith("pumpkin")) {
continue;
}
db.i(" - " + name);
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + name));
result.add(Config.parseBlockLocation( sLoc));
}
return result;
}
/**
* get the location from a coord string
*
* @param place
* the coord string
* @return the location of that string
*/
public static PALocation getCoords(Arena arena, String place) {
db.i("get coords: " + place);
if (place.equals("spawn") || place.equals("powerup")) {
HashMap<Integer, String> locs = new HashMap<Integer, String>();
int i = 0;
db.i("searching for spawns");
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (name.startsWith(place)) {
locs.put(i++, name);
db.i("found match: " + name);
}
}
Random r = new Random();
place = locs.get(r.nextInt(locs.size()));
} else if (arena.getArenaConfig().getUnsafe("spawns." + place) == null) {
place = PVPArena.instance.getAgm().guessSpawn(arena, place);
if (place == null) {
return null;
}
}
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + place));
db.i("parsing location: " + sLoc);
if (place.contains("flag")) {
- return new PALocation(Config.parseBlockLocation(sLoc).toLocation()).add(0.5, 0.1, 0.5);
+ return new PALocation(Config.parseBlockLocation(sLoc).toLocation()).add(0.5, 1.1, 0.5);
}
- return Config.parseLocation(sLoc).add(0.5, 0.1, 0.5);
+ return Config.parseLocation(sLoc).add(0.5, 1.1, 0.5);
}
/**
* get the nearest spawn location from a location
*
* @param hashSet
* the spawns to check
* @param location
* the location to check
* @return the spawn location next to the location
*/
public static PALocation getNearest(HashSet<PALocation> hashSet,
PALocation location) {
PALocation result = null;
for (PALocation loc : hashSet) {
if (result == null
|| result.getDistance(location) > loc.getDistance(location)) {
result = loc;
}
}
return result;
}
public static PABlockLocation getBlockNearest(HashSet<PABlockLocation> hashSet,
PABlockLocation location) {
PABlockLocation result = null;
for (PABlockLocation loc : hashSet) {
if (result == null
|| result.getDistance(location) > loc.getDistance(location)) {
result = loc;
}
}
return result;
}
/**
* get all (team) spawns of an arena
*
* @param arena
* the arena to check
* @param sTeam
* a team name or "flags" or "[team]pumpkin" or "[team]flag"
* @return a set of possible spawn matches
*/
public static HashSet<PALocation> getSpawns(Arena arena, String sTeam) {
db.i("reading spawns of arena " + arena + " (" + sTeam + ")");
HashSet<PALocation> result = new HashSet<PALocation>();
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (sTeam.equals("flags")) {
if (!name.startsWith("flag")) {
continue;
}
} else if (name.endsWith("flag") || name.endsWith("pumpkin")) {
String sName = sTeam.replace("flag", "");
sName = sName.replace("pumpkin", "");
db.i("checking if " + name + " starts with " + sName);
if (!name.startsWith(sName)) {
continue;
}
} else if (sTeam.equals("free")) {
if (!name.startsWith("spawn")) {
continue;
}
} else if (name.contains("lounge")) {
continue;
} else if (sTeam.endsWith("flag") || sTeam.endsWith("pumpkin")) {
continue;
}
db.i(" - " + name);
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + name));
result.add(Config.parseLocation(sLoc));
}
return result;
}
/**
* calculate the arena center, including all team spawn locations
*
* @param arena
* @return
*/
public static PABlockLocation getRegionCenter(Arena arena) {
HashSet<PALocation> locs = new HashSet<PALocation>();
for (ArenaTeam team : arena.getTeams()) {
String sTeam = team.getName();
for (PALocation loc : getSpawns(arena, sTeam)) {
locs.add(loc);
}
}
long x = 0;
long y = 0;
long z = 0;
for (PALocation loc : locs) {
x += loc.getX();
y += loc.getY();
z += loc.getZ();
}
return new PABlockLocation(arena.getWorld(),(int) x / locs.size(),(int) y / locs.size(),(int) z / locs.size());
}
/**
* is a player near a spawn?
*
* @param arena
* the arena to check
* @param player
* the player to check
* @param diff
* the distance to check
* @return true if the player is near, false otherwise
*/
public static boolean isNearSpawn(Arena arena, Player player, int diff) {
db.i("checking if arena is near a spawn");
if (!arena.hasPlayer(player)) {
return false;
}
ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName());
ArenaTeam team = ap.getArenaTeam();
if (team == null) {
return false;
}
HashSet<PALocation> spawns = getSpawns(arena, team.getName());
for (PALocation loc : spawns) {
if (loc.getDistance(new PALocation(player.getLocation())) <= diff) {
db.i("found near spawn: " + loc.toString());
return true;
}
}
return false;
}
/**
* set an arena coord to a player's position
*
* @param player
* the player saving the coord
* @param place
* the coord name to save the location to
*/
public static void setCoords(Arena arena, Player player, String place) {
// "x,y,z,yaw,pitch"
Location location = player.getLocation();
Integer x = location.getBlockX();
Integer y = location.getBlockY();
Integer z = location.getBlockZ();
Float yaw = location.getYaw();
Float pitch = location.getPitch();
String s = x.toString() + "," + y.toString() + "," + z.toString() + ","
+ yaw.toString() + "," + pitch.toString();
db.i("setting spawn " + place + " to " + s.toString());
arena.getArenaConfig().setManually("spawns." + place, s);
arena.getArenaConfig().save();
}
/**
* set an arena coord to a given location
*
* @param loc
* the location to save
* @param place
* the coord name to save the location to
*/
public static void setCoords(Arena arena, Location loc, String place) {
// "x,y,z,yaw,pitch"
Integer x = loc.getBlockX();
Integer y = loc.getBlockY();
Integer z = loc.getBlockZ();
Float yaw = loc.getYaw();
Float pitch = loc.getPitch();
String s = x.toString() + "," + y.toString() + "," + z.toString() + ","
+ yaw.toString() + "," + pitch.toString();
db.i("setting spawn " + place + " to " + s.toString());
arena.getArenaConfig().setManually("spawns." + place, s);
arena.getArenaConfig().save();
}
/**
* set an arena coord to a given block
*
* @param loc
* the location to save
* @param place
* the coord name to save the location to
*/
public static void setBlock(Arena arena, PABlockLocation loc, String place) {
// "x,y,z,yaw,pitch"
String s = Config.parseToString(loc);
db.i("setting spawn " + place + " to " + s.toString());
arena.getArenaConfig().setManually("spawns." + place, s);
arena.getArenaConfig().save();
}
}
| false | true | public static PALocation getCoords(Arena arena, String place) {
db.i("get coords: " + place);
if (place.equals("spawn") || place.equals("powerup")) {
HashMap<Integer, String> locs = new HashMap<Integer, String>();
int i = 0;
db.i("searching for spawns");
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (name.startsWith(place)) {
locs.put(i++, name);
db.i("found match: " + name);
}
}
Random r = new Random();
place = locs.get(r.nextInt(locs.size()));
} else if (arena.getArenaConfig().getUnsafe("spawns." + place) == null) {
place = PVPArena.instance.getAgm().guessSpawn(arena, place);
if (place == null) {
return null;
}
}
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + place));
db.i("parsing location: " + sLoc);
if (place.contains("flag")) {
return new PALocation(Config.parseBlockLocation(sLoc).toLocation()).add(0.5, 0.1, 0.5);
}
return Config.parseLocation(sLoc).add(0.5, 0.1, 0.5);
}
| public static PALocation getCoords(Arena arena, String place) {
db.i("get coords: " + place);
if (place.equals("spawn") || place.equals("powerup")) {
HashMap<Integer, String> locs = new HashMap<Integer, String>();
int i = 0;
db.i("searching for spawns");
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (name.startsWith(place)) {
locs.put(i++, name);
db.i("found match: " + name);
}
}
Random r = new Random();
place = locs.get(r.nextInt(locs.size()));
} else if (arena.getArenaConfig().getUnsafe("spawns." + place) == null) {
place = PVPArena.instance.getAgm().guessSpawn(arena, place);
if (place == null) {
return null;
}
}
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + place));
db.i("parsing location: " + sLoc);
if (place.contains("flag")) {
return new PALocation(Config.parseBlockLocation(sLoc).toLocation()).add(0.5, 1.1, 0.5);
}
return Config.parseLocation(sLoc).add(0.5, 1.1, 0.5);
}
|
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/ui/video/player/SerenitySurfaceViewVideoActivity.java b/serenity-app/src/main/java/us/nineworlds/serenity/ui/video/player/SerenitySurfaceViewVideoActivity.java
index 8f0ea9a1..ce2f94fe 100644
--- a/serenity-app/src/main/java/us/nineworlds/serenity/ui/video/player/SerenitySurfaceViewVideoActivity.java
+++ b/serenity-app/src/main/java/us/nineworlds/serenity/ui/video/player/SerenitySurfaceViewVideoActivity.java
@@ -1,765 +1,767 @@
/**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package us.nineworlds.serenity.ui.video.player;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.LinkedList;
import org.mozilla.universalchardet.UniversalDetector;
import us.nineworlds.plex.rest.PlexappFactory;
import us.nineworlds.serenity.SerenityApplication;
import us.nineworlds.serenity.core.SerenityConstants;
import us.nineworlds.serenity.core.model.VideoContentInfo;
import us.nineworlds.serenity.core.model.impl.EpisodePosterInfo;
import us.nineworlds.serenity.core.services.CompletedVideoRequest;
import us.nineworlds.serenity.core.services.WatchedVideoAsyncTask;
import us.nineworlds.serenity.core.subtitles.formats.Caption;
import us.nineworlds.serenity.core.subtitles.formats.FormatASS;
import us.nineworlds.serenity.core.subtitles.formats.FormatSRT;
import us.nineworlds.serenity.core.subtitles.formats.TimedTextObject;
import us.nineworlds.serenity.ui.activity.SerenityActivity;
import us.nineworlds.serenity.R;
import com.google.analytics.tracking.android.EasyTracker;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* A view that handles the internal video playback and representation of a movie
* or tv show.
*
* @author dcarver
*
*/
public class SerenitySurfaceViewVideoActivity extends SerenityActivity
implements SurfaceHolder.Callback {
/**
*
*/
static final int PROGRESS_UPDATE_DELAY = 5000;
static final int SUBTITLE_DISPLAY_CHECK = 100;
int playbackPos = 0;
static final String TAG = "SerenitySurfaceViewVideoActivity";
static final int CONTROLLER_DELAY = 16000; // Sixteen seconds
private MediaPlayer mediaPlayer;
private String videoURL;
private SurfaceView surfaceView;
private View videoActivityView;
private MediaController mediaController;
private String aspectRatio;
private String videoId;
private int resumeOffset;
private boolean mediaplayer_error_state = false;
private boolean mediaplayer_released = false;
private String subtitleURL;
private String subtitleType;
private String mediaTagIdentifier;
private TimedTextObject subtitleTimedText;
private boolean subtitlesPlaybackEnabled = true;
private String subtitleInputEncoding = null;
private Handler subtitleDisplayHandler = new Handler();
private Runnable subtitle = new Runnable() {
@Override
public void run() {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
if (hasSubtitles()) {
int currentPos = mediaPlayer.getCurrentPosition();
Collection<Caption> subtitles = subtitleTimedText.captions
.values();
for (Caption caption : subtitles) {
if (currentPos >= caption.start.getMilliseconds()
&& currentPos <= caption.end.getMilliseconds()) {
onTimedText(caption);
break;
} else if (currentPos > caption.end.getMilliseconds()) {
onTimedText(null);
}
}
} else {
subtitlesPlaybackEnabled = false;
Toast.makeText(
getApplicationContext(),
"Invalid or Missing Subtitle. Subtitle playback disabled.",
Toast.LENGTH_LONG).show();
}
}
if (subtitlesPlaybackEnabled) {
subtitleDisplayHandler
.postDelayed(this, SUBTITLE_DISPLAY_CHECK);
}
}
/**
* @return
*/
protected boolean hasSubtitles() {
return subtitleTimedText != null
&& subtitleTimedText.captions != null;
};
};
private Handler progressReportinghandler = new Handler();
private Runnable progressRunnable = new Runnable() {
@Override
public void run() {
try {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
float percentage = Float.valueOf(mediaPlayer.getCurrentPosition()) / Float.valueOf(mediaPlayer.getDuration());
playbackPos = mediaPlayer.getCurrentPosition();
if (percentage <= 90.f) {
new UpdateProgressRequest().execute();
progressReportinghandler.postDelayed(this,
PROGRESS_UPDATE_DELAY); // Update progress every 5
// seconds
} else {
new WatchedVideoAsyncTask().execute(videoId);
}
}
} catch (IllegalStateException ex) {
Log.w(getClass().getName(),
"Illegalstate exception occurred durring progress update. No further updates will occur.",
ex);
}
};
};
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource(videoURL);
mediaPlayer.setOnPreparedListener(new VideoPlayerPrepareListener(
this, mediaPlayer, mediaController, surfaceView,
resumeOffset, videoId, aspectRatio,
progressReportinghandler, progressRunnable, subtitleURL));
mediaPlayer
.setOnCompletionListener(new VideoPlayerOnCompletionListener());
mediaPlayer.prepareAsync();
} catch (Exception ex) {
Log.e(TAG, "Video Playback Error. ", ex);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (!mediaplayer_released) {
mediaPlayer.release();
mediaplayer_released = true;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_playback);
init();
}
/**
* Initialize the mediaplayer and mediacontroller.
*/
protected void init() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new SerenityOnErrorListener());
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
videoActivityView = findViewById(R.id.video_playeback);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("overscan_compensation", false)) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) videoActivityView
.getLayoutParams();
params.setMargins(35, 20, 20, 20);
}
surfaceView.setKeepScreenOn(true);
SurfaceHolder holder = surfaceView.getHolder();
holder.addCallback(this);
holder.setSizeFromLayout();
retrieveIntentExtras();
}
protected void retrieveIntentExtras() {
Bundle extras = getIntent().getExtras();
if (extras == null || extras.isEmpty()) {
playBackFromVideoQueue();
} else {
playbackFromIntent(extras);
}
new SubtitleAsyncTask().execute();
}
private void playbackFromIntent(Bundle extras) {
videoURL = extras.getString("videoUrl");
if (videoURL == null) {
videoURL = extras.getString("encodedvideoUrl");
if (videoURL != null) {
videoURL = URLDecoder.decode(videoURL);
}
}
videoId = extras.getString("id");
String summary = extras.getString("summary");
String title = extras.getString("title");
String posterURL = extras.getString("posterUrl");
aspectRatio = extras.getString("aspectRatio");
String videoFormat = extras.getString("videoFormat");
String videoResolution = extras.getString("videoResolution");
String audioFormat = extras.getString("audioFormat");
String audioChannels = extras.getString("audioChannels");
resumeOffset = extras.getInt("resumeOffset");
subtitleURL = extras.getString("subtitleURL");
subtitleType = extras.getString("subtitleFormat");
mediaTagIdentifier = extras.getString("mediaTagId");
initMediaController(summary, title, posterURL, videoFormat,
videoResolution, audioFormat, audioChannels);
}
private void playBackFromVideoQueue() {
LinkedList<VideoContentInfo> queue = SerenityApplication
.getVideoPlaybackQueue();
if (queue.isEmpty()) {
return;
}
VideoContentInfo video = queue.poll();
videoURL = video.getDirectPlayUrl();
videoId = video.id();
String summary = video.getSummary();
String title = video.getTitle();
String posterURL = video.getImageURL();
;
if (video instanceof EpisodePosterInfo) {
if (video.getParentPosterURL() != null) {
posterURL = video.getParentPosterURL();
}
}
aspectRatio = video.getAspectRatio();
String videoFormat = video.getVideoCodec();
String videoResolution = video.getVideoResolution();
String audioFormat = video.getAudioCodec();
String audioChannels = video.getAudioChannels();
resumeOffset = video.getResumeOffset();
if (video.getSubtitle() != null
&& !"none".equals(video.getSubtitle().getFormat())) {
subtitleURL = video.getSubtitle().getKey();
subtitleType = video.getSubtitle().getFormat();
}
mediaTagIdentifier = video.getMediaTagIdentifier();
initMediaController(summary, title, posterURL, videoFormat,
videoResolution, audioFormat, audioChannels);
}
/**
* @param summary
* @param title
* @param posterURL
* @param videoFormat
* @param videoResolution
* @param audioFormat
* @param audioChannels
*/
protected void initMediaController(String summary, String title,
String posterURL, String videoFormat, String videoResolution,
String audioFormat, String audioChannels) {
mediaController = new MediaController(this, summary, title, posterURL,
videoResolution, videoFormat, audioFormat, audioChannels,
mediaTagIdentifier);
mediaController.setAnchorView(videoActivityView);
mediaController.setMediaPlayer(new SerenityMediaPlayerControl(
mediaPlayer));
}
@Override
public void finish() {
subtitleDisplayHandler.removeCallbacks(subtitle);
progressReportinghandler.removeCallbacks(progressRunnable);
super.finish();
}
protected void setExitResultCode() {
Intent returnIntent = new Intent();
returnIntent.putExtra("position", playbackPos);
if (getParent() == null) {
setResult(SerenityConstants.EXIT_PLAYBACK_IMMEDIATELY, returnIntent);
} else {
getParent().setResult(SerenityConstants.EXIT_PLAYBACK_IMMEDIATELY,
returnIntent);
}
}
protected void setExitResultCodeFinished() {
Intent returnIntent = new Intent();
returnIntent.putExtra("position", playbackPos);
if (getParent() == null) {
setResult(Activity.RESULT_OK, returnIntent);
} else {
getParent().setResult(Activity.RESULT_OK,
returnIntent);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mediaController.isShowing()) {
if (isKeyCodeBack(keyCode)) {
mediaController.hide();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
setExitResultCode();
finish();
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
mediaController.hide();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
finish();
return true;
}
} else {
if (isKeyCodeBack(keyCode)) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
setExitResultCode();
finish();
return true;
}
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
finish();
return true;
}
if (isKeyCodeInfo(keyCode)) {
if (isMediaPlayerStateValid()) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isKeyCodePauseResume(keyCode)) {
- if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
- mediaPlayer.pause();
- mediaController.show(CONTROLLER_DELAY);
- progressReportinghandler.removeCallbacks(progressRunnable);
- } else {
- mediaPlayer.start();
- mediaController.hide();
- progressReportinghandler.postDelayed(progressRunnable, 5000);
+ if (isMediaPlayerStateValid()) {
+ if (mediaPlayer.isPlaying()) {
+ mediaPlayer.pause();
+ mediaController.show(CONTROLLER_DELAY);
+ progressReportinghandler.removeCallbacks(progressRunnable);
+ } else {
+ mediaPlayer.start();
+ mediaController.hide();
+ progressReportinghandler.postDelayed(progressRunnable, 5000);
+ }
+ return true;
}
- return true;
}
if (isKeyCodeSkipForward(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = 10000 + mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (skipOffset > duration) {
skipOffset = duration - 1;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeSkipBack(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = mediaPlayer.getCurrentPosition() - 10000;
if (skipOffset < 0) {
skipOffset = 0;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeStop(keyCode) && isMediaPlayerStateValid()) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isMediaPlayerStateValid()) {
if (isSkipByPercentage(keyCode)) {
return true;
}
}
return super.onKeyDown(keyCode, event);
}
protected boolean isSkipByPercentage(int keyCode) {
if (keyCode == KeyEvent.KEYCODE_1) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.10f);
skipToPercentage(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_2) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.20f);
skipToPercentage(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_3) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.30f);
skipToPercentage(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_4) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.40f);
skipToPercentage(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_5) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.50f);
skipToPercentage(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_6) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.60f);
skipToPercentage(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_8) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.80f);
skipToPercentage(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_9) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.90f);
skipToPercentage(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_0) {
skipToPercentage(0);
return true;
}
return false;
}
/**
* @param newPos
*/
protected void skipToPercentage(int newPos) {
mediaPlayer.seekTo(newPos);
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
}
/**
* @param keyCode
* @return
*/
protected boolean isKeyCodeStop(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_STOP
|| keyCode == KeyEvent.KEYCODE_S;
}
/**
* @param keyCode
* @return
*/
@Override
protected boolean isKeyCodeSkipBack(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_REWIND
|| keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS
|| keyCode == KeyEvent.KEYCODE_R
|| keyCode == KeyEvent.KEYCODE_BUTTON_L1;
}
/**
* @param keyCode
* @return
*/
@Override
protected boolean isKeyCodeSkipForward(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD
|| keyCode == KeyEvent.KEYCODE_F
|| keyCode == KeyEvent.KEYCODE_BUTTON_R1;
}
/**
* @param keyCode
* @return
*/
protected boolean isKeyCodePauseResume(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY
|| keyCode == KeyEvent.KEYCODE_P
|| keyCode == KeyEvent.KEYCODE_SPACE
|| keyCode == KeyEvent.KEYCODE_BUTTON_A;
}
protected boolean isKeyCodeInfo(int keyCode) {
return keyCode == KeyEvent.KEYCODE_INFO
|| keyCode == KeyEvent.KEYCODE_I
|| keyCode == KeyEvent.KEYCODE_BUTTON_Y;
}
protected boolean isKeyCodeBack(int keyCode) {
return keyCode == KeyEvent.KEYCODE_BACK
|| keyCode == KeyEvent.KEYCODE_ESCAPE
|| keyCode == KeyEvent.KEYCODE_BUTTON_B;
}
protected boolean isMediaPlayerStateValid() {
if (mediaPlayer != null && mediaplayer_error_state == false
&& mediaplayer_released == false) {
return true;
}
return false;
}
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
/**
* A task that updates the progress position of a video while it is being
* played.
*
* @author dcarver
*
*/
protected class UpdateProgressRequest extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
PlexappFactory factory = SerenityApplication.getPlexFactory();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
String offset = Integer.valueOf(
mediaPlayer.getCurrentPosition()).toString();
factory.setProgress(videoId, offset);
}
return null;
}
}
/*
* (non-Javadoc)
*
* @see us.nineworlds.serenity.ui.activity.SerenityActivity#createSideMenu()
*/
@Override
protected void createSideMenu() {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show();
}
return true;
}
return super.onTouchEvent(event);
}
protected class VideoPlayerOnCompletionListener implements
OnCompletionListener {
@Override
public void onCompletion(MediaPlayer mp) {
new CompletedVideoRequest(videoId).execute();
if (!mediaplayer_released) {
if (isMediaPlayerStateValid()) {
if (mediaController.isShowing()) {
mediaController.hide();
}
}
mp.release();
mediaplayer_released = true;
}
setExitResultCodeFinished();
finish();
}
}
/*
* (non-Javadoc)
*
* @see
* android.media.MediaPlayer.OnTimedTextListener#onTimedText(android.media
* .MediaPlayer, android.media.TimedText)
*/
public void onTimedText(Caption text) {
TextView subtitles = (TextView) findViewById(R.id.txtSubtitles);
if (text == null) {
subtitles.setVisibility(View.INVISIBLE);
return;
}
String subtitleText = convertCharSet(text.content);
subtitles.setText(Html.fromHtml(subtitleText));
subtitles.setVisibility(View.VISIBLE);
}
private String convertCharSet(String textToConvert) {
String outputEncoding = "UTF-8";
if (outputEncoding.equalsIgnoreCase(subtitleInputEncoding)) {
return textToConvert;
}
Charset charsetOutput = Charset.forName(outputEncoding);
Charset charsetInput = Charset.forName(subtitleInputEncoding);
CharBuffer inputEncoded = charsetInput.decode(ByteBuffer.wrap(textToConvert.getBytes(Charset.forName(subtitleInputEncoding))));
byte[] utfEncoded = charsetOutput.encode(inputEncoded).array();
return new String(utfEncoded, Charset.forName("UTF-8"));
}
public class SubtitleAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
if (subtitleURL != null) {
try {
URL url = new URL(subtitleURL);
getInputEncoding(url);
if ("srt".equals(subtitleType)) {
FormatSRT formatSRT = new FormatSRT();
subtitleTimedText = formatSRT.parseFile(url
.openStream());
} else if ("ass".equals(subtitleType)) {
FormatASS formatASS = new FormatASS();
subtitleTimedText = formatASS.parseFile(url
.openStream());
}
subtitleDisplayHandler.post(subtitle);
} catch (Exception e) {
Log.e(getClass().getName(), e.getMessage(), e);
}
}
return null;
}
private void getInputEncoding(URL url) {
InputStream is = null;
try {
byte[] buf = new byte[4096];
is = url.openStream();
UniversalDetector detector = new UniversalDetector(null);
int nread;
while ((nread = is.read(buf)) > 0 && !detector.isDone()) {
detector.handleData(buf, 0, nread);
}
detector.dataEnd();
subtitleInputEncoding = detector.getDetectedCharset();
if (subtitleInputEncoding != null) {
Log.d(getClass().getName(), "Detected encoding = " + subtitleInputEncoding);
}
detector.reset();
} catch (IOException ex) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
}
}
| false | true | public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mediaController.isShowing()) {
if (isKeyCodeBack(keyCode)) {
mediaController.hide();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
setExitResultCode();
finish();
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
mediaController.hide();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
finish();
return true;
}
} else {
if (isKeyCodeBack(keyCode)) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
setExitResultCode();
finish();
return true;
}
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
finish();
return true;
}
if (isKeyCodeInfo(keyCode)) {
if (isMediaPlayerStateValid()) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isKeyCodePauseResume(keyCode)) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mediaController.show(CONTROLLER_DELAY);
progressReportinghandler.removeCallbacks(progressRunnable);
} else {
mediaPlayer.start();
mediaController.hide();
progressReportinghandler.postDelayed(progressRunnable, 5000);
}
return true;
}
if (isKeyCodeSkipForward(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = 10000 + mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (skipOffset > duration) {
skipOffset = duration - 1;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeSkipBack(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = mediaPlayer.getCurrentPosition() - 10000;
if (skipOffset < 0) {
skipOffset = 0;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeStop(keyCode) && isMediaPlayerStateValid()) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isMediaPlayerStateValid()) {
if (isSkipByPercentage(keyCode)) {
return true;
}
}
return super.onKeyDown(keyCode, event);
}
| public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mediaController.isShowing()) {
if (isKeyCodeBack(keyCode)) {
mediaController.hide();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
setExitResultCode();
finish();
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
mediaController.hide();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
finish();
return true;
}
} else {
if (isKeyCodeBack(keyCode)) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
setExitResultCode();
finish();
return true;
}
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
finish();
return true;
}
if (isKeyCodeInfo(keyCode)) {
if (isMediaPlayerStateValid()) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isKeyCodePauseResume(keyCode)) {
if (isMediaPlayerStateValid()) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mediaController.show(CONTROLLER_DELAY);
progressReportinghandler.removeCallbacks(progressRunnable);
} else {
mediaPlayer.start();
mediaController.hide();
progressReportinghandler.postDelayed(progressRunnable, 5000);
}
return true;
}
}
if (isKeyCodeSkipForward(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = 10000 + mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (skipOffset > duration) {
skipOffset = duration - 1;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeSkipBack(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = mediaPlayer.getCurrentPosition() - 10000;
if (skipOffset < 0) {
skipOffset = 0;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeStop(keyCode) && isMediaPlayerStateValid()) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isMediaPlayerStateValid()) {
if (isSkipByPercentage(keyCode)) {
return true;
}
}
return super.onKeyDown(keyCode, event);
}
|
diff --git a/java/src/org/broadinstitute/sting/playground/utils/AlleleFrequencyEstimate.java b/java/src/org/broadinstitute/sting/playground/utils/AlleleFrequencyEstimate.java
index 3c25ee803..c84995d27 100755
--- a/java/src/org/broadinstitute/sting/playground/utils/AlleleFrequencyEstimate.java
+++ b/java/src/org/broadinstitute/sting/playground/utils/AlleleFrequencyEstimate.java
@@ -1,175 +1,175 @@
package org.broadinstitute.sting.playground.utils;
import org.broadinstitute.sting.playground.gatk.walkers.AlleleFrequencyWalker;
import java.util.Arrays;
import java.lang.Math;
import org.broadinstitute.sting.utils.GenomeLoc;
public class AlleleFrequencyEstimate {
static
{
boolean assertsEnabled = false;
assert assertsEnabled = true; // Intentional side effect!!!
if (!assertsEnabled)
{
System.err.printf("\n\n\nERROR: You must run with asserts enabled. \"java -ea\".\n\n\n");
throw new RuntimeException("Asserts must be enabled!");
}
}
//AlleleFrequencyEstimate();
public GenomeLoc location;
public char ref;
public char alt;
public int N;
public double qhat;
public double qstar;
public double lodVsRef;
public double lodVsNextBest;
public double pBest;
public double pRef;
public int depth;
public String notes;
public String bases;
public double[][] quals;
public double[] posteriors;
GenomeLoc l;
public AlleleFrequencyEstimate(GenomeLoc location, char ref, char alt, int N, double qhat, double qstar, double lodVsRef, double lodVsNextBest, double pBest, double pRef, int depth, String bases, double[][] quals, double[] posteriors)
{
- if( Double.isNaN(lodVsRef)) { System.out.printf("lodVsRef is NaN\n"); }
+ if( Double.isNaN(lodVsRef)) { System.out.printf("%s: lodVsRef is NaN\n", location.toString()); }
if( Double.isNaN(lodVsNextBest)) { System.out.printf("lodVsNextBest is NaN\n"); }
if( Double.isNaN(qhat)) { System.out.printf("qhat is NaN\n"); }
if( Double.isNaN(qstar)) { System.out.printf("qstar is NaN\n"); }
if( Double.isNaN(pBest)) { System.out.printf("pBest is NaN\n"); }
if( Double.isNaN(pRef)) { System.out.printf("pRef is NaN\n"); }
if( Double.isInfinite(lodVsRef))
{
- System.out.printf("lodVsRef is Infinite: %c %s\n", ref, bases);
+ System.out.printf("lodVsRef is Infinite: %s %c %s\n", location.toString(), ref, bases);
for (int i = 0; i < posteriors.length; i++)
{
System.out.printf("POSTERIOR %d %f\n", i, posteriors[i]);
}
}
if( Double.isInfinite(lodVsNextBest)) { System.out.printf("lodVsNextBest is Infinite\n"); }
if( Double.isInfinite(qhat)) { System.out.printf("qhat is Infinite\n"); }
if( Double.isInfinite(qstar)) { System.out.printf("qstar is Infinite\n"); }
if( Double.isInfinite(pBest)) { System.out.printf("pBest is Infinite\n"); }
if( Double.isInfinite(pRef)) { System.out.printf("pRef is Infinite\n"); }
assert(! Double.isNaN(lodVsRef));
assert(! Double.isNaN(lodVsNextBest));
assert(! Double.isNaN(qhat));
assert(! Double.isNaN(qstar));
assert(! Double.isNaN(pBest));
assert(! Double.isNaN(pRef));
assert(! Double.isInfinite(lodVsRef));
assert(! Double.isInfinite(lodVsNextBest));
assert(! Double.isInfinite(qhat));
assert(! Double.isInfinite(qstar));
assert(! Double.isInfinite(pBest));
assert(! Double.isInfinite(pRef));
this.location = location;
this.ref = ref;
this.alt = alt;
this.N = N;
this.qhat = qhat;
this.qstar = qstar;
this.lodVsRef = lodVsRef;
this.lodVsNextBest = lodVsNextBest;
this.depth = depth;
this.notes = "";
this.bases = bases;
this.quals = quals;
this.posteriors = posteriors;
}
/** Return the most likely genotype. */
public String genotype()
{
int alt_count = (int)(qstar * N);
int ref_count = N-alt_count;
char[] alleles = new char[N];
int i;
for (i = 0; i < ref_count; i++) { alleles[i] = ref; }
for (; i < N; i++) { alleles[i] = alt; }
Arrays.sort(alleles);
return new String(alleles);
}
public double emperical_allele_frequency()
{
return (double)Math.round((double)qstar * (double)N) / (double)N;
}
public double emperical_allele_frequency(int N)
{
return (double)Math.round((double)qstar * (double)N) / (double)N;
}
public String asGFFString()
{
String s = "";
s += String.format("%s\tCALLER\tVARIANT\t%s\t%s\t%f\t.\t.\t",
location.getContig(),
location.getStart(),
location.getStart(),
lodVsRef);
s += String.format("\t;\tREF %c", ref);
s += String.format("\t;\tALT %c", alt);
s += String.format("\t;\tFREQ %f", qstar);
s += String.format("\t;\tDEPTH %d", depth);
s += String.format("\t;\tLODvsREF %f", lodVsRef);
s += String.format("\t;\tLODvsNEXTBEST %f", lodVsNextBest);
s += String.format("\t;\tQHAT %f", qhat);
s += String.format("\t;\tQSTAR %f", qstar);
s += String.format("\t;\tBASES %s", bases);
s += ";\n";
// add quals.
return s;
}
public String asTabularString() {
return String.format("RESULT %s %c %c %f %f %f %f %d %s\n",
location,
ref,
alt,
qhat,
qstar,
lodVsRef,
lodVsNextBest,
depth,
notes);
}
public String toString() { return asTabularString(); }
public String asString() {
// Print out the called bases
// Notes: switched from qhat to qstar because qhat doesn't work at n=1 (1 observed base) where having a single non-ref
// base has you calculate qstar = 0.0 and qhat = 0.49 and that leads to a genotype predicition of AG according
// to qhat, but AA according to qstar. This needs to be further investigated to see whether we really want
// to use qstar, but make N (number of chormosomes) switch to n (number of reads at locus) for n=1
long numNonrefBases = Math.round(qstar * N);
long numRefBases = N - numNonrefBases;
if (ref < alt) { // order bases alphabetically
return AlleleFrequencyWalker.repeat(ref, numRefBases) + AlleleFrequencyWalker.repeat(alt, numNonrefBases);
}else{
return AlleleFrequencyWalker.repeat(alt, numNonrefBases) + AlleleFrequencyWalker.repeat(ref, numRefBases);
}
}
public double posterior()
{
return this.posteriors[(int)this.qstar * this.N];
}
}
| false | true | public AlleleFrequencyEstimate(GenomeLoc location, char ref, char alt, int N, double qhat, double qstar, double lodVsRef, double lodVsNextBest, double pBest, double pRef, int depth, String bases, double[][] quals, double[] posteriors)
{
if( Double.isNaN(lodVsRef)) { System.out.printf("lodVsRef is NaN\n"); }
if( Double.isNaN(lodVsNextBest)) { System.out.printf("lodVsNextBest is NaN\n"); }
if( Double.isNaN(qhat)) { System.out.printf("qhat is NaN\n"); }
if( Double.isNaN(qstar)) { System.out.printf("qstar is NaN\n"); }
if( Double.isNaN(pBest)) { System.out.printf("pBest is NaN\n"); }
if( Double.isNaN(pRef)) { System.out.printf("pRef is NaN\n"); }
if( Double.isInfinite(lodVsRef))
{
System.out.printf("lodVsRef is Infinite: %c %s\n", ref, bases);
for (int i = 0; i < posteriors.length; i++)
{
System.out.printf("POSTERIOR %d %f\n", i, posteriors[i]);
}
}
if( Double.isInfinite(lodVsNextBest)) { System.out.printf("lodVsNextBest is Infinite\n"); }
if( Double.isInfinite(qhat)) { System.out.printf("qhat is Infinite\n"); }
if( Double.isInfinite(qstar)) { System.out.printf("qstar is Infinite\n"); }
if( Double.isInfinite(pBest)) { System.out.printf("pBest is Infinite\n"); }
if( Double.isInfinite(pRef)) { System.out.printf("pRef is Infinite\n"); }
assert(! Double.isNaN(lodVsRef));
assert(! Double.isNaN(lodVsNextBest));
assert(! Double.isNaN(qhat));
assert(! Double.isNaN(qstar));
assert(! Double.isNaN(pBest));
assert(! Double.isNaN(pRef));
assert(! Double.isInfinite(lodVsRef));
assert(! Double.isInfinite(lodVsNextBest));
assert(! Double.isInfinite(qhat));
assert(! Double.isInfinite(qstar));
assert(! Double.isInfinite(pBest));
assert(! Double.isInfinite(pRef));
this.location = location;
this.ref = ref;
this.alt = alt;
this.N = N;
this.qhat = qhat;
this.qstar = qstar;
this.lodVsRef = lodVsRef;
this.lodVsNextBest = lodVsNextBest;
this.depth = depth;
this.notes = "";
this.bases = bases;
this.quals = quals;
this.posteriors = posteriors;
}
| public AlleleFrequencyEstimate(GenomeLoc location, char ref, char alt, int N, double qhat, double qstar, double lodVsRef, double lodVsNextBest, double pBest, double pRef, int depth, String bases, double[][] quals, double[] posteriors)
{
if( Double.isNaN(lodVsRef)) { System.out.printf("%s: lodVsRef is NaN\n", location.toString()); }
if( Double.isNaN(lodVsNextBest)) { System.out.printf("lodVsNextBest is NaN\n"); }
if( Double.isNaN(qhat)) { System.out.printf("qhat is NaN\n"); }
if( Double.isNaN(qstar)) { System.out.printf("qstar is NaN\n"); }
if( Double.isNaN(pBest)) { System.out.printf("pBest is NaN\n"); }
if( Double.isNaN(pRef)) { System.out.printf("pRef is NaN\n"); }
if( Double.isInfinite(lodVsRef))
{
System.out.printf("lodVsRef is Infinite: %s %c %s\n", location.toString(), ref, bases);
for (int i = 0; i < posteriors.length; i++)
{
System.out.printf("POSTERIOR %d %f\n", i, posteriors[i]);
}
}
if( Double.isInfinite(lodVsNextBest)) { System.out.printf("lodVsNextBest is Infinite\n"); }
if( Double.isInfinite(qhat)) { System.out.printf("qhat is Infinite\n"); }
if( Double.isInfinite(qstar)) { System.out.printf("qstar is Infinite\n"); }
if( Double.isInfinite(pBest)) { System.out.printf("pBest is Infinite\n"); }
if( Double.isInfinite(pRef)) { System.out.printf("pRef is Infinite\n"); }
assert(! Double.isNaN(lodVsRef));
assert(! Double.isNaN(lodVsNextBest));
assert(! Double.isNaN(qhat));
assert(! Double.isNaN(qstar));
assert(! Double.isNaN(pBest));
assert(! Double.isNaN(pRef));
assert(! Double.isInfinite(lodVsRef));
assert(! Double.isInfinite(lodVsNextBest));
assert(! Double.isInfinite(qhat));
assert(! Double.isInfinite(qstar));
assert(! Double.isInfinite(pBest));
assert(! Double.isInfinite(pRef));
this.location = location;
this.ref = ref;
this.alt = alt;
this.N = N;
this.qhat = qhat;
this.qstar = qstar;
this.lodVsRef = lodVsRef;
this.lodVsNextBest = lodVsNextBest;
this.depth = depth;
this.notes = "";
this.bases = bases;
this.quals = quals;
this.posteriors = posteriors;
}
|
diff --git a/Rentability/app/controllers/Rentability.java b/Rentability/app/controllers/Rentability.java
index d2b9f5c..5b7a87b 100644
--- a/Rentability/app/controllers/Rentability.java
+++ b/Rentability/app/controllers/Rentability.java
@@ -1,444 +1,447 @@
package controllers;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import play.db.jpa.Blob;
import play.libs.Mail;
import play.mvc.*;
import tools.Mailing;
import models.*;
import play.data.validation.*;
import play.data.validation.Error;
@With(Secure.class)
public class Rentability extends Controller {
@Before
static void setConnectedUser() {
if(Security.isConnected()) {
User user = User.find("byEmail", Security.connected()).first();
// if(user!= null)
renderArgs.put("user", user);
// else
// renderArgs.put("user", "guest");
}
}
@Before
static void addDefaults() {
renderArgs.put("mainCates", Inventory.getAllMainCategories());
}
//Rendering the (personalized) index page
public static void index() {
/*Personalized content to be implemented!*/
render();
}
//Rendering the create offer page using all existing categories
public static void createOffer() {
User u = (User)renderArgs.get("user");
List<Category> categories = Inventory.getAllMainCategories();
List<Article> articles = Inventory.getArticlesByOwner(u.id);
render(categories, articles);
}
public static void reloadSubCate(String name) {
long cateID = Long.parseLong(name);
List<Category> subCates = Inventory.getSubCategories(cateID);
render("@selectSubCate", subCates);
}
//Creating a new Offer
public static void saveOffer(String article, Blob image, String articleName, String articleDescription, String name, String subName,
String offerDescription, String pickUpAddress, String startTime, String endTime, String price, String insurance) {
Article a = null;
Category c = null;
User u = (User)renderArgs.get("user");
//An existing article has been choosen
if(!articleName.isEmpty()){
validation.required(articleName);
validation.required(articleDescription);
validation.required(subName).message("Please specify a Subcategory");
}
+ else{
+ validation.required(article);
+ }
validation.required(offerDescription);
validation.required(pickUpAddress);
validation.required(startTime);
//Make sure the date is entered in this format DD.MM.YYYY
- validation.match(startTime, "\\d{2}\\.\\d{2}\\.\\d{4}").message("Please indicate the Date in the given format!");
+ validation.match(startTime, "\\d{2}/\\d{2}/\\d{4}").message("Please indicate the Date in the given format!");
validation.required(endTime);
- validation.match(endTime, "\\d{2}\\.\\d{2}\\.\\d{4}").message("Please indicate the Date in the given format!");
+ validation.match(endTime, "\\d{2}/\\d{2}/\\d{4}").message("Please indicate the Date in the given format!");
validation.required(price);
//Ensures that the price field is followed by 2 digits after the point
validation.match(price, "\\d+\\.\\d{2}").message("Please indicate the Price in the given format!");
if(validation.hasErrors())
{
List<Category> categories = Category.findAll();
List<Article> articles = Inventory.getArticlesByOwner(u.id);
render("@createOffer", articles, articleName, articleDescription, categories, offerDescription, pickUpAddress,
startTime, endTime, price, insurance);
}
else
{
boolean insuranceRequired;
//Create new article or retrieve existing one
if(!articleName.isEmpty()) {
List<Category> categories = Category.findAll();
c = categories.get(Integer.valueOf(subName) - 1);
a = new Article(articleName, articleDescription, u, c, image);
}
else {
a = Article.findById(Long.parseLong(article));
}
//Conversion of String Values to Dates, Boolean, etc.
- SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
+ SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
try {
Date start = sdf.parse(startTime);
Date end = sdf.parse(endTime);
if(insurance == null || !insurance.equals("true"))
insuranceRequired = false;
else
insuranceRequired = true;
double doublePrice = Double.parseDouble(price);
- //null value to be implemented - represents the description
- new Offer(pickUpAddress, insuranceRequired, 0, doublePrice, null, start, end, a);
+ //Insert new article - a=the choosen or created article
+ new Offer(pickUpAddress, insuranceRequired, 0, doublePrice, offerDescription, start, end, a);
flash.success("Your offer has successfully been created!");
Application.index();
} catch (Exception ex) {
flash.error("Sorry an error occured, please try again!");
}
}
}
// Creating a new request:
public static void saveRequest(double adjustedPrice, String startTime, String endTime, Long offerID) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
try {
Offer offer = Offer.findById(offerID);
boolean duplicate = false;
Request duplicatedRequest = null;
Date start = sdf.parse(startTime);
Date end = sdf.parse(endTime);
for (Request oldRequest : Offer.getAllRequests(offer)){
if (oldRequest.startTime.equals(start)){
duplicate = true;
duplicatedRequest = oldRequest;
}
}
User requestingUser;
if(renderArgs.get("user") != null) {
requestingUser = renderArgs.get("user", User.class);
}
else {
String username = session.get("user");
if(username != null) {
requestingUser = User.find("byUsername", username).first();
}
else requestingUser = null;
}
Request requested;
short state = 1;
if (!duplicate) {requested = new Request(state,adjustedPrice,start,end,offer,requestingUser);}
else {
requested = duplicatedRequest;
}
//Sending the newRequest Email
Mailing.newRequest(requestingUser, requested);
showRequest(requested);
} catch (Exception ex) {
flash.error("Sorry an error occured, please try again!");
}
}
public static void showRequest(Request requested){
render(requested);
}
//go to user Management page
public static void userManagement()
{
render();
}
//go to user Management page
public static void userManagement2(long id)
{
User user = User.find("byId", id).first();
renderArgs.put("nick_name",user.nick_name );
renderArgs.put("first_name", user.first_name);
renderArgs.put("last_name", user.last_name);
renderArgs.put("phone", user.phone);
render("@userManagement");
}
public static void updateUser(@Required String nick_name, @Required String first_name, @Required String last_name,String phone)
{
validation.required(nick_name).message("Field is required");
validation.required(first_name);
validation.required(last_name);
if(validation.hasErrors()){
// render("@userManagement",nick_name,first_name,last_name,phone);
render("@userProfile",nick_name,first_name,last_name,phone);
}
else
{
User user = User.find("byEmail", Security.connected()).first();
user.nick_name = nick_name;
user.first_name = first_name;
user.last_name= last_name;
user.phone= phone;
user.save();
flash.success("Successfully updated profile");
// userManagement2(user.id);
userProfile2(user.id);
}
}
//go to user Management page
public static void userProfile()
{
render();
}
//go to user Management page
public static void userProfile2(long id)
{
User user = User.find("byId", id).first();
renderArgs.put("nick_name",user.nick_name );
renderArgs.put("first_name", user.first_name);
renderArgs.put("last_name", user.last_name);
renderArgs.put("phone", user.phone);
render("@userProfile");
}
public static void userArticles()
{
if(Security.isConnected()) {
User user = User.find("byEmail", Security.connected()).first();
List<Article> userArticles= Article.find("owner.id", user.id).fetch();
renderArgs.put("articles", userArticles);
render();
}
}
public static void articleOffers(long articleId)
{
Article article= Article.findById(articleId);
List<Offer> offers= Article.getAllOffers(article);
renderArgs.put("article", article);
renderArgs.put("offers", offers);
render();
}
public static void offerRequests(long offerId)
{
Offer offer= Offer.findById(offerId);
List<Request> requests= Offer.getAllRequests(offer);
boolean alreadyApproved=false;
for(int i=0;i<requests.size();i++)
{
if(requests.get(i).state ==5) alreadyApproved=true;
}
renderArgs.put("alreadyApproved",alreadyApproved);
renderArgs.put("offer", offer);
renderArgs.put("requests", requests);
render();
}
public static void approveRequest(long requestId,long offerId)
{
Request request= Request.findById(requestId);
request.state=5;
request.save();
Offer offer= Offer.findById(offerId);
offer.state= -1;
offerRequests(offerId);
}
//Rendering the create offer page using all existing categories
public static void createOfferWithArticle(long articleId) {
List<Category> categories = Category.findAll();
Article article= Article.findById(articleId);
session.put("article", articleId);
renderArgs.put("article", article);
render(categories);
}
//Creating a new Offer
public static void saveOfferOfArticle(String description, String name,
String pickUpAddress, String startTime, String endTime, String price, String insurance) {
Article article =Article.findById(Long.parseLong(session.get("article")));
validation.required(description);
validation.required(pickUpAddress);
validation.required(startTime);
//Make sure the date is entered in this format DD.MM.YYYY
validation.match(startTime, "\\d{2}\\.\\d{2}\\.\\d{4}").message("Please indicate the Date in the given format!");
validation.required(endTime);
validation.match(endTime, "\\d{2}\\.\\d{2}\\.\\d{4}").message("Please indicate the Date in the given format!");
validation.required(price);
//Ensures that the price field is followed by 2 digits after the point
validation.match(price, "\\d+\\.\\d{2}").message("Please indicate the Price in the given format!");
if(validation.hasErrors())
{
List<Category> categories = Category.findAll();
render("@createOfferWithArticle" ,article, description, categories, pickUpAddress,
startTime, endTime, price, insurance);
}
else
{
boolean insuranceRequired;
//Conversion of String Values to Dates, Boolean, etc.
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
try {
Date start = sdf.parse(startTime);
Date end = sdf.parse(endTime);
if(insurance == null || !insurance.equals("true"))
insuranceRequired = false;
else
insuranceRequired = true;
double doublePrice = Double.parseDouble(price);
//null value to be implemented - represents the description
new Offer(pickUpAddress, insuranceRequired, 0, doublePrice, description, start, end, article);
flash.success("Your offer has successfully been created!");
Application.index();
} catch (Exception ex) {
flash.error("Sorry an error occured, please try again!");
}
}
}
public static void removeOffer(long offerId,long articleId)
{
//if offer has requests can not be deleted
Offer offer= Offer.findById(offerId);
int requestssize=offer.getAllRequests(offer).size();
if(requestssize>0)
{
flash.error("This offer has "+requestssize +" rent requests(s)! Can not be removed" );
}
else
{
///remove offer
offer.delete();
}
articleOffers(articleId);
}
public static void removeArticle(long articleId)
{
//if article has offer can not be deleted
Article article= Article.findById(articleId);
int offerssize=Article.getAllOffers(article).size();
if(offerssize>0)
{
flash.error("This article has "+offerssize +" offer(s)! First remove offers in order to be able remove the article" );
}
else
{
///remove article
article.delete();
}
userArticles();
}
///Provide requests of current user and their state approved or pending
public static void userRequests()
{
if(Security.isConnected()) {
User user = User.find("byEmail", Security.connected()).first();
List<Request> userRequest= Request.find("user.id", user.id).fetch();
renderArgs.put("requests", userRequest);
render();
}
}
///Provide requests which have been sent to current user equipments from other users
public static void userReceivedRequests()
{
if(Security.isConnected()) {
User user = User.find("byEmail", Security.connected()).first();
List<Request> userRequest= Request.find("offer.article.owner.id", user.id).fetch();
///iterate to change seen to true so that, notification in main page will be removed
for(int i=0;i<userRequest.size();i++)
{
if(!userRequest.get(i).seen)
{
userRequest.get(i).seen=true;
userRequest.get(i).save();
}
}
renderArgs.put("requests", userRequest);
render();
}
}
public static void changePassword()
{
render();
}
public static void updatePassword(@Required String currentpassword,@Required String newpassword,@Required String verifypassword)
{
validation.required(currentpassword).message("Field is required");
validation.required(newpassword).message("Field is required");
validation.required(verifypassword).message("Field is required");
validation.equals(verifypassword, newpassword).message("Your password doesn't match");
if(validation.hasErrors()){
render("@changePassword",currentpassword);
}
else
{
User user = User.find("byEmail", Security.connected()).first();
if( user.password.equals(Application.getHash(currentpassword, "SHA-256"))) {
user.password= Application.getHash(newpassword,"SHA-256");
user.save();
flash.success("Successfully updated your password");
changePassword();
}
else
{
flash.error("Entered password is not correct ");
render("@changePassword",currentpassword);
}
}
}
}
| false | true | public static void saveOffer(String article, Blob image, String articleName, String articleDescription, String name, String subName,
String offerDescription, String pickUpAddress, String startTime, String endTime, String price, String insurance) {
Article a = null;
Category c = null;
User u = (User)renderArgs.get("user");
//An existing article has been choosen
if(!articleName.isEmpty()){
validation.required(articleName);
validation.required(articleDescription);
validation.required(subName).message("Please specify a Subcategory");
}
validation.required(offerDescription);
validation.required(pickUpAddress);
validation.required(startTime);
//Make sure the date is entered in this format DD.MM.YYYY
validation.match(startTime, "\\d{2}\\.\\d{2}\\.\\d{4}").message("Please indicate the Date in the given format!");
validation.required(endTime);
validation.match(endTime, "\\d{2}\\.\\d{2}\\.\\d{4}").message("Please indicate the Date in the given format!");
validation.required(price);
//Ensures that the price field is followed by 2 digits after the point
validation.match(price, "\\d+\\.\\d{2}").message("Please indicate the Price in the given format!");
if(validation.hasErrors())
{
List<Category> categories = Category.findAll();
List<Article> articles = Inventory.getArticlesByOwner(u.id);
render("@createOffer", articles, articleName, articleDescription, categories, offerDescription, pickUpAddress,
startTime, endTime, price, insurance);
}
else
{
boolean insuranceRequired;
//Create new article or retrieve existing one
if(!articleName.isEmpty()) {
List<Category> categories = Category.findAll();
c = categories.get(Integer.valueOf(subName) - 1);
a = new Article(articleName, articleDescription, u, c, image);
}
else {
a = Article.findById(Long.parseLong(article));
}
//Conversion of String Values to Dates, Boolean, etc.
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
try {
Date start = sdf.parse(startTime);
Date end = sdf.parse(endTime);
if(insurance == null || !insurance.equals("true"))
insuranceRequired = false;
else
insuranceRequired = true;
double doublePrice = Double.parseDouble(price);
//null value to be implemented - represents the description
new Offer(pickUpAddress, insuranceRequired, 0, doublePrice, null, start, end, a);
flash.success("Your offer has successfully been created!");
Application.index();
} catch (Exception ex) {
flash.error("Sorry an error occured, please try again!");
}
}
}
| public static void saveOffer(String article, Blob image, String articleName, String articleDescription, String name, String subName,
String offerDescription, String pickUpAddress, String startTime, String endTime, String price, String insurance) {
Article a = null;
Category c = null;
User u = (User)renderArgs.get("user");
//An existing article has been choosen
if(!articleName.isEmpty()){
validation.required(articleName);
validation.required(articleDescription);
validation.required(subName).message("Please specify a Subcategory");
}
else{
validation.required(article);
}
validation.required(offerDescription);
validation.required(pickUpAddress);
validation.required(startTime);
//Make sure the date is entered in this format DD.MM.YYYY
validation.match(startTime, "\\d{2}/\\d{2}/\\d{4}").message("Please indicate the Date in the given format!");
validation.required(endTime);
validation.match(endTime, "\\d{2}/\\d{2}/\\d{4}").message("Please indicate the Date in the given format!");
validation.required(price);
//Ensures that the price field is followed by 2 digits after the point
validation.match(price, "\\d+\\.\\d{2}").message("Please indicate the Price in the given format!");
if(validation.hasErrors())
{
List<Category> categories = Category.findAll();
List<Article> articles = Inventory.getArticlesByOwner(u.id);
render("@createOffer", articles, articleName, articleDescription, categories, offerDescription, pickUpAddress,
startTime, endTime, price, insurance);
}
else
{
boolean insuranceRequired;
//Create new article or retrieve existing one
if(!articleName.isEmpty()) {
List<Category> categories = Category.findAll();
c = categories.get(Integer.valueOf(subName) - 1);
a = new Article(articleName, articleDescription, u, c, image);
}
else {
a = Article.findById(Long.parseLong(article));
}
//Conversion of String Values to Dates, Boolean, etc.
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
try {
Date start = sdf.parse(startTime);
Date end = sdf.parse(endTime);
if(insurance == null || !insurance.equals("true"))
insuranceRequired = false;
else
insuranceRequired = true;
double doublePrice = Double.parseDouble(price);
//Insert new article - a=the choosen or created article
new Offer(pickUpAddress, insuranceRequired, 0, doublePrice, offerDescription, start, end, a);
flash.success("Your offer has successfully been created!");
Application.index();
} catch (Exception ex) {
flash.error("Sorry an error occured, please try again!");
}
}
}
|
diff --git a/branches/5.0.0/Crux/src/ui/widgets/org/cruxframework/crux/widgets/client/storyboard/StoryboardLargeMouseController.java b/branches/5.0.0/Crux/src/ui/widgets/org/cruxframework/crux/widgets/client/storyboard/StoryboardLargeMouseController.java
index 3086532d4..fc207d2a8 100644
--- a/branches/5.0.0/Crux/src/ui/widgets/org/cruxframework/crux/widgets/client/storyboard/StoryboardLargeMouseController.java
+++ b/branches/5.0.0/Crux/src/ui/widgets/org/cruxframework/crux/widgets/client/storyboard/StoryboardLargeMouseController.java
@@ -1,50 +1,51 @@
package org.cruxframework.crux.widgets.client.storyboard;
import org.cruxframework.crux.core.client.controller.Controller;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Widget;
@Controller("storyboardLargeMouseController")
public class StoryboardLargeMouseController extends StoryboardLargeController
{
@Override
protected Widget createClickablePanelForCell(Widget widget)
{
final FocusPanel panel = new FocusPanel();
panel.add(widget);
panel.setStyleName("item");
configHeightWidth(panel);
panel.addClickHandler(new ClickHandler()
{
@Override
public void onClick(ClickEvent event)
{
int index = storyboard.getWidgetIndex(panel);
SelectionEvent.fire(StoryboardLargeMouseController.this, index);
}
});
panel.getElement().getStyle().setProperty("display", "inline-table");
+ panel.getElement().getStyle().setProperty("verticalAlign", "bottom");
panel.addKeyPressHandler(new KeyPressHandler()
{
@Override
public void onKeyPress(KeyPressEvent event)
{
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
{
int index = storyboard.getWidgetIndex(panel);
SelectionEvent.fire(StoryboardLargeMouseController.this, index);
}
}
});
return panel;
}
}
| true | true | protected Widget createClickablePanelForCell(Widget widget)
{
final FocusPanel panel = new FocusPanel();
panel.add(widget);
panel.setStyleName("item");
configHeightWidth(panel);
panel.addClickHandler(new ClickHandler()
{
@Override
public void onClick(ClickEvent event)
{
int index = storyboard.getWidgetIndex(panel);
SelectionEvent.fire(StoryboardLargeMouseController.this, index);
}
});
panel.getElement().getStyle().setProperty("display", "inline-table");
panel.addKeyPressHandler(new KeyPressHandler()
{
@Override
public void onKeyPress(KeyPressEvent event)
{
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
{
int index = storyboard.getWidgetIndex(panel);
SelectionEvent.fire(StoryboardLargeMouseController.this, index);
}
}
});
return panel;
}
| protected Widget createClickablePanelForCell(Widget widget)
{
final FocusPanel panel = new FocusPanel();
panel.add(widget);
panel.setStyleName("item");
configHeightWidth(panel);
panel.addClickHandler(new ClickHandler()
{
@Override
public void onClick(ClickEvent event)
{
int index = storyboard.getWidgetIndex(panel);
SelectionEvent.fire(StoryboardLargeMouseController.this, index);
}
});
panel.getElement().getStyle().setProperty("display", "inline-table");
panel.getElement().getStyle().setProperty("verticalAlign", "bottom");
panel.addKeyPressHandler(new KeyPressHandler()
{
@Override
public void onKeyPress(KeyPressEvent event)
{
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
{
int index = storyboard.getWidgetIndex(panel);
SelectionEvent.fire(StoryboardLargeMouseController.this, index);
}
}
});
return panel;
}
|
diff --git a/org.envirocar.app/src/org/envirocar/app/application/ECApplication.java b/org.envirocar.app/src/org/envirocar/app/application/ECApplication.java
index 2da9fae6..81f5aedc 100644
--- a/org.envirocar.app/src/org/envirocar/app/application/ECApplication.java
+++ b/org.envirocar.app/src/org/envirocar/app/application/ECApplication.java
@@ -1,1063 +1,1063 @@
/*
* enviroCar 2013
* Copyright (C) 2013
* Martin Dueren, Jakob Moellers, Gerald Pape, Christopher Stephan
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.envirocar.app.application;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.envirocar.app.R;
import org.envirocar.app.activity.MainActivity;
import org.envirocar.app.commands.CommonCommand;
import org.envirocar.app.commands.IntakePressure;
import org.envirocar.app.commands.IntakeTemperature;
import org.envirocar.app.commands.MAF;
import org.envirocar.app.commands.RPM;
import org.envirocar.app.commands.Speed;
import org.envirocar.app.exception.LocationInvalidException;
import org.envirocar.app.exception.MeasurementsException;
import org.envirocar.app.exception.TracksException;
import org.envirocar.app.storage.DbAdapter;
import org.envirocar.app.storage.DbAdapterLocal;
import org.envirocar.app.storage.DbAdapterRemote;
import org.envirocar.app.storage.Measurement;
import org.envirocar.app.storage.Track;
import org.envirocar.app.views.Utils;
import android.app.Application;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
/**
* This is the main application that is the central linking component for all adapters, services and so on.
* This application is implemented like a singleton, it exists only once while the app is running.
* @author gerald, jakob
*
*/
public class ECApplication extends Application implements LocationListener {
// Strings
public static final String BASE_URL = "https://giv-car.uni-muenster.de/stable/rest";
public static final String PREF_KEY_CAR_MODEL = "carmodel";
public static final String PREF_KEY_CAR_MANUFACTURER = "manufacturer";
public static final String PREF_KEY_CAR_CONSTRUCTION_YEAR = "constructionyear";
public static final String PREF_KEY_FUEL_TYPE = "fueltype";
public static final String PREF_KEY_SENSOR_ID = "sensorid";
private SharedPreferences preferences = null;
private boolean imperialUnits = false;
// Helpers and objects
private DbAdapter dbAdapterLocal;
private DbAdapter dbAdapterRemote;
private final ScheduledExecutorService scheduleTaskExecutor = Executors
.newScheduledThreadPool(1);
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
private ServiceConnector serviceConnector = null;
private Intent backgroundService = null;
private Handler handler = new Handler();
private Listener listener = null;
private LocationManager locationManager;
private int mId = 1133;
// Measurement values
private float locationLatitude;
private float locationLongitude;
private int speedMeasurement = 0;
private double co2Measurement = 0.0;
private double mafMeasurement;
private double calculatedMafMeasurement = 0;
private int rpmMeasurement = 0;
private int intakeTemperatureMeasurement = 0;
private int intakePressureMeasurement = 0;
private Measurement measurement = null;
private long lastInsertTime = 0;
// Track properties
private Track track;
private String trackDescription = "Description of the track";
//private boolean requirementsFulfilled = true;
private static User user;
/**
* Returns the service connector of the server
* @return the serviceConnector
*/
public ServiceConnector getServiceConnector() {
startBackgroundService();
return serviceConnector;
}
/**
* Returns whether requirements were fulfilled (bluetooth activated)
* @return requirementsFulfilled?
*/
public boolean requirementsFulfilled() {
if (bluetoothAdapter == null) {
return false;
} else {
return bluetoothAdapter.isEnabled();
}
}
/**
* This method updates the attributes of the current sensor (=car)
* @param sensorid the id that is stored on the server
* @param carManufacturer the car manufacturer
* @param carModel the car model
* @param fuelType the fuel type of the car
* @param year construction year of the car
*/
public void updateCurrentSensor(String sensorid, String carManufacturer,
String carModel, String fuelType, int year) {
Editor e = preferences.edit();
e.putString(PREF_KEY_SENSOR_ID, sensorid);
e.putString(PREF_KEY_CAR_MANUFACTURER, carManufacturer);
e.putString(PREF_KEY_CAR_MODEL, carModel);
e.putString(PREF_KEY_FUEL_TYPE, fuelType);
e.putString(PREF_KEY_CAR_CONSTRUCTION_YEAR, year + "");
e.commit();
}
@Override
public void onCreate() {
super.onCreate();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
user = getUserFromSharedPreferences();
initDbAdapter();
initLocationManager();
// Make a new listener to interpret the measurement values that are
// returned
Log.e("obd2", "init listener");
startListener();
// If everything is available, start the service connector and listener
startBackgroundService();
//Make sure that there are coordinates for the first measurement
try {
measurement = new Measurement(locationLatitude, locationLongitude);
} catch (LocationInvalidException e) {
e.printStackTrace();
}
}
/**
* Returns the sensor properties as a string
* @return
*/
public String getCurrentSensorString(){
if(PreferenceManager.getDefaultSharedPreferences(this).contains(ECApplication.PREF_KEY_SENSOR_ID) &&
PreferenceManager.getDefaultSharedPreferences(this).contains(ECApplication.PREF_KEY_FUEL_TYPE) &&
PreferenceManager.getDefaultSharedPreferences(this).contains(ECApplication.PREF_KEY_CAR_CONSTRUCTION_YEAR) &&
PreferenceManager.getDefaultSharedPreferences(this).contains(ECApplication.PREF_KEY_CAR_MODEL) &&
PreferenceManager.getDefaultSharedPreferences(this).contains(ECApplication.PREF_KEY_CAR_MANUFACTURER)){
String prefSensorid = PreferenceManager.getDefaultSharedPreferences(this).getString(ECApplication.PREF_KEY_SENSOR_ID, "nosensor");
String prefFuelType = PreferenceManager.getDefaultSharedPreferences(this).getString(ECApplication.PREF_KEY_FUEL_TYPE, "nosensor");
String prefYear = PreferenceManager.getDefaultSharedPreferences(this).getString(ECApplication.PREF_KEY_CAR_CONSTRUCTION_YEAR, "nosensor");
String prefModel = PreferenceManager.getDefaultSharedPreferences(this).getString(ECApplication.PREF_KEY_CAR_MODEL, "nosensor");
String prefManu = PreferenceManager.getDefaultSharedPreferences(this).getString(ECApplication.PREF_KEY_CAR_MANUFACTURER, "nosensor");
if(prefSensorid.equals("nosensor") == false ||
prefYear.equals("nosensor") == false ||
prefFuelType.equals("nosensor") == false ||
prefModel.equals("nosensor") == false ||
prefManu.equals("nosensor") == false ){
return prefManu+" "+prefModel+" ("+prefFuelType+" "+prefYear+")";
}
}
return getResources().getString(R.string.no_sensor_selected);
}
/**
* This method determines whether it is necessary to create a new track or
* of the current/last used track should be reused
*/
public void createNewTrackIfNecessary() {
// setting undefined, will hopefully prevent correct uploading.
// but this shouldn't be possible to record tracks without these values
String fuelType = preferences
.getString(PREF_KEY_FUEL_TYPE, "undefined");
String carManufacturer = preferences.getString(
PREF_KEY_CAR_MANUFACTURER, "undefined");
String carModel = preferences
.getString(PREF_KEY_CAR_MODEL, "undefined");
String sensorId = preferences
.getString(PREF_KEY_SENSOR_ID, "undefined");
// if track is null, create a new one or take the last one from the
// database
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
- int day = calendar.get(Calendar.DAY_OF_MONTH);
+ int day = calendar.get(Calendar.DAY_OF_MONTH)+1;
String date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day);
if (track == null) {
Log.e("obd2", "The track was null");
Track lastUsedTrack;
try {
lastUsedTrack = dbAdapterLocal.getLastUsedTrack();
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - lastUsedTrack
.getLastMeasurement().getMeasurementTime()) > 3600000) {
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
return;
}
// new track if last position is significantly different
// from the current position (more than 3 km)
if (Utils.getDistance(lastUsedTrack.getLastMeasurement().getLatitude(),lastUsedTrack.getLastMeasurement().getLongitude(),
locationLatitude, locationLongitude) > 3.0) {
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
return;
}
// TODO: New track if user clicks on create new track button
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
track = lastUsedTrack;
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "The last track contains no measurements. I will delete it and create a new one.");
dbAdapterLocal.deleteTrack(lastUsedTrack.getId());
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
}
} catch (TracksException e) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
e.printStackTrace();
Log.e("obd2",
"There was no track in the database so I created a new one");
}
return;
}
// if track is not null, determine whether it is useful to create a new
// track and store the current one
if (track != null) {
Log.e("obd2", "the track was not null");
Track currentTrack = track;
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - currentTrack
.getLastMeasurement().getMeasurementTime()) > 3600000) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
return;
}
// TODO: New track if user clicks on create new track button
// new track if last position is significantly different from
// the
// current position (more than 3 km)
if (Utils.getDistance(currentTrack.getLastMeasurement().getLatitude(),currentTrack.getLastMeasurement().getLongitude(),
locationLatitude, locationLongitude) > 3.0) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
return;
}
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "The last track contains no measurements. I will delete it and create a new one.");
dbAdapterLocal.deleteTrack(currentTrack.getId());
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
}
}
}
/**
* This method opens both dbadapters or also gets them and opens them afterwards.
*/
private void initDbAdapter() {
if (dbAdapterLocal == null) {
dbAdapterLocal = new DbAdapterLocal(this.getApplicationContext());
dbAdapterLocal.open();
} else {
if (!dbAdapterLocal.isOpen())
dbAdapterLocal.open();
}
if (dbAdapterRemote == null) {
dbAdapterRemote = new DbAdapterRemote(this.getApplicationContext());
dbAdapterRemote.open();
} else {
if (!dbAdapterRemote.isOpen())
dbAdapterRemote.open();
}
}
/**
* Checks if a track with specific index is already present in the
* dbAdapterRemote
*
* @param index
* @return true if track already stored, false if track is new
*/
public boolean trackAlreadyInDB(String index) {
boolean matchFound = false;
ArrayList<Track> allStoredTracks = dbAdapterRemote.getAllTracks();
for (Track trackCompare : allStoredTracks) {
Log.i("obd2", "comparing: " + index + "");
Log.i("obd2", "to: " + trackCompare.getId() + "");
if (trackCompare.getId().equals(index)) {
Log.i("obd2", "match found");
matchFound = true;
return matchFound;
}
}
return matchFound;
}
/**
* Get a user object from the shared preferences
* @return the user that is stored on the device
*/
private User getUserFromSharedPreferences() {
if (preferences.contains("username") && preferences.contains("token")) {
return new User(preferences.getString("username", "anonymous"),
preferences.getString("token", "anon"));
}
return null;
}
/**
* Set the user (to the application and also store it in the preferences)
* @param user The user you want to set
*/
public void setUser(User user) {
ECApplication.user = user;
Editor e = preferences.edit();
e.putString("username", user.getUsername());
e.putString("token", user.getToken());
e.apply();
}
/**
* Get the user
* @return user
*/
public User getUser() {
return user;
}
/**
* Determines whether the user is logged in. A user is logged in when
* the application has a user as a variable.
* @return
*/
public boolean isLoggedIn() {
return user != null;
}
/**
* Logs out the user.
*/
public void logOut() {
Editor e = preferences.edit();
if (preferences.contains("username"))
e.remove("username");
if (preferences.contains("token"))
e.remove("token");
e.commit();
user = null;
}
/**
* Returns the local db adadpter. This has to be called by other
* functions in order to work with the data (change tracks and measurements).
* @return the local db adapter
*/
public DbAdapter getDbAdapterLocal() {
initDbAdapter();
return dbAdapterLocal;
}
/**
* Get the remote db adapter (to work with the measurements from the server).
* @return the remote dbadapter
*/
public DbAdapter getDbAdapterRemote() {
initDbAdapter();
return dbAdapterRemote;
}
/**
* Starts the location manager again after an resume.
*/
public void startLocationManager() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
/**
* Stops the location manager (removeUpdates) for pause.
*/
public void stopLocating() {
if(locationManager != null){
locationManager.removeUpdates(this);
}
}
/**
* This method starts the service that connects to the adapter to the app.
*/
public void startBackgroundService() {
if (requirementsFulfilled()) {
Log.e("obd2", "requirements met");
backgroundService = new Intent(this, BackgroundService.class);
serviceConnector = new ServiceConnector();
serviceConnector.setServiceListener(listener);
bindService(backgroundService, serviceConnector,
Context.BIND_AUTO_CREATE);
} else {
Log.e("obd2", "requirements not met");
}
}
/**
* This method starts the service connector every five minutes if the user
* wants an autoconnection
*/
public void startServiceConnector() {
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
if (requirementsFulfilled()) {
if (!serviceConnector.isRunning()) {
startConnection();
} else {
Log.e("obd2", "serviceConnector not running");
}
} else {
Log.e("obd2", "requirementsFulfilled was false!");
}
}
}, 0, 5, TimeUnit.MINUTES);
}
/**
* This method starts the listener that interprets the answers from the BT adapter.
*/
public void startListener() {
listener = new Listener() {
public void receiveUpdate(CommonCommand job) {
Log.e("obd2", "update received");
// Get the name and the result of the Command
String commandName = job.getCommandName();
String commandResult = job.getResult();
Log.i("btlogger", commandName + " " + commandResult);
if (commandResult.equals("NODATA"))
return;
/*
* Check which measurent is returned and save the value in the
* previously created measurement
*/
// Speed
if (commandName.equals("Vehicle Speed")) {
try {
speedMeasurement = Integer.valueOf(commandResult);
} catch (NumberFormatException e) {
Log.e("obd2", "speed parse exception");
e.printStackTrace();
}
}
//RPM
if (commandName.equals("Engine RPM")) {
// TextView speedTextView = (TextView)
// findViewById(R.id.spd_text);
// speedTextView.setText(commandResult + " km/h");
try {
rpmMeasurement = Integer.valueOf(commandResult);
} catch (NumberFormatException e) {
Log.e("obd2", "rpm parse exception");
e.printStackTrace();
}
}
//IntakePressure
if (commandName.equals("Intake Manifold Pressure")) {
// TextView speedTextView = (TextView)
// findViewById(R.id.spd_text);
// speedTextView.setText(commandResult + " km/h");
try {
intakePressureMeasurement = Integer.valueOf(commandResult);
} catch (NumberFormatException e) {
Log.e("obd2", "Intake Pressure parse exception");
e.printStackTrace();
}
}
//IntakeTemperature
if (commandName.equals("Air Intake Temperature")) {
// TextView speedTextView = (TextView)
// findViewById(R.id.spd_text);
// speedTextView.setText(commandResult + " km/h");
try {
intakeTemperatureMeasurement = Integer.valueOf(commandResult);
} catch (NumberFormatException e) {
Log.e("obd2", "Intake Temperature parse exception");
e.printStackTrace();
}
}
//calculate alternative maf from iat, map, rpm
double imap = rpmMeasurement * intakePressureMeasurement / (intakeTemperatureMeasurement+273);
//VE = 85 in most modern cars
double calculatedMaf = imap / 120.0 * 85/100 * Float.parseFloat(preferences.getString("pref_engine_displacement","2.0")) * 28.97 / 8.317;
calculatedMafMeasurement = calculatedMaf;
// MAF
if (commandName.equals("Mass Air Flow")) {
String maf = commandResult;
try {
NumberFormat format = NumberFormat
.getInstance(Locale.GERMAN);
Number number;
number = format.parse(maf);
mafMeasurement = number.doubleValue();
// Dashboard Co2 current value preparation
double consumption = 0.0;
if (mafMeasurement > 0.0) {
if (preferences.getString(PREF_KEY_FUEL_TYPE,
"gasoline").equals("gasoline")) {
consumption = (mafMeasurement / 14.7) / 747;
} else if (preferences.getString(
PREF_KEY_FUEL_TYPE, "gasoline").equals(
"diesel")) {
consumption = (mafMeasurement / 14.5) / 832;
}
}else{
if (preferences.getString(PREF_KEY_FUEL_TYPE,
"gasoline").equals("gasoline")) {
consumption = (calculatedMafMeasurement / 14.7) / 747;
} else if (preferences.getString(
PREF_KEY_FUEL_TYPE, "gasoline").equals(
"diesel")) {
consumption = (calculatedMafMeasurement / 14.5) / 832;
}
}
if (preferences.getString(PREF_KEY_FUEL_TYPE,
"gasoline").equals("gasoline")) {
co2Measurement = consumption * 2.35;
} else if (preferences.getString(PREF_KEY_FUEL_TYPE,
"gasoline").equals("diesel")) {
co2Measurement = consumption * 2.65;
}
} catch (ParseException e) {
Log.e("obd", "parse exception maf");
e.printStackTrace();
} catch (java.text.ParseException e) {
Log.e("obd", "parse exception maf");
e.printStackTrace();
}
}
// Update and insert the measurement
updateMeasurement();
}
};
}
/**
* Stop the service connector and therefore the scheduled tasks.
*/
public void stopServiceConnector() {
scheduleTaskExecutor.shutdown();
}
/**
* Connects to the Bluetooth Adapter and starts the execution of the
* commands. also opens the db and starts the gps.
*/
public void startConnection() {
initDbAdapter();
startLocationManager();
//createNewTrackIfNecessary();
if (!serviceConnector.isRunning()) {
Log.e("obd2", "service start");
startService(backgroundService);
bindService(backgroundService, serviceConnector,
Context.BIND_AUTO_CREATE);
}
handler.post(waitingListRunnable);
}
/**
* Ends the connection with the Bluetooth Adapter. also stops gps and closes the db.
*/
public void stopConnection() {
if (serviceConnector.isRunning()) {
stopService(backgroundService);
unbindService(serviceConnector);
}
handler.removeCallbacks(waitingListRunnable);
stopLocating();
closeDb();
}
/**
* Handles the waiting-list
*/
private Runnable waitingListRunnable = new Runnable() {
public void run() {
if (serviceConnector.isRunning())
addCommandstoWaitinglist();
handler.postDelayed(waitingListRunnable, 2000);
}
};
/**
* Helper method that adds the desired commands to the waiting list where
* all commands are executed
*/
private void addCommandstoWaitinglist() {
final CommonCommand speed = new Speed();
final CommonCommand maf = new MAF();
final CommonCommand rpm = new RPM();
final CommonCommand intakePressure = new IntakePressure();
final CommonCommand intakeTemperature = new IntakeTemperature();
serviceConnector.addJobToWaitingList(speed);
serviceConnector.addJobToWaitingList(maf);
serviceConnector.addJobToWaitingList(rpm);
serviceConnector.addJobToWaitingList(intakePressure);
serviceConnector.addJobToWaitingList(intakeTemperature);
}
/**
* Helper Command that updates the current measurement with the last
* measurement data and inserts it into the database if the measurements is
* young enough
*/
public void updateMeasurement() {
// Create track new measurement if necessary
if (measurement == null) {
try {
measurement = new Measurement(locationLatitude,
locationLongitude);
} catch (LocationInvalidException e) {
e.printStackTrace();
}
}
// Insert the values if the measurement (with the coordinates) is young
// enough (5000ms) or create track new one if it is too old
if (measurement != null) {
if (Math.abs(measurement.getMeasurementTime()
- System.currentTimeMillis()) < 5000) {
measurement.setSpeed(speedMeasurement);
measurement.setMaf(mafMeasurement);
measurement.setCalculatedMaf(calculatedMafMeasurement);
measurement.setRpm(rpmMeasurement);
measurement.setIntakePressure(intakePressureMeasurement);
measurement.setIntakeTemperature(intakeTemperatureMeasurement);
Log.e("obd2", "new measurement");
Log.e("obd2",
measurement.getLatitude() + " "
+ measurement.getLongitude());
Log.e("obd2", measurement.toString());
insertMeasurement(measurement);
} else {
try {
measurement = new Measurement(locationLatitude,
locationLongitude);
} catch (LocationInvalidException e) {
e.printStackTrace();
}
}
}
}
/**
* Helper method to insert track measurement into the database (ensures that
* track measurement is only stored every 5 seconds and not faster...)
*
* @param measurement2
* The measurement you want to insert
*/
private void insertMeasurement(Measurement measurement2) {
// TODO: This has to be added with the following conditions:
/*
* 1)New measurement if more than 50 meters away 2)New measurement if
* last measurement more than 1 minute ago 3)New measurement if MAF
* value changed significantly (whatever this means... we will have to
* investigate on that. also it is not clear whether we should use this
* condition because we are vulnerable to noise from the sensor.
* therefore, we should include a minimum time between measurements (1
* sec) as well.)
*/
if (Math.abs(lastInsertTime - measurement2.getMeasurementTime()) > 5000) {
lastInsertTime = measurement2.getMeasurementTime();
track.addMeasurement(measurement2);
Log.i("obd2", measurement2.toString());
//Toast.makeText(getApplicationContext(), measurement2.toString(),
// Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "" + measurement.getCalculatedMaf(),
Toast.LENGTH_SHORT).show();
}
}
/**
* Init the location Manager
*/
private void initLocationManager() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
// 0,
// 0, this);
}
/**
* Stops gps, kills service, kills service connector, kills listener and handler
*/
public void destroyStuff() {
stopLocating();
locationManager = null;
backgroundService = null;
serviceConnector = null;
listener = null;
handler = null;
}
/**
* updates the location variables when the device moved
*/
@Override
public void onLocationChanged(Location location) {
locationLatitude = (float) location.getLatitude();
locationLongitude = (float) location.getLongitude();
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String arg0) {
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
/**
* Closes both databases.
*/
public void closeDb() {
if (dbAdapterLocal != null) {
dbAdapterLocal.close();
// dbAdapterLocal = null;
}
if (dbAdapterRemote != null) {
dbAdapterRemote.close();
// dbAdapterRemote = null;
}
}
/**
* @return the speedMeasurement
*/
public int getSpeedMeasurement() {
return speedMeasurement;
}
/**
* @return the track
*/
public Track getTrack() {
return track;
}
/**
* @param track
* the track to set
*/
public void setTrack(Track track) {
this.track = track;
}
/**
*
* @return the current co2 value
*/
public double getCo2Measurement() {
return co2Measurement;
}
/**
*
* @action Can also contain the http status code with error if fail
*/
public void createNotification(String action) {
String notification_text = "";
if(action.equals("success")){
notification_text = getString(R.string.upload_notification_success);
}else if(action.equals("start")){
notification_text = getString(R.string.upload_notification);
}else{
notification_text = action;
}
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("EnviroCar")
.setContentText(notification_text)
.setContentIntent(pintent)
.setTicker(notification_text)
.setProgress(0, 0, !action.equals("success"));
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
}
/**
* method to get the current version
*
*/
public String getVersionString() {
StringBuilder out = new StringBuilder("Version ");
try {
out.append(this.getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
out.append(" (");
out.append(this.getPackageManager().getPackageInfo(getPackageName(), 0).versionCode);
out.append("), ");
} catch (NameNotFoundException e) {
}
try {
ApplicationInfo ai = getPackageManager().getApplicationInfo(
getPackageName(), 0);
ZipFile zf = new ZipFile(ai.sourceDir);
ZipEntry ze = zf.getEntry("classes.dex");
long time = ze.getTime();
out.append(SimpleDateFormat.getInstance().format(new java.util.Date(time)));
} catch (Exception e) {
}
return out.toString();
}
/**
* @return the imperialUnits
*/
public boolean isImperialUnits() {
return imperialUnits;
}
/**
* @param imperialUnits the imperialUnits to set
*/
public void setImperialUnits(boolean imperialUnits) {
this.imperialUnits = imperialUnits;
}
public final BroadcastReceiver bluetoothChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_ON:
Log.i("bt","is now on");
startBackgroundService();
break;
}
}
}
};
}
| true | true | public void createNewTrackIfNecessary() {
// setting undefined, will hopefully prevent correct uploading.
// but this shouldn't be possible to record tracks without these values
String fuelType = preferences
.getString(PREF_KEY_FUEL_TYPE, "undefined");
String carManufacturer = preferences.getString(
PREF_KEY_CAR_MANUFACTURER, "undefined");
String carModel = preferences
.getString(PREF_KEY_CAR_MODEL, "undefined");
String sensorId = preferences
.getString(PREF_KEY_SENSOR_ID, "undefined");
// if track is null, create a new one or take the last one from the
// database
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day);
if (track == null) {
Log.e("obd2", "The track was null");
Track lastUsedTrack;
try {
lastUsedTrack = dbAdapterLocal.getLastUsedTrack();
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - lastUsedTrack
.getLastMeasurement().getMeasurementTime()) > 3600000) {
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
return;
}
// new track if last position is significantly different
// from the current position (more than 3 km)
if (Utils.getDistance(lastUsedTrack.getLastMeasurement().getLatitude(),lastUsedTrack.getLastMeasurement().getLongitude(),
locationLatitude, locationLongitude) > 3.0) {
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
return;
}
// TODO: New track if user clicks on create new track button
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
track = lastUsedTrack;
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "The last track contains no measurements. I will delete it and create a new one.");
dbAdapterLocal.deleteTrack(lastUsedTrack.getId());
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
}
} catch (TracksException e) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
e.printStackTrace();
Log.e("obd2",
"There was no track in the database so I created a new one");
}
return;
}
// if track is not null, determine whether it is useful to create a new
// track and store the current one
if (track != null) {
Log.e("obd2", "the track was not null");
Track currentTrack = track;
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - currentTrack
.getLastMeasurement().getMeasurementTime()) > 3600000) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
return;
}
// TODO: New track if user clicks on create new track button
// new track if last position is significantly different from
// the
// current position (more than 3 km)
if (Utils.getDistance(currentTrack.getLastMeasurement().getLatitude(),currentTrack.getLastMeasurement().getLongitude(),
locationLatitude, locationLongitude) > 3.0) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
return;
}
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "The last track contains no measurements. I will delete it and create a new one.");
dbAdapterLocal.deleteTrack(currentTrack.getId());
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
}
}
}
| public void createNewTrackIfNecessary() {
// setting undefined, will hopefully prevent correct uploading.
// but this shouldn't be possible to record tracks without these values
String fuelType = preferences
.getString(PREF_KEY_FUEL_TYPE, "undefined");
String carManufacturer = preferences.getString(
PREF_KEY_CAR_MANUFACTURER, "undefined");
String carModel = preferences
.getString(PREF_KEY_CAR_MODEL, "undefined");
String sensorId = preferences
.getString(PREF_KEY_SENSOR_ID, "undefined");
// if track is null, create a new one or take the last one from the
// database
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH)+1;
String date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day);
if (track == null) {
Log.e("obd2", "The track was null");
Track lastUsedTrack;
try {
lastUsedTrack = dbAdapterLocal.getLastUsedTrack();
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - lastUsedTrack
.getLastMeasurement().getMeasurementTime()) > 3600000) {
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
return;
}
// new track if last position is significantly different
// from the current position (more than 3 km)
if (Utils.getDistance(lastUsedTrack.getLastMeasurement().getLatitude(),lastUsedTrack.getLastMeasurement().getLongitude(),
locationLatitude, locationLongitude) > 3.0) {
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
return;
}
// TODO: New track if user clicks on create new track button
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
track = lastUsedTrack;
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "The last track contains no measurements. I will delete it and create a new one.");
dbAdapterLocal.deleteTrack(lastUsedTrack.getId());
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
}
} catch (TracksException e) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
e.printStackTrace();
Log.e("obd2",
"There was no track in the database so I created a new one");
}
return;
}
// if track is not null, determine whether it is useful to create a new
// track and store the current one
if (track != null) {
Log.e("obd2", "the track was not null");
Track currentTrack = track;
try {
// New track if last measurement is more than 60 minutes
// ago
if ((System.currentTimeMillis() - currentTrack
.getLastMeasurement().getMeasurementTime()) > 3600000) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
Log.e("obd2",
"I create a new track because the last measurement is more than 60 mins ago");
return;
}
// TODO: New track if user clicks on create new track button
// new track if last position is significantly different from
// the
// current position (more than 3 km)
if (Utils.getDistance(currentTrack.getLastMeasurement().getLatitude(),currentTrack.getLastMeasurement().getLongitude(),
locationLatitude, locationLongitude) > 3.0) {
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
Log.e("obd2",
"The last measurement's position is more than 3 km away. I will create a new track");
return;
}
// TODO: new track if VIN changed
else {
Log.e("obd2",
"I will append to the last track because that still makes sense");
return;
}
} catch (MeasurementsException e) {
Log.e("obd", "The last track contains no measurements. I will delete it and create a new one.");
dbAdapterLocal.deleteTrack(currentTrack.getId());
track = new Track("123456", fuelType, carManufacturer,
carModel, sensorId, dbAdapterLocal);
track.setName("Track " + date);
track.setDescription(trackDescription);
track.commitTrackToDatabase();
}
}
}
|
diff --git a/ui/plugins/eu.esdihumboldt.hale.ui.views.report/src/eu/esdihumboldt/hale/ui/views/report/ReportListLabelDateProvider.java b/ui/plugins/eu.esdihumboldt.hale.ui.views.report/src/eu/esdihumboldt/hale/ui/views/report/ReportListLabelDateProvider.java
index cde1eb0e7..598ce9461 100644
--- a/ui/plugins/eu.esdihumboldt.hale.ui.views.report/src/eu/esdihumboldt/hale/ui/views/report/ReportListLabelDateProvider.java
+++ b/ui/plugins/eu.esdihumboldt.hale.ui.views.report/src/eu/esdihumboldt/hale/ui/views/report/ReportListLabelDateProvider.java
@@ -1,87 +1,87 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2011.
*/
package eu.esdihumboldt.hale.ui.views.report;
import java.text.SimpleDateFormat;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.swt.graphics.Image;
import eu.esdihumboldt.hale.common.core.report.Report;
/**
* LabelProvider for {@link ReportList}, which provides date and time
* information.
*
* @author Andreas Burchert
* @partner 01 / Fraunhofer Institute for Computer Graphics Research
*/
public class ReportListLabelDateProvider implements ILabelProvider {
private SimpleDateFormat df = new SimpleDateFormat("HH:mm.ss");
/**
* @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener)
*/
@Override
public void addListener(ILabelProviderListener listener) {
/* not supported/needed */
}
/**
* @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
*/
@Override
public void dispose() {
/* not supported/needed */
}
/**
* @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object, java.lang.String)
*/
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
/**
* @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener)
*/
@Override
public void removeListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
}
/**
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
@Override
public Image getImage(Object element) {
return null;
}
/**
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
@Override
public String getText(Object element) {
- if (element instanceof Report<?>) {
+ if (element instanceof Report<?> && ((Report<?>) element).getStartTime() != null) {
return df.format(((Report<?>) element).getStartTime());
}
return "";
}
}
| true | true | public String getText(Object element) {
if (element instanceof Report<?>) {
return df.format(((Report<?>) element).getStartTime());
}
return "";
}
| public String getText(Object element) {
if (element instanceof Report<?> && ((Report<?>) element).getStartTime() != null) {
return df.format(((Report<?>) element).getStartTime());
}
return "";
}
|
diff --git a/src/org/madlonkay/supertmxmerge/gui/DiffWindow.java b/src/org/madlonkay/supertmxmerge/gui/DiffWindow.java
index cb9f36e..7c63f6a 100644
--- a/src/org/madlonkay/supertmxmerge/gui/DiffWindow.java
+++ b/src/org/madlonkay/supertmxmerge/gui/DiffWindow.java
@@ -1,191 +1,191 @@
/*
* Copyright (C) 2013 Aaron Madlon-Kay <[email protected]>.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.madlonkay.supertmxmerge.gui;
import java.util.List;
import javax.swing.ToolTipManager;
import org.madlonkay.supertmxmerge.DiffController;
import org.madlonkay.supertmxmerge.data.DiffInfo;
import org.madlonkay.supertmxmerge.util.GuiUtil;
import org.madlonkay.supertmxmerge.util.LocString;
/**
*
* @author Aaron Madlon-Kay <[email protected]>
*/
public class DiffWindow extends javax.swing.JFrame {
private final ProgressWindow progress;
/**
* Creates new form DiffWindow
*/
public DiffWindow(DiffController controller) {
progress = new ProgressWindow();
this.controller = controller;
initComponents();
// Keep tooltips open. Via:
// http://www.rgagnon.com/javadetails/java-0528.html
ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE);
initContent();
}
private void initContent() {
List<DiffInfo> infos = controller.getDiffInfos();
progress.setMaximum(infos.size());
int n = 1;
for (DiffInfo info : infos) {
progress.setValue(n);
progress.setMessage(LocString.getFormat("diff_progress", n, infos.size()));
diffsPanel.add(new DiffCell(n, info));
n++;
}
}
private DiffController getController() {
return controller;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
controller = getController();
unitCountConverter = new LocStringConverter("number_of_units", "number_of_units_singular");
changeCountConverter = new LocStringConverter("number_of_changes", "number_of_changes_singular");
mapToTextConverter = new org.madlonkay.supertmxmerge.gui.MapToTextConverter();
jPanel3 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
file1Label = new javax.swing.JLabel();
file2Label = new javax.swing.JLabel();
file1TextUnits = new javax.swing.JLabel();
file2TextUnits = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
changeCountLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
diffsPanel = new org.madlonkay.supertmxmerge.gui.ReasonablySizedPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(LocString.get("diff_window_title")); // NOI18N
setLocationByPlatform(true);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.PAGE_AXIS));
jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
- jPanel2.setLayout(new java.awt.GridLayout(2, 2, 0, 10));
+ jPanel2.setLayout(new java.awt.GridLayout(2, 2, 10, 0));
file1Label.setFont(file1Label.getFont().deriveFont(file1Label.getFont().getStyle() | java.awt.Font.BOLD, file1Label.getFont().getSize()+2));
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.name}"), file1Label, org.jdesktop.beansbinding.BeanProperty.create("text"), "file1Name");
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.metadata}"), file1Label, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"), "file1Metadata");
binding.setSourceNullValue(LocString.get("tmx_details_unavailable")); // NOI18N
binding.setConverter(mapToTextConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file1Label);
file2Label.setFont(file2Label.getFont().deriveFont(file2Label.getFont().getStyle() | java.awt.Font.BOLD, file2Label.getFont().getSize()+2));
file2Label.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.name}"), file2Label, org.jdesktop.beansbinding.BeanProperty.create("text"), "file2Name");
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.metadata}"), file2Label, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"), "tmx2Metadata");
binding.setSourceNullValue(LocString.get("tmx_details_unavailable")); // NOI18N
binding.setConverter(mapToTextConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file2Label);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.size}"), file1TextUnits, org.jdesktop.beansbinding.BeanProperty.create("text"), "file1UnitCount");
binding.setConverter(unitCountConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file1TextUnits);
file2TextUnits.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.size}"), file2TextUnits, org.jdesktop.beansbinding.BeanProperty.create("text"), "file2UnitCount");
binding.setConverter(unitCountConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file2TextUnits);
jPanel3.add(jPanel2);
jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.LINE_AXIS));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${changeCount}"), changeCountLabel, org.jdesktop.beansbinding.BeanProperty.create("text"), "changeCount");
binding.setConverter(changeCountConverter);
bindingGroup.addBinding(binding);
jPanel4.add(changeCountLabel);
jPanel3.add(jPanel4);
getContentPane().add(jPanel3, java.awt.BorderLayout.NORTH);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
diffsPanel.setLayout(new javax.swing.BoxLayout(diffsPanel, javax.swing.BoxLayout.PAGE_AXIS));
jScrollPane1.setViewportView(diffsPanel);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
bindingGroup.bind();
pack();
}// </editor-fold>//GEN-END:initComponents
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
GuiUtil.closeWindow(progress);
}//GEN-LAST:event_formComponentShown
// Variables declaration - do not modify//GEN-BEGIN:variables
private org.madlonkay.supertmxmerge.gui.LocStringConverter changeCountConverter;
private javax.swing.JLabel changeCountLabel;
private org.madlonkay.supertmxmerge.DiffController controller;
private org.madlonkay.supertmxmerge.gui.ReasonablySizedPanel diffsPanel;
private javax.swing.JLabel file1Label;
private javax.swing.JLabel file1TextUnits;
private javax.swing.JLabel file2Label;
private javax.swing.JLabel file2TextUnits;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private org.madlonkay.supertmxmerge.gui.MapToTextConverter mapToTextConverter;
private org.madlonkay.supertmxmerge.gui.LocStringConverter unitCountConverter;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
controller = getController();
unitCountConverter = new LocStringConverter("number_of_units", "number_of_units_singular");
changeCountConverter = new LocStringConverter("number_of_changes", "number_of_changes_singular");
mapToTextConverter = new org.madlonkay.supertmxmerge.gui.MapToTextConverter();
jPanel3 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
file1Label = new javax.swing.JLabel();
file2Label = new javax.swing.JLabel();
file1TextUnits = new javax.swing.JLabel();
file2TextUnits = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
changeCountLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
diffsPanel = new org.madlonkay.supertmxmerge.gui.ReasonablySizedPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(LocString.get("diff_window_title")); // NOI18N
setLocationByPlatform(true);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.PAGE_AXIS));
jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
jPanel2.setLayout(new java.awt.GridLayout(2, 2, 0, 10));
file1Label.setFont(file1Label.getFont().deriveFont(file1Label.getFont().getStyle() | java.awt.Font.BOLD, file1Label.getFont().getSize()+2));
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.name}"), file1Label, org.jdesktop.beansbinding.BeanProperty.create("text"), "file1Name");
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.metadata}"), file1Label, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"), "file1Metadata");
binding.setSourceNullValue(LocString.get("tmx_details_unavailable")); // NOI18N
binding.setConverter(mapToTextConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file1Label);
file2Label.setFont(file2Label.getFont().deriveFont(file2Label.getFont().getStyle() | java.awt.Font.BOLD, file2Label.getFont().getSize()+2));
file2Label.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.name}"), file2Label, org.jdesktop.beansbinding.BeanProperty.create("text"), "file2Name");
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.metadata}"), file2Label, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"), "tmx2Metadata");
binding.setSourceNullValue(LocString.get("tmx_details_unavailable")); // NOI18N
binding.setConverter(mapToTextConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file2Label);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.size}"), file1TextUnits, org.jdesktop.beansbinding.BeanProperty.create("text"), "file1UnitCount");
binding.setConverter(unitCountConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file1TextUnits);
file2TextUnits.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.size}"), file2TextUnits, org.jdesktop.beansbinding.BeanProperty.create("text"), "file2UnitCount");
binding.setConverter(unitCountConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file2TextUnits);
jPanel3.add(jPanel2);
jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.LINE_AXIS));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${changeCount}"), changeCountLabel, org.jdesktop.beansbinding.BeanProperty.create("text"), "changeCount");
binding.setConverter(changeCountConverter);
bindingGroup.addBinding(binding);
jPanel4.add(changeCountLabel);
jPanel3.add(jPanel4);
getContentPane().add(jPanel3, java.awt.BorderLayout.NORTH);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
diffsPanel.setLayout(new javax.swing.BoxLayout(diffsPanel, javax.swing.BoxLayout.PAGE_AXIS));
jScrollPane1.setViewportView(diffsPanel);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
bindingGroup.bind();
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
controller = getController();
unitCountConverter = new LocStringConverter("number_of_units", "number_of_units_singular");
changeCountConverter = new LocStringConverter("number_of_changes", "number_of_changes_singular");
mapToTextConverter = new org.madlonkay.supertmxmerge.gui.MapToTextConverter();
jPanel3 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
file1Label = new javax.swing.JLabel();
file2Label = new javax.swing.JLabel();
file1TextUnits = new javax.swing.JLabel();
file2TextUnits = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
changeCountLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
diffsPanel = new org.madlonkay.supertmxmerge.gui.ReasonablySizedPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(LocString.get("diff_window_title")); // NOI18N
setLocationByPlatform(true);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.PAGE_AXIS));
jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
jPanel2.setLayout(new java.awt.GridLayout(2, 2, 10, 0));
file1Label.setFont(file1Label.getFont().deriveFont(file1Label.getFont().getStyle() | java.awt.Font.BOLD, file1Label.getFont().getSize()+2));
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.name}"), file1Label, org.jdesktop.beansbinding.BeanProperty.create("text"), "file1Name");
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.metadata}"), file1Label, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"), "file1Metadata");
binding.setSourceNullValue(LocString.get("tmx_details_unavailable")); // NOI18N
binding.setConverter(mapToTextConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file1Label);
file2Label.setFont(file2Label.getFont().deriveFont(file2Label.getFont().getStyle() | java.awt.Font.BOLD, file2Label.getFont().getSize()+2));
file2Label.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.name}"), file2Label, org.jdesktop.beansbinding.BeanProperty.create("text"), "file2Name");
bindingGroup.addBinding(binding);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.metadata}"), file2Label, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"), "tmx2Metadata");
binding.setSourceNullValue(LocString.get("tmx_details_unavailable")); // NOI18N
binding.setConverter(mapToTextConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file2Label);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.size}"), file1TextUnits, org.jdesktop.beansbinding.BeanProperty.create("text"), "file1UnitCount");
binding.setConverter(unitCountConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file1TextUnits);
file2TextUnits.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.size}"), file2TextUnits, org.jdesktop.beansbinding.BeanProperty.create("text"), "file2UnitCount");
binding.setConverter(unitCountConverter);
bindingGroup.addBinding(binding);
jPanel2.add(file2TextUnits);
jPanel3.add(jPanel2);
jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.LINE_AXIS));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${changeCount}"), changeCountLabel, org.jdesktop.beansbinding.BeanProperty.create("text"), "changeCount");
binding.setConverter(changeCountConverter);
bindingGroup.addBinding(binding);
jPanel4.add(changeCountLabel);
jPanel3.add(jPanel4);
getContentPane().add(jPanel3, java.awt.BorderLayout.NORTH);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
diffsPanel.setLayout(new javax.swing.BoxLayout(diffsPanel, javax.swing.BoxLayout.PAGE_AXIS));
jScrollPane1.setViewportView(diffsPanel);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
bindingGroup.bind();
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/sch-pek-ejb-impl/src/main/java/hu/sch/ejb/search/SearchQueryBuilder.java b/sch-pek-ejb-impl/src/main/java/hu/sch/ejb/search/SearchQueryBuilder.java
index 677b7579..9d7edd89 100644
--- a/sch-pek-ejb-impl/src/main/java/hu/sch/ejb/search/SearchQueryBuilder.java
+++ b/sch-pek-ejb-impl/src/main/java/hu/sch/ejb/search/SearchQueryBuilder.java
@@ -1,95 +1,96 @@
package hu.sch.ejb.search;
import hu.sch.domain.user.User;
import hu.sch.domain.user.UserAttribute;
import hu.sch.domain.user.UserAttributeName;
import hu.sch.domain.user.UserAttribute_;
import hu.sch.domain.user.User_;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
/**
* Builds the query for complex search.
*
* @author tomi
*/
public class SearchQueryBuilder {
private EntityManager em;
private final String keyword;
private Root<User> usr;
private Join<User, UserAttribute> privAttr;
private CriteriaBuilder builder;
public SearchQueryBuilder(EntityManager em, String keyword) {
this.em = em;
this.keyword = keyword;
}
public TypedQuery<User> build() {
builder = em.getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
usr = q.from(User.class);
privAttr = usr.join(User_.privateAttributes, JoinType.LEFT);
List<Predicate> andFilters = new ArrayList<>();
for (String word : keyword.split(" ")) {
Predicate or = builder.or(
buildLikeQueryPart(usr.get(User_.firstName), word),
buildLikeQueryPart(usr.get(User_.lastName), word),
buildLikeQueryPart(usr.get(User_.nickName), word),
buildLikeQueryPart(usr.get(User_.screenName), word),
buildEmailQueryPart(word),
buildRoomNumberQueryPart(word)
);
andFilters.add(or);
}
q.where(andFilters.toArray(new Predicate[andFilters.size()]));
+ q.distinct(true);
return em.createQuery(q);
}
private Predicate buildLikeQueryPart(Expression<String> expr, String word) {
return builder.like(builder.lower(expr), buildLikeString(word));
}
private String buildLikeString(String word) {
if (word == null) {
throw new IllegalArgumentException("Argument 'word' cannot be null");
}
return "%".concat(word.toLowerCase()).concat("%");
}
private Predicate buildEmailQueryPart(String word) {
return builder.and(
// email is visible
builder.equal(privAttr.get(UserAttribute_.attrName), UserAttributeName.EMAIL),
builder.isTrue(privAttr.get(UserAttribute_.visible)),
// and equals to the given word
builder.equal(usr.get(User_.emailAddress), word));
}
private Predicate buildRoomNumberQueryPart(String word) {
return builder.and(
// roomnumber is visible
builder.equal(privAttr.get(UserAttribute_.attrName), UserAttributeName.ROOM_NUMBER),
builder.isTrue(privAttr.get(UserAttribute_.visible)),
// room number consists of [dormitor] [room]
builder.or(
builder.like(usr.get(User_.dormitory), buildLikeString(word)),
builder.like(usr.get(User_.room), buildLikeString(word))
)
);
}
}
| true | true | public TypedQuery<User> build() {
builder = em.getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
usr = q.from(User.class);
privAttr = usr.join(User_.privateAttributes, JoinType.LEFT);
List<Predicate> andFilters = new ArrayList<>();
for (String word : keyword.split(" ")) {
Predicate or = builder.or(
buildLikeQueryPart(usr.get(User_.firstName), word),
buildLikeQueryPart(usr.get(User_.lastName), word),
buildLikeQueryPart(usr.get(User_.nickName), word),
buildLikeQueryPart(usr.get(User_.screenName), word),
buildEmailQueryPart(word),
buildRoomNumberQueryPart(word)
);
andFilters.add(or);
}
q.where(andFilters.toArray(new Predicate[andFilters.size()]));
return em.createQuery(q);
}
| public TypedQuery<User> build() {
builder = em.getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
usr = q.from(User.class);
privAttr = usr.join(User_.privateAttributes, JoinType.LEFT);
List<Predicate> andFilters = new ArrayList<>();
for (String word : keyword.split(" ")) {
Predicate or = builder.or(
buildLikeQueryPart(usr.get(User_.firstName), word),
buildLikeQueryPart(usr.get(User_.lastName), word),
buildLikeQueryPart(usr.get(User_.nickName), word),
buildLikeQueryPart(usr.get(User_.screenName), word),
buildEmailQueryPart(word),
buildRoomNumberQueryPart(word)
);
andFilters.add(or);
}
q.where(andFilters.toArray(new Predicate[andFilters.size()]));
q.distinct(true);
return em.createQuery(q);
}
|
diff --git a/nanite-hadoop/src/test/java/uk/bl/wap/hadoop/profiler/FormatProfilerTest.java b/nanite-hadoop/src/test/java/uk/bl/wap/hadoop/profiler/FormatProfilerTest.java
index 8cf5cc0..e0d00d5 100644
--- a/nanite-hadoop/src/test/java/uk/bl/wap/hadoop/profiler/FormatProfilerTest.java
+++ b/nanite-hadoop/src/test/java/uk/bl/wap/hadoop/profiler/FormatProfilerTest.java
@@ -1,168 +1,167 @@
/**
*
*/
package uk.bl.wap.hadoop.profiler;
import static org.junit.Assert.*;
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 org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MiniMRCluster;
import org.apache.hadoop.mapred.OutputLogFilter;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
/**
* @author Andrew Jackson <[email protected]>
*
*/
public class FormatProfilerTest {
private static final Log log = LogFactory.getLog(FormatProfiler.class);
// Test cluster:
private MiniDFSCluster dfsCluster = null;
private MiniMRCluster mrCluster = null;
// Input files:
// 1. The variations.warc.gz example is rather large, and there are mysterious problems parsing the statusCode.
// 2. System can't cope with uncompressed inputs right now.
private final String[] testWarcs = new String[] {
"IAH-urls-wget.warc.gz"
};
private final Path input = new Path("inputs");
private final Path output = new Path("outputs");
@Before
public void setUp() throws Exception {
// Print out the full config for debugging purposes:
//Config index_conf = ConfigFactory.load();
//LOG.debug(index_conf.root().render());
log.warn("Spinning up test cluster...");
// make sure the log folder exists,
// otherwise the test fill fail
new File("target/test-logs").mkdirs();
//
System.setProperty("hadoop.log.dir", "target/test-logs");
System.setProperty("javax.xml.parsers.SAXParserFactory",
"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
//
Configuration conf = new Configuration();
dfsCluster = new MiniDFSCluster(conf, 1, true, null );
dfsCluster.getFileSystem().makeQualified(input);
dfsCluster.getFileSystem().makeQualified(output);
//
mrCluster = new MiniMRCluster(1, getFileSystem().getUri().toString(), 1);
// prepare for tests
for( String filename : testWarcs ) {
copyFileToTestCluster(filename);
}
log.warn("Spun up test cluster.");
}
protected FileSystem getFileSystem() throws IOException {
return dfsCluster.getFileSystem();
}
private void copyFileToTestCluster(String filename) throws IOException {
Path targetPath = new Path(input, filename);
File sourceFile = new File("src/test/resources/"+filename);
log.info("Copying "+filename+" into cluster at "+targetPath.toUri()+"...");
FSDataOutputStream os = getFileSystem().create(targetPath);
InputStream is = new FileInputStream(sourceFile);
IOUtils.copy(is, os);
is.close();
os.close();
log.info("Copy completed.");
}
@Test
public void testFullFormatProfilerJob() throws Exception {
// prepare for test
//createTextInputFile();
log.info("Checking input file is present...");
// Check that the input file is present:
Path[] inputFiles = FileUtil.stat2Paths(getFileSystem().listStatus(
input, new OutputLogFilter()));
Assert.assertEquals(1, inputFiles.length);
// Set up arguments for the job:
// FIXME The input file could be written by this test.
String[] args = {"src/test/resources/test-inputs.txt", this.output.getName()};
// Set up the config and tool
Config config = ConfigFactory.load();
FormatProfiler wir = new FormatProfiler();
// run job
log.info("Setting up job config...");
JobConf conf = this.mrCluster.createJobConf();
wir.createJobConf(conf, args);
log.info("Running job...");
JobClient.runJob(conf);
log.info("Job finished, checking the results...");
// check the output
- Path[] outputFiles = FileUtil.stat2Paths(getFileSystem().listStatus(
- output, new OutputLogFilter()));
- //Assert.assertEquals( config.getInt( "warc.hadoop.num_reducers" ), outputFiles.length );
+ Path[] outputFiles = FileUtil.stat2Paths( getFileSystem().listStatus(output) );
+ Assert.assertEquals( config.getInt( "warc.hadoop.num_reducers" ) + 1, outputFiles.length );
// Check contents of the output:
for( Path output : outputFiles ) {
log.info(" --- output : "+output);
InputStream is = getFileSystem().open(output);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while( ( line = reader.readLine()) != null ) {
log.info(line);
if( line.startsWith("RECORD-TOTAL")) {
assertEquals("RECORD-TOTAL\t32",line);
}
}
reader.close();
}
//Assert.assertEquals("a\t2", reader.readLine());
//Assert.assertEquals("b\t1", reader.readLine());
//Assert.assertNull(reader.readLine());
}
@After
public void tearDown() throws Exception {
log.warn("Tearing down test cluster...");
if (dfsCluster != null) {
dfsCluster.shutdown();
dfsCluster = null;
}
if (mrCluster != null) {
mrCluster.shutdown();
mrCluster = null;
}
log.warn("Torn down test cluster.");
}}
| true | true | public void testFullFormatProfilerJob() throws Exception {
// prepare for test
//createTextInputFile();
log.info("Checking input file is present...");
// Check that the input file is present:
Path[] inputFiles = FileUtil.stat2Paths(getFileSystem().listStatus(
input, new OutputLogFilter()));
Assert.assertEquals(1, inputFiles.length);
// Set up arguments for the job:
// FIXME The input file could be written by this test.
String[] args = {"src/test/resources/test-inputs.txt", this.output.getName()};
// Set up the config and tool
Config config = ConfigFactory.load();
FormatProfiler wir = new FormatProfiler();
// run job
log.info("Setting up job config...");
JobConf conf = this.mrCluster.createJobConf();
wir.createJobConf(conf, args);
log.info("Running job...");
JobClient.runJob(conf);
log.info("Job finished, checking the results...");
// check the output
Path[] outputFiles = FileUtil.stat2Paths(getFileSystem().listStatus(
output, new OutputLogFilter()));
//Assert.assertEquals( config.getInt( "warc.hadoop.num_reducers" ), outputFiles.length );
// Check contents of the output:
for( Path output : outputFiles ) {
log.info(" --- output : "+output);
InputStream is = getFileSystem().open(output);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while( ( line = reader.readLine()) != null ) {
log.info(line);
if( line.startsWith("RECORD-TOTAL")) {
assertEquals("RECORD-TOTAL\t32",line);
}
}
reader.close();
}
//Assert.assertEquals("a\t2", reader.readLine());
//Assert.assertEquals("b\t1", reader.readLine());
//Assert.assertNull(reader.readLine());
}
| public void testFullFormatProfilerJob() throws Exception {
// prepare for test
//createTextInputFile();
log.info("Checking input file is present...");
// Check that the input file is present:
Path[] inputFiles = FileUtil.stat2Paths(getFileSystem().listStatus(
input, new OutputLogFilter()));
Assert.assertEquals(1, inputFiles.length);
// Set up arguments for the job:
// FIXME The input file could be written by this test.
String[] args = {"src/test/resources/test-inputs.txt", this.output.getName()};
// Set up the config and tool
Config config = ConfigFactory.load();
FormatProfiler wir = new FormatProfiler();
// run job
log.info("Setting up job config...");
JobConf conf = this.mrCluster.createJobConf();
wir.createJobConf(conf, args);
log.info("Running job...");
JobClient.runJob(conf);
log.info("Job finished, checking the results...");
// check the output
Path[] outputFiles = FileUtil.stat2Paths( getFileSystem().listStatus(output) );
Assert.assertEquals( config.getInt( "warc.hadoop.num_reducers" ) + 1, outputFiles.length );
// Check contents of the output:
for( Path output : outputFiles ) {
log.info(" --- output : "+output);
InputStream is = getFileSystem().open(output);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while( ( line = reader.readLine()) != null ) {
log.info(line);
if( line.startsWith("RECORD-TOTAL")) {
assertEquals("RECORD-TOTAL\t32",line);
}
}
reader.close();
}
//Assert.assertEquals("a\t2", reader.readLine());
//Assert.assertEquals("b\t1", reader.readLine());
//Assert.assertNull(reader.readLine());
}
|
diff --git a/src/main/java/org/sikuli/slides/parsing/SlideParser.java b/src/main/java/org/sikuli/slides/parsing/SlideParser.java
index 36723ad..2d8cc97 100644
--- a/src/main/java/org/sikuli/slides/parsing/SlideParser.java
+++ b/src/main/java/org/sikuli/slides/parsing/SlideParser.java
@@ -1,291 +1,296 @@
/**
Khalid
*/
package org.sikuli.slides.parsing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.sikuli.slides.screenshots.Screenshot;
import org.sikuli.slides.shapes.Cloud;
import org.sikuli.slides.shapes.Oval;
import org.sikuli.slides.shapes.Rectangle;
import org.sikuli.slides.shapes.RoundedRectangle;
import org.sikuli.slides.shapes.Shape;
import org.sikuli.slides.shapes.TextBox;
public class SlideParser extends DefaultHandler {
private Screenshot originalScreenshot;
private String xmlFile;
private boolean inScreenshot=false;
private boolean inShapeProperties=false;
private boolean inShape=false;
private boolean inArrowShape=false;
private boolean isMultipleShapes=false;
private Shape shape;
private boolean inTextBody=false;
private String textBody="";
private String arrowHeadId="";
private String arrowEndId="";
private List<Shape> shapesList;
private int order;
private String _shapeName, _shapeId;
private int _offx, _offy, _cx, _cy;
public SlideParser(String xmlFile){
this.xmlFile=xmlFile;
}
public void parseDocument(){
// reset variables
textBody="";
arrowHeadId="";
arrowEndId="";
shapesList=null;
order=-1;
SAXParserFactory factory = SAXParserFactory.newInstance();
try{
SAXParser parser = factory.newSAXParser();
parser.parse(xmlFile, this);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException{
// Part 1: Parsing the original screen shoot info
// if current element is the original screenshot, create a new screenshot
if (qName.equalsIgnoreCase("p:pic")) {
originalScreenshot=new Screenshot();
inScreenshot=true;
}
/*
* if the current child element is the "a:blip", get the qualified name or the relationship id.
* This must be done because the slide.xml file doesn't include the image file name in the /media directory.
*/
else if(inScreenshot && qName.equalsIgnoreCase("a:blip")){
// get the relationship id
originalScreenshot.setRelationshipID(attributes.getValue("r:embed"));
}
/* if the current child element is the non-visual propeties of the shape (p:cNvPr),
then get the screenshot name and filename
*/
else if(inScreenshot && qName.equalsIgnoreCase("p:cNvPr")){
originalScreenshot.setName(attributes.getValue("name"));
}
// if the current child element is the shape properties (p:spPr), then get the screenshot dimensions
else if(inScreenshot && qName.equals("p:spPr")){
inShapeProperties=true;
}
// if the current child element is bounding box, get the offset in x and y
else if(inScreenshot && inShapeProperties && qName.equalsIgnoreCase("a:off")){
//TODO: not sure if we will need this. See: http://openxmldeveloper.org/discussions/formats/f/13/p/867/2206.aspx
originalScreenshot.setOffX(Integer.parseInt(attributes.getValue("x")));
originalScreenshot.setOffY(Integer.parseInt(attributes.getValue("y")));
}
// if the current child element is the extents in x and y, get the values
else if(inScreenshot && inShapeProperties && qName.equalsIgnoreCase("a:ext")){
- originalScreenshot.setCx(Integer.parseInt(attributes.getValue("cx")));
- originalScreenshot.setCy(Integer.parseInt(attributes.getValue("cy")));
+ // Bug#39: check if the cx and cy attributes exist in case of copying and pasting the slide
+ String cx_val=attributes.getValue("cx");
+ String cy_val=attributes.getValue("cy");
+ if(cx_val!=null&&cy_val!=null){
+ originalScreenshot.setCx(Integer.parseInt(attributes.getValue("cx")));
+ originalScreenshot.setCy(Integer.parseInt(attributes.getValue("cy")));
+ }
}
// Part2: Parsing the shape information.
// if the current element is a shape
else if(qName.equalsIgnoreCase("p:sp")){
inShape=true;
order++;
// shape info variables
_shapeName="";
_shapeId="";
_offx=0; _offy=0; _cx=0; _cy=0;
}
// if the current element is the shape type, create the corresponding shape object
//TODO check if a:prstGeom is more accurate than p:cNvPr
else if(inShape&&qName.equalsIgnoreCase("p:cNvPr")){
// get the shape name
_shapeName=attributes.getValue("name");
// get the shape id
_shapeId=attributes.getValue("id");
}
// if the current child element is bounding box, get the offset in x and y
else if(inShape && qName.equalsIgnoreCase("a:off")){
_offx=Integer.parseInt(attributes.getValue("x"));
_offy=Integer.parseInt(attributes.getValue("y"));
}
// if the current child element is the extents in x and y, get the values
else if(inShape && qName.equalsIgnoreCase("a:ext")){
_cx=Integer.parseInt(attributes.getValue("cx"));
_cy=Integer.parseInt(attributes.getValue("cy"));
}
// if the current child element is the shape persistent geometry, create the shape based on its type
else if(inShape && qName.equalsIgnoreCase("a:prstGeom")){
String shapeType=attributes.getValue("prst");
// the shape is a rounded rectangle
if(shapeType.equals("roundRect") && _shapeName.contains("Rounded Rectangle")){
shape=new RoundedRectangle(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
if(shapesList==null){
shapesList=new ArrayList<Shape>();
}
if(shapesList!=null){
shapesList.add(shape);
}
}
// the shape is a rectangle
else if(shapeType.equals("rect") && _shapeName.contains("Rectangle")){
shape=new Rectangle(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is an ellipse/oval
else if(shapeType.equals("ellipse") && _shapeName.contains("Oval")){
shape=new Oval(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is a cloud
else if(shapeType.equals("cloud") && _shapeName.contains("Cloud")){
shape=new Cloud(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is a TextBox
else if(shapeType.equals("rect") && _shapeName.contains("TextBox")){
shape=new TextBox(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
}
// if the current element is the shape text body
else if(inShape && qName.equalsIgnoreCase("p:txBody")){
inTextBody=true;
}
// Parsing connected shapes like arrows
else if(qName.equalsIgnoreCase("p:cxnSp")){
inArrowShape=true;
isMultipleShapes=true;
}
// get the start connected shape id
else if(inArrowShape&&qName.equalsIgnoreCase("a:stCxn")){
arrowHeadId=attributes.getValue("id");
}
// get the end connected shape id
else if(inArrowShape&&qName.equalsIgnoreCase("a:endCxn")){
arrowEndId=attributes.getValue("id");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(inScreenshot && qName.equalsIgnoreCase("p:pic")){
inScreenshot=false;
}
else if(inScreenshot && inShapeProperties && qName.equalsIgnoreCase("p:spPr")){
inShapeProperties=false;
}
else if(inShape && qName.equalsIgnoreCase("p:sp")){
inShape=false;
}
else if(inArrowShape && qName.equalsIgnoreCase("p:cxnSp")){
inArrowShape=false;
setRoundedRectangleDragAndDropOrder();
}
else if(inTextBody && qName.equalsIgnoreCase("p:txBody")){
inTextBody=false;
if(shape!=null)
shape.setText(textBody);
}
}
private void setRoundedRectangleDragAndDropOrder() {
if(shapesList!=null){
for(Shape mShape:shapesList){
if(mShape.getId().equals(arrowHeadId)){
mShape.setOrder(0);
System.out.println(mShape.getName()+" is the drag shape");
}
else if(mShape.getId().equals(arrowEndId)){
mShape.setOrder(1);
System.out.println(mShape.getName()+" is the drop shape");
}
}
}
}
public boolean isMultipleShapes(){
if(isMultipleShapes){
isMultipleShapes=false;
return true;
}
return false;
}
@Override
public void characters(char[] ch, int start, int length){
if(inTextBody){
textBody+=new String(ch, start, length);
}
}
// return the original screenshot
public Screenshot getScreenshot(){
return originalScreenshot;
}
// return the shape
public Shape getShape(){
return shape;
}
// return list of shapes
public List<Shape> getShapes(){
return shapesList;
}
}
| true | true | public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException{
// Part 1: Parsing the original screen shoot info
// if current element is the original screenshot, create a new screenshot
if (qName.equalsIgnoreCase("p:pic")) {
originalScreenshot=new Screenshot();
inScreenshot=true;
}
/*
* if the current child element is the "a:blip", get the qualified name or the relationship id.
* This must be done because the slide.xml file doesn't include the image file name in the /media directory.
*/
else if(inScreenshot && qName.equalsIgnoreCase("a:blip")){
// get the relationship id
originalScreenshot.setRelationshipID(attributes.getValue("r:embed"));
}
/* if the current child element is the non-visual propeties of the shape (p:cNvPr),
then get the screenshot name and filename
*/
else if(inScreenshot && qName.equalsIgnoreCase("p:cNvPr")){
originalScreenshot.setName(attributes.getValue("name"));
}
// if the current child element is the shape properties (p:spPr), then get the screenshot dimensions
else if(inScreenshot && qName.equals("p:spPr")){
inShapeProperties=true;
}
// if the current child element is bounding box, get the offset in x and y
else if(inScreenshot && inShapeProperties && qName.equalsIgnoreCase("a:off")){
//TODO: not sure if we will need this. See: http://openxmldeveloper.org/discussions/formats/f/13/p/867/2206.aspx
originalScreenshot.setOffX(Integer.parseInt(attributes.getValue("x")));
originalScreenshot.setOffY(Integer.parseInt(attributes.getValue("y")));
}
// if the current child element is the extents in x and y, get the values
else if(inScreenshot && inShapeProperties && qName.equalsIgnoreCase("a:ext")){
originalScreenshot.setCx(Integer.parseInt(attributes.getValue("cx")));
originalScreenshot.setCy(Integer.parseInt(attributes.getValue("cy")));
}
// Part2: Parsing the shape information.
// if the current element is a shape
else if(qName.equalsIgnoreCase("p:sp")){
inShape=true;
order++;
// shape info variables
_shapeName="";
_shapeId="";
_offx=0; _offy=0; _cx=0; _cy=0;
}
// if the current element is the shape type, create the corresponding shape object
//TODO check if a:prstGeom is more accurate than p:cNvPr
else if(inShape&&qName.equalsIgnoreCase("p:cNvPr")){
// get the shape name
_shapeName=attributes.getValue("name");
// get the shape id
_shapeId=attributes.getValue("id");
}
// if the current child element is bounding box, get the offset in x and y
else if(inShape && qName.equalsIgnoreCase("a:off")){
_offx=Integer.parseInt(attributes.getValue("x"));
_offy=Integer.parseInt(attributes.getValue("y"));
}
// if the current child element is the extents in x and y, get the values
else if(inShape && qName.equalsIgnoreCase("a:ext")){
_cx=Integer.parseInt(attributes.getValue("cx"));
_cy=Integer.parseInt(attributes.getValue("cy"));
}
// if the current child element is the shape persistent geometry, create the shape based on its type
else if(inShape && qName.equalsIgnoreCase("a:prstGeom")){
String shapeType=attributes.getValue("prst");
// the shape is a rounded rectangle
if(shapeType.equals("roundRect") && _shapeName.contains("Rounded Rectangle")){
shape=new RoundedRectangle(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
if(shapesList==null){
shapesList=new ArrayList<Shape>();
}
if(shapesList!=null){
shapesList.add(shape);
}
}
// the shape is a rectangle
else if(shapeType.equals("rect") && _shapeName.contains("Rectangle")){
shape=new Rectangle(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is an ellipse/oval
else if(shapeType.equals("ellipse") && _shapeName.contains("Oval")){
shape=new Oval(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is a cloud
else if(shapeType.equals("cloud") && _shapeName.contains("Cloud")){
shape=new Cloud(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is a TextBox
else if(shapeType.equals("rect") && _shapeName.contains("TextBox")){
shape=new TextBox(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
}
// if the current element is the shape text body
else if(inShape && qName.equalsIgnoreCase("p:txBody")){
inTextBody=true;
}
// Parsing connected shapes like arrows
else if(qName.equalsIgnoreCase("p:cxnSp")){
inArrowShape=true;
isMultipleShapes=true;
}
// get the start connected shape id
else if(inArrowShape&&qName.equalsIgnoreCase("a:stCxn")){
arrowHeadId=attributes.getValue("id");
}
// get the end connected shape id
else if(inArrowShape&&qName.equalsIgnoreCase("a:endCxn")){
arrowEndId=attributes.getValue("id");
}
}
| public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException{
// Part 1: Parsing the original screen shoot info
// if current element is the original screenshot, create a new screenshot
if (qName.equalsIgnoreCase("p:pic")) {
originalScreenshot=new Screenshot();
inScreenshot=true;
}
/*
* if the current child element is the "a:blip", get the qualified name or the relationship id.
* This must be done because the slide.xml file doesn't include the image file name in the /media directory.
*/
else if(inScreenshot && qName.equalsIgnoreCase("a:blip")){
// get the relationship id
originalScreenshot.setRelationshipID(attributes.getValue("r:embed"));
}
/* if the current child element is the non-visual propeties of the shape (p:cNvPr),
then get the screenshot name and filename
*/
else if(inScreenshot && qName.equalsIgnoreCase("p:cNvPr")){
originalScreenshot.setName(attributes.getValue("name"));
}
// if the current child element is the shape properties (p:spPr), then get the screenshot dimensions
else if(inScreenshot && qName.equals("p:spPr")){
inShapeProperties=true;
}
// if the current child element is bounding box, get the offset in x and y
else if(inScreenshot && inShapeProperties && qName.equalsIgnoreCase("a:off")){
//TODO: not sure if we will need this. See: http://openxmldeveloper.org/discussions/formats/f/13/p/867/2206.aspx
originalScreenshot.setOffX(Integer.parseInt(attributes.getValue("x")));
originalScreenshot.setOffY(Integer.parseInt(attributes.getValue("y")));
}
// if the current child element is the extents in x and y, get the values
else if(inScreenshot && inShapeProperties && qName.equalsIgnoreCase("a:ext")){
// Bug#39: check if the cx and cy attributes exist in case of copying and pasting the slide
String cx_val=attributes.getValue("cx");
String cy_val=attributes.getValue("cy");
if(cx_val!=null&&cy_val!=null){
originalScreenshot.setCx(Integer.parseInt(attributes.getValue("cx")));
originalScreenshot.setCy(Integer.parseInt(attributes.getValue("cy")));
}
}
// Part2: Parsing the shape information.
// if the current element is a shape
else if(qName.equalsIgnoreCase("p:sp")){
inShape=true;
order++;
// shape info variables
_shapeName="";
_shapeId="";
_offx=0; _offy=0; _cx=0; _cy=0;
}
// if the current element is the shape type, create the corresponding shape object
//TODO check if a:prstGeom is more accurate than p:cNvPr
else if(inShape&&qName.equalsIgnoreCase("p:cNvPr")){
// get the shape name
_shapeName=attributes.getValue("name");
// get the shape id
_shapeId=attributes.getValue("id");
}
// if the current child element is bounding box, get the offset in x and y
else if(inShape && qName.equalsIgnoreCase("a:off")){
_offx=Integer.parseInt(attributes.getValue("x"));
_offy=Integer.parseInt(attributes.getValue("y"));
}
// if the current child element is the extents in x and y, get the values
else if(inShape && qName.equalsIgnoreCase("a:ext")){
_cx=Integer.parseInt(attributes.getValue("cx"));
_cy=Integer.parseInt(attributes.getValue("cy"));
}
// if the current child element is the shape persistent geometry, create the shape based on its type
else if(inShape && qName.equalsIgnoreCase("a:prstGeom")){
String shapeType=attributes.getValue("prst");
// the shape is a rounded rectangle
if(shapeType.equals("roundRect") && _shapeName.contains("Rounded Rectangle")){
shape=new RoundedRectangle(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
if(shapesList==null){
shapesList=new ArrayList<Shape>();
}
if(shapesList!=null){
shapesList.add(shape);
}
}
// the shape is a rectangle
else if(shapeType.equals("rect") && _shapeName.contains("Rectangle")){
shape=new Rectangle(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is an ellipse/oval
else if(shapeType.equals("ellipse") && _shapeName.contains("Oval")){
shape=new Oval(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is a cloud
else if(shapeType.equals("cloud") && _shapeName.contains("Cloud")){
shape=new Cloud(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
// the shape is a TextBox
else if(shapeType.equals("rect") && _shapeName.contains("TextBox")){
shape=new TextBox(_shapeId,_shapeName,order);
shape.setOffx(_offx);
shape.setOffy(_offy);
shape.setCx(_cx);
shape.setCy(_cy);
}
}
// if the current element is the shape text body
else if(inShape && qName.equalsIgnoreCase("p:txBody")){
inTextBody=true;
}
// Parsing connected shapes like arrows
else if(qName.equalsIgnoreCase("p:cxnSp")){
inArrowShape=true;
isMultipleShapes=true;
}
// get the start connected shape id
else if(inArrowShape&&qName.equalsIgnoreCase("a:stCxn")){
arrowHeadId=attributes.getValue("id");
}
// get the end connected shape id
else if(inArrowShape&&qName.equalsIgnoreCase("a:endCxn")){
arrowEndId=attributes.getValue("id");
}
}
|
diff --git a/javasrc/src/org/ccnx/ccn/test/impl/CCNFlowControlTest.java b/javasrc/src/org/ccnx/ccn/test/impl/CCNFlowControlTest.java
index 1a7206b79..6f4f512f5 100644
--- a/javasrc/src/org/ccnx/ccn/test/impl/CCNFlowControlTest.java
+++ b/javasrc/src/org/ccnx/ccn/test/impl/CCNFlowControlTest.java
@@ -1,105 +1,105 @@
/*
* A CCNx library test.
*
* Copyright (C) 2008, 2009, 2011 Palo Alto Research Center, Inc.
*
* This work is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
* This work 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.ccnx.ccn.test.impl;
import java.io.IOException;
import junit.framework.Assert;
import org.ccnx.ccn.impl.CCNFlowControl;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
import org.junit.Before;
import org.junit.Test;
/**
* Test flow controller functionality.
*/
public class CCNFlowControlTest extends CCNFlowControlTestBase {
@Before
public void setUp() throws Exception {
fc = new CCNFlowControl(_handle);
}
/**
* Test method for an order case that failed in practice for
* RepoIOTest when matching was broken.
* @throws Throwable
*/
@Test
public void testMixedOrderInterestPut() throws Throwable {
normalReset(name1);
// First one normal order exchange: put first, interest next
fc.put(segments[0]);
ContentObject co = testExpected(_handle.get(segment_names[0], 0), segments[0]);
// Next we get the interest for the next segment before the data
interestList.add(Interest.next(co.name(), 3, null));
fc.handleInterests(interestList);
// Data arrives for the waiting interest, should be sent out
fc.put(segments[1]);
testExpected(queue.poll(), segments[1]);
// Remainder in order, puts first
fc.put(segments[2]);
co = testNext(co, segments[2]);
fc.put(segments[3]);
co = testNext(co, segments[3]);
}
@Test
public void testWaitForPutDrain() throws Throwable {
normalReset(name1);
- fc.put(segments[0]);
+ fc.put(segments[1]);
fc.put(segments[3]);
fc.put(segments[0]);
fc.put(segments[2]);
testLast(segments[0], segments[3]);
testLast(segments[0], segments[2]);
testLast(segments[0], segments[1]);
- ContentObject lastOne = _handle.get(new Interest(segment_names[1]), 0);
+ ContentObject lastOne = _handle.get(new Interest(segment_names[0]), 0);
Log.info("Retrieved final object {0}, blocks still in fc: {1}", lastOne.name(), fc.getCapacity()-fc.availableCapacity());
System.out.println("Testing \"waitForPutDrain\"");
try {
// can't call waitForPutDrain directly; call it via afterClose
fc.afterClose();
} catch (IOException ioe) {
Assert.fail("WaitforPutDrain threw unexpected exception");
}
fc.put(obj1);
try {
// can't call waitForPutDrain directly; call it via afterClose
fc.afterClose();
Assert.fail("WaitforPutDrain succeeded when it should have failed");
} catch (IOException ioe) {}
}
protected void normalReset(ContentName n) throws IOException {
_handle.reset();
interestList.clear();
fc = new CCNFlowControl(n, _handle);
}
}
| false | true | public void testWaitForPutDrain() throws Throwable {
normalReset(name1);
fc.put(segments[0]);
fc.put(segments[3]);
fc.put(segments[0]);
fc.put(segments[2]);
testLast(segments[0], segments[3]);
testLast(segments[0], segments[2]);
testLast(segments[0], segments[1]);
ContentObject lastOne = _handle.get(new Interest(segment_names[1]), 0);
Log.info("Retrieved final object {0}, blocks still in fc: {1}", lastOne.name(), fc.getCapacity()-fc.availableCapacity());
System.out.println("Testing \"waitForPutDrain\"");
try {
// can't call waitForPutDrain directly; call it via afterClose
fc.afterClose();
} catch (IOException ioe) {
Assert.fail("WaitforPutDrain threw unexpected exception");
}
fc.put(obj1);
try {
// can't call waitForPutDrain directly; call it via afterClose
fc.afterClose();
Assert.fail("WaitforPutDrain succeeded when it should have failed");
} catch (IOException ioe) {}
}
| public void testWaitForPutDrain() throws Throwable {
normalReset(name1);
fc.put(segments[1]);
fc.put(segments[3]);
fc.put(segments[0]);
fc.put(segments[2]);
testLast(segments[0], segments[3]);
testLast(segments[0], segments[2]);
testLast(segments[0], segments[1]);
ContentObject lastOne = _handle.get(new Interest(segment_names[0]), 0);
Log.info("Retrieved final object {0}, blocks still in fc: {1}", lastOne.name(), fc.getCapacity()-fc.availableCapacity());
System.out.println("Testing \"waitForPutDrain\"");
try {
// can't call waitForPutDrain directly; call it via afterClose
fc.afterClose();
} catch (IOException ioe) {
Assert.fail("WaitforPutDrain threw unexpected exception");
}
fc.put(obj1);
try {
// can't call waitForPutDrain directly; call it via afterClose
fc.afterClose();
Assert.fail("WaitforPutDrain succeeded when it should have failed");
} catch (IOException ioe) {}
}
|
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
index 5bd6296..994f48a 100644
--- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
+++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
@@ -1,176 +1,179 @@
package uk.ac.gla.dcs.tp3.w.algorithm;
import java.util.LinkedList;
import uk.ac.gla.dcs.tp3.w.league.*;
import uk.ac.gla.dcs.tp3.w.algorithm.Graph;
/**
* @author gordon
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170 - 8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170 - 4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170 - 7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170 - 7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
atlVny.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
LinkedList<AdjListNode> list = g.getSource().getAdjList();
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
System.out.println("Source to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
g.bfs();
for (Vertex v : g.getV()) {
Vertex pred = g.getV()[v.getPredecessor()];
if (v instanceof TeamVertex) {
TeamVertex tv = (TeamVertex) v;
System.out.print(tv.getTeam().getName() + " has predecessor ");
} else if (v instanceof PairVertex) {
PairVertex pv = (PairVertex) v;
System.out.print(pv.getTeamA().getName() + " and "
+ pv.getTeamB().getName() + " has predecessor ");
} else {
System.out.print(v.getIndex() + " has predecessor ");
}
if (pred instanceof TeamVertex) {
TeamVertex tv = (TeamVertex) pred;
System.out.print(tv.getTeam().getName());
} else if (pred instanceof PairVertex) {
PairVertex pv = (PairVertex) pred;
System.out.print(pv.getTeamA().getName() + " and "
+ pv.getTeamB().getName());
} else {
System.out.print(pred.getIndex());
}
System.out.println();
}
ResidualGraph rG = new ResidualGraph(g);
- list = rG.getSource().getAdjList();
- System.out.println(list.size() + " foo");
+ for (Vertex v : rG.getV()) {
+ list = v.getAdjList();
+ System.out.println(list.size()
+ + " nodes in adjacency list for vertex " + v.getIndex());
+ }
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
System.out.println("Source to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
}
}
| true | true | public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170 - 8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170 - 4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170 - 7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170 - 7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
atlVny.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
LinkedList<AdjListNode> list = g.getSource().getAdjList();
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
System.out.println("Source to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
g.bfs();
for (Vertex v : g.getV()) {
Vertex pred = g.getV()[v.getPredecessor()];
if (v instanceof TeamVertex) {
TeamVertex tv = (TeamVertex) v;
System.out.print(tv.getTeam().getName() + " has predecessor ");
} else if (v instanceof PairVertex) {
PairVertex pv = (PairVertex) v;
System.out.print(pv.getTeamA().getName() + " and "
+ pv.getTeamB().getName() + " has predecessor ");
} else {
System.out.print(v.getIndex() + " has predecessor ");
}
if (pred instanceof TeamVertex) {
TeamVertex tv = (TeamVertex) pred;
System.out.print(tv.getTeam().getName());
} else if (pred instanceof PairVertex) {
PairVertex pv = (PairVertex) pred;
System.out.print(pv.getTeamA().getName() + " and "
+ pv.getTeamB().getName());
} else {
System.out.print(pred.getIndex());
}
System.out.println();
}
ResidualGraph rG = new ResidualGraph(g);
list = rG.getSource().getAdjList();
System.out.println(list.size() + " foo");
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
System.out.println("Source to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
}
| public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170 - 8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170 - 4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170 - 7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170 - 7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
atlVny.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
LinkedList<AdjListNode> list = g.getSource().getAdjList();
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
System.out.println("Source to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
g.bfs();
for (Vertex v : g.getV()) {
Vertex pred = g.getV()[v.getPredecessor()];
if (v instanceof TeamVertex) {
TeamVertex tv = (TeamVertex) v;
System.out.print(tv.getTeam().getName() + " has predecessor ");
} else if (v instanceof PairVertex) {
PairVertex pv = (PairVertex) v;
System.out.print(pv.getTeamA().getName() + " and "
+ pv.getTeamB().getName() + " has predecessor ");
} else {
System.out.print(v.getIndex() + " has predecessor ");
}
if (pred instanceof TeamVertex) {
TeamVertex tv = (TeamVertex) pred;
System.out.print(tv.getTeam().getName());
} else if (pred instanceof PairVertex) {
PairVertex pv = (PairVertex) pred;
System.out.print(pv.getTeamA().getName() + " and "
+ pv.getTeamB().getName());
} else {
System.out.print(pred.getIndex());
}
System.out.println();
}
ResidualGraph rG = new ResidualGraph(g);
for (Vertex v : rG.getV()) {
list = v.getAdjList();
System.out.println(list.size()
+ " nodes in adjacency list for vertex " + v.getIndex());
}
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
System.out.println("Source to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
}
|
diff --git a/org/mailster/pop3/mailbox/MailBox.java b/org/mailster/pop3/mailbox/MailBox.java
index 5eda901..4661a72 100644
--- a/org/mailster/pop3/mailbox/MailBox.java
+++ b/org/mailster/pop3/mailbox/MailBox.java
@@ -1,254 +1,254 @@
package org.mailster.pop3.mailbox;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import javax.mail.Flags.Flag;
import org.mailster.message.SmtpMessage;
import org.mailster.service.Pop3Service;
import org.mailster.util.StreamUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ---<br>
* Mailster (C) 2007-2009 De Oliveira Edouard
* <p>
* 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.
* <p>
* 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.
* <p>
* 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.
* <p>
* See <a href="http://tedorg.free.fr/en/projects.php" target="_parent">Mailster
* Web Site</a> <br>
* ---
* <p>
* MailBox.java - In-memory store of a user mails .
*
* @author <a href="mailto:[email protected]">Edouard De Oliveira</a>
* @version $Revision$, $Date$
*/
public class MailBox
{
private static final Logger log = LoggerFactory.getLogger(MailBox.class);
private final Semaphore available = new Semaphore(1);
private ConcurrentHashMap<Long, StoredSmtpMessage> mails = new ConcurrentHashMap<Long, StoredSmtpMessage>();
private String mailBoxID;
private String email;
// Unique counter ID for the mailbox
private long counter = 1;
public MailBox(Pop3User user)
{
this.mailBoxID = user.getQualifiedMailboxID();
this.email = user.getEmail();
}
public String toString()
{
return getEmail()+" ("+getMessageCount()+")";
}
public String getEmail()
{
return email;
}
public boolean tryAcquireLock(int nbOfRetries, long delayInMs)
{
if (nbOfRetries<1 || delayInMs<0)
throw new IllegalArgumentException("Number of retries must be >=1 and delayInMs must be > 0");
boolean acquired = false;
for (int i=0;!acquired && i<nbOfRetries;i++)
{
if (i>0)
{
try
{
Thread.sleep(delayInMs);
}
catch (InterruptedException e) {}
}
- log.debug("Try n�={} to acquire lock on mailbox of {}", i, getEmail());
+ log.debug("Try n�={} to acquire lock on mailbox of {}", i+1, getEmail());
acquired = available.tryAcquire();
}
log.debug("Lock acquired {}",acquired);
return acquired;
}
public boolean tryAcquireLock()
{
return available.tryAcquire();
}
public void releaseLock()
{
available.release();
}
public void removeMessage(StoredSmtpMessage msg)
{
mails.remove(msg.getId());
}
public void removeAllMessages()
{
mails.clear();
}
/**
* Stores a mail in the mailbox.
*
* @param message the message to be stored
* @return the stored object
*/
public StoredSmtpMessage storeMessage(SmtpMessage message)
{
StoredSmtpMessage stored = null;
synchronized (mails)
{
Long id = new Long(counter);
stored = new StoredSmtpMessage(message, id);
stored.setMailBox(this);
mails.put(id, stored);
counter++;
}
return stored;
}
/**
* Removes everything from the to-be-deleted set
*/
public void reset()
{
for (StoredSmtpMessage msg : mails.values())
msg.getFlags().remove(Flag.DELETED);
}
/**
* Returns the list of mails that are not marked for deletion.
*
* @return the list
*/
public List<StoredSmtpMessage> getNonDeletedMessages()
{
List<StoredSmtpMessage> l = new ArrayList<StoredSmtpMessage>();
for (StoredSmtpMessage msg : mails.values())
{
if (!msg.getFlags().contains(Flag.DELETED))
l.add(msg);
}
return l;
}
/**
* Returns mail size by its ID
*/
public long getMessageSize(Long id)
{
if (mails.containsKey(id))
return mails.get(id).getMessageSize();
else
return 0;
}
/**
* Get mail from the mailbox by its ID
*/
public StoredSmtpMessage getMessage(Long id)
{
return mails.get(id);
}
/**
* Returns the mailbox unique-id This implementation returns the hexed
* hashcode of the mailbox concatened with the message hexed hashcode
* separated by the ':' char.
*/
public String getMessageUniqueID(Long id)
{
return Integer.toHexString(hashCode()) + ":"
+ Integer.toHexString(mails.get(id).hashCode());
}
/**
* Deletes mails marked for deletion.
*
* @throws Exception
*/
public void deleteMarked() throws Exception
{
for (StoredSmtpMessage msg : mails.values())
{
if (msg.getFlags().contains(Flag.DELETED))
mails.remove(msg);
}
}
/**
* Returns the number of emails in the mailbox
*/
public long getMessageCount()
{
return mails.values().size();
}
/**
* Returns the size in bytes of the emails in the mailbox
*/
public long getMailBoxByteSize()
{
int total = 0;
for (StoredSmtpMessage msg : mails.values())
total += msg.getMessage().toString().length();
return total;
}
/**
* Writes mailbox to mbox format
*/
public void writeMailBoxToFile(Pop3Service pop3Service)
{
try
{
PrintWriter out = new PrintWriter(new FileWriter(
pop3Service.getOutputDirectory()
+ File.separator + mailBoxID
+ ".mbox", false));
for (StoredSmtpMessage msg : mails.values())
{
if (!msg.getFlags().contains(Flag.DELETED))
StreamUtilities.writeMessageToMBoxRDFormat(msg, out);
}
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
| true | true | public boolean tryAcquireLock(int nbOfRetries, long delayInMs)
{
if (nbOfRetries<1 || delayInMs<0)
throw new IllegalArgumentException("Number of retries must be >=1 and delayInMs must be > 0");
boolean acquired = false;
for (int i=0;!acquired && i<nbOfRetries;i++)
{
if (i>0)
{
try
{
Thread.sleep(delayInMs);
}
catch (InterruptedException e) {}
}
log.debug("Try n�={} to acquire lock on mailbox of {}", i, getEmail());
acquired = available.tryAcquire();
}
log.debug("Lock acquired {}",acquired);
return acquired;
}
| public boolean tryAcquireLock(int nbOfRetries, long delayInMs)
{
if (nbOfRetries<1 || delayInMs<0)
throw new IllegalArgumentException("Number of retries must be >=1 and delayInMs must be > 0");
boolean acquired = false;
for (int i=0;!acquired && i<nbOfRetries;i++)
{
if (i>0)
{
try
{
Thread.sleep(delayInMs);
}
catch (InterruptedException e) {}
}
log.debug("Try n�={} to acquire lock on mailbox of {}", i+1, getEmail());
acquired = available.tryAcquire();
}
log.debug("Lock acquired {}",acquired);
return acquired;
}
|
diff --git a/src/java/org/apache/fop/layoutmgr/table/TableRowIterator.java b/src/java/org/apache/fop/layoutmgr/table/TableRowIterator.java
index 0781d4ee6..72c285700 100644
--- a/src/java/org/apache/fop/layoutmgr/table/TableRowIterator.java
+++ b/src/java/org/apache/fop/layoutmgr/table/TableRowIterator.java
@@ -1,486 +1,503 @@
/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$ */
package org.apache.fop.layoutmgr.table;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fop.fo.flow.Marker;
import org.apache.fop.fo.flow.Table;
import org.apache.fop.fo.flow.TableBody;
import org.apache.fop.fo.flow.TableCell;
import org.apache.fop.fo.flow.TableColumn;
import org.apache.fop.fo.flow.TableRow;
import org.apache.fop.fo.properties.CommonBorderPaddingBackground;
/**
* <p>Iterator that lets the table layout manager step over all rows of a table.
* </p>
* <p>Note: This class is not thread-safe.
* </p>
*/
public class TableRowIterator {
/** Selects the list of table-body elements for iteration. */
public static final int BODY = 0;
/** Selects the table-header element for iteration. */
public static final int HEADER = 1;
/** Selects the table-footer element for iteration. */
public static final int FOOTER = 2;
/** Logger **/
private static Log log = LogFactory.getLog(TableRowIterator.class);
/** The table on with this instance operates. */
protected Table table;
private ColumnSetup columns;
private int type;
/** Holds the current row (TableCell instances) */
private List currentRow = new java.util.ArrayList();
/** Holds the grid units of cell from the last row while will span over the current row
* (GridUnit instance) */
private List lastRowsSpanningCells = new java.util.ArrayList();
private int currentRowIndex = -1;
//TODO rows should later be a Jakarta Commons LinkedList so concurrent modifications while
//using a ListIterator are possible
/** List of cache rows. */
private List rows = new java.util.ArrayList();
//private int indexOfFirstRowInList;
private int currentIndex = -1;
private int pendingRowSpans;
//prefetch state
private ListIterator bodyIterator = null;
private ListIterator childInBodyIterator = null;
/**
* Creates a new TableRowIterator.
* @param table the table to iterate over
* @param columns the column setup for the table
* @param what indicates what part of the table to iterate over (HEADER, FOOTER, BODY)
*/
public TableRowIterator(Table table, ColumnSetup columns, int what) {
this.table = table;
this.columns = columns;
this.type = what;
switch(what) {
case HEADER: {
List bodyList = new java.util.ArrayList();
bodyList.add(table.getTableHeader());
this.bodyIterator = bodyList.listIterator();
break;
}
case FOOTER: {
List bodyList = new java.util.ArrayList();
bodyList.add(table.getTableFooter());
this.bodyIterator = bodyList.listIterator();
break;
}
default: {
this.bodyIterator = table.getChildNodes();
}
}
}
/**
* <p>Preloads the whole table.
* </p>
* <p>Note:This is inefficient for large tables.
* </p>
*/
public void prefetchAll() {
while (prefetchNext()) {
log.trace("found row...");
}
}
/**
* Returns the next row group if any. A row group in this context is the minimum number of
* consecutive rows which contains all spanned grid units of its cells.
* @return the next row group, or null
*/
public EffRow[] getNextRowGroup() {
EffRow firstRowInGroup = getNextRow();
if (firstRowInGroup == null) {
return null;
}
EffRow lastRowInGroup = firstRowInGroup;
int lastIndex = lastRowInGroup.getIndex();
boolean allFinished;
do {
allFinished = true;
Iterator iter = lastRowInGroup.getGridUnits().iterator();
while (iter.hasNext()) {
GridUnit gu = (GridUnit)iter.next();
if (!gu.isLastGridUnitRowSpan()) {
allFinished = false;
break;
}
}
lastIndex = lastRowInGroup.getIndex();
if (!allFinished) {
lastRowInGroup = getNextRow();
if (lastRowInGroup == null) {
allFinished = true;
}
}
} while (!allFinished);
int rowCount = lastIndex - firstRowInGroup.getIndex() + 1;
EffRow[] rowGroup = new EffRow[rowCount];
for (int i = 0; i < rowCount; i++) {
rowGroup[i] = getCachedRow(i + firstRowInGroup.getIndex());
}
return rowGroup;
}
/**
* Retuns the next effective row.
* @return the requested effective row.
*/
public EffRow getNextRow() {
currentIndex++;
boolean moreRows = true;
while (moreRows && rows.size() < currentIndex + 1) {
moreRows = prefetchNext();
}
if (currentIndex < rows.size()) {
return getCachedRow(currentIndex);
} else {
return null;
}
}
/**
* Sets the iterator to the previous row.
*/
public void backToPreviousRow() {
currentIndex--;
}
/**
* Returns the first effective row.
* @return the requested effective row.
*/
public EffRow getFirstRow() {
if (rows.size() == 0) {
prefetchNext();
}
return getCachedRow(0);
}
/**
* <p>Returns the last effective row.
* </p>
* <p>Note:This is inefficient for large tables because the whole table
* if preloaded.
* </p>
* @return the requested effective row.
*/
public EffRow getLastRow() {
while (prefetchNext()) {
//nop
}
return getCachedRow(rows.size() - 1);
}
/**
* Returns a cached effective row.
* @param index index of the row (zero-based)
* @return the requested effective row
*/
public EffRow getCachedRow(int index) {
if (index < 0 || index >= rows.size()) {
return null;
} else {
return (EffRow)rows.get(index);
}
}
private boolean prefetchNext() {
boolean firstInTable = false;
boolean firstInBody = false;
if (childInBodyIterator != null) {
if (!childInBodyIterator.hasNext()) {
//force skip on to next body
if (pendingRowSpans > 0) {
this.currentRow.clear();
this.currentRowIndex++;
EffRow gridUnits = buildGridRow(this.currentRow, null);
log.debug(gridUnits);
rows.add(gridUnits);
return true;
}
childInBodyIterator = null;
if (rows.size() > 0) {
getCachedRow(rows.size() - 1).setFlagForAllGridUnits(
GridUnit.LAST_IN_BODY, true);
}
}
}
if (childInBodyIterator == null) {
if (bodyIterator.hasNext()) {
childInBodyIterator = ((TableBody)bodyIterator.next()).getChildNodes();
if (rows.size() == 0) {
firstInTable = true;
}
firstInBody = true;
} else {
//no more rows
if (rows.size() > 0) {
getCachedRow(rows.size() - 1).setFlagForAllGridUnits(
GridUnit.LAST_IN_BODY, true);
if ((type == FOOTER || table.getTableFooter() == null)
&& type != HEADER) {
getCachedRow(rows.size() - 1).setFlagForAllGridUnits(
GridUnit.LAST_IN_TABLE, true);
}
}
return false;
}
}
Object node = childInBodyIterator.next();
while (node instanceof Marker) {
node = childInBodyIterator.next();
}
this.currentRow.clear();
this.currentRowIndex++;
TableRow rowFO = null;
if (node instanceof TableRow) {
rowFO = (TableRow)node;
ListIterator cellIterator = rowFO.getChildNodes();
while (cellIterator.hasNext()) {
this.currentRow.add(cellIterator.next());
}
} else if (node instanceof TableCell) {
this.currentRow.add(node);
if (!((TableCell)node).endsRow()) {
while (childInBodyIterator.hasNext()) {
TableCell cell = (TableCell)childInBodyIterator.next();
if (cell.startsRow()) {
//next row already starts here, one step back
childInBodyIterator.previous();
break;
}
this.currentRow.add(cell);
if (cell.endsRow()) {
break;
}
}
}
} else {
throw new IllegalStateException("Illegal class found: " + node.getClass().getName());
}
EffRow gridUnits = buildGridRow(this.currentRow, rowFO);
if (firstInBody) {
gridUnits.setFlagForAllGridUnits(GridUnit.FIRST_IN_BODY, true);
}
if (firstInTable && (type == HEADER || table.getTableHeader() == null)
&& type != FOOTER) {
gridUnits.setFlagForAllGridUnits(GridUnit.FIRST_IN_TABLE, true);
}
log.debug(gridUnits);
rows.add(gridUnits);
return true;
}
private void safelySetListItem(List list, int position, Object obj) {
while (position >= list.size()) {
list.add(null);
}
list.set(position, obj);
}
private Object safelyGetListItem(List list, int position) {
if (position >= list.size()) {
return null;
} else {
return list.get(position);
}
}
private EffRow buildGridRow(List cells, TableRow rowFO) {
EffRow row = new EffRow(this.currentRowIndex, type);
List gridUnits = row.getGridUnits();
TableBody bodyFO = null;
//Create all row-spanned grid units based on information from the last row
int colnum = 1;
GridUnit[] horzSpan = null;
if (pendingRowSpans > 0) {
ListIterator spanIter = lastRowsSpanningCells.listIterator();
while (spanIter.hasNext()) {
GridUnit gu = (GridUnit)spanIter.next();
if (gu != null) {
if (gu.getColSpanIndex() == 0) {
horzSpan = new GridUnit[gu.getCell().getNumberColumnsSpanned()];
}
GridUnit newGU = gu.createNextRowSpanningGridUnit();
newGU.setRow(rowFO);
safelySetListItem(gridUnits, colnum - 1, newGU);
horzSpan[newGU.getColSpanIndex()] = newGU;
if (newGU.isLastGridUnitColSpan()) {
//Add the array of row-spanned grid units to the primary grid unit
newGU.getPrimary().addRow(horzSpan);
horzSpan = null;
}
if (newGU.isLastGridUnitRowSpan()) {
spanIter.set(null);
pendingRowSpans--;
} else {
spanIter.set(newGU);
}
}
colnum++;
}
}
+ if (pendingRowSpans < 0) {
+ throw new IllegalStateException("pendingRowSpans must not become negative!");
+ }
//Transfer available cells to their slots
colnum = 1;
ListIterator iter = cells.listIterator();
while (iter.hasNext()) {
TableCell cell = (TableCell)iter.next();
colnum = cell.getColumnNumber();
//TODO: remove the check below???
//shouldn't happen here, since
//overlapping cells already caught in
//fo.flow.TableCell.bind()...
- if (safelyGetListItem(gridUnits, colnum - 1) != null) {
- log.error("Overlapping cell at position " + colnum);
- //TODO throw layout exception
+ GridUnit other = (GridUnit)safelyGetListItem(gridUnits, colnum - 1);
+ if (other != null) {
+ String err = "A table-cell ("
+ + cell.getContextInfo()
+ + ") is overlapping with another ("
+ + other.getCell().getContextInfo()
+ + ") in column " + colnum;
+ throw new IllegalStateException(err
+ + " (this should have been catched by FO tree validation)");
}
TableColumn col = columns.getColumn(colnum);
//Add grid unit for primary grid unit
PrimaryGridUnit gu = new PrimaryGridUnit(cell, col, colnum - 1, this.currentRowIndex);
safelySetListItem(gridUnits, colnum - 1, gu);
boolean hasRowSpanningLeft = !gu.isLastGridUnitRowSpan();
if (hasRowSpanningLeft) {
pendingRowSpans++;
safelySetListItem(lastRowsSpanningCells, colnum - 1, gu);
}
if (gu.hasSpanning()) {
//Add grid units on spanned slots if any
horzSpan = new GridUnit[cell.getNumberColumnsSpanned()];
horzSpan[0] = gu;
for (int j = 1; j < cell.getNumberColumnsSpanned(); j++) {
colnum++;
GridUnit guSpan = new GridUnit(gu, columns.getColumn(colnum), colnum - 1, j);
- if (safelyGetListItem(gridUnits, colnum - 1) != null) {
- log.error("Overlapping cell at position " + colnum);
- //TODO throw layout exception
+ //TODO: remove the check below???
+ other = (GridUnit)safelyGetListItem(gridUnits, colnum - 1);
+ if (other != null) {
+ String err = "A table-cell ("
+ + cell.getContextInfo()
+ + ") is overlapping with another ("
+ + other.getCell().getContextInfo()
+ + ") in column " + colnum;
+ throw new IllegalStateException(err
+ + " (this should have been catched by FO tree validation)");
}
safelySetListItem(gridUnits, colnum - 1, guSpan);
if (hasRowSpanningLeft) {
+ pendingRowSpans++;
safelySetListItem(lastRowsSpanningCells, colnum - 1, gu);
}
horzSpan[j] = guSpan;
}
gu.addRow(horzSpan);
}
//Gather info for empty grid units (used later)
if (bodyFO == null) {
bodyFO = gu.getBody();
}
colnum++;
}
//Post-processing the list (looking for gaps and resolve start and end borders)
fillEmptyGridUnits(gridUnits, rowFO, bodyFO);
resolveStartEndBorders(gridUnits);
return row;
}
private void fillEmptyGridUnits(List gridUnits, TableRow row, TableBody body) {
for (int pos = 1; pos <= gridUnits.size(); pos++) {
GridUnit gu = (GridUnit)gridUnits.get(pos - 1);
//Empty grid units
if (gu == null) {
//Add grid unit
gu = new EmptyGridUnit(row, columns.getColumn(pos), body,
pos - 1);
gridUnits.set(pos - 1, gu);
}
//Set flags
gu.setFlag(GridUnit.IN_FIRST_COLUMN, (pos == 1));
gu.setFlag(GridUnit.IN_LAST_COLUMN, (pos == gridUnits.size()));
}
}
private void resolveStartEndBorders(List gridUnits) {
for (int pos = 1; pos <= gridUnits.size(); pos++) {
GridUnit starting = (GridUnit)gridUnits.get(pos - 1);
//Border resolution
if (table.isSeparateBorderModel()) {
starting.assignBorderForSeparateBorderModel();
} else {
//Neighbouring grid unit at start edge
GridUnit start = null;
int find = pos - 1;
while (find >= 1) {
GridUnit candidate = (GridUnit)gridUnits.get(find - 1);
if (candidate.isLastGridUnitColSpan()) {
start = candidate;
break;
}
find--;
}
//Ending grid unit for current cell
GridUnit ending = null;
if (starting.getCell() != null) {
pos += starting.getCell().getNumberColumnsSpanned() - 1;
}
ending = (GridUnit)gridUnits.get(pos - 1);
//Neighbouring grid unit at end edge
GridUnit end = null;
find = pos + 1;
while (find <= gridUnits.size()) {
GridUnit candidate = (GridUnit)gridUnits.get(find - 1);
if (candidate.isPrimary()) {
end = candidate;
break;
}
find++;
}
starting.resolveBorder(start,
CommonBorderPaddingBackground.START);
ending.resolveBorder(end,
CommonBorderPaddingBackground.END);
//Only start and end borders here, before and after during layout
}
}
}
}
| false | true | private EffRow buildGridRow(List cells, TableRow rowFO) {
EffRow row = new EffRow(this.currentRowIndex, type);
List gridUnits = row.getGridUnits();
TableBody bodyFO = null;
//Create all row-spanned grid units based on information from the last row
int colnum = 1;
GridUnit[] horzSpan = null;
if (pendingRowSpans > 0) {
ListIterator spanIter = lastRowsSpanningCells.listIterator();
while (spanIter.hasNext()) {
GridUnit gu = (GridUnit)spanIter.next();
if (gu != null) {
if (gu.getColSpanIndex() == 0) {
horzSpan = new GridUnit[gu.getCell().getNumberColumnsSpanned()];
}
GridUnit newGU = gu.createNextRowSpanningGridUnit();
newGU.setRow(rowFO);
safelySetListItem(gridUnits, colnum - 1, newGU);
horzSpan[newGU.getColSpanIndex()] = newGU;
if (newGU.isLastGridUnitColSpan()) {
//Add the array of row-spanned grid units to the primary grid unit
newGU.getPrimary().addRow(horzSpan);
horzSpan = null;
}
if (newGU.isLastGridUnitRowSpan()) {
spanIter.set(null);
pendingRowSpans--;
} else {
spanIter.set(newGU);
}
}
colnum++;
}
}
//Transfer available cells to their slots
colnum = 1;
ListIterator iter = cells.listIterator();
while (iter.hasNext()) {
TableCell cell = (TableCell)iter.next();
colnum = cell.getColumnNumber();
//TODO: remove the check below???
//shouldn't happen here, since
//overlapping cells already caught in
//fo.flow.TableCell.bind()...
if (safelyGetListItem(gridUnits, colnum - 1) != null) {
log.error("Overlapping cell at position " + colnum);
//TODO throw layout exception
}
TableColumn col = columns.getColumn(colnum);
//Add grid unit for primary grid unit
PrimaryGridUnit gu = new PrimaryGridUnit(cell, col, colnum - 1, this.currentRowIndex);
safelySetListItem(gridUnits, colnum - 1, gu);
boolean hasRowSpanningLeft = !gu.isLastGridUnitRowSpan();
if (hasRowSpanningLeft) {
pendingRowSpans++;
safelySetListItem(lastRowsSpanningCells, colnum - 1, gu);
}
if (gu.hasSpanning()) {
//Add grid units on spanned slots if any
horzSpan = new GridUnit[cell.getNumberColumnsSpanned()];
horzSpan[0] = gu;
for (int j = 1; j < cell.getNumberColumnsSpanned(); j++) {
colnum++;
GridUnit guSpan = new GridUnit(gu, columns.getColumn(colnum), colnum - 1, j);
if (safelyGetListItem(gridUnits, colnum - 1) != null) {
log.error("Overlapping cell at position " + colnum);
//TODO throw layout exception
}
safelySetListItem(gridUnits, colnum - 1, guSpan);
if (hasRowSpanningLeft) {
safelySetListItem(lastRowsSpanningCells, colnum - 1, gu);
}
horzSpan[j] = guSpan;
}
gu.addRow(horzSpan);
}
//Gather info for empty grid units (used later)
if (bodyFO == null) {
bodyFO = gu.getBody();
}
colnum++;
}
//Post-processing the list (looking for gaps and resolve start and end borders)
fillEmptyGridUnits(gridUnits, rowFO, bodyFO);
resolveStartEndBorders(gridUnits);
return row;
}
| private EffRow buildGridRow(List cells, TableRow rowFO) {
EffRow row = new EffRow(this.currentRowIndex, type);
List gridUnits = row.getGridUnits();
TableBody bodyFO = null;
//Create all row-spanned grid units based on information from the last row
int colnum = 1;
GridUnit[] horzSpan = null;
if (pendingRowSpans > 0) {
ListIterator spanIter = lastRowsSpanningCells.listIterator();
while (spanIter.hasNext()) {
GridUnit gu = (GridUnit)spanIter.next();
if (gu != null) {
if (gu.getColSpanIndex() == 0) {
horzSpan = new GridUnit[gu.getCell().getNumberColumnsSpanned()];
}
GridUnit newGU = gu.createNextRowSpanningGridUnit();
newGU.setRow(rowFO);
safelySetListItem(gridUnits, colnum - 1, newGU);
horzSpan[newGU.getColSpanIndex()] = newGU;
if (newGU.isLastGridUnitColSpan()) {
//Add the array of row-spanned grid units to the primary grid unit
newGU.getPrimary().addRow(horzSpan);
horzSpan = null;
}
if (newGU.isLastGridUnitRowSpan()) {
spanIter.set(null);
pendingRowSpans--;
} else {
spanIter.set(newGU);
}
}
colnum++;
}
}
if (pendingRowSpans < 0) {
throw new IllegalStateException("pendingRowSpans must not become negative!");
}
//Transfer available cells to their slots
colnum = 1;
ListIterator iter = cells.listIterator();
while (iter.hasNext()) {
TableCell cell = (TableCell)iter.next();
colnum = cell.getColumnNumber();
//TODO: remove the check below???
//shouldn't happen here, since
//overlapping cells already caught in
//fo.flow.TableCell.bind()...
GridUnit other = (GridUnit)safelyGetListItem(gridUnits, colnum - 1);
if (other != null) {
String err = "A table-cell ("
+ cell.getContextInfo()
+ ") is overlapping with another ("
+ other.getCell().getContextInfo()
+ ") in column " + colnum;
throw new IllegalStateException(err
+ " (this should have been catched by FO tree validation)");
}
TableColumn col = columns.getColumn(colnum);
//Add grid unit for primary grid unit
PrimaryGridUnit gu = new PrimaryGridUnit(cell, col, colnum - 1, this.currentRowIndex);
safelySetListItem(gridUnits, colnum - 1, gu);
boolean hasRowSpanningLeft = !gu.isLastGridUnitRowSpan();
if (hasRowSpanningLeft) {
pendingRowSpans++;
safelySetListItem(lastRowsSpanningCells, colnum - 1, gu);
}
if (gu.hasSpanning()) {
//Add grid units on spanned slots if any
horzSpan = new GridUnit[cell.getNumberColumnsSpanned()];
horzSpan[0] = gu;
for (int j = 1; j < cell.getNumberColumnsSpanned(); j++) {
colnum++;
GridUnit guSpan = new GridUnit(gu, columns.getColumn(colnum), colnum - 1, j);
//TODO: remove the check below???
other = (GridUnit)safelyGetListItem(gridUnits, colnum - 1);
if (other != null) {
String err = "A table-cell ("
+ cell.getContextInfo()
+ ") is overlapping with another ("
+ other.getCell().getContextInfo()
+ ") in column " + colnum;
throw new IllegalStateException(err
+ " (this should have been catched by FO tree validation)");
}
safelySetListItem(gridUnits, colnum - 1, guSpan);
if (hasRowSpanningLeft) {
pendingRowSpans++;
safelySetListItem(lastRowsSpanningCells, colnum - 1, gu);
}
horzSpan[j] = guSpan;
}
gu.addRow(horzSpan);
}
//Gather info for empty grid units (used later)
if (bodyFO == null) {
bodyFO = gu.getBody();
}
colnum++;
}
//Post-processing the list (looking for gaps and resolve start and end borders)
fillEmptyGridUnits(gridUnits, rowFO, bodyFO);
resolveStartEndBorders(gridUnits);
return row;
}
|
diff --git a/core/src/main/java/org/mule/galaxy/impl/jcr/CommentManagerImpl.java b/core/src/main/java/org/mule/galaxy/impl/jcr/CommentManagerImpl.java
index ffc9deb8..973b2c1a 100755
--- a/core/src/main/java/org/mule/galaxy/impl/jcr/CommentManagerImpl.java
+++ b/core/src/main/java/org/mule/galaxy/impl/jcr/CommentManagerImpl.java
@@ -1,95 +1,95 @@
package org.mule.galaxy.impl.jcr;
import java.io.IOException;
import java.util.List;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.mule.galaxy.DuplicateItemException;
import org.mule.galaxy.Item;
import org.mule.galaxy.NotFoundException;
import org.mule.galaxy.collab.Comment;
import org.mule.galaxy.collab.CommentManager;
import org.mule.galaxy.event.EntryCommentCreatedEvent;
import org.mule.galaxy.event.EventManager;
import org.mule.galaxy.impl.jcr.onm.AbstractReflectionDao;
import org.mule.galaxy.util.SecurityUtils;
import org.springmodules.jcr.JcrCallback;
public class CommentManagerImpl extends AbstractReflectionDao<Comment> implements CommentManager {
private EventManager eventManager;
public CommentManagerImpl() throws Exception {
super(Comment.class, "comments", true);
}
public List<Comment> getComments(final String artifactId) {
return getComments(artifactId, false);
}
@SuppressWarnings("unchecked")
public List<Comment> getComments(final String artifactId, final boolean includeChildren) {
return (List<Comment>) execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
StringBuilder qstr = new StringBuilder();
qstr.append("/jcr:root/comments/*[");
if (!includeChildren) {
qstr.append("not(@parent) and");
}
qstr.append("@item='")
.append(artifactId)
.append("'] order by @date ascending");
return query(qstr.toString(), session);
}
});
}
@SuppressWarnings("unchecked")
public List<Comment> getRecentComments(final int maxResults) {
return (List<Comment>) execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
return query("/jcr:root/comments/* order by @date descending", session, maxResults);
}
});
}
public void addComment(Comment c) {
try {
save(c);
} catch (DuplicateItemException e1) {
// should never happen
throw new RuntimeException(e1);
} catch (NotFoundException e1) {
// should never happen
throw new RuntimeException(e1);
}
// fire the event
// FIXME: null pointer on test and itemNotFoundException over rpc
Item item = c.getItem();
Comment parent = c;
while (item == null) {
- parent = c.getParent();
+ parent = parent.getParent();
item = parent.getItem();
}
EntryCommentCreatedEvent event = new EntryCommentCreatedEvent(item, c);
event.setUser(SecurityUtils.getCurrentUser());
eventManager.fireEvent(event);
}
public Comment getComment(String commentId) throws NotFoundException {
return get(commentId);
}
public EventManager getEventManager() {
return eventManager;
}
public void setEventManager(final EventManager eventManager) {
this.eventManager = eventManager;
}
}
| true | true | public void addComment(Comment c) {
try {
save(c);
} catch (DuplicateItemException e1) {
// should never happen
throw new RuntimeException(e1);
} catch (NotFoundException e1) {
// should never happen
throw new RuntimeException(e1);
}
// fire the event
// FIXME: null pointer on test and itemNotFoundException over rpc
Item item = c.getItem();
Comment parent = c;
while (item == null) {
parent = c.getParent();
item = parent.getItem();
}
EntryCommentCreatedEvent event = new EntryCommentCreatedEvent(item, c);
event.setUser(SecurityUtils.getCurrentUser());
eventManager.fireEvent(event);
}
| public void addComment(Comment c) {
try {
save(c);
} catch (DuplicateItemException e1) {
// should never happen
throw new RuntimeException(e1);
} catch (NotFoundException e1) {
// should never happen
throw new RuntimeException(e1);
}
// fire the event
// FIXME: null pointer on test and itemNotFoundException over rpc
Item item = c.getItem();
Comment parent = c;
while (item == null) {
parent = parent.getParent();
item = parent.getItem();
}
EntryCommentCreatedEvent event = new EntryCommentCreatedEvent(item, c);
event.setUser(SecurityUtils.getCurrentUser());
eventManager.fireEvent(event);
}
|
diff --git a/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/repository/AddonPackage.java b/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/repository/AddonPackage.java
index 8bdd26080..ae630e324 100755
--- a/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/repository/AddonPackage.java
+++ b/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/repository/AddonPackage.java
@@ -1,308 +1,308 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.sdklib.internal.repository;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.SdkConstants;
import com.android.sdklib.SdkManager;
import com.android.sdklib.IAndroidTarget.IOptionalLibrary;
import com.android.sdklib.internal.repository.Archive.Arch;
import com.android.sdklib.internal.repository.Archive.Os;
import com.android.sdklib.repository.SdkRepository;
import org.w3c.dom.Node;
import java.io.File;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
/**
* Represents an add-on XML node in an SDK repository.
*/
public class AddonPackage extends Package
implements IPackageVersion, IPlatformDependency {
private static final String PROP_NAME = "Addon.Name"; //$NON-NLS-1$
private static final String PROP_VENDOR = "Addon.Vendor"; //$NON-NLS-1$
private final String mVendor;
private final String mName;
private final AndroidVersion mVersion;
/** An add-on library. */
public static class Lib {
private final String mName;
private final String mDescription;
public Lib(String name, String description) {
mName = name;
mDescription = description;
}
public String getName() {
return mName;
}
public String getDescription() {
return mDescription;
}
}
private final Lib[] mLibs;
/**
* Creates a new add-on package from the attributes and elements of the given XML node.
* <p/>
* This constructor should throw an exception if the package cannot be created.
*/
AddonPackage(RepoSource source, Node packageNode, Map<String,String> licenses) {
super(source, packageNode, licenses);
mVendor = XmlParserUtils.getXmlString(packageNode, SdkRepository.NODE_VENDOR);
mName = XmlParserUtils.getXmlString(packageNode, SdkRepository.NODE_NAME);
int apiLevel = XmlParserUtils.getXmlInt (packageNode, SdkRepository.NODE_API_LEVEL, 0);
String codeName = XmlParserUtils.getXmlString(packageNode, SdkRepository.NODE_CODENAME);
if (codeName.length() == 0) {
codeName = null;
}
mVersion = new AndroidVersion(apiLevel, codeName);
mLibs = parseLibs(XmlParserUtils.getFirstChild(packageNode, SdkRepository.NODE_LIBS));
}
/**
* Creates a new platform package based on an actual {@link IAndroidTarget} (which
* {@link IAndroidTarget#isPlatform()} false) from the {@link SdkManager}.
* This is used to list local SDK folders in which case there is one archive which
* URL is the actual target location.
* <p/>
* By design, this creates a package with one and only one archive.
*/
AddonPackage(IAndroidTarget target, Properties props) {
super( null, //source
props, //properties
target.getRevision(), //revision
null, //license
target.getDescription(), //description
null, //descUrl
Os.getCurrentOs(), //archiveOs
Arch.getCurrentArch(), //archiveArch
target.getLocation() //archiveOsPath
);
mVersion = target.getVersion();
mName = target.getName();
mVendor = target.getVendor();
IOptionalLibrary[] optLibs = target.getOptionalLibraries();
if (optLibs == null || optLibs.length == 0) {
mLibs = new Lib[0];
} else {
mLibs = new Lib[optLibs.length];
for (int i = 0; i < optLibs.length; i++) {
mLibs[i] = new Lib(optLibs[i].getName(), optLibs[i].getDescription());
}
}
}
/**
* Save the properties of the current packages in the given {@link Properties} object.
* These properties will later be given to a constructor that takes a {@link Properties} object.
*/
@Override
void saveProperties(Properties props) {
super.saveProperties(props);
mVersion.saveProperties(props);
if (mName != null) {
props.setProperty(PROP_NAME, mName);
}
if (mVendor != null) {
props.setProperty(PROP_VENDOR, mVendor);
}
}
/**
* Parses a <libs> element.
*/
private Lib[] parseLibs(Node libsNode) {
ArrayList<Lib> libs = new ArrayList<Lib>();
if (libsNode != null) {
String nsUri = libsNode.getNamespaceURI();
for(Node child = libsNode.getFirstChild();
child != null;
child = child.getNextSibling()) {
if (child.getNodeType() == Node.ELEMENT_NODE &&
nsUri.equals(child.getNamespaceURI()) &&
SdkRepository.NODE_LIB.equals(child.getLocalName())) {
libs.add(parseLib(child));
}
}
}
return libs.toArray(new Lib[libs.size()]);
}
/**
* Parses a <lib> element from a <libs> container.
*/
private Lib parseLib(Node libNode) {
return new Lib(XmlParserUtils.getXmlString(libNode, SdkRepository.NODE_NAME),
XmlParserUtils.getXmlString(libNode, SdkRepository.NODE_DESCRIPTION));
}
/** Returns the vendor, a string, for add-on packages. */
public String getVendor() {
return mVendor;
}
/** Returns the name, a string, for add-on packages or for libraries. */
public String getName() {
return mName;
}
/**
* Returns the version of the platform dependency of this package.
* <p/>
* An add-on has the same {@link AndroidVersion} as the platform it depends on.
*/
public AndroidVersion getVersion() {
return mVersion;
}
/** Returns the libs defined in this add-on. Can be an empty array but not null. */
public Lib[] getLibs() {
return mLibs;
}
/** Returns a short description for an {@link IDescription}. */
@Override
public String getShortDescription() {
return String.format("%1$s by %2$s, Android API %3$s, revision %4$s%5$s",
getName(),
getVendor(),
mVersion.getApiString(),
getRevision(),
isObsolete() ? " (Obsolete)" : "");
}
/**
* Returns a long description for an {@link IDescription}.
*
* The long description is whatever the XML contains for the <description> field,
* or the short description if the former is empty.
*/
@Override
public String getLongDescription() {
String s = getDescription();
if (s == null || s.length() == 0) {
s = getShortDescription();
}
if (s.indexOf("revision") == -1) {
s += String.format("\nRevision %1$d%2$s",
getRevision(),
isObsolete() ? " (Obsolete)" : "");
}
s += String.format("\nRequires SDK Platform Android API %1$s",
mVersion.getApiString());
return s;
}
/**
* Computes a potential installation folder if an archive of this package were
* to be installed right away in the given SDK root.
* <p/>
* An add-on package is typically installed in SDK/add-ons/"addon-name"-"api-level".
* The name needs to be sanitized to be acceptable as a directory name.
* However if we can find a different directory under SDK/add-ons that already
* has this add-ons installed, we'll use that one.
*
* @param osSdkRoot The OS path of the SDK root folder.
* @param suggestedDir A suggestion for the installation folder name, based on the root
* folder used in the zip archive.
* @param sdkManager An existing SDK manager to list current platforms and addons.
* @return A new {@link File} corresponding to the directory to use to install this package.
*/
@Override
public File getInstallFolder(String osSdkRoot, String suggestedDir, SdkManager sdkManager) {
File addons = new File(osSdkRoot, SdkConstants.FD_ADDONS);
// First find if this add-on is already installed. If so, reuse the same directory.
for (IAndroidTarget target : sdkManager.getTargets()) {
if (!target.isPlatform() &&
target.getVersion().equals(mVersion) &&
target.getName().equals(getName()) &&
target.getVendor().equals(getVendor())) {
return new File(target.getLocation());
}
}
// Compute a folder directory using the addon declared name and vendor strings.
- // This purposedly ignores the suggestedDir.
+ // This purposely ignores the suggestedDir.
String name = String.format("addon_%s_%s_%s", //$NON-NLS-1$
getName(), getVendor(), mVersion.getApiString());
name = name.toLowerCase();
name = name.replaceAll("[^a-z0-9_-]+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
name = name.replaceAll("_+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i < 100; i++) {
String name2 = i == 0 ? name : String.format("%s-%d", name, i); //$NON-NLS-1$
File folder = new File(addons, name2);
if (!folder.exists()) {
return folder;
}
}
// We shouldn't really get here. I mean, seriously, we tried hard enough.
return null;
}
/**
* Makes sure the base /add-ons folder exists before installing.
*/
@Override
public boolean preInstallHook(Archive archive,
ITaskMonitor monitor,
String osSdkRoot,
File installFolder) {
File addonsRoot = new File(osSdkRoot, SdkConstants.FD_ADDONS);
if (!addonsRoot.isDirectory()) {
addonsRoot.mkdir();
}
return super.preInstallHook(archive, monitor, osSdkRoot, installFolder);
}
@Override
public boolean sameItemAs(Package pkg) {
if (pkg instanceof AddonPackage) {
AddonPackage newPkg = (AddonPackage)pkg;
// check they are the same add-on.
return getName().equals(newPkg.getName()) &&
getVendor().equals(newPkg.getVendor()) &&
getVersion().equals(newPkg.getVersion());
}
return false;
}
}
| true | true | public File getInstallFolder(String osSdkRoot, String suggestedDir, SdkManager sdkManager) {
File addons = new File(osSdkRoot, SdkConstants.FD_ADDONS);
// First find if this add-on is already installed. If so, reuse the same directory.
for (IAndroidTarget target : sdkManager.getTargets()) {
if (!target.isPlatform() &&
target.getVersion().equals(mVersion) &&
target.getName().equals(getName()) &&
target.getVendor().equals(getVendor())) {
return new File(target.getLocation());
}
}
// Compute a folder directory using the addon declared name and vendor strings.
// This purposedly ignores the suggestedDir.
String name = String.format("addon_%s_%s_%s", //$NON-NLS-1$
getName(), getVendor(), mVersion.getApiString());
name = name.toLowerCase();
name = name.replaceAll("[^a-z0-9_-]+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
name = name.replaceAll("_+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i < 100; i++) {
String name2 = i == 0 ? name : String.format("%s-%d", name, i); //$NON-NLS-1$
File folder = new File(addons, name2);
if (!folder.exists()) {
return folder;
}
}
// We shouldn't really get here. I mean, seriously, we tried hard enough.
return null;
}
| public File getInstallFolder(String osSdkRoot, String suggestedDir, SdkManager sdkManager) {
File addons = new File(osSdkRoot, SdkConstants.FD_ADDONS);
// First find if this add-on is already installed. If so, reuse the same directory.
for (IAndroidTarget target : sdkManager.getTargets()) {
if (!target.isPlatform() &&
target.getVersion().equals(mVersion) &&
target.getName().equals(getName()) &&
target.getVendor().equals(getVendor())) {
return new File(target.getLocation());
}
}
// Compute a folder directory using the addon declared name and vendor strings.
// This purposely ignores the suggestedDir.
String name = String.format("addon_%s_%s_%s", //$NON-NLS-1$
getName(), getVendor(), mVersion.getApiString());
name = name.toLowerCase();
name = name.replaceAll("[^a-z0-9_-]+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
name = name.replaceAll("_+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i < 100; i++) {
String name2 = i == 0 ? name : String.format("%s-%d", name, i); //$NON-NLS-1$
File folder = new File(addons, name2);
if (!folder.exists()) {
return folder;
}
}
// We shouldn't really get here. I mean, seriously, we tried hard enough.
return null;
}
|
diff --git a/src/main/java/com/alta189/chavabot/events/botevents/InvitedEvent.java b/src/main/java/com/alta189/chavabot/events/botevents/InvitedEvent.java
index 5fa3448..a506f04 100644
--- a/src/main/java/com/alta189/chavabot/events/botevents/InvitedEvent.java
+++ b/src/main/java/com/alta189/chavabot/events/botevents/InvitedEvent.java
@@ -1,39 +1,40 @@
package com.alta189.chavabot.events.botevents;
import com.alta189.chavabot.ChavaUser;
import com.alta189.chavabot.events.HandlerList;
public class InvitedEvent extends BotEvent<InvitedEvent> {
private static final InvitedEvent instance = new InvitedEvent();
private static final HandlerList<InvitedEvent> handlers = new HandlerList<InvitedEvent>();
private String channel;
private ChavaUser user;
public static InvitedEvent getInstance(String channel, ChavaUser sender) {
instance.channel = channel;
+ instance.user = sender;
return instance;
}
public String getChannel() {
return channel;
}
public ChavaUser getSender() {
return user;
}
@Override
public HandlerList<InvitedEvent> getHandlers() {
return handlers;
}
@Override
protected String getEventName() {
return "Invited Event";
}
public void setCancelled(boolean cancelled) {
super.setCancelled(cancelled);
}
}
| true | true | public static InvitedEvent getInstance(String channel, ChavaUser sender) {
instance.channel = channel;
return instance;
}
| public static InvitedEvent getInstance(String channel, ChavaUser sender) {
instance.channel = channel;
instance.user = sender;
return instance;
}
|
diff --git a/src/balle/brick/milestone1/RollAndKick.java b/src/balle/brick/milestone1/RollAndKick.java
index fc87db6..4c320eb 100644
--- a/src/balle/brick/milestone1/RollAndKick.java
+++ b/src/balle/brick/milestone1/RollAndKick.java
@@ -1,56 +1,62 @@
package balle.brick.milestone1;
import lejos.nxt.LCD;
import lejos.nxt.SensorPort;
import lejos.nxt.TouchSensor;
import balle.brick.BrickController;
public class RollAndKick {
private static void drawMessage(String message) {
LCD.clear();
LCD.drawString(message, 0, 0);
LCD.refresh();
}
public static void main(String[] args) {
BrickController controller = new BrickController();
TouchSensor sensorLeft = new TouchSensor(SensorPort.S1);
TouchSensor sensorRight = new TouchSensor(SensorPort.S2);
boolean movingForward = false;
+ boolean isAccelerating = false;
while (true) {
if (sensorLeft.isPressed() || sensorRight.isPressed()) {
drawMessage("Whoops, wall!");
controller.stop();
controller.setWheelSpeeds(-controller.getMaximumWheelSpeed(),
-controller.getMaximumWheelSpeed());
try {
Thread.sleep(200);
break;
} catch (Exception e) {
drawMessage(";/");
break;
}
}
if (!movingForward) {
drawMessage("Roll");
movingForward = true;
+ isAccelerating = true;
controller.reset();
- controller.forward(300);
+ controller.forward(200);
} else {
float distance = controller.getTravelDistance();
- if (distance > 500) {
+ if (distance > 1000) {
drawMessage("Kick!");
controller.kick();
- break;
+ break;
+ }
+ else if (distance > 100 && isAccelerating) {
+ controller.forward(300);
+ isAccelerating = false;
} else {
drawMessage(Float.toString(distance));
}
}
}
}
}
| false | true | public static void main(String[] args) {
BrickController controller = new BrickController();
TouchSensor sensorLeft = new TouchSensor(SensorPort.S1);
TouchSensor sensorRight = new TouchSensor(SensorPort.S2);
boolean movingForward = false;
while (true) {
if (sensorLeft.isPressed() || sensorRight.isPressed()) {
drawMessage("Whoops, wall!");
controller.stop();
controller.setWheelSpeeds(-controller.getMaximumWheelSpeed(),
-controller.getMaximumWheelSpeed());
try {
Thread.sleep(200);
break;
} catch (Exception e) {
drawMessage(";/");
break;
}
}
if (!movingForward) {
drawMessage("Roll");
movingForward = true;
controller.reset();
controller.forward(300);
} else {
float distance = controller.getTravelDistance();
if (distance > 500) {
drawMessage("Kick!");
controller.kick();
break;
} else {
drawMessage(Float.toString(distance));
}
}
}
}
| public static void main(String[] args) {
BrickController controller = new BrickController();
TouchSensor sensorLeft = new TouchSensor(SensorPort.S1);
TouchSensor sensorRight = new TouchSensor(SensorPort.S2);
boolean movingForward = false;
boolean isAccelerating = false;
while (true) {
if (sensorLeft.isPressed() || sensorRight.isPressed()) {
drawMessage("Whoops, wall!");
controller.stop();
controller.setWheelSpeeds(-controller.getMaximumWheelSpeed(),
-controller.getMaximumWheelSpeed());
try {
Thread.sleep(200);
break;
} catch (Exception e) {
drawMessage(";/");
break;
}
}
if (!movingForward) {
drawMessage("Roll");
movingForward = true;
isAccelerating = true;
controller.reset();
controller.forward(200);
} else {
float distance = controller.getTravelDistance();
if (distance > 1000) {
drawMessage("Kick!");
controller.kick();
break;
}
else if (distance > 100 && isAccelerating) {
controller.forward(300);
isAccelerating = false;
} else {
drawMessage(Float.toString(distance));
}
}
}
}
|
diff --git a/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java b/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
index f840945a..a41f08e4 100644
--- a/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
+++ b/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
@@ -1,259 +1,268 @@
package de.hpi.bpmn2execpn.converter;
import java.util.ArrayList;
import java.util.List;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import de.hpi.bpmn.BPMNDiagram;
import de.hpi.bpmn.IntermediateEvent;
import de.hpi.bpmn.SubProcess;
import de.hpi.bpmn.Task;
import de.hpi.bpmn2execpn.model.ExecTask;
import de.hpi.bpmn2pn.converter.Converter;
import de.hpi.bpmn2pn.model.ConversionContext;
import de.hpi.bpmn2pn.model.SubProcessPlaces;
import de.hpi.execpn.ExecPetriNet;
import de.hpi.execpn.impl.ExecPNFactoryImpl;
import de.hpi.petrinet.LabeledTransition;
import de.hpi.petrinet.PetriNet;
import de.hpi.petrinet.Place;
import de.hpi.petrinet.Transition;
public class ExecConverter extends Converter {
private static final boolean abortWhenFinalize = true;
protected String modelURL;
private List<ExecTask> taskList;
public ExecConverter(BPMNDiagram diagram, String modelURL) {
super(diagram, new ExecPNFactoryImpl(modelURL));
this.modelURL = modelURL;
this.taskList = new ArrayList<ExecTask>();
}
@Override
protected void handleDiagram(PetriNet net, ConversionContext c) {
((ExecPetriNet) net).setName(diagram.getTitle());
}
@Override
protected void createStartPlaces(PetriNet net, ConversionContext c) {
// do nothing...: we want start transitions instead of start places
}
// TODO this is a dirty hack...
@Override
protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
// start Transition
LabeledTransition startT = addLabeledTransition(net, "start_" + task.getId(), task.getLabel());
startT.setAction("start");
exTask.startT = startT;
exTask.running = addPlace(net, "running_" + task.getId());
// skip Transition
LabeledTransition skipT = addLabeledTransition(net, "skip_" + task.getId(), task.getLabel());
skipT.setAction("skip");
exTask.skip = skipT;
// end Transition
LabeledTransition endT = addLabeledTransition(net, "end_" + task.getId(), task.getLabel());
endT.setAction("end");
exTask.endT = endT;
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.startT);
addFlowRelationship(net, exTask.endT, c.map.get(getOutgoingSequenceFlow(task)));
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.skip);
addFlowRelationship(net, exTask.skip, c.map.get(getOutgoingSequenceFlow(task)));
addFlowRelationship(net, exTask.startT, exTask.running);
addFlowRelationship(net, exTask.running, exTask.endT);
// suspend/resume
LabeledTransition suspendT = addLabeledTransition(net, "suspend_" + task.getId(), task.getLabel());
suspendT.setAction("suspend");
exTask.suspend = suspendT;
LabeledTransition resumeT = addLabeledTransition(net, "resume_" + task.getId(), task.getLabel());
resumeT.setAction("resume");
exTask.resume = resumeT;
exTask.suspended = addPlace(net, "suspended_" + task.getId());
addFlowRelationship(net, exTask.running, exTask.suspend);
addFlowRelationship(net, exTask.suspend, exTask.suspended);
addFlowRelationship(net, exTask.suspended, exTask.resume);
addFlowRelationship(net, exTask.resume, exTask.running);
taskList.add(exTask);
handleMessageFlow(net, task, exTask.startT, exTask.endT, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.endT, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
@Override
protected void handleSubProcess(PetriNet net, SubProcess process,
ConversionContext c) {
super.handleSubProcess(net, process, c);
if (process.isAdhoc()) {
handleSubProcessAdHoc(net, process, c);
}
}
// TODO: Data dependencies
// TODO missing completion condition concept
protected void handleSubProcessAdHoc(PetriNet net, SubProcess process,
ConversionContext c) {
SubProcessPlaces pl = c.getSubprocessPlaces(process);
// start and end transitions
Transition startT = addTauTransition(net, "ad-hoc_start_" + process.getId());
Transition endT = addTauTransition(net, "ad-hoc_end_" + process.getId());
Transition defaultEndT = addTauTransition(net, "ad-hoc_defaultEnd_" + process.getId());
Place execState = addPlace(net, "ad-hoc_execState_" + process.getId());
addFlowRelationship(net, pl.startP, startT);
addFlowRelationship(net, startT, execState);
addFlowRelationship(net, execState, defaultEndT);
addFlowRelationship(net, execState, endT);
addFlowRelationship(net, defaultEndT, pl.endP);
addFlowRelationship(net, endT, pl.endP);
// standard completion condition check
Place updatedState = addPlace(net, "ad-hoc_updatedState_" + process.getId());
Place ccStatus = addPlace(net, "ad-hoc_ccStatus_" + process.getId());
// TODO: make AutomaticTransition with functionality to evaluate completion condition
//Transition ccCheck = addLabeledTransition(net, "ad-hoc_ccCheck_" + process.getId(), "ad-hoc_cc_" + process.getCompletionCondition());
Transition ccCheck = addTauTransition(net, "ad-hoc_ccCheck_" + process.getId());
// TODO: make Tau when guards work
Transition finalize = addLabeledTransition(net, "ad-hoc_finalize_" + process.getId(), "ad-hoc_finalize");
// TODO: make Tau when guards work
//Transition resume = addLabeledTransition(net, "ad-hoc_resume_" + process.getId(), "ad-hoc_resume");
Transition resume = addTauTransition(net, "ad-hoc_resume_" + process.getId());
addFlowRelationship(net, updatedState, ccCheck);
addFlowRelationship(net, execState, ccCheck);
addFlowRelationship(net, ccCheck, execState);
addFlowRelationship(net, ccCheck, ccStatus);
if (process.isParallelOrdering() && abortWhenFinalize) {
// parallel ad-hoc construct with abortion of tasks when completion condition is true -------------------------------
// synchronization and completionCondition checks(enableStarting, enableFinishing)
Place enableStarting = addPlace(net, "ad-hoc_enableStarting_" + process.getId());
Place enableFinishing = addPlace(net, "ad-hoc_enableFinishing_" + process.getId());
addFlowRelationship(net, startT, enableStarting);
addFlowRelationship(net, startT, enableFinishing);
addFlowRelationship(net, enableStarting, defaultEndT);
addFlowRelationship(net, enableFinishing, defaultEndT);
addFlowRelationship(net, enableStarting, ccCheck);
addFlowRelationship(net, resume, enableStarting);
addFlowRelationship(net, resume, enableFinishing);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_"
+ exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_"
+ exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.startT);
+ addFlowRelationship(net, enabled, exTask.skip);
addFlowRelationship(net, enableStarting, exTask.startT);
+ addFlowRelationship(net, enableStarting, exTask.skip);
addFlowRelationship(net, exTask.startT, enableStarting);
+ addFlowRelationship(net, exTask.skip, enableStarting);
addFlowRelationship(net, enableFinishing, exTask.endT);
- addFlowRelationship(net, exTask.endT, executed);
+ addFlowRelationship(net, exTask.endT, executed);
addFlowRelationship(net, exTask.endT, updatedState);
+ addFlowRelationship(net, exTask.skip, executed);
+ addFlowRelationship(net, exTask.skip, updatedState);
addFlowRelationship(net, executed, defaultEndT);
// finishing construct(finalize with skip, finish, abort and leave_suspend)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
Transition abort = addTauTransition(net, "ad-hoc_abort_task_" + exTask.getId());
Transition leaveSuspended = addTauTransition(net, "ad-hoc_leave_suspended_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, enableFinalize, abort);
addFlowRelationship(net, exTask.running, abort);
addFlowRelationship(net, abort, taskFinalized);
addFlowRelationship(net, enableFinalize, leaveSuspended);
addFlowRelationship(net, exTask.suspended, leaveSuspended);
addFlowRelationship(net, leaveSuspended, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}else if (process.isParallelOrdering() && !abortWhenFinalize) {
// parallel ad-hoc construct, running tasks can finish on their own after completion condition is true -------------
throw new NotImplementedException();
}else {
// sequential ad-hoc construct -----------------------------------------------------------------------------------------------
// synchronization and completionCondition checks(synch, corresponds to enableStarting)
Place synch = addPlace(net, "ad-hoc_synch_" + process.getId());
addFlowRelationship(net, startT, synch);
addFlowRelationship(net, synch, defaultEndT);
addFlowRelationship(net, resume, synch);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.startT);
addFlowRelationship(net, synch, exTask.startT);
+ addFlowRelationship(net, enabled, exTask.skip);
+ addFlowRelationship(net, synch, exTask.skip);
addFlowRelationship(net, exTask.endT, executed);
addFlowRelationship(net, exTask.endT, updatedState);
+ addFlowRelationship(net, exTask.skip, executed);
+ addFlowRelationship(net, exTask.skip, updatedState);
addFlowRelationship(net, executed, defaultEndT);
// finishing construct(finalize with skip, finish and abort)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}
}
}
| false | true | protected void handleSubProcessAdHoc(PetriNet net, SubProcess process,
ConversionContext c) {
SubProcessPlaces pl = c.getSubprocessPlaces(process);
// start and end transitions
Transition startT = addTauTransition(net, "ad-hoc_start_" + process.getId());
Transition endT = addTauTransition(net, "ad-hoc_end_" + process.getId());
Transition defaultEndT = addTauTransition(net, "ad-hoc_defaultEnd_" + process.getId());
Place execState = addPlace(net, "ad-hoc_execState_" + process.getId());
addFlowRelationship(net, pl.startP, startT);
addFlowRelationship(net, startT, execState);
addFlowRelationship(net, execState, defaultEndT);
addFlowRelationship(net, execState, endT);
addFlowRelationship(net, defaultEndT, pl.endP);
addFlowRelationship(net, endT, pl.endP);
// standard completion condition check
Place updatedState = addPlace(net, "ad-hoc_updatedState_" + process.getId());
Place ccStatus = addPlace(net, "ad-hoc_ccStatus_" + process.getId());
// TODO: make AutomaticTransition with functionality to evaluate completion condition
//Transition ccCheck = addLabeledTransition(net, "ad-hoc_ccCheck_" + process.getId(), "ad-hoc_cc_" + process.getCompletionCondition());
Transition ccCheck = addTauTransition(net, "ad-hoc_ccCheck_" + process.getId());
// TODO: make Tau when guards work
Transition finalize = addLabeledTransition(net, "ad-hoc_finalize_" + process.getId(), "ad-hoc_finalize");
// TODO: make Tau when guards work
//Transition resume = addLabeledTransition(net, "ad-hoc_resume_" + process.getId(), "ad-hoc_resume");
Transition resume = addTauTransition(net, "ad-hoc_resume_" + process.getId());
addFlowRelationship(net, updatedState, ccCheck);
addFlowRelationship(net, execState, ccCheck);
addFlowRelationship(net, ccCheck, execState);
addFlowRelationship(net, ccCheck, ccStatus);
if (process.isParallelOrdering() && abortWhenFinalize) {
// parallel ad-hoc construct with abortion of tasks when completion condition is true -------------------------------
// synchronization and completionCondition checks(enableStarting, enableFinishing)
Place enableStarting = addPlace(net, "ad-hoc_enableStarting_" + process.getId());
Place enableFinishing = addPlace(net, "ad-hoc_enableFinishing_" + process.getId());
addFlowRelationship(net, startT, enableStarting);
addFlowRelationship(net, startT, enableFinishing);
addFlowRelationship(net, enableStarting, defaultEndT);
addFlowRelationship(net, enableFinishing, defaultEndT);
addFlowRelationship(net, enableStarting, ccCheck);
addFlowRelationship(net, resume, enableStarting);
addFlowRelationship(net, resume, enableFinishing);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_"
+ exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_"
+ exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.startT);
addFlowRelationship(net, enableStarting, exTask.startT);
addFlowRelationship(net, exTask.startT, enableStarting);
addFlowRelationship(net, enableFinishing, exTask.endT);
addFlowRelationship(net, exTask.endT, executed);
addFlowRelationship(net, exTask.endT, updatedState);
addFlowRelationship(net, executed, defaultEndT);
// finishing construct(finalize with skip, finish, abort and leave_suspend)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
Transition abort = addTauTransition(net, "ad-hoc_abort_task_" + exTask.getId());
Transition leaveSuspended = addTauTransition(net, "ad-hoc_leave_suspended_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, enableFinalize, abort);
addFlowRelationship(net, exTask.running, abort);
addFlowRelationship(net, abort, taskFinalized);
addFlowRelationship(net, enableFinalize, leaveSuspended);
addFlowRelationship(net, exTask.suspended, leaveSuspended);
addFlowRelationship(net, leaveSuspended, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}else if (process.isParallelOrdering() && !abortWhenFinalize) {
// parallel ad-hoc construct, running tasks can finish on their own after completion condition is true -------------
throw new NotImplementedException();
}else {
// sequential ad-hoc construct -----------------------------------------------------------------------------------------------
// synchronization and completionCondition checks(synch, corresponds to enableStarting)
Place synch = addPlace(net, "ad-hoc_synch_" + process.getId());
addFlowRelationship(net, startT, synch);
addFlowRelationship(net, synch, defaultEndT);
addFlowRelationship(net, resume, synch);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.startT);
addFlowRelationship(net, synch, exTask.startT);
addFlowRelationship(net, exTask.endT, executed);
addFlowRelationship(net, exTask.endT, updatedState);
addFlowRelationship(net, executed, defaultEndT);
// finishing construct(finalize with skip, finish and abort)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}
}
| protected void handleSubProcessAdHoc(PetriNet net, SubProcess process,
ConversionContext c) {
SubProcessPlaces pl = c.getSubprocessPlaces(process);
// start and end transitions
Transition startT = addTauTransition(net, "ad-hoc_start_" + process.getId());
Transition endT = addTauTransition(net, "ad-hoc_end_" + process.getId());
Transition defaultEndT = addTauTransition(net, "ad-hoc_defaultEnd_" + process.getId());
Place execState = addPlace(net, "ad-hoc_execState_" + process.getId());
addFlowRelationship(net, pl.startP, startT);
addFlowRelationship(net, startT, execState);
addFlowRelationship(net, execState, defaultEndT);
addFlowRelationship(net, execState, endT);
addFlowRelationship(net, defaultEndT, pl.endP);
addFlowRelationship(net, endT, pl.endP);
// standard completion condition check
Place updatedState = addPlace(net, "ad-hoc_updatedState_" + process.getId());
Place ccStatus = addPlace(net, "ad-hoc_ccStatus_" + process.getId());
// TODO: make AutomaticTransition with functionality to evaluate completion condition
//Transition ccCheck = addLabeledTransition(net, "ad-hoc_ccCheck_" + process.getId(), "ad-hoc_cc_" + process.getCompletionCondition());
Transition ccCheck = addTauTransition(net, "ad-hoc_ccCheck_" + process.getId());
// TODO: make Tau when guards work
Transition finalize = addLabeledTransition(net, "ad-hoc_finalize_" + process.getId(), "ad-hoc_finalize");
// TODO: make Tau when guards work
//Transition resume = addLabeledTransition(net, "ad-hoc_resume_" + process.getId(), "ad-hoc_resume");
Transition resume = addTauTransition(net, "ad-hoc_resume_" + process.getId());
addFlowRelationship(net, updatedState, ccCheck);
addFlowRelationship(net, execState, ccCheck);
addFlowRelationship(net, ccCheck, execState);
addFlowRelationship(net, ccCheck, ccStatus);
if (process.isParallelOrdering() && abortWhenFinalize) {
// parallel ad-hoc construct with abortion of tasks when completion condition is true -------------------------------
// synchronization and completionCondition checks(enableStarting, enableFinishing)
Place enableStarting = addPlace(net, "ad-hoc_enableStarting_" + process.getId());
Place enableFinishing = addPlace(net, "ad-hoc_enableFinishing_" + process.getId());
addFlowRelationship(net, startT, enableStarting);
addFlowRelationship(net, startT, enableFinishing);
addFlowRelationship(net, enableStarting, defaultEndT);
addFlowRelationship(net, enableFinishing, defaultEndT);
addFlowRelationship(net, enableStarting, ccCheck);
addFlowRelationship(net, resume, enableStarting);
addFlowRelationship(net, resume, enableFinishing);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_"
+ exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_"
+ exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.startT);
addFlowRelationship(net, enabled, exTask.skip);
addFlowRelationship(net, enableStarting, exTask.startT);
addFlowRelationship(net, enableStarting, exTask.skip);
addFlowRelationship(net, exTask.startT, enableStarting);
addFlowRelationship(net, exTask.skip, enableStarting);
addFlowRelationship(net, enableFinishing, exTask.endT);
addFlowRelationship(net, exTask.endT, executed);
addFlowRelationship(net, exTask.endT, updatedState);
addFlowRelationship(net, exTask.skip, executed);
addFlowRelationship(net, exTask.skip, updatedState);
addFlowRelationship(net, executed, defaultEndT);
// finishing construct(finalize with skip, finish, abort and leave_suspend)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
Transition abort = addTauTransition(net, "ad-hoc_abort_task_" + exTask.getId());
Transition leaveSuspended = addTauTransition(net, "ad-hoc_leave_suspended_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, enableFinalize, abort);
addFlowRelationship(net, exTask.running, abort);
addFlowRelationship(net, abort, taskFinalized);
addFlowRelationship(net, enableFinalize, leaveSuspended);
addFlowRelationship(net, exTask.suspended, leaveSuspended);
addFlowRelationship(net, leaveSuspended, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}else if (process.isParallelOrdering() && !abortWhenFinalize) {
// parallel ad-hoc construct, running tasks can finish on their own after completion condition is true -------------
throw new NotImplementedException();
}else {
// sequential ad-hoc construct -----------------------------------------------------------------------------------------------
// synchronization and completionCondition checks(synch, corresponds to enableStarting)
Place synch = addPlace(net, "ad-hoc_synch_" + process.getId());
addFlowRelationship(net, startT, synch);
addFlowRelationship(net, synch, defaultEndT);
addFlowRelationship(net, resume, synch);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.startT);
addFlowRelationship(net, synch, exTask.startT);
addFlowRelationship(net, enabled, exTask.skip);
addFlowRelationship(net, synch, exTask.skip);
addFlowRelationship(net, exTask.endT, executed);
addFlowRelationship(net, exTask.endT, updatedState);
addFlowRelationship(net, exTask.skip, executed);
addFlowRelationship(net, exTask.skip, updatedState);
addFlowRelationship(net, executed, defaultEndT);
// finishing construct(finalize with skip, finish and abort)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}
}
|
diff --git a/maven-scm-providers/maven-scm-provider-vss/src/test/java/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.java b/maven-scm-providers/maven-scm-provider-vss/src/test/java/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.java
index 9cc0ec93..8f85009d 100644
--- a/maven-scm-providers/maven-scm-provider-vss/src/test/java/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.java
+++ b/maven-scm-providers/maven-scm-provider-vss/src/test/java/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.java
@@ -1,147 +1,147 @@
package org.apache.maven.scm.provider.vss.commands.edit;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmTestCase;
import org.apache.maven.scm.manager.ScmManager;
import org.apache.maven.scm.provider.vss.commands.VssCommandLineUtils;
import org.apache.maven.scm.provider.vss.repository.VssScmProviderRepository;
import org.apache.maven.scm.repository.ScmRepository;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.Commandline;
/**
* @author <a href="mailto:[email protected]">Emmanuel Venisse</a>
* @version $Id$
*/
public class VssEditCommandTest
extends ScmTestCase
{
private ScmManager scmManager;
public void setUp()
throws Exception
{
super.setUp();
scmManager = getScmManager();
}
public void testCommandLine()
throws Exception
{
ScmRepository repository = scmManager
.makeScmRepository( "scm:vss|username|password@C:/Program File/Visual Source Safe|D:/myProject" );
ScmFileSet fileSet = new ScmFileSet( getTestFile( "target" ) );
VssEditCommand command = new VssEditCommand();
List<Commandline> commands = command.buildCmdLine( (VssScmProviderRepository) repository.getProviderRepository(), fileSet );
Commandline cl = commands.get( 0 );
String ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
assertCommandLine( ssPath + "ss Checkout $D:/myProject -R -Yusername,password -I-", fileSet.getBasedir(), cl );
}
public void testCommandLineFileSet()
throws Exception
{
File target = getTestFile( "." );
ScmRepository repository = scmManager
.makeScmRepository( "scm:vss|username|password@C:/Program File/Visual Source Safe|D:/myProject" );
ScmFileSet fileSet = new ScmFileSet( target, "**/target/**/VssEditCommandTest.class" );
VssEditCommand command = new VssEditCommand();
List<Commandline> commands = command.buildCmdLine( (VssScmProviderRepository) repository.getProviderRepository(), fileSet );
Commandline cl =commands.get( 0 );
String ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
assertCommandLine(
ssPath
+ "ss Checkout $D:/myProject/target/test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class -Yusername,password -I-",
((File) fileSet.getFileList().get( 0 )).getParentFile().getCanonicalFile(), cl );
}
public void testCommandLineRelativePath()
throws Exception
{
ScmRepository repository = scmManager
.makeScmRepository( "scm:vss|username|password@C:/Program File/Visual Source Safe|D:/myProject" );
File target = getTestFile( "target" );
ScmFileSet fileSet = new ScmFileSet(
target,
new File( target,
"test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class" ) );
VssEditCommand command = new VssEditCommand();
List<Commandline> commands = command.buildCmdLine( (VssScmProviderRepository) repository.getProviderRepository(), fileSet );
Commandline cl = commands.get( 0 );
String ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
assertCommandLine(
ssPath
+ "ss Checkout $D:/myProject/test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class -Yusername,password -I-",
((File) fileSet.getFileList().get( 0 )).getParentFile().getCanonicalFile(), cl );
}
public void testCommandLineMultipleFiles()
throws Exception
{
ScmRepository repository = scmManager
.makeScmRepository( "scm:vss|username|password@C:/Program File/Visual Source Safe|D:/myProject" );
File target = getTestFile( "target" );
ScmFileSet fileSet = new ScmFileSet( target, Arrays
.asList( new File[] {
new File( target,
"test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class" ),
new File( target, "test-classes/META-INF/LICENSE" ) } ) );
VssEditCommand command = new VssEditCommand();
List<Commandline> commands = command.buildCmdLine( (VssScmProviderRepository) repository.getProviderRepository(), fileSet );
assertEquals( 2, commands.size() );
Commandline cl;
String ssPath;
cl = (Commandline) commands.get( 0 );
ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
// vss is windauze so don't care about the case
assertEquals( StringUtils.lowerCase( normSep( target.getCanonicalPath()
+ "/test-classes/org/apache/maven/scm/provider/vss/commands/edit" ) ), StringUtils.lowerCase( cl
.getWorkingDirectory().getCanonicalPath() ) );
assertCommandLine(
ssPath
+ "ss Checkout $D:/myProject/test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class -Yusername,password -I-",
((File) fileSet.getFileList().get( 0 )).getParentFile().getCanonicalFile(), cl );
cl = (Commandline) commands.get( 1 );
ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
// vss is windauze so don't care about the case
- assertEquals( StringUtils.lowerCase( normSep( target.getPath() + "/test-classes/META-INF" ) ), StringUtils
- .lowerCase( cl.getWorkingDirectory().getPath() ) );
+ assertEquals( StringUtils.lowerCase( normSep( target.getCanonicalPath() + "/test-classes/META-INF" ) ), StringUtils
+ .lowerCase( cl.getWorkingDirectory().getCanonicalPath() ) );
assertCommandLine( ssPath + "ss Checkout $D:/myProject/test-classes/META-INF/LICENSE -Yusername,password -I-",
((File) fileSet.getFileList().get( 1 )).getParentFile().getCanonicalFile() , cl );
}
private String normSep( String str )
{
return str.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar );
}
}
| true | true | public void testCommandLineMultipleFiles()
throws Exception
{
ScmRepository repository = scmManager
.makeScmRepository( "scm:vss|username|password@C:/Program File/Visual Source Safe|D:/myProject" );
File target = getTestFile( "target" );
ScmFileSet fileSet = new ScmFileSet( target, Arrays
.asList( new File[] {
new File( target,
"test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class" ),
new File( target, "test-classes/META-INF/LICENSE" ) } ) );
VssEditCommand command = new VssEditCommand();
List<Commandline> commands = command.buildCmdLine( (VssScmProviderRepository) repository.getProviderRepository(), fileSet );
assertEquals( 2, commands.size() );
Commandline cl;
String ssPath;
cl = (Commandline) commands.get( 0 );
ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
// vss is windauze so don't care about the case
assertEquals( StringUtils.lowerCase( normSep( target.getCanonicalPath()
+ "/test-classes/org/apache/maven/scm/provider/vss/commands/edit" ) ), StringUtils.lowerCase( cl
.getWorkingDirectory().getCanonicalPath() ) );
assertCommandLine(
ssPath
+ "ss Checkout $D:/myProject/test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class -Yusername,password -I-",
((File) fileSet.getFileList().get( 0 )).getParentFile().getCanonicalFile(), cl );
cl = (Commandline) commands.get( 1 );
ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
// vss is windauze so don't care about the case
assertEquals( StringUtils.lowerCase( normSep( target.getPath() + "/test-classes/META-INF" ) ), StringUtils
.lowerCase( cl.getWorkingDirectory().getPath() ) );
assertCommandLine( ssPath + "ss Checkout $D:/myProject/test-classes/META-INF/LICENSE -Yusername,password -I-",
((File) fileSet.getFileList().get( 1 )).getParentFile().getCanonicalFile() , cl );
}
| public void testCommandLineMultipleFiles()
throws Exception
{
ScmRepository repository = scmManager
.makeScmRepository( "scm:vss|username|password@C:/Program File/Visual Source Safe|D:/myProject" );
File target = getTestFile( "target" );
ScmFileSet fileSet = new ScmFileSet( target, Arrays
.asList( new File[] {
new File( target,
"test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class" ),
new File( target, "test-classes/META-INF/LICENSE" ) } ) );
VssEditCommand command = new VssEditCommand();
List<Commandline> commands = command.buildCmdLine( (VssScmProviderRepository) repository.getProviderRepository(), fileSet );
assertEquals( 2, commands.size() );
Commandline cl;
String ssPath;
cl = (Commandline) commands.get( 0 );
ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
// vss is windauze so don't care about the case
assertEquals( StringUtils.lowerCase( normSep( target.getCanonicalPath()
+ "/test-classes/org/apache/maven/scm/provider/vss/commands/edit" ) ), StringUtils.lowerCase( cl
.getWorkingDirectory().getCanonicalPath() ) );
assertCommandLine(
ssPath
+ "ss Checkout $D:/myProject/test-classes/org/apache/maven/scm/provider/vss/commands/edit/VssEditCommandTest.class -Yusername,password -I-",
((File) fileSet.getFileList().get( 0 )).getParentFile().getCanonicalFile(), cl );
cl = (Commandline) commands.get( 1 );
ssPath = VssCommandLineUtils.getSsDir().replace( '/', File.separatorChar );
// vss is windauze so don't care about the case
assertEquals( StringUtils.lowerCase( normSep( target.getCanonicalPath() + "/test-classes/META-INF" ) ), StringUtils
.lowerCase( cl.getWorkingDirectory().getCanonicalPath() ) );
assertCommandLine( ssPath + "ss Checkout $D:/myProject/test-classes/META-INF/LICENSE -Yusername,password -I-",
((File) fileSet.getFileList().get( 1 )).getParentFile().getCanonicalFile() , cl );
}
|
diff --git a/src/org/selfkleptomaniac/ti/imageasresized/ImageasresizedModule.java b/src/org/selfkleptomaniac/ti/imageasresized/ImageasresizedModule.java
index 65010d8..2b1738d 100644
--- a/src/org/selfkleptomaniac/ti/imageasresized/ImageasresizedModule.java
+++ b/src/org/selfkleptomaniac/ti/imageasresized/ImageasresizedModule.java
@@ -1,241 +1,245 @@
/**
* This file was auto-generated by the Titanium Module SDK helper for Android
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
*/
package org.selfkleptomaniac.ti.imageasresized;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiBlob;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.File;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.content.res.AssetManager;
import android.os.Environment;
@Kroll.module(name="Imageasresized", id="org.selfkleptomaniac.ti.imageasresized")
public class ImageasresizedModule extends KrollModule
{
// Standard Debugging variables
private static final String LCAT = "ImageasresizedModule";
private static InputStream is;
// You can define constants with @Kroll.constant, for example:
// @Kroll.constant public static final String EXTERNAL_NAME = value;
public ImageasresizedModule()
{
super();
}
@Kroll.onAppCreate
public static void onAppCreate(TiApplication app)
{
Log.d(LCAT, "inside onAppCreate");
// put module init code that needs to run when the application is created
}
// Methods
@Kroll.method
public String example()
{
Log.d(LCAT, "example called");
return "hello world";
}
// Properties
@Kroll.getProperty
public String getExampleProp()
{
Log.d(LCAT, "get example property");
return "hello world";
}
@Kroll.setProperty
public void setExampleProp(String value) {
Log.d(LCAT, "set example property: " + value);
}
@Kroll.method
public TiBlob cameraImageAsCropped(TiBlob image, int width, int height, int rotate, int x, int y){
return cameraResizer(image, width, height, rotate, x, y);
}
@Kroll.method
public TiBlob cameraImageAsResized(TiBlob image, int width, int height, int rotate){
return cameraResizer(image, width, height, rotate, 0, 0);
}
private TiBlob cameraResizer(TiBlob image, int width, int height, int rotate, int x, int y){
byte[] image_data = image.getBytes();
try{
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(image_data, 0, image_data.length, opts);
opts.inSampleSize = calcSampleSize(opts, width, height);
opts.inJustDecodeBounds = false;
Bitmap image_base = BitmapFactory.decodeByteArray(image_data, 0, image_data.length, opts);
Matrix matrix = getScaleMatrix(opts.outWidth, opts.outHeight, image_base.getWidth(), image_base.getHeight());
if(rotate > 0){
matrix.postRotate(rotate);
}
return returnBlob(opts, image_base, matrix, width, height, x, y);
}catch(NullPointerException e){
return null;
}
}
@Kroll.method
public TiBlob imageAsCropped(int width, int height, String path, int rotate, int x, int y){
return resizer(width, height, path, rotate, x, y);
}
@Kroll.method
public TiBlob imageAsResized(int width, int height, String path, int rotate){
return resizer(width, height, path, rotate, 0, 0);
}
public TiBlob resizer(int width, int height, String path, int rotate, int x, int y){
//Log.d(LCAT, "path:" + path);
try{
Activity activity = getActivity();
AssetManager as = activity.getResources().getAssets();
String fpath = null;
String save_path = null;
- if(path.startsWith("file://") || path.startsWith("content://") || path.startsWith("appdata://")){
- path = path.replaceAll("(appdata|file|content)://", "");
+ if(path.startsWith("file://") || path.startsWith("content://") || path.startsWith("appdata://") || path.startsWith("appdata-private://")){
+ // files outside of apk
+ path = path.replaceAll("file://", "");
+ path = path.replaceAll("appdata:///?", "/mnt/sdcard/" + TiApplication.getInstance().getPackageName() + "/");
+ path = path.replaceAll("appdata-private:///?", "/data/data/" + TiApplication.getInstance().getPackageName() + "/app_appdata/");
fpath = path;
//Log.d(LCAT, "path:" + fpath);
is = new FileInputStream(new File(path));
}else{
+ // files in apk
if(path.startsWith("app://")){
path = path.replaceFirst("app://", "Resources/");
}else if(path.startsWith("Resources") == false){
if(path.startsWith("/")){
path = "Resources" + path;
}else{
path = "Resources/" + path;
}
}
fpath = path;
is = as.open(fpath);
}
File save_path_base = new File(path);
save_path = "camera/" + save_path_base.getName();
String toFile = "/data/data/"+ TiApplication.getInstance().getPackageName() +"/app_appdata/" + save_path;
// File must be copied to /data/data. you can't handle files under Resouces dir.
// Who knows? Not me.
copyFile(is, toFile);
// Load image file data, not image file it self.
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(toFile, opts);
try{
// Load image
opts.inJustDecodeBounds = false;
opts.inSampleSize = calcSampleSize(opts, width, height);
Bitmap image_base = BitmapFactory.decodeFile(toFile, opts);
// Calc scale.
int w = image_base.getWidth();
int h = image_base.getHeight();
Matrix matrix = getScaleMatrix(opts.outWidth, opts.outHeight, w, h);
if(rotate > 0){
matrix.postRotate(rotate);
}
// Voila!
return returnBlob(opts, image_base, matrix, width, height, x, y);
}catch(NullPointerException e){
Log.d(LCAT, "Bitmap IOException:" + e);
return null;
}
}catch(IOException e){
Log.d(LCAT, "Bitmap IOException:" + e);
return null;
}
}
// Copy from inputstream to file
private static void copyFile(InputStream input, String dstFilePath) throws IOException{
File dstFile = new File(dstFilePath);
String parent_dir = dstFile.getParent();
File dir = new File(parent_dir);
dir.mkdirs();
OutputStream output = null;
output = new FileOutputStream(dstFile);
int DEFAULT_BUFFER_SIZE = 1024 * 4;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
input.close();
output.close();
}
private Matrix getScaleMatrix(int orig_w, int orig_h, int w, int h){
int scale = Math.min((int)orig_w/w, (int)orig_h/h);
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
return matrix;
}
private TiBlob returnBlob(BitmapFactory.Options opts, Bitmap image_base, Matrix matrix, int w, int h, int x, int y)
throws NullPointerException{
// Log.d(LCAT, "returnBlob w:" + w);
// Log.d(LCAT, "returnBlob h:" + h);
// Log.d(LCAT, "returnBlob x:" + x);
// Log.d(LCAT, "returnBlob y:" + y);
Bitmap scaled_image = Bitmap.createBitmap(image_base, x, y, w, h, matrix, true);
TiBlob blob = TiBlob.blobFromImage(scaled_image);
image_base.recycle();
image_base = null;
scaled_image.recycle();
scaled_image = null;
return blob;
}
private int calcSampleSize(BitmapFactory.Options opts, int width, int height){
int scaleW = Math.max(1, opts.outWidth / width);
int scaleH = Math.max(1, opts.outHeight / height);
int sampleSize = (int)Math.min(scaleW, scaleH);
return sampleSize;
}
}
| false | true | public TiBlob resizer(int width, int height, String path, int rotate, int x, int y){
//Log.d(LCAT, "path:" + path);
try{
Activity activity = getActivity();
AssetManager as = activity.getResources().getAssets();
String fpath = null;
String save_path = null;
if(path.startsWith("file://") || path.startsWith("content://") || path.startsWith("appdata://")){
path = path.replaceAll("(appdata|file|content)://", "");
fpath = path;
//Log.d(LCAT, "path:" + fpath);
is = new FileInputStream(new File(path));
}else{
if(path.startsWith("app://")){
path = path.replaceFirst("app://", "Resources/");
}else if(path.startsWith("Resources") == false){
if(path.startsWith("/")){
path = "Resources" + path;
}else{
path = "Resources/" + path;
}
}
fpath = path;
is = as.open(fpath);
}
File save_path_base = new File(path);
save_path = "camera/" + save_path_base.getName();
String toFile = "/data/data/"+ TiApplication.getInstance().getPackageName() +"/app_appdata/" + save_path;
// File must be copied to /data/data. you can't handle files under Resouces dir.
// Who knows? Not me.
copyFile(is, toFile);
// Load image file data, not image file it self.
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(toFile, opts);
try{
// Load image
opts.inJustDecodeBounds = false;
opts.inSampleSize = calcSampleSize(opts, width, height);
Bitmap image_base = BitmapFactory.decodeFile(toFile, opts);
// Calc scale.
int w = image_base.getWidth();
int h = image_base.getHeight();
Matrix matrix = getScaleMatrix(opts.outWidth, opts.outHeight, w, h);
if(rotate > 0){
matrix.postRotate(rotate);
}
// Voila!
return returnBlob(opts, image_base, matrix, width, height, x, y);
}catch(NullPointerException e){
Log.d(LCAT, "Bitmap IOException:" + e);
return null;
}
}catch(IOException e){
Log.d(LCAT, "Bitmap IOException:" + e);
return null;
}
}
| public TiBlob resizer(int width, int height, String path, int rotate, int x, int y){
//Log.d(LCAT, "path:" + path);
try{
Activity activity = getActivity();
AssetManager as = activity.getResources().getAssets();
String fpath = null;
String save_path = null;
if(path.startsWith("file://") || path.startsWith("content://") || path.startsWith("appdata://") || path.startsWith("appdata-private://")){
// files outside of apk
path = path.replaceAll("file://", "");
path = path.replaceAll("appdata:///?", "/mnt/sdcard/" + TiApplication.getInstance().getPackageName() + "/");
path = path.replaceAll("appdata-private:///?", "/data/data/" + TiApplication.getInstance().getPackageName() + "/app_appdata/");
fpath = path;
//Log.d(LCAT, "path:" + fpath);
is = new FileInputStream(new File(path));
}else{
// files in apk
if(path.startsWith("app://")){
path = path.replaceFirst("app://", "Resources/");
}else if(path.startsWith("Resources") == false){
if(path.startsWith("/")){
path = "Resources" + path;
}else{
path = "Resources/" + path;
}
}
fpath = path;
is = as.open(fpath);
}
File save_path_base = new File(path);
save_path = "camera/" + save_path_base.getName();
String toFile = "/data/data/"+ TiApplication.getInstance().getPackageName() +"/app_appdata/" + save_path;
// File must be copied to /data/data. you can't handle files under Resouces dir.
// Who knows? Not me.
copyFile(is, toFile);
// Load image file data, not image file it self.
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(toFile, opts);
try{
// Load image
opts.inJustDecodeBounds = false;
opts.inSampleSize = calcSampleSize(opts, width, height);
Bitmap image_base = BitmapFactory.decodeFile(toFile, opts);
// Calc scale.
int w = image_base.getWidth();
int h = image_base.getHeight();
Matrix matrix = getScaleMatrix(opts.outWidth, opts.outHeight, w, h);
if(rotate > 0){
matrix.postRotate(rotate);
}
// Voila!
return returnBlob(opts, image_base, matrix, width, height, x, y);
}catch(NullPointerException e){
Log.d(LCAT, "Bitmap IOException:" + e);
return null;
}
}catch(IOException e){
Log.d(LCAT, "Bitmap IOException:" + e);
return null;
}
}
|
diff --git a/app/utils/DataUtil.java b/app/utils/DataUtil.java
index 2dd46ca..4d7d0ff 100644
--- a/app/utils/DataUtil.java
+++ b/app/utils/DataUtil.java
@@ -1,84 +1,84 @@
package utils;
import com.mongodb.DB;
import com.mongodb.MongoException;
import com.mongodb.ReadPreference;
import com.mongodb.MongoClient;
import models.User;
import net.vz.mongodb.jackson.DBCursor;
import net.vz.mongodb.jackson.DBQuery;
import net.vz.mongodb.jackson.JacksonDBCollection;
import java.net.UnknownHostException;
/**
* User: Charles
* Date: 4/28/13
*/
public class DataUtil {
private static MongoClient mongoClient;
public static DB getDB() {
try {
- mongoClient = new MongoClient("ds061787.mongolab.com", 61787);
-// mongoClient = new MongoClient( );
+// mongoClient = new MongoClient("ds061787.mongolab.com", 61787);
+ mongoClient = new MongoClient( );
mongoClient.setReadPreference(ReadPreference.primary());
- DB dataBase = mongoClient.getDB("heroku_app15452455");
-// DB dataBase = mongoClient.getDB("icm");
+// DB dataBase = mongoClient.getDB("heroku_app15452455");
+ DB dataBase = mongoClient.getDB("icm");
- dataBase.authenticate("heroku_app15452455", "73mi73eoolvr4s7v47ugutfru9".toCharArray());
+// dataBase.authenticate("heroku_app15452455", "73mi73eoolvr4s7v47ugutfru9".toCharArray());
return dataBase;
} catch (UnknownHostException e) {
return null;
}
}
public static JacksonDBCollection getCollection(String collection, Class clazz) {
try {
return JacksonDBCollection.wrap(getDB().getCollection(collection), clazz, String.class);
} catch (Exception e) {
return null;
}
}
public static Object getEntityById(String collection, Class clazz, String id) {
try {
JacksonDBCollection jacksonDBCollection = JacksonDBCollection.wrap(getDB().getCollection(collection), clazz, String.class);
return jacksonDBCollection.findOneById(id);
} catch (Exception e) {
return null;
}
}
public static Boolean isDatabase() {
try {
JacksonDBCollection<User, String> collection = DataUtil.getCollection("users", User.class);
DBCursor cursorDoc = collection.find(DBQuery.is("username", "test"));
if (cursorDoc.hasNext())
return true;
else
return true;
} catch (MongoException e) {
e.printStackTrace();
return false;
}
}
}
| false | true | public static DB getDB() {
try {
mongoClient = new MongoClient("ds061787.mongolab.com", 61787);
// mongoClient = new MongoClient( );
mongoClient.setReadPreference(ReadPreference.primary());
DB dataBase = mongoClient.getDB("heroku_app15452455");
// DB dataBase = mongoClient.getDB("icm");
dataBase.authenticate("heroku_app15452455", "73mi73eoolvr4s7v47ugutfru9".toCharArray());
return dataBase;
} catch (UnknownHostException e) {
return null;
}
}
| public static DB getDB() {
try {
// mongoClient = new MongoClient("ds061787.mongolab.com", 61787);
mongoClient = new MongoClient( );
mongoClient.setReadPreference(ReadPreference.primary());
// DB dataBase = mongoClient.getDB("heroku_app15452455");
DB dataBase = mongoClient.getDB("icm");
// dataBase.authenticate("heroku_app15452455", "73mi73eoolvr4s7v47ugutfru9".toCharArray());
return dataBase;
} catch (UnknownHostException e) {
return null;
}
}
|
diff --git a/dspace-springui/src/main/java/org/dspace/springui/web/interceptor/InstallationInterceptor.java b/dspace-springui/src/main/java/org/dspace/springui/web/interceptor/InstallationInterceptor.java
index 6126354..d8b329d 100644
--- a/dspace-springui/src/main/java/org/dspace/springui/web/interceptor/InstallationInterceptor.java
+++ b/dspace-springui/src/main/java/org/dspace/springui/web/interceptor/InstallationInterceptor.java
@@ -1,43 +1,43 @@
package org.dspace.springui.web.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dspace.services.api.configuration.ConfigurationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class InstallationInterceptor implements HandlerInterceptor {
private static final String INSTALL_REQUEST = "/install";
@Autowired ConfigurationService configurationService;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
- if (!request.getPathInfo().contains(INSTALL_REQUEST) && !configurationService.getProperty("dspace.installed", Boolean.class, false)) {
+ if (!request.getPathInfo().contains(INSTALL_REQUEST) && !configurationService.isInstalled()) {
response.sendRedirect(request.getContextPath() + INSTALL_REQUEST);
return false;
}
- if (configurationService.getProperty("dspace.installed", Boolean.class, false) && request.getPathInfo().contains(INSTALL_REQUEST)) {
+ if (configurationService.isInstalled() && request.getPathInfo().contains(INSTALL_REQUEST)) {
response.sendRedirect(request.getContextPath());
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// Nothing
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// Nothing
}
}
| false | true | public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
if (!request.getPathInfo().contains(INSTALL_REQUEST) && !configurationService.getProperty("dspace.installed", Boolean.class, false)) {
response.sendRedirect(request.getContextPath() + INSTALL_REQUEST);
return false;
}
if (configurationService.getProperty("dspace.installed", Boolean.class, false) && request.getPathInfo().contains(INSTALL_REQUEST)) {
response.sendRedirect(request.getContextPath());
return false;
}
return true;
}
| public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
if (!request.getPathInfo().contains(INSTALL_REQUEST) && !configurationService.isInstalled()) {
response.sendRedirect(request.getContextPath() + INSTALL_REQUEST);
return false;
}
if (configurationService.isInstalled() && request.getPathInfo().contains(INSTALL_REQUEST)) {
response.sendRedirect(request.getContextPath());
return false;
}
return true;
}
|
diff --git a/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRACron.java b/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRACron.java
index d47ae604..b6d5938c 100644
--- a/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRACron.java
+++ b/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRACron.java
@@ -1,190 +1,191 @@
package uk.ac.ebi.fgpt.sampletab.sra;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.dom4j.DocumentException;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress2.magetab.exception.ParseException;
import uk.ac.ebi.fgpt.sampletab.utils.ConanUtils;
import uk.ac.ebi.fgpt.sampletab.utils.FileRecursiveIterable;
import uk.ac.ebi.fgpt.sampletab.utils.SampleTabUtils;
public class ENASRACron {
@Option(name = "--help", aliases = { "-h" }, usage = "display help")
private boolean help;
@Argument(required=true, index=0, metaVar="OUTPUT", usage = "output directory")
private String outputDirName;
@Option(name = "--threads", aliases = { "-t" }, usage = "number of additional threads")
private int threads = 0;
@Option(name = "--no-conan", usage = "do not trigger conan loads?")
private boolean noconan = false;
private Logger log = LoggerFactory.getLogger(getClass());
private ENASRACron() {
}
public static void main(String[] args) {
new ENASRACron().doMain(args);
}
public void doMain(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
// TODO check for extra arguments?
} catch (CmdLineException e) {
System.err.println(e.getMessage());
help = true;
}
if (help) {
// print the list of available options
parser.printSingleLineUsage(System.err);
System.err.println();
parser.printUsage(System.err);
System.err.println();
System.exit(1);
return;
}
File outdir = new File(this.outputDirName);
if (outdir.exists() && !outdir.isDirectory()) {
System.err.println("Target is not a directory");
System.exit(1);
return;
}
if (!outdir.exists()) {
outdir.mkdirs();
}
ExecutorService pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//first get a map of all possible submissions
//this might take a while
log.info("Getting groups...");
ENASRAGrouper grouper = new ENASRAGrouper(pool);
log.info("Got groups...");
log.info("Checking deletions");
//also get a set of existing submissions to delete
Set<String> toDelete = new HashSet<String>();
- for (File sampletabpre : new FileRecursiveIterable("sampletab.pre.txt", new File(outdir, "sra"))) { //TODO do this properly somehow
+ for (File sampletabpre : new FileRecursiveIterable("sampletab.pre.txt", new File(outdir, "sra"))) {
+ //TODO do this properly somehow
File subdir = sampletabpre.getParentFile();
String subId = subdir.getName();
if (!grouper.groups.containsKey(subId) && !grouper.ungrouped.contains(subId)) {
toDelete.add(subId);
}
}
log.info("Processing updates");
//restart the pool for part II
pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//process updates
ENASRAWebDownload downloader = new ENASRAWebDownload();
for(String key : grouper.groups.keySet()) {
String submissionID = "GEN-"+key;
log.info("checking "+submissionID);
File outsubdir = SampleTabUtils.getSubmissionDirFile(submissionID);
boolean changed = false;
outsubdir = new File(outdir.toString(), outsubdir.toString());
try {
changed = downloader.downloadXML(key, outsubdir);
} catch (IOException e) {
log.error("Problem downloading samples of "+key, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading samples of "+key, e);
continue;
}
for (String sample : grouper.groups.get(key)) {
try {
changed |= downloader.downloadXML(sample, outsubdir);
} catch (IOException e) {
log.error("Problem downloading sample "+sample, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading sample "+sample, e);
continue;
}
}
if (changed) {
//process the subdir
log.info("updated "+submissionID);
Runnable t = new ENASRAUpdateRunnable(outsubdir, key, grouper.groups.get(key), !noconan);
if (threads > 0) {
pool.execute(t);
} else {
t.run();
}
}
}
//process deletes
for (String submissionID : toDelete) {
File sampletabpre = new File(SampleTabUtils.getSubmissionDirFile(submissionID), "sampletab.pre.txt");
try {
SampleTabUtils.releaseInACentury(sampletabpre);
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
} catch (ParseException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
}
//trigger conan, if appropriate
if (!noconan) {
try {
ConanUtils.submit(submissionID, "BioSamples (other)");
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private through Conan", e);
}
}
}
if (pool != null) {
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination", e);
}
}
}
log.info("Finished processing updates");
}
}
| true | true | public void doMain(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
// TODO check for extra arguments?
} catch (CmdLineException e) {
System.err.println(e.getMessage());
help = true;
}
if (help) {
// print the list of available options
parser.printSingleLineUsage(System.err);
System.err.println();
parser.printUsage(System.err);
System.err.println();
System.exit(1);
return;
}
File outdir = new File(this.outputDirName);
if (outdir.exists() && !outdir.isDirectory()) {
System.err.println("Target is not a directory");
System.exit(1);
return;
}
if (!outdir.exists()) {
outdir.mkdirs();
}
ExecutorService pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//first get a map of all possible submissions
//this might take a while
log.info("Getting groups...");
ENASRAGrouper grouper = new ENASRAGrouper(pool);
log.info("Got groups...");
log.info("Checking deletions");
//also get a set of existing submissions to delete
Set<String> toDelete = new HashSet<String>();
for (File sampletabpre : new FileRecursiveIterable("sampletab.pre.txt", new File(outdir, "sra"))) { //TODO do this properly somehow
File subdir = sampletabpre.getParentFile();
String subId = subdir.getName();
if (!grouper.groups.containsKey(subId) && !grouper.ungrouped.contains(subId)) {
toDelete.add(subId);
}
}
log.info("Processing updates");
//restart the pool for part II
pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//process updates
ENASRAWebDownload downloader = new ENASRAWebDownload();
for(String key : grouper.groups.keySet()) {
String submissionID = "GEN-"+key;
log.info("checking "+submissionID);
File outsubdir = SampleTabUtils.getSubmissionDirFile(submissionID);
boolean changed = false;
outsubdir = new File(outdir.toString(), outsubdir.toString());
try {
changed = downloader.downloadXML(key, outsubdir);
} catch (IOException e) {
log.error("Problem downloading samples of "+key, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading samples of "+key, e);
continue;
}
for (String sample : grouper.groups.get(key)) {
try {
changed |= downloader.downloadXML(sample, outsubdir);
} catch (IOException e) {
log.error("Problem downloading sample "+sample, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading sample "+sample, e);
continue;
}
}
if (changed) {
//process the subdir
log.info("updated "+submissionID);
Runnable t = new ENASRAUpdateRunnable(outsubdir, key, grouper.groups.get(key), !noconan);
if (threads > 0) {
pool.execute(t);
} else {
t.run();
}
}
}
//process deletes
for (String submissionID : toDelete) {
File sampletabpre = new File(SampleTabUtils.getSubmissionDirFile(submissionID), "sampletab.pre.txt");
try {
SampleTabUtils.releaseInACentury(sampletabpre);
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
} catch (ParseException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
}
//trigger conan, if appropriate
if (!noconan) {
try {
ConanUtils.submit(submissionID, "BioSamples (other)");
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private through Conan", e);
}
}
}
if (pool != null) {
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination", e);
}
}
}
log.info("Finished processing updates");
}
| public void doMain(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
// parse the arguments.
parser.parseArgument(args);
// TODO check for extra arguments?
} catch (CmdLineException e) {
System.err.println(e.getMessage());
help = true;
}
if (help) {
// print the list of available options
parser.printSingleLineUsage(System.err);
System.err.println();
parser.printUsage(System.err);
System.err.println();
System.exit(1);
return;
}
File outdir = new File(this.outputDirName);
if (outdir.exists() && !outdir.isDirectory()) {
System.err.println("Target is not a directory");
System.exit(1);
return;
}
if (!outdir.exists()) {
outdir.mkdirs();
}
ExecutorService pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//first get a map of all possible submissions
//this might take a while
log.info("Getting groups...");
ENASRAGrouper grouper = new ENASRAGrouper(pool);
log.info("Got groups...");
log.info("Checking deletions");
//also get a set of existing submissions to delete
Set<String> toDelete = new HashSet<String>();
for (File sampletabpre : new FileRecursiveIterable("sampletab.pre.txt", new File(outdir, "sra"))) {
//TODO do this properly somehow
File subdir = sampletabpre.getParentFile();
String subId = subdir.getName();
if (!grouper.groups.containsKey(subId) && !grouper.ungrouped.contains(subId)) {
toDelete.add(subId);
}
}
log.info("Processing updates");
//restart the pool for part II
pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
//process updates
ENASRAWebDownload downloader = new ENASRAWebDownload();
for(String key : grouper.groups.keySet()) {
String submissionID = "GEN-"+key;
log.info("checking "+submissionID);
File outsubdir = SampleTabUtils.getSubmissionDirFile(submissionID);
boolean changed = false;
outsubdir = new File(outdir.toString(), outsubdir.toString());
try {
changed = downloader.downloadXML(key, outsubdir);
} catch (IOException e) {
log.error("Problem downloading samples of "+key, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading samples of "+key, e);
continue;
}
for (String sample : grouper.groups.get(key)) {
try {
changed |= downloader.downloadXML(sample, outsubdir);
} catch (IOException e) {
log.error("Problem downloading sample "+sample, e);
continue;
} catch (DocumentException e) {
log.error("Problem downloading sample "+sample, e);
continue;
}
}
if (changed) {
//process the subdir
log.info("updated "+submissionID);
Runnable t = new ENASRAUpdateRunnable(outsubdir, key, grouper.groups.get(key), !noconan);
if (threads > 0) {
pool.execute(t);
} else {
t.run();
}
}
}
//process deletes
for (String submissionID : toDelete) {
File sampletabpre = new File(SampleTabUtils.getSubmissionDirFile(submissionID), "sampletab.pre.txt");
try {
SampleTabUtils.releaseInACentury(sampletabpre);
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
} catch (ParseException e) {
log.error("problem making "+sampletabpre+" private", e);
continue;
}
//trigger conan, if appropriate
if (!noconan) {
try {
ConanUtils.submit(submissionID, "BioSamples (other)");
} catch (IOException e) {
log.error("problem making "+sampletabpre+" private through Conan", e);
}
}
}
if (pool != null) {
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interuppted awaiting thread pool termination", e);
}
}
}
log.info("Finished processing updates");
}
|
diff --git a/javafxdoc/src/com/sun/tools/javafxdoc/ProgramElementDocImpl.java b/javafxdoc/src/com/sun/tools/javafxdoc/ProgramElementDocImpl.java
index eb1c64c6e..43c07d925 100644
--- a/javafxdoc/src/com/sun/tools/javafxdoc/ProgramElementDocImpl.java
+++ b/javafxdoc/src/com/sun/tools/javafxdoc/ProgramElementDocImpl.java
@@ -1,233 +1,233 @@
/*
* Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* 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 2 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
* 2 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafxdoc;
import com.sun.javadoc.*;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javafx.tree.JFXTree;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javafx.code.JavafxFlags;
import java.lang.reflect.Modifier;
import java.text.CollationKey;
/**
* Represents a java program element: class, interface, field,
* constructor, or method.
* This is an abstract class dealing with information common to
* these elements.
*
* @see MemberDocImpl
* @see ClassDocImpl
*
* @author Robert Field
* @author Neal Gafter (rewrite)
* @author Scott Seligman (generics, enums, annotations)
*/
public abstract class ProgramElementDocImpl
extends DocImpl implements ProgramElementDoc {
// For source position information.
JFXTree tree = null;
Position.LineMap lineMap = null;
// Cache for getModifiers().
private int modifiers = -1;
protected ProgramElementDocImpl(DocEnv env, Symbol sym,
String doc, JFXTree tree, Position.LineMap lineMap) {
super(env, doc);
this.tree = tree;
this.lineMap = lineMap;
}
void setTree(JFXTree tree) {
this.tree = tree;
}
/**
* Subclasses override to identify the containing class
*/
protected abstract ClassSymbol getContainingClass();
/**
* Returns the flags in terms of javac's flags
*/
abstract protected long getFlags();
/**
* Returns the modifier flags in terms of java.lang.reflect.Modifier.
*/
protected int getModifiers() {
if (modifiers == -1) {
modifiers = DocEnv.translateModifiers(getFlags());
}
return modifiers;
}
/**
* Get the containing class of this program element.
*
* @return a ClassDocImpl for this element's containing class.
* If this is a class with no outer class, return null.
*/
public ClassDoc containingClass() {
if (getContainingClass() == null) {
return null;
}
return env.getClassDoc(getContainingClass());
}
/**
* Return the package that this member is contained in.
* Return "" if in unnamed package.
*/
public PackageDoc containingPackage() {
return env.getPackageDoc(getContainingClass().packge());
}
/**
* Get the modifier specifier integer.
*
* @see java.lang.reflect.Modifier
*/
public int modifierSpecifier() {
int modifiers = getModifiers();
if (isMethod() && containingClass().isInterface())
// Remove the implicit abstract modifier.
return modifiers & ~Modifier.ABSTRACT;
return modifiers;
}
/**
* Get modifiers string.
* <pre>
* Example, for:
* public abstract int foo() { ... }
* modifiers() would return:
* 'public abstract'
* </pre>
* Annotations are not included.
*/
public String modifiers() {
long flags = getFlags();
if (isAnnotationTypeElement() ||
(isMethod() && containingClass().isInterface())) {
// Remove the implicit abstract modifier.
flags &= ~Modifier.ABSTRACT;
}
StringBuffer sb = new StringBuffer();
- if ((flags & JavafxFlags.PUBLIC_INIT) == 0) sb.append("public-init ");
- if ((flags & JavafxFlags.PUBLIC_READ) == 0) sb.append("public-read ");
+ if ((flags & JavafxFlags.PUBLIC_INIT) != 0) sb.append("public-init ");
+ if ((flags & JavafxFlags.PUBLIC_READ) != 0) sb.append("public-read ");
if ((flags & Flags.PUBLIC) != 0) sb.append("public ");
if ((flags & Flags.PROTECTED) != 0) sb.append("protected ");
if ((flags & (Flags.PUBLIC | Flags.PROTECTED | JavafxFlags.SCRIPT_PRIVATE)) == 0) sb.append("package ");
- if ((flags & JavafxFlags.BOUND) == 0) sb.append("bound ");
+ if ((flags & JavafxFlags.BOUND) != 0) sb.append("bound ");
if ((flags & Flags.ABSTRACT) != 0) sb.append("abstract ");
int len = sb.length();
if (len > 0) /* trim trailing space */
return sb.toString().substring(0, len-1);
return "";
}
/**
* Get the annotations of this program element.
* Return an empty array if there are none.
*/
public AnnotationDesc[] annotations() {
return new AnnotationDesc[0];
}
/**
* Return true if this program element is public
*/
public boolean isPublic() {
int modifiers = getModifiers();
return Modifier.isPublic(modifiers);
}
/**
* Return true if this program element is protected
*/
public boolean isProtected() {
int modifiers = getModifiers();
return Modifier.isProtected(modifiers);
}
/**
* Return true if this program element is private
*/
public boolean isPrivate() {
int modifiers = getModifiers();
return Modifier.isPrivate(modifiers);
}
/**
* Returns true if this program element is script-private
*/
public boolean isScriptPrivate() {
return (getFlags() & JavafxFlags.SCRIPT_PRIVATE) != 0;
}
/**
* Return true if this program element is package private
*/
public boolean isPackagePrivate() {
return !(isPublic() || isScriptPrivate() || isPrivate() || isProtected());
}
/**
* Return true if this program element is static
*/
public boolean isStatic() {
int modifiers = getModifiers();
return Modifier.isStatic(modifiers);
}
/**
* Return true if this program element is final
*/
public boolean isFinal() {
int modifiers = getModifiers();
return Modifier.isFinal(modifiers);
}
/**
* Generate a key for sorting.
*/
CollationKey generateKey() {
String k = name();
// System.out.println("COLLATION KEY FOR " + this + " is \"" + k + "\"");
return env.doclocale.collator.getCollationKey(k);
}
}
| false | true | public String modifiers() {
long flags = getFlags();
if (isAnnotationTypeElement() ||
(isMethod() && containingClass().isInterface())) {
// Remove the implicit abstract modifier.
flags &= ~Modifier.ABSTRACT;
}
StringBuffer sb = new StringBuffer();
if ((flags & JavafxFlags.PUBLIC_INIT) == 0) sb.append("public-init ");
if ((flags & JavafxFlags.PUBLIC_READ) == 0) sb.append("public-read ");
if ((flags & Flags.PUBLIC) != 0) sb.append("public ");
if ((flags & Flags.PROTECTED) != 0) sb.append("protected ");
if ((flags & (Flags.PUBLIC | Flags.PROTECTED | JavafxFlags.SCRIPT_PRIVATE)) == 0) sb.append("package ");
if ((flags & JavafxFlags.BOUND) == 0) sb.append("bound ");
if ((flags & Flags.ABSTRACT) != 0) sb.append("abstract ");
int len = sb.length();
if (len > 0) /* trim trailing space */
return sb.toString().substring(0, len-1);
return "";
}
| public String modifiers() {
long flags = getFlags();
if (isAnnotationTypeElement() ||
(isMethod() && containingClass().isInterface())) {
// Remove the implicit abstract modifier.
flags &= ~Modifier.ABSTRACT;
}
StringBuffer sb = new StringBuffer();
if ((flags & JavafxFlags.PUBLIC_INIT) != 0) sb.append("public-init ");
if ((flags & JavafxFlags.PUBLIC_READ) != 0) sb.append("public-read ");
if ((flags & Flags.PUBLIC) != 0) sb.append("public ");
if ((flags & Flags.PROTECTED) != 0) sb.append("protected ");
if ((flags & (Flags.PUBLIC | Flags.PROTECTED | JavafxFlags.SCRIPT_PRIVATE)) == 0) sb.append("package ");
if ((flags & JavafxFlags.BOUND) != 0) sb.append("bound ");
if ((flags & Flags.ABSTRACT) != 0) sb.append("abstract ");
int len = sb.length();
if (len > 0) /* trim trailing space */
return sb.toString().substring(0, len-1);
return "";
}
|
diff --git a/src/controller/InGameController.java b/src/controller/InGameController.java
index 62e3043..330a97e 100644
--- a/src/controller/InGameController.java
+++ b/src/controller/InGameController.java
@@ -1,116 +1,119 @@
package controller;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.KeyListener;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.tiled.TiledMap;
import utils.BlockMapUtils;
import view.BlockMapView;
import view.InGameView;
import model.BlockMap;
import model.Game;
import model.InGame;
public class InGameController extends BasicGameState {
private InGame inGame;
private InGameView inGameView;
private CharacterController characterController;
private WorldController worldController;
private BlockMapController blockMapController;
private ArrayList <CandyMonsterController> candyMonsterController;
private ArrayList <ItemController> itemController;
private ArrayList <SpikesController> spikeController;
//should be based on the frame update (delta or something like that)
private float timeStep = 1.0f / 60.0f;
private int velocityIterations = 6;
private int positionIterations = 2;
public InGameController() {
}
@Override
public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException {
+ this.candyMonsterController = new ArrayList<CandyMonsterController>();
+ this.itemController = new ArrayList<ItemController>();
+ this.spikeController = new ArrayList<SpikesController>();
//TODO ladda in filer
this.blockMapController = new BlockMapController(new TiledMap(BlockMapUtils.getTmxFile(1)));
this.characterController = new CharacterController(this);
/*Create candy monster and its items*/
for(int i = 0; i < blockMapController.getCandyMonsterMap().getBlockList().size(); i++){
this.candyMonsterController.add(new CandyMonsterController(this, i));
this.itemController.add(new ItemController(this, i));
}
/*Create spikes*/
for(int i = 0; i < blockMapController.getSpikesMap().getBlockList().size(); i++){
this.spikeController.add(new SpikesController(this, i));
}
this.worldController = new WorldController(this);
this.inGame = new InGame(worldController.getWorld());
this.inGameView = new InGameView(inGame, worldController.getWorldView());
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
throws SlickException {
this.inGameView.render(gc, sbg, g);
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
characterController.keyPressedUpdate(gc);
//simulate the JBox2D world TODO timeStep --> delta
if(delta > 0) {
this.timeStep = (float) delta / 1000f;
}
worldController.getWorldView().getJBox2DWorld().step(timeStep, velocityIterations, positionIterations);
worldController.updateSlickShape();
}
@Override
public int getID() {
return Game.IN_GAME;
}
public CharacterController getCharacterController() {
return characterController;
}
public WorldController getWorldController() {
return worldController;
}
public BlockMapController getBlockMapController() {
return blockMapController;
}
public ArrayList<CandyMonsterController> getCandyMonsterController() {
return candyMonsterController;
}
public ArrayList<ItemController> getItemController() {
return itemController;
}
public ArrayList<SpikesController> getSpikeController() {
return spikeController;
}
}
| true | true | public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException {
//TODO ladda in filer
this.blockMapController = new BlockMapController(new TiledMap(BlockMapUtils.getTmxFile(1)));
this.characterController = new CharacterController(this);
/*Create candy monster and its items*/
for(int i = 0; i < blockMapController.getCandyMonsterMap().getBlockList().size(); i++){
this.candyMonsterController.add(new CandyMonsterController(this, i));
this.itemController.add(new ItemController(this, i));
}
/*Create spikes*/
for(int i = 0; i < blockMapController.getSpikesMap().getBlockList().size(); i++){
this.spikeController.add(new SpikesController(this, i));
}
this.worldController = new WorldController(this);
this.inGame = new InGame(worldController.getWorld());
this.inGameView = new InGameView(inGame, worldController.getWorldView());
}
| public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException {
this.candyMonsterController = new ArrayList<CandyMonsterController>();
this.itemController = new ArrayList<ItemController>();
this.spikeController = new ArrayList<SpikesController>();
//TODO ladda in filer
this.blockMapController = new BlockMapController(new TiledMap(BlockMapUtils.getTmxFile(1)));
this.characterController = new CharacterController(this);
/*Create candy monster and its items*/
for(int i = 0; i < blockMapController.getCandyMonsterMap().getBlockList().size(); i++){
this.candyMonsterController.add(new CandyMonsterController(this, i));
this.itemController.add(new ItemController(this, i));
}
/*Create spikes*/
for(int i = 0; i < blockMapController.getSpikesMap().getBlockList().size(); i++){
this.spikeController.add(new SpikesController(this, i));
}
this.worldController = new WorldController(this);
this.inGame = new InGame(worldController.getWorld());
this.inGameView = new InGameView(inGame, worldController.getWorldView());
}
|
diff --git a/Nof1/src/uk/co/jwlawson/nof1/Scheduler.java b/Nof1/src/uk/co/jwlawson/nof1/Scheduler.java
index 4e525cd..781c368 100644
--- a/Nof1/src/uk/co/jwlawson/nof1/Scheduler.java
+++ b/Nof1/src/uk/co/jwlawson/nof1/Scheduler.java
@@ -1,381 +1,383 @@
/*******************************************************************************
* Nof1 Trials helper, making life easier for clinicians and patients in N of 1 trials.
* Copyright (C) 2012 WMG, University of Warwick
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You may obtain a copy of the GNU General Public License at
* <http://www.gnu.org/licenses/>.
*
* Contributors:
* John Lawson - initial API and implementation
******************************************************************************/
package uk.co.jwlawson.nof1;
import java.util.Calendar;
import uk.co.jwlawson.nof1.preferences.TimePreference;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.backup.BackupManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Handles scheduling next notification.
*
* @author John Lawson
*
*/
public class Scheduler extends Service {
private static final String TAG = "Scheduler";
private static final boolean DEBUG = false;
private static final int REQUEST_QUES = 0;
private static final int REQUEST_MED = 1;
private AlarmManager mAlarmManager;
private BackupManager mBackupManager;
@TargetApi(8)
public Scheduler() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mBackupManager = new BackupManager(this);
}
}
@Override
public void onCreate() {
super.onCreate();
mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (DEBUG) Log.d(TAG, "Service created");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getBooleanExtra(Keys.INTENT_BOOT, false)) {
if (DEBUG) Log.d(TAG, "Scheduler started after boot");
Thread thread = new Thread(mBootSchedule);
thread.start();
} else if (intent.getBooleanExtra(Keys.INTENT_ALARM, false)) {
if (DEBUG) Log.d(TAG, "Scheduler started to schedule new alarm");
Thread thread = new Thread(mNotiSchedule);
thread.start();
if (intent.getBooleanExtra(Keys.INTENT_FIRST, false)) {
// If first is sent as well, then need to set up medicine reminders
Thread t = new Thread(new Runnable() {
@Override
public void run() {
setMedicineAlarm();
}
});
t.start();
}
} else if (intent.getBooleanExtra(Keys.INTENT_FIRST, false)) {
if (DEBUG) Log.d(TAG, "Scheduler run for the first time");
Thread thread = new Thread(mFirstRun);
thread.start();
} else if (intent.hasExtra(Keys.INTENT_RESCHEDULE)) {
if (DEBUG) Log.d(TAG, "Rescheduling alarm");
final int mins = intent.getIntExtra(Keys.INTENT_RESCHEDULE, 0);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
reschedule(mins);
}
});
thread.start();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
if (DEBUG) Log.d(TAG, "Service destroyed");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void reschedule(int mins) {
// Work out when next to set the alarm, set it and save in preferences
SharedPreferences schedPrefs = getSharedPreferences(Keys.SCHED_NAME, MODE_PRIVATE);
SharedPreferences.Editor schedEdit = schedPrefs.edit();
// Roll back settings in preferences
schedEdit.putInt(Keys.SCHED_NEXT_DAY, schedPrefs.getInt(Keys.SCHED_LAST_DAY, 1));
schedEdit.putInt(Keys.SCHED_CUR_PERIOD, schedPrefs.getInt(Keys.SCHED_LAST_PERIOD, 1));
schedEdit.putString(Keys.SCHED_NEXT_DATE, schedPrefs.getString(Keys.SCHED_LAST_DATE, null));
schedEdit.putInt(Keys.SCHED_NEXT_CUMULATIVE_DAY, schedPrefs.getInt(Keys.SCHED_CUMULATIVE_DAY, 1));
// Get calendar for this time + mins
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, mins);
schedEdit.commit();
backup();
// Finally, use the new values to set an alarm
Intent intent = new Intent(Scheduler.this, Receiver.class);
intent.putExtra(Keys.INTENT_ALARM, true);
setAlarm(intent, cal);
// Close service once done
Scheduler.this.stopSelf();
}
/** Load next date to set alarm from preferences and set alarm for then */
private void setRepeatAlarm() {
Intent intent = new Intent(Scheduler.this, Receiver.class);
intent.putExtra(Keys.INTENT_ALARM, true);
setAlarmFromPrefs(intent);
}
/** Load first date to set alarm from preferences and set alarm for then */
private void setFirstAlarm() {
Intent intent = new Intent(Scheduler.this, Receiver.class);
intent.putExtra(Keys.INTENT_FIRST, true);
setAlarmFromPrefs(intent);
}
/** Sets an alarm for time saved in prefs which fires off the supplied intent */
private void setAlarmFromPrefs(Intent intent) {
SharedPreferences sp = getSharedPreferences(Keys.SCHED_NAME, MODE_PRIVATE);
SharedPreferences userPrefs = getSharedPreferences(Keys.DEFAULT_PREFS, MODE_PRIVATE);
String dateStr = sp.getString(Keys.SCHED_NEXT_DATE, null);
String timeStr = userPrefs.getString(Keys.DEFAULT_TIME, "12:00");
if (dateStr == null) {
Log.d(TAG, "Config not yet run");
return;
}
setAlarm(intent, dateStr, timeStr);
}
/** Set an alarm to fire off specified intent at time stored in calendar */
private void setAlarm(Intent intent, Calendar cal) {
PendingIntent pi = PendingIntent.getBroadcast(Scheduler.this, REQUEST_QUES, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
}
/**
* Set an alarm at specified date and time.
*
* @param intent
* @param dateStr DD:MM:YYYY
* @param timeStr HH:MM
*/
private void setAlarm(Intent intent, String dateStr, String timeStr) {
String[] dateArr = dateStr.split(":");
String[] timeArr = timeStr.split(":");
int[] dateInt = new int[] { Integer.parseInt(dateArr[0]), Integer.parseInt(dateArr[1]), Integer.parseInt(dateArr[2]) };
int[] timeInt = new int[] { Integer.parseInt(timeArr[0]), Integer.parseInt(timeArr[1]) };
Calendar cal = Calendar.getInstance();
cal.set(dateInt[2], dateInt[1], dateInt[0], timeInt[0], timeInt[1]);
PendingIntent pi = PendingIntent.getBroadcast(Scheduler.this, REQUEST_QUES, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
if (DEBUG) Log.d(TAG, "Scheduled alarm for: " + dateInt[2] + " " + dateInt[1] + " " + dateInt[0] + " " + timeInt[0] + " " + timeInt[1]);
}
private void setMedicineAlarm() {
SharedPreferences sp = getSharedPreferences(Keys.CONFIG_NAME, MODE_PRIVATE);
Calendar now = Calendar.getInstance();
for (int i = 0; sp.contains(Keys.CONFIG_TIME + i); i++) {
Calendar cal = Calendar.getInstance();
String time = sp.getString(Keys.CONFIG_TIME + i, "12:00");
int hour = TimePreference.getHour(time);
int min = TimePreference.getMinute(time);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, min);
if (cal.before(now)) {
// If we would be setting a notification in the past, add an extra day to ensure it is only called in
// the future
cal.add(Calendar.DAY_OF_MONTH, 1);
}
Intent intent = new Intent(this, Receiver.class);
intent.putExtra(Keys.INTENT_MEDICINE, true);
// Make sure each medicine notification gets a different request id
PendingIntent pi = PendingIntent.getBroadcast(this, REQUEST_MED + i, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
if (DEBUG) Log.d(TAG, "Scheduling a repeating medicine alarm at " + time);
}
}
private Runnable mNotiSchedule = new Runnable() {
@Override
public void run() {
// Work out when next to set the alarm, set it and save in preferences
SharedPreferences schedPrefs = getSharedPreferences(Keys.SCHED_NAME, MODE_PRIVATE);
SharedPreferences.Editor schedEdit = schedPrefs.edit();
SharedPreferences configPrefs = getSharedPreferences(Keys.CONFIG_NAME, MODE_PRIVATE);
int lastDay = schedPrefs.getInt(Keys.SCHED_NEXT_DAY, 1);
int periodLength = configPrefs.getInt(Keys.CONFIG_PERIOD_LENGTH, 1);
int nextDay = -1;
int add;
// TODO on the very first day, could have add = 0
- for (add = 1; add < periodLength + 1; add++) {
- nextDay = (lastDay + add) % (periodLength + 1);
+ for (add = 1; add <= periodLength; add++) {
+ nextDay = (lastDay + add) % (periodLength);
+ // Because of modulo, when the nextday would be the last in period nextDay is set to zero
+ if (nextDay == 0) nextDay = periodLength;
if (configPrefs.getBoolean(Keys.CONFIG_DAY + nextDay, false)) {
if (DEBUG) Log.d(TAG, "Found the next day to send notification: " + nextDay);
break;
}
}
if (nextDay < 0) {
throw new RuntimeException("Invalid config settings");
}
int period = schedPrefs.getInt(Keys.SCHED_CUR_PERIOD, 1);
if (nextDay < lastDay) {
// Moving into next treatment period
if (period + 1 > 2 * configPrefs.getInt(Keys.CONFIG_NUMBER_PERIODS, Integer.MAX_VALUE)) {
// TODO Finished trial!
schedEdit.putBoolean(Keys.SCHED_FINISHED, true);
return;
}
schedEdit.putInt(Keys.SCHED_CUR_PERIOD, period + 1);
}
schedEdit.putInt(Keys.SCHED_LAST_PERIOD, period);
// Save next day to set alarm
schedEdit.putInt(Keys.SCHED_NEXT_DAY, nextDay);
schedEdit.putInt(Keys.SCHED_LAST_DAY, lastDay);
// Get the new date to set the alarm on
String lastDate = schedPrefs.getString(Keys.SCHED_NEXT_DATE, null);
String[] lastArr = lastDate.split(":");
int[] lastInt = new int[] { Integer.parseInt(lastArr[0]), Integer.parseInt(lastArr[1]), Integer.parseInt(lastArr[2]) };
Calendar cal = Calendar.getInstance();
cal.set(lastInt[2], lastInt[1], lastInt[0]);
cal.add(Calendar.DAY_OF_MONTH, add);
StringBuilder sb = new StringBuilder();
sb.append(cal.get(Calendar.DAY_OF_MONTH)).append(":");
sb.append(cal.get(Calendar.MONTH)).append(":");
sb.append(cal.get(Calendar.YEAR));
schedEdit.putString(Keys.SCHED_NEXT_DATE, sb.toString());
schedEdit.putString(Keys.SCHED_LAST_DATE, lastDate);
// Increment cumulative day counter
int cumDay = schedPrefs.getInt(Keys.SCHED_NEXT_CUMULATIVE_DAY, 1);
schedEdit.putInt(Keys.SCHED_NEXT_CUMULATIVE_DAY, cumDay + add);
schedEdit.putInt(Keys.SCHED_CUMULATIVE_DAY, cumDay);
schedEdit.commit();
backup();
// Finally, use the new values to set an alarm
setRepeatAlarm();
// Close service once done
Scheduler.this.stopSelf();
}
};
private Runnable mFirstRun = new Runnable() {
@Override
public void run() {
// Load preferences to hold information.
// Set alarm for start date of trial
SharedPreferences configPrefs = getSharedPreferences(Keys.CONFIG_NAME, MODE_PRIVATE);
SharedPreferences schedPrefs = getSharedPreferences(Keys.SCHED_NAME, MODE_PRIVATE);
SharedPreferences.Editor schedEdit = schedPrefs.edit();
// Load start date as next time for notification
String start = configPrefs.getString(Keys.CONFIG_START, null);
if (start == null) {
Log.e(TAG, "Start date not initialised, config needs to be run");
Toast.makeText(Scheduler.this, R.string.config_not_run, Toast.LENGTH_SHORT).show();
} else {
schedEdit.putString(Keys.SCHED_NEXT_DATE, start);
schedEdit.putInt(Keys.SCHED_NEXT_DAY, 1);
schedEdit.putInt(Keys.SCHED_CUR_PERIOD, 1);
schedEdit.commit();
backup();
// Set up first time run notification
setFirstAlarm();
}
// Close service once done
Scheduler.this.stopSelf();
}
};
private Runnable mBootSchedule = new Runnable() {
@Override
public void run() {
// Get the next alarm time from preferences and set it
setRepeatAlarm();
setMedicineAlarm();
// Close service once done
Scheduler.this.stopSelf();
}
};
@TargetApi(8)
private void backup() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mBackupManager.dataChanged();
}
}
}
| true | true | public void run() {
// Work out when next to set the alarm, set it and save in preferences
SharedPreferences schedPrefs = getSharedPreferences(Keys.SCHED_NAME, MODE_PRIVATE);
SharedPreferences.Editor schedEdit = schedPrefs.edit();
SharedPreferences configPrefs = getSharedPreferences(Keys.CONFIG_NAME, MODE_PRIVATE);
int lastDay = schedPrefs.getInt(Keys.SCHED_NEXT_DAY, 1);
int periodLength = configPrefs.getInt(Keys.CONFIG_PERIOD_LENGTH, 1);
int nextDay = -1;
int add;
// TODO on the very first day, could have add = 0
for (add = 1; add < periodLength + 1; add++) {
nextDay = (lastDay + add) % (periodLength + 1);
if (configPrefs.getBoolean(Keys.CONFIG_DAY + nextDay, false)) {
if (DEBUG) Log.d(TAG, "Found the next day to send notification: " + nextDay);
break;
}
}
if (nextDay < 0) {
throw new RuntimeException("Invalid config settings");
}
int period = schedPrefs.getInt(Keys.SCHED_CUR_PERIOD, 1);
if (nextDay < lastDay) {
// Moving into next treatment period
if (period + 1 > 2 * configPrefs.getInt(Keys.CONFIG_NUMBER_PERIODS, Integer.MAX_VALUE)) {
// TODO Finished trial!
schedEdit.putBoolean(Keys.SCHED_FINISHED, true);
return;
}
schedEdit.putInt(Keys.SCHED_CUR_PERIOD, period + 1);
}
schedEdit.putInt(Keys.SCHED_LAST_PERIOD, period);
// Save next day to set alarm
schedEdit.putInt(Keys.SCHED_NEXT_DAY, nextDay);
schedEdit.putInt(Keys.SCHED_LAST_DAY, lastDay);
// Get the new date to set the alarm on
String lastDate = schedPrefs.getString(Keys.SCHED_NEXT_DATE, null);
String[] lastArr = lastDate.split(":");
int[] lastInt = new int[] { Integer.parseInt(lastArr[0]), Integer.parseInt(lastArr[1]), Integer.parseInt(lastArr[2]) };
Calendar cal = Calendar.getInstance();
cal.set(lastInt[2], lastInt[1], lastInt[0]);
cal.add(Calendar.DAY_OF_MONTH, add);
StringBuilder sb = new StringBuilder();
sb.append(cal.get(Calendar.DAY_OF_MONTH)).append(":");
sb.append(cal.get(Calendar.MONTH)).append(":");
sb.append(cal.get(Calendar.YEAR));
schedEdit.putString(Keys.SCHED_NEXT_DATE, sb.toString());
schedEdit.putString(Keys.SCHED_LAST_DATE, lastDate);
// Increment cumulative day counter
int cumDay = schedPrefs.getInt(Keys.SCHED_NEXT_CUMULATIVE_DAY, 1);
schedEdit.putInt(Keys.SCHED_NEXT_CUMULATIVE_DAY, cumDay + add);
schedEdit.putInt(Keys.SCHED_CUMULATIVE_DAY, cumDay);
schedEdit.commit();
backup();
// Finally, use the new values to set an alarm
setRepeatAlarm();
// Close service once done
Scheduler.this.stopSelf();
}
| public void run() {
// Work out when next to set the alarm, set it and save in preferences
SharedPreferences schedPrefs = getSharedPreferences(Keys.SCHED_NAME, MODE_PRIVATE);
SharedPreferences.Editor schedEdit = schedPrefs.edit();
SharedPreferences configPrefs = getSharedPreferences(Keys.CONFIG_NAME, MODE_PRIVATE);
int lastDay = schedPrefs.getInt(Keys.SCHED_NEXT_DAY, 1);
int periodLength = configPrefs.getInt(Keys.CONFIG_PERIOD_LENGTH, 1);
int nextDay = -1;
int add;
// TODO on the very first day, could have add = 0
for (add = 1; add <= periodLength; add++) {
nextDay = (lastDay + add) % (periodLength);
// Because of modulo, when the nextday would be the last in period nextDay is set to zero
if (nextDay == 0) nextDay = periodLength;
if (configPrefs.getBoolean(Keys.CONFIG_DAY + nextDay, false)) {
if (DEBUG) Log.d(TAG, "Found the next day to send notification: " + nextDay);
break;
}
}
if (nextDay < 0) {
throw new RuntimeException("Invalid config settings");
}
int period = schedPrefs.getInt(Keys.SCHED_CUR_PERIOD, 1);
if (nextDay < lastDay) {
// Moving into next treatment period
if (period + 1 > 2 * configPrefs.getInt(Keys.CONFIG_NUMBER_PERIODS, Integer.MAX_VALUE)) {
// TODO Finished trial!
schedEdit.putBoolean(Keys.SCHED_FINISHED, true);
return;
}
schedEdit.putInt(Keys.SCHED_CUR_PERIOD, period + 1);
}
schedEdit.putInt(Keys.SCHED_LAST_PERIOD, period);
// Save next day to set alarm
schedEdit.putInt(Keys.SCHED_NEXT_DAY, nextDay);
schedEdit.putInt(Keys.SCHED_LAST_DAY, lastDay);
// Get the new date to set the alarm on
String lastDate = schedPrefs.getString(Keys.SCHED_NEXT_DATE, null);
String[] lastArr = lastDate.split(":");
int[] lastInt = new int[] { Integer.parseInt(lastArr[0]), Integer.parseInt(lastArr[1]), Integer.parseInt(lastArr[2]) };
Calendar cal = Calendar.getInstance();
cal.set(lastInt[2], lastInt[1], lastInt[0]);
cal.add(Calendar.DAY_OF_MONTH, add);
StringBuilder sb = new StringBuilder();
sb.append(cal.get(Calendar.DAY_OF_MONTH)).append(":");
sb.append(cal.get(Calendar.MONTH)).append(":");
sb.append(cal.get(Calendar.YEAR));
schedEdit.putString(Keys.SCHED_NEXT_DATE, sb.toString());
schedEdit.putString(Keys.SCHED_LAST_DATE, lastDate);
// Increment cumulative day counter
int cumDay = schedPrefs.getInt(Keys.SCHED_NEXT_CUMULATIVE_DAY, 1);
schedEdit.putInt(Keys.SCHED_NEXT_CUMULATIVE_DAY, cumDay + add);
schedEdit.putInt(Keys.SCHED_CUMULATIVE_DAY, cumDay);
schedEdit.commit();
backup();
// Finally, use the new values to set an alarm
setRepeatAlarm();
// Close service once done
Scheduler.this.stopSelf();
}
|
diff --git a/component/src/test/java/com/celements/photo/service/ImageServiceTest.java b/component/src/test/java/com/celements/photo/service/ImageServiceTest.java
index 7982d99..a8d9b07 100644
--- a/component/src/test/java/com/celements/photo/service/ImageServiceTest.java
+++ b/component/src/test/java/com/celements/photo/service/ImageServiceTest.java
@@ -1,442 +1,442 @@
package com.celements.photo.service;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import java.util.Map;
import org.apache.velocity.VelocityContext;
import org.junit.Before;
import org.junit.Test;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import com.celements.common.test.AbstractBridgedComponentTestCase;
import com.celements.navigation.NavigationClasses;
import com.celements.photo.container.ImageDimensions;
import com.celements.web.classcollections.OldCoreClasses;
import com.celements.web.plugin.cmd.AttachmentURLCommand;
import com.celements.web.service.IWebUtilsService;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.user.api.XWikiRightService;
public class ImageServiceTest extends AbstractBridgedComponentTestCase {
private XWikiContext context;
private ImageService imageService;
private XWiki xwiki;
private XWikiRightService rightServiceMock;
@Before
public void setUp_ImageServiceTest() throws Exception {
context = getContext();
xwiki = getWikiMock();
rightServiceMock = createMockAndAddToDefault(XWikiRightService.class);
expect(xwiki.getRightService()).andReturn(rightServiceMock).anyTimes();
imageService = (ImageService) getComponentManager().lookup(IImageService.class);
}
@Test
public void testGetPhotoAlbumNavObject() throws Exception {
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "galleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
BaseObject expectedPhotoAlbumNavObj = new BaseObject();
expectedPhotoAlbumNavObj.setXClassReference(new NavigationClasses(
).getNavigationConfigClassRef(context.getDatabase()));
galleryDoc.addXObject(expectedPhotoAlbumNavObj);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).once();
replayDefault();
BaseObject photoAlbumNavObj = imageService.getPhotoAlbumNavObject(galleryDocRef);
assertNotNull(photoAlbumNavObj);
assertSame(expectedPhotoAlbumNavObj, photoAlbumNavObj);
verifyDefault();
}
@Test
public void testGetPhotoAlbumNavObject_noObject() throws Exception {
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "noGalleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).once();
replayDefault();
try {
imageService.getPhotoAlbumNavObject(galleryDocRef);
fail("expecting NoGalleryDocumentException");
} catch (NoGalleryDocumentException exp) {
//expected
}
verifyDefault();
}
@Test
public void testGetPhotoAlbumSpaceRef_noGalleryDoc() throws Exception {
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "noGalleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).once();
replayDefault();
try {
imageService.getPhotoAlbumSpaceRef(galleryDocRef);
} catch (NoGalleryDocumentException exp) {
//expected
}
verifyDefault();
}
@Test
public void testGetPhotoAlbumSpaceRef_galleryDoc() throws Exception {
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "galleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
BaseObject expectedPhotoAlbumNavObj = new BaseObject();
expectedPhotoAlbumNavObj.setXClassReference(new NavigationClasses(
).getNavigationConfigClassRef(context.getDatabase()));
String gallerySpaceName = "gallerySpace";
expectedPhotoAlbumNavObj.setStringValue("menu_space", gallerySpaceName);
galleryDoc.addXObject(expectedPhotoAlbumNavObj);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).once();
replayDefault();
SpaceReference expectedSpaceRef = new SpaceReference("gallerySpace",
(WikiReference)galleryDocRef.getLastSpaceReference().getParent());
assertEquals(expectedSpaceRef, imageService.getPhotoAlbumSpaceRef(galleryDocRef));
verifyDefault();
}
@Test
public void testCheckAddSlideRights_noObjects_noGalleryDoc() throws Exception {
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "noGalleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).once();
replayDefault();
assertFalse("Expecting no addSlide rights if document is no gallery document.",
imageService.checkAddSlideRights(galleryDocRef));
verifyDefault();
}
@Test
public void testGetImageSlideTemplateRef_local() throws Exception {
DocumentReference localTemplateRef = new DocumentReference(context.getDatabase(),
"ImageGalleryTemplates", "NewImageGallerySlide");
expect(xwiki.exists(eq(localTemplateRef), same(context))).andReturn(true).once();
replayDefault();
assertEquals(localTemplateRef, imageService.getImageSlideTemplateRef());
verifyDefault();
}
@Test
public void testGetImageSlideTemplateRef_central() throws Exception {
DocumentReference localTemplateRef = new DocumentReference(context.getDatabase(),
"ImageGalleryTemplates", "NewImageGallerySlide");
DocumentReference centralTemplateRef = new DocumentReference("celements2web",
"ImageGalleryTemplates", "NewImageGallerySlide");
expect(xwiki.exists(eq(localTemplateRef), same(context))).andReturn(false).once();
replayDefault();
assertEquals(centralTemplateRef, imageService.getImageSlideTemplateRef());
verifyDefault();
}
@Test
public void testCheckAddSlideRights_yes() throws Exception {
String editorUser = "XWiki.myEditor";
context.setUser(editorUser);
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "galleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
BaseObject photoAlbumNavObj = new BaseObject();
photoAlbumNavObj.setXClassReference(new NavigationClasses(
).getNavigationConfigClassRef(context.getDatabase()));
String gallerySpaceName = "gallerySpace";
photoAlbumNavObj.setStringValue("menu_space", gallerySpaceName);
galleryDoc.addXObject(photoAlbumNavObj);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).once();
DocumentReference testSlideDocRef = new DocumentReference(context.getDatabase(),
gallerySpaceName, "Testname1");
XWikiDocument testSlideDocMock = createMockAndAddToDefault(XWikiDocument.class);
expect(xwiki.getDocument(eq(testSlideDocRef), same(context))).andReturn(
testSlideDocMock).once();
expect(xwiki.exists(eq(testSlideDocRef), same(context))).andReturn(false).once();
expect(testSlideDocMock.getLock(same(context))).andReturn(null).once();
expect(rightServiceMock.hasAccessLevel(eq("edit"), eq(editorUser),
eq("xwikidb:gallerySpace.Testname1"), same(context))).andReturn(true).once();
replayDefault();
assertTrue("Expecting addSlide rights if 'edit' rights on space available",
imageService.checkAddSlideRights(galleryDocRef));
verifyDefault();
}
@Test
public void testCheckAddSlideRights_no() throws Exception {
String editorUser = "XWiki.myNoEditor";
context.setUser(editorUser);
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "galleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
BaseObject photoAlbumNavObj = new BaseObject();
photoAlbumNavObj.setXClassReference(new NavigationClasses(
).getNavigationConfigClassRef(context.getDatabase()));
String gallerySpaceName = "gallerySpace";
photoAlbumNavObj.setStringValue("menu_space", gallerySpaceName);
galleryDoc.addXObject(photoAlbumNavObj);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).once();
DocumentReference testSlideDocRef = new DocumentReference(context.getDatabase(),
gallerySpaceName, "Testname1");
XWikiDocument testSlideDocMock = createMockAndAddToDefault(XWikiDocument.class);
expect(xwiki.getDocument(eq(testSlideDocRef), same(context))).andReturn(
testSlideDocMock).once();
expect(xwiki.exists(eq(testSlideDocRef), same(context))).andReturn(false).once();
expect(testSlideDocMock.getLock(same(context))).andReturn(null).once();
expect(rightServiceMock.hasAccessLevel(eq("edit"), eq(editorUser),
eq("xwikidb:gallerySpace.Testname1"), same(context))).andReturn(false).once();
replayDefault();
assertFalse("Expecting no addSlide rights if no 'edit' rights on space available",
imageService.checkAddSlideRights(galleryDocRef));
verifyDefault();
}
@SuppressWarnings("unchecked")
@Test
public void testAddSlideFromTemplate() throws Exception {
String editorUser = "XWiki.myEditor";
context.setUser(editorUser);
AttachmentURLCommand attURLCmdMock = createMockAndAddToDefault(
AttachmentURLCommand.class);
imageService.attURLCmd = attURLCmdMock;
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "galleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
BaseObject photoAlbumNavObj = new BaseObject();
photoAlbumNavObj.setXClassReference(new NavigationClasses(
).getNavigationConfigClassRef(context.getDatabase()));
String gallerySpaceName = "gallerySpace";
photoAlbumNavObj.setStringValue("menu_space", gallerySpaceName);
galleryDoc.addXObject(photoAlbumNavObj);
BaseObject photoAlbumObj = new BaseObject();
photoAlbumObj.setXClassReference(new OldCoreClasses().getPhotoAlbumClassRef(
context.getDatabase()));
int maxWidth = 800;
int maxHeight = 800;
photoAlbumObj.setIntValue("height2", maxHeight);
photoAlbumObj.setIntValue("photoWidth", maxWidth);
galleryDoc.addXObject(photoAlbumObj);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).atLeastOnce();
DocumentReference slideDocRef = new DocumentReference(context.getDatabase(),
gallerySpaceName, "Slide1");
XWikiDocument slideDocMock = createMockAndAddToDefault(XWikiDocument.class);
expect(xwiki.getDocument(eq(slideDocRef), same(context))).andReturn(
slideDocMock).once();
expect(xwiki.exists(eq(slideDocRef), same(context))).andReturn(false).once();
expect(slideDocMock.getLock(same(context))).andReturn(null).once();
XWikiDocument slideDoc = new XWikiDocument(slideDocRef);
expect(xwiki.getDocument(eq(slideDocRef), same(context))).andReturn(slideDoc).once();
DocumentReference localTemplateRef = new DocumentReference(context.getDatabase(),
"ImageGalleryTemplates", "NewImageGallerySlide");
expect(xwiki.exists(eq(localTemplateRef), same(context))).andReturn(true).once();
expect(xwiki.copyDocument(eq(localTemplateRef), eq(slideDocRef), eq(true),
same(context))).andReturn(true).once();
String attFullName = "ContentAttachment.FileBaseDoc;myImg.png";
String imgAttURL = "/download/ContentAttachment/FileBaseDoc/myImg.png";
expect(attURLCmdMock.getAttachmentURL(eq(attFullName), eq("download"), same(context))
).andReturn(imgAttURL).once();
imageService.webUtilsService = createMock(IWebUtilsService.class);
DocumentReference attDocRef = new DocumentReference(getContext().getDatabase(),
"ContentAttachment", "FileBaseDoc");
IWebUtilsService webUtils = imageService.webUtilsService;
expect(webUtils.resolveDocumentReference(
eq("ContentAttachment.FileBaseDoc"))).andReturn(attDocRef).once();
XWikiDocument attDoc = new XWikiDocument(new DocumentReference("a", "b", "c"));
expect(xwiki.getDocument(eq(attDocRef), same(context))).andReturn(attDoc).once();
expect(webUtils.resolveDocumentReference(
eq("Classes.PhotoMetainfoClass"))).andReturn(attDocRef).once();
xwiki.saveDocument(same(slideDoc), eq("add default image slide content"), eq(true),
same(context));
expectLastCall().once();
expect(webUtils.getWikiRef((DocumentReference)anyObject())
).andReturn(attDocRef.getWikiReference()).anyTimes();
expect(webUtils.getDefaultLanguage()).andReturn("de").anyTimes();
expect(webUtils.getDefaultLanguage((String)anyObject())).andReturn("de").anyTimes();
expect(xwiki.getSpacePreference(eq("default_language"), eq("gallerySpace"), eq(""),
same(context))).andReturn("de").anyTimes();
VelocityContext vcontext = new VelocityContext();
context.put("vcontext", vcontext);
DocumentReference imgImportContentRef = new DocumentReference(context.getDatabase(),
"Templates", "ImageSlideImportContent");
expect(webUtils.renderInheritableDocument(eq(imgImportContentRef),
eq(context.getLanguage()), eq("de"))).andReturn("content").once();
expect(xwiki.getWebPreference(eq("cel_centralfilebase"), same(getContext()))
- ).andReturn("");
+ ).andReturn("").once();
expect(xwiki.exists(eq(attDocRef), same(getContext()))).andReturn(true);
replayDefault();
replay(webUtils);
assertTrue("Expecting successful adding slide", imageService.addSlideFromTemplate(
galleryDocRef, "Slide", attFullName));
String expectedImgURL = imgAttURL + "?celwidth=" + maxWidth + "&celheight="
+ maxHeight;
verifyDefault();
verify(webUtils);
assertEquals(expectedImgURL, vcontext.get("imageURL"));
assertEquals(attFullName, vcontext.get("attFullName"));
assertEquals(0, ((Map<String, String>)vcontext.get("metaTagMap")).size());
}
@Test
public void testGetFixedAspectURL_isSquare_tarSquare() {
String params = imageService.getFixedAspectURL(new ImageDimensions(300, 300), 1, 1);
assertEquals("Expecting no params if image matches target aspect ratio.", "", params);
}
@Test
public void testGetFixedAspectURL_isPortrait_tarSquare() {
String params = imageService.getFixedAspectURL(new ImageDimensions(300, 400), 1, 1);
assertTrue("Expecting no crop on left. [" + params + "]",
params.indexOf("cropX=0") >= 0);
assertTrue("Expecting full width. [" + params + "]",
params.indexOf("cropW=300") >= 0);
assertTrue("Expecting cropped border on top. [" + params + "]",
params.indexOf("cropY=50") >= 0);
assertTrue("Expecting height equals full width. [" + params + "]",
params.indexOf("cropH=300") >= 0);
}
@Test
public void testGetFixedAspectURL_isLandscape_tarSquare() {
String params = imageService.getFixedAspectURL(new ImageDimensions(400, 300), 1, 1);
assertTrue("Expecting cropped border on left. [" + params + "]",
params.indexOf("cropX=50") >= 0);
assertTrue("Expecting width equals full height. [" + params + "]",
params.indexOf("cropW=300") >= 0);
assertTrue("Expecting no crop on top. [" + params + "]",
params.indexOf("cropY=0") >= 0);
assertTrue("Expecting full height. [" + params + "]",
params.indexOf("cropH=300") >= 0);
}
@Test
public void testGetFixedAspectURL_is3to4_tar3to4() {
String params = imageService.getFixedAspectURL(new ImageDimensions(300, 400), 3, 4);
assertEquals("Expecting no params if image matches target aspect ratio.", "", params);
}
@Test
public void testGetFixedAspectURL_isSquare_tar3to4() {
String params = imageService.getFixedAspectURL(new ImageDimensions(300, 300), 3, 4);
assertTrue("Expecting cropped border on left. [" + params + "]",
params.indexOf("cropX=37") >= 0);
assertTrue("Expecting width equals .75 * height. [" + params + "]",
params.indexOf("cropW=225") >= 0);
assertTrue("Expecting no crop on top. [" + params + "]",
params.indexOf("cropY=0") >= 0);
assertTrue("Expecting full height. [" + params + "]",
params.indexOf("cropH=300") >= 0);
}
@Test
public void testGetFixedAspectURL_isLandscape_tar3to4() {
String params = imageService.getFixedAspectURL(new ImageDimensions(400, 300), 3, 4);
assertTrue("Expecting cropped border on left. [" + params + "]",
params.indexOf("cropX=87") >= 0);
assertTrue("Expecting width equals .75 * height. [" + params + "]",
params.indexOf("cropW=225") >= 0);
assertTrue("Expecting no crop on top. [" + params + "]",
params.indexOf("cropY=0") >= 0);
assertTrue("Expecting full height. [" + params + "]",
params.indexOf("cropH=300") >= 0);
}
@Test
public void testGetFixedAspectURL_isPortraitWide_tar3to4() {
String params = imageService.getFixedAspectURL(new ImageDimensions(350, 400), 3, 4);
assertTrue("Expecting cropped border on left. [" + params + "]",
params.indexOf("cropX=25") >= 0);
assertTrue("Expecting width equals .75 * height. [" + params + "]",
params.indexOf("cropW=300") >= 0);
assertTrue("Expecting no crop on top. [" + params + "]",
params.indexOf("cropY=0") >= 0);
assertTrue("Expecting full height. [" + params + "]",
params.indexOf("cropH=400") >= 0);
}
@Test
public void testGetFixedAspectURL_isPortraitSmall_tar3to4() {
String params = imageService.getFixedAspectURL(new ImageDimensions(240, 400), 3, 4);
assertTrue("Expecting no crop on left. [" + params + "]",
params.indexOf("cropX=0") >= 0);
assertTrue("Expecting full width. [" + params + "]",
params.indexOf("cropW=240") >= 0);
assertTrue("Expecting cropped border on top. [" + params + "]",
params.indexOf("cropY=40") >= 0);
assertTrue("Expecting width * 4/3. [" + params + "]",
params.indexOf("cropH=320") >= 0);
}
@Test
public void testGetFixedAspectURL_is4to3_tar4to3() {
String params = imageService.getFixedAspectURL(new ImageDimensions(400, 300), 4, 3);
assertEquals("Expecting no params if image matches target aspect ratio.", "", params);
}
@Test
public void testGetFixedAspectURL_isSquare_tar4to3() {
String params = imageService.getFixedAspectURL(new ImageDimensions(300, 300), 4, 3);
assertTrue("Expecting no crop on left. [" + params + "]",
params.indexOf("cropX=0") >= 0);
assertTrue("Expecting full width. [" + params + "]",
params.indexOf("cropW=300") >= 0);
assertTrue("Expecting cropped border on top. [" + params + "]",
params.indexOf("cropY=37") >= 0);
assertTrue("Expecting height equals .75 * width. [" + params + "]",
params.indexOf("cropH=225") >= 0);
}
@Test
public void testGetFixedAspectURL_isPortrait_tar4to3() {
String params = imageService.getFixedAspectURL(new ImageDimensions(300, 400), 4, 3);
assertTrue("Expecting no crop on left. [" + params + "]",
params.indexOf("cropX=0") >= 0);
assertTrue("Expecting full width. [" + params + "]",
params.indexOf("cropW=300") >= 0);
assertTrue("Expecting cropped border on top. [" + params + "]",
params.indexOf("cropY=87") >= 0);
assertTrue("Expecting height equals .75 * width. [" + params + "]",
params.indexOf("cropH=225") >= 0);
}
@Test
public void testGetFixedAspectURL_isLandscapeHigh_tar4to3() {
String params = imageService.getFixedAspectURL(new ImageDimensions(400, 350), 4, 3);
assertTrue("Expecting no crop on left. [" + params + "]",
params.indexOf("cropX=0") >= 0);
assertTrue("Expecting full width. [" + params + "]",
params.indexOf("cropW=400") >= 0);
assertTrue("Expecting cropped border on top. [" + params + "]",
params.indexOf("cropY=25") >= 0);
assertTrue("Expecting height equals .75 * width. [" + params + "]",
params.indexOf("cropH=300") >= 0);
}
@Test
public void testGetFixedAspectURL_isLandscapeLow_tar4to3() {
String params = imageService.getFixedAspectURL(new ImageDimensions(400, 240), 4, 3);
assertTrue("Expecting cropped border on left. [" + params + "]",
params.indexOf("cropX=40") >= 0);
assertTrue("Expecting width * 4/3. [" + params + "]",
params.indexOf("cropW=320") >= 0);
assertTrue("Expecting no crop on top. [" + params + "]",
params.indexOf("cropY=0") >= 0);
assertTrue("Expecting full height. [" + params + "]",
params.indexOf("cropH=240") >= 0);
}
}
| true | true | public void testAddSlideFromTemplate() throws Exception {
String editorUser = "XWiki.myEditor";
context.setUser(editorUser);
AttachmentURLCommand attURLCmdMock = createMockAndAddToDefault(
AttachmentURLCommand.class);
imageService.attURLCmd = attURLCmdMock;
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "galleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
BaseObject photoAlbumNavObj = new BaseObject();
photoAlbumNavObj.setXClassReference(new NavigationClasses(
).getNavigationConfigClassRef(context.getDatabase()));
String gallerySpaceName = "gallerySpace";
photoAlbumNavObj.setStringValue("menu_space", gallerySpaceName);
galleryDoc.addXObject(photoAlbumNavObj);
BaseObject photoAlbumObj = new BaseObject();
photoAlbumObj.setXClassReference(new OldCoreClasses().getPhotoAlbumClassRef(
context.getDatabase()));
int maxWidth = 800;
int maxHeight = 800;
photoAlbumObj.setIntValue("height2", maxHeight);
photoAlbumObj.setIntValue("photoWidth", maxWidth);
galleryDoc.addXObject(photoAlbumObj);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).atLeastOnce();
DocumentReference slideDocRef = new DocumentReference(context.getDatabase(),
gallerySpaceName, "Slide1");
XWikiDocument slideDocMock = createMockAndAddToDefault(XWikiDocument.class);
expect(xwiki.getDocument(eq(slideDocRef), same(context))).andReturn(
slideDocMock).once();
expect(xwiki.exists(eq(slideDocRef), same(context))).andReturn(false).once();
expect(slideDocMock.getLock(same(context))).andReturn(null).once();
XWikiDocument slideDoc = new XWikiDocument(slideDocRef);
expect(xwiki.getDocument(eq(slideDocRef), same(context))).andReturn(slideDoc).once();
DocumentReference localTemplateRef = new DocumentReference(context.getDatabase(),
"ImageGalleryTemplates", "NewImageGallerySlide");
expect(xwiki.exists(eq(localTemplateRef), same(context))).andReturn(true).once();
expect(xwiki.copyDocument(eq(localTemplateRef), eq(slideDocRef), eq(true),
same(context))).andReturn(true).once();
String attFullName = "ContentAttachment.FileBaseDoc;myImg.png";
String imgAttURL = "/download/ContentAttachment/FileBaseDoc/myImg.png";
expect(attURLCmdMock.getAttachmentURL(eq(attFullName), eq("download"), same(context))
).andReturn(imgAttURL).once();
imageService.webUtilsService = createMock(IWebUtilsService.class);
DocumentReference attDocRef = new DocumentReference(getContext().getDatabase(),
"ContentAttachment", "FileBaseDoc");
IWebUtilsService webUtils = imageService.webUtilsService;
expect(webUtils.resolveDocumentReference(
eq("ContentAttachment.FileBaseDoc"))).andReturn(attDocRef).once();
XWikiDocument attDoc = new XWikiDocument(new DocumentReference("a", "b", "c"));
expect(xwiki.getDocument(eq(attDocRef), same(context))).andReturn(attDoc).once();
expect(webUtils.resolveDocumentReference(
eq("Classes.PhotoMetainfoClass"))).andReturn(attDocRef).once();
xwiki.saveDocument(same(slideDoc), eq("add default image slide content"), eq(true),
same(context));
expectLastCall().once();
expect(webUtils.getWikiRef((DocumentReference)anyObject())
).andReturn(attDocRef.getWikiReference()).anyTimes();
expect(webUtils.getDefaultLanguage()).andReturn("de").anyTimes();
expect(webUtils.getDefaultLanguage((String)anyObject())).andReturn("de").anyTimes();
expect(xwiki.getSpacePreference(eq("default_language"), eq("gallerySpace"), eq(""),
same(context))).andReturn("de").anyTimes();
VelocityContext vcontext = new VelocityContext();
context.put("vcontext", vcontext);
DocumentReference imgImportContentRef = new DocumentReference(context.getDatabase(),
"Templates", "ImageSlideImportContent");
expect(webUtils.renderInheritableDocument(eq(imgImportContentRef),
eq(context.getLanguage()), eq("de"))).andReturn("content").once();
expect(xwiki.getWebPreference(eq("cel_centralfilebase"), same(getContext()))
).andReturn("");
expect(xwiki.exists(eq(attDocRef), same(getContext()))).andReturn(true);
replayDefault();
replay(webUtils);
assertTrue("Expecting successful adding slide", imageService.addSlideFromTemplate(
galleryDocRef, "Slide", attFullName));
String expectedImgURL = imgAttURL + "?celwidth=" + maxWidth + "&celheight="
+ maxHeight;
verifyDefault();
verify(webUtils);
assertEquals(expectedImgURL, vcontext.get("imageURL"));
assertEquals(attFullName, vcontext.get("attFullName"));
assertEquals(0, ((Map<String, String>)vcontext.get("metaTagMap")).size());
}
| public void testAddSlideFromTemplate() throws Exception {
String editorUser = "XWiki.myEditor";
context.setUser(editorUser);
AttachmentURLCommand attURLCmdMock = createMockAndAddToDefault(
AttachmentURLCommand.class);
imageService.attURLCmd = attURLCmdMock;
DocumentReference galleryDocRef = new DocumentReference(context.getDatabase(),
"mySpace", "galleryDoc");
XWikiDocument galleryDoc = new XWikiDocument(galleryDocRef);
BaseObject photoAlbumNavObj = new BaseObject();
photoAlbumNavObj.setXClassReference(new NavigationClasses(
).getNavigationConfigClassRef(context.getDatabase()));
String gallerySpaceName = "gallerySpace";
photoAlbumNavObj.setStringValue("menu_space", gallerySpaceName);
galleryDoc.addXObject(photoAlbumNavObj);
BaseObject photoAlbumObj = new BaseObject();
photoAlbumObj.setXClassReference(new OldCoreClasses().getPhotoAlbumClassRef(
context.getDatabase()));
int maxWidth = 800;
int maxHeight = 800;
photoAlbumObj.setIntValue("height2", maxHeight);
photoAlbumObj.setIntValue("photoWidth", maxWidth);
galleryDoc.addXObject(photoAlbumObj);
expect(xwiki.getDocument(eq(galleryDocRef), same(context))).andReturn(galleryDoc
).atLeastOnce();
DocumentReference slideDocRef = new DocumentReference(context.getDatabase(),
gallerySpaceName, "Slide1");
XWikiDocument slideDocMock = createMockAndAddToDefault(XWikiDocument.class);
expect(xwiki.getDocument(eq(slideDocRef), same(context))).andReturn(
slideDocMock).once();
expect(xwiki.exists(eq(slideDocRef), same(context))).andReturn(false).once();
expect(slideDocMock.getLock(same(context))).andReturn(null).once();
XWikiDocument slideDoc = new XWikiDocument(slideDocRef);
expect(xwiki.getDocument(eq(slideDocRef), same(context))).andReturn(slideDoc).once();
DocumentReference localTemplateRef = new DocumentReference(context.getDatabase(),
"ImageGalleryTemplates", "NewImageGallerySlide");
expect(xwiki.exists(eq(localTemplateRef), same(context))).andReturn(true).once();
expect(xwiki.copyDocument(eq(localTemplateRef), eq(slideDocRef), eq(true),
same(context))).andReturn(true).once();
String attFullName = "ContentAttachment.FileBaseDoc;myImg.png";
String imgAttURL = "/download/ContentAttachment/FileBaseDoc/myImg.png";
expect(attURLCmdMock.getAttachmentURL(eq(attFullName), eq("download"), same(context))
).andReturn(imgAttURL).once();
imageService.webUtilsService = createMock(IWebUtilsService.class);
DocumentReference attDocRef = new DocumentReference(getContext().getDatabase(),
"ContentAttachment", "FileBaseDoc");
IWebUtilsService webUtils = imageService.webUtilsService;
expect(webUtils.resolveDocumentReference(
eq("ContentAttachment.FileBaseDoc"))).andReturn(attDocRef).once();
XWikiDocument attDoc = new XWikiDocument(new DocumentReference("a", "b", "c"));
expect(xwiki.getDocument(eq(attDocRef), same(context))).andReturn(attDoc).once();
expect(webUtils.resolveDocumentReference(
eq("Classes.PhotoMetainfoClass"))).andReturn(attDocRef).once();
xwiki.saveDocument(same(slideDoc), eq("add default image slide content"), eq(true),
same(context));
expectLastCall().once();
expect(webUtils.getWikiRef((DocumentReference)anyObject())
).andReturn(attDocRef.getWikiReference()).anyTimes();
expect(webUtils.getDefaultLanguage()).andReturn("de").anyTimes();
expect(webUtils.getDefaultLanguage((String)anyObject())).andReturn("de").anyTimes();
expect(xwiki.getSpacePreference(eq("default_language"), eq("gallerySpace"), eq(""),
same(context))).andReturn("de").anyTimes();
VelocityContext vcontext = new VelocityContext();
context.put("vcontext", vcontext);
DocumentReference imgImportContentRef = new DocumentReference(context.getDatabase(),
"Templates", "ImageSlideImportContent");
expect(webUtils.renderInheritableDocument(eq(imgImportContentRef),
eq(context.getLanguage()), eq("de"))).andReturn("content").once();
expect(xwiki.getWebPreference(eq("cel_centralfilebase"), same(getContext()))
).andReturn("").once();
expect(xwiki.exists(eq(attDocRef), same(getContext()))).andReturn(true);
replayDefault();
replay(webUtils);
assertTrue("Expecting successful adding slide", imageService.addSlideFromTemplate(
galleryDocRef, "Slide", attFullName));
String expectedImgURL = imgAttURL + "?celwidth=" + maxWidth + "&celheight="
+ maxHeight;
verifyDefault();
verify(webUtils);
assertEquals(expectedImgURL, vcontext.get("imageURL"));
assertEquals(attFullName, vcontext.get("attFullName"));
assertEquals(0, ((Map<String, String>)vcontext.get("metaTagMap")).size());
}
|
diff --git a/examServer/src/main/java/de/thorstenberger/examServer/ws/remoteusermanager/RadiusAuthenticationProvider.java b/examServer/src/main/java/de/thorstenberger/examServer/ws/remoteusermanager/RadiusAuthenticationProvider.java
index d7f5a30..27219c6 100644
--- a/examServer/src/main/java/de/thorstenberger/examServer/ws/remoteusermanager/RadiusAuthenticationProvider.java
+++ b/examServer/src/main/java/de/thorstenberger/examServer/ws/remoteusermanager/RadiusAuthenticationProvider.java
@@ -1,252 +1,248 @@
/*
Copyright (C) 2010 Steffen Dienst
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package de.thorstenberger.examServer.ws.remoteusermanager;
import java.io.IOException;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationServiceException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
import org.tinyradius.util.RadiusClient;
import org.tinyradius.util.RadiusException;
import de.thorstenberger.examServer.model.User;
import de.thorstenberger.examServer.service.ConfigManager;
import de.thorstenberger.examServer.service.RoleManager;
import de.thorstenberger.examServer.service.UserExistsException;
import de.thorstenberger.examServer.service.UserManager;
import de.thorstenberger.examServer.util.StringUtil;
import de.thorstenberger.examServer.ws.remoteusermanager.client.UserBean;
/**
* Authenticate against a radius server (not challenge based!). See RFC 2865.
*
* @author Steffen Dienst
*
*/
public class RadiusAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider implements AuthenticationProvider,
MessageSourceAware {
private final Log log = LogFactory.getLog(RadiusAuthenticationProvider.class);
private MessageSourceAccessor messageSourceAccessor;
private final ConfigManager configManager;
private final UserManager userManager;
private final RoleManager roleManager;
private boolean forcePrincipalAsString = false;
/**
*
*/
public RadiusAuthenticationProvider(final ConfigManager configManager, final UserManager userManager,
final RoleManager roleManager) {
this.configManager = configManager;
this.userManager = userManager;
this.roleManager = roleManager;
}
/*
* (non-Javadoc)
*
* @see org.acegisecurity.providers.AuthenticationProvider#authenticate(org.acegisecurity.Authentication)
*/
@Override
public Authentication authenticate(final Authentication authentication)
throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
messageSourceAccessor.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
"Only UsernamePasswordAuthenticationToken is supported"));
- if (!configManager.isStudentsLoginEnabled()) {
- throw new AuthenticationServiceException("Login disabled for student role.");
- }
if (!StringUtils.isEmpty(configManager.getRadiusHost()) && !StringUtils.isEmpty(configManager.getRadiusSharedSecret())) {
// Determine username
final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
final String password = (authentication.getCredentials() == null) ? "NONE_PROVIDED"
: (String) authentication.getCredentials();
UserBean userBean;
try {
userBean = getRemoteUserInfos(username, password);
- if (!userBean.getRole().equals("student")) {
- throw new AuthenticationServiceException("Only student role allowed.");
- }
+ if (userBean.getRole().equals("student") && !configManager.isStudentsLoginEnabled())
+ throw new AuthenticationServiceException("Login disabled for student role.");
try {
userManager.getUserByUsername(userBean.getLogin());
} catch (final UsernameNotFoundException e) {
final User user = new User();
user.setEnabled(true);
user.setUsername(userBean.getLogin());
user.setFirstName(userBean.getFirstName() == null ? "" : userBean.getFirstName());
user.setLastName(userBean.getName() == null ? "" : userBean.getName());
user.setEmail(userBean.getEmail() == null ? "" : userBean.getEmail());
user.setPassword(StringUtil.encodePassword(userBean.getPassword(), "SHA"));
user.addRole(roleManager.getRole("student"));
try {
userManager.saveUser(user);
} catch (final UserExistsException e2) {
// should not happen
throw new RuntimeException(e2);
}
}
} catch (final AuthenticationServiceException e) {
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials", "Invalid username or password."));
}
final UserDetails userDetails = userManager.getUserByUsername(username);
Object principalToReturn = userDetails;
if (forcePrincipalAsString) {
principalToReturn = userDetails.getUsername();
}
return createSuccessAuthentication(principalToReturn, authentication, userDetails);
}
return null;
}
private UserBean getRemoteUserInfos(final String login, final String pwd) throws AuthenticationServiceException {
final boolean auth = authenticateUser(login, pwd);
if (auth) {
// now we know that at least login and password are correct, so we create the user bean
String email = login;
if (!login.contains("@")) {
email = login+"@"+configManager.getHTTPAuthMail();
}
final UserBean bean = new UserBean(email, login, null, pwd, "student", null);
return bean;
} else {
log.warn("Wrong radius authentication for " + login);
throw new AuthenticationServiceException("Invalid username/password!");
}
}
/**
* Send authentication request to the radius server. Concatenates <code>login</code> with <code>@mailsuffix</code> if
* such a suffix is configured at {@link ConfigManager#getHTTPAuthMail()}.
*
* @param login
* @param pwd
* @return
*/
private boolean authenticateUser(final String login, final String pwd) {
// if there is a configured mail suffix, construct the username
// to send to the radius server: login@mailsuffix
String username = login;
final String mailSuffix = configManager.getHTTPAuthMail();
if (!StringUtils.isEmpty(mailSuffix) && !login.contains("@")) {
username = login + "@" + mailSuffix;
}
log.debug(String.format("Trying to authenticate user '%s' against radius server at %s", username, configManager.getRadiusHost()));
final RadiusClient radiusClient = new RadiusClient(configManager.getRadiusHost(), configManager.getRadiusSharedSecret());
try {
return radiusClient.authenticate(username, pwd);
} catch (final IOException e) {
throw new AuthenticationServiceException("Could not authenticate user!", e);
} catch (final RadiusException e) {
throw new AuthenticationServiceException("Could not authenticate user!", e);
}
}
/*
* (non-Javadoc)
*
* @see org.acegisecurity.providers.AuthenticationProvider#supports(java.lang.Class)
*/
@Override
public boolean supports(final Class authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
/*
* (non-Javadoc)
*
* @see org.springframework.context.MessageSourceAware#setMessageSource(org.springframework.context.MessageSource)
*/
@Override
public void setMessageSource(final MessageSource messageSource) {
this.messageSourceAccessor = new MessageSourceAccessor(messageSource);
}
/*
* (non-Javadoc)
*
* @seeorg.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider#additionalAuthenticationChecks(org.
* acegisecurity.userdetails.UserDetails, org.acegisecurity.providers.UsernamePasswordAuthenticationToken)
*/
@Override
protected void additionalAuthenticationChecks(final UserDetails arg0, final UsernamePasswordAuthenticationToken arg1) throws AuthenticationException {
}
/*
* (non-Javadoc)
*
* @see org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider#retrieveUser(java.lang.String,
* org.acegisecurity.providers.UsernamePasswordAuthenticationToken)
*/
@Override
protected UserDetails retrieveUser(final String arg0, final UsernamePasswordAuthenticationToken arg1) throws AuthenticationException {
return null;
}
/**
* @return Returns the forcePrincipalAsString.
*/
@Override
public boolean isForcePrincipalAsString() {
return forcePrincipalAsString;
}
/**
* @param forcePrincipalAsString
* The forcePrincipalAsString to set.
*/
@Override
public void setForcePrincipalAsString(final boolean forcePrincipalAsString) {
this.forcePrincipalAsString = forcePrincipalAsString;
}
}
| false | true | public Authentication authenticate(final Authentication authentication)
throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
messageSourceAccessor.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
"Only UsernamePasswordAuthenticationToken is supported"));
if (!configManager.isStudentsLoginEnabled()) {
throw new AuthenticationServiceException("Login disabled for student role.");
}
if (!StringUtils.isEmpty(configManager.getRadiusHost()) && !StringUtils.isEmpty(configManager.getRadiusSharedSecret())) {
// Determine username
final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
final String password = (authentication.getCredentials() == null) ? "NONE_PROVIDED"
: (String) authentication.getCredentials();
UserBean userBean;
try {
userBean = getRemoteUserInfos(username, password);
if (!userBean.getRole().equals("student")) {
throw new AuthenticationServiceException("Only student role allowed.");
}
try {
userManager.getUserByUsername(userBean.getLogin());
} catch (final UsernameNotFoundException e) {
final User user = new User();
user.setEnabled(true);
user.setUsername(userBean.getLogin());
user.setFirstName(userBean.getFirstName() == null ? "" : userBean.getFirstName());
user.setLastName(userBean.getName() == null ? "" : userBean.getName());
user.setEmail(userBean.getEmail() == null ? "" : userBean.getEmail());
user.setPassword(StringUtil.encodePassword(userBean.getPassword(), "SHA"));
user.addRole(roleManager.getRole("student"));
try {
userManager.saveUser(user);
} catch (final UserExistsException e2) {
// should not happen
throw new RuntimeException(e2);
}
}
} catch (final AuthenticationServiceException e) {
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials", "Invalid username or password."));
}
final UserDetails userDetails = userManager.getUserByUsername(username);
Object principalToReturn = userDetails;
if (forcePrincipalAsString) {
principalToReturn = userDetails.getUsername();
}
return createSuccessAuthentication(principalToReturn, authentication, userDetails);
}
return null;
}
| public Authentication authenticate(final Authentication authentication)
throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
messageSourceAccessor.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
"Only UsernamePasswordAuthenticationToken is supported"));
if (!StringUtils.isEmpty(configManager.getRadiusHost()) && !StringUtils.isEmpty(configManager.getRadiusSharedSecret())) {
// Determine username
final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
final String password = (authentication.getCredentials() == null) ? "NONE_PROVIDED"
: (String) authentication.getCredentials();
UserBean userBean;
try {
userBean = getRemoteUserInfos(username, password);
if (userBean.getRole().equals("student") && !configManager.isStudentsLoginEnabled())
throw new AuthenticationServiceException("Login disabled for student role.");
try {
userManager.getUserByUsername(userBean.getLogin());
} catch (final UsernameNotFoundException e) {
final User user = new User();
user.setEnabled(true);
user.setUsername(userBean.getLogin());
user.setFirstName(userBean.getFirstName() == null ? "" : userBean.getFirstName());
user.setLastName(userBean.getName() == null ? "" : userBean.getName());
user.setEmail(userBean.getEmail() == null ? "" : userBean.getEmail());
user.setPassword(StringUtil.encodePassword(userBean.getPassword(), "SHA"));
user.addRole(roleManager.getRole("student"));
try {
userManager.saveUser(user);
} catch (final UserExistsException e2) {
// should not happen
throw new RuntimeException(e2);
}
}
} catch (final AuthenticationServiceException e) {
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials", "Invalid username or password."));
}
final UserDetails userDetails = userManager.getUserByUsername(username);
Object principalToReturn = userDetails;
if (forcePrincipalAsString) {
principalToReturn = userDetails.getUsername();
}
return createSuccessAuthentication(principalToReturn, authentication, userDetails);
}
return null;
}
|
diff --git a/Balls.java b/Balls.java
index 136440d..75944ba 100644
--- a/Balls.java
+++ b/Balls.java
@@ -1,130 +1,136 @@
import java.util.ArrayList;
public class Balls implements Runnable {
ArrayList<Ball> ballList;
Game gui;
final static int MAXIMUM_ANGLE = 75;
public Balls(Game game) {
// TODO Auto-generated constructor stub
ballList = new ArrayList<Ball>();
gui = game;
}
public boolean isEmpty() {
return ballList.isEmpty();
}
public ArrayList<Ball> getList() {
return ballList;
}
public void add(double x, double y, double dx, double dy, double radius) {
ballList.add(new Ball(x, y, dx, dy, radius));
}
@Override
public void run() {
// TODO Auto-generated method stub
Ball b;
while (true) {
for (int i = 0; i < ballList.size(); i++) {
b = ballList.get(i);
b.setX(b.getX() + b.getDX());
b.setY(b.getY() + b.getDY());
// TODO Remove X Bounce
/*
* X Bounce
*/
if (b.getX() - b.getRadius() < 0
|| b.getX() + b.getRadius() > gui.getGUIWidth()) {
b.setDX(-b.getDX());
}
/*
* Y Bounce
*/
- if (b.getY() - b.getRadius() < 0
- || b.getY() + b.getRadius() > gui.getGUIHeight()) {
+ if (b.getY() - b.getRadius() < 0 && b.getDY() < 0
+ || b.getY() + b.getRadius() > gui.getGUIHeight() && b.getDY() > 0) {
b.setDY(-b.getDY());
}
/*
* Paddle1 Bounce
*/
Paddle paddle1 = gui.getPaddle1();
if (b.getX() - b.getRadius() <= paddle1.getX()
+ paddle1.getThick()
&& b.getX() - b.getRadius() > paddle1.getX()
- paddle1.getThick()
&& paddle1.isRangeY(b.getY()) && b.getDX() < 0) {
double x = paddle1.getLength() / Math.tan(Math.toRadians(MAXIMUM_ANGLE)) / 2;
double theta = Math.atan((b.getY() - paddle1.getY()) / x);
double phi = -Math.atan(b.getDY() / b.getDX());
double phi2;
// System.out.println("theta:"+Math.toDegrees(theta)+" phi:"+Math.toDegrees(phi));
if(theta == 0)
phi2 = phi;
else if(theta > 0)
{
if(phi >= theta)
phi2 = (Math.toRadians(90) + phi)/2;
else
phi2 = (phi+theta)/2;
}
else
{
if(phi <= theta)
phi2 = (Math.toRadians(-90) + phi)/2;
else
phi2 = (phi+theta)/2;
}
+ if(phi > Math.toRadians(MAXIMUM_ANGLE))
+ phi = Math.toRadians(MAXIMUM_ANGLE);
+ if(phi < Math.toRadians(-MAXIMUM_ANGLE))
+ phi = Math.toRadians(-MAXIMUM_ANGLE);
+ if(Math.abs(phi) < Math.toRadians(5))
+ phi = Math.random()*10-5;
// System.out.println("phi2: "+Math.toDegrees(phi2));
double v = Math.sqrt(Math.pow(b.getDX(), 2)+Math.pow(b.getDY(), 2));
b.setDX(Math.cos(phi2)*v);
b.setDY(Math.sin(phi2)*v);
}
/*
* Paddle2 Bounce
*/
Paddle paddle2 = gui.getPaddle2();
if (b.getX() + b.getRadius() <= paddle2.getX()
+ paddle2.getThick()
&& b.getX() + b.getRadius() > paddle2.getX()
- paddle2.getThick()
&& paddle2.isRangeY(b.getY()) && b.getDX() > 0) {
double x = paddle2.getLength() / Math.tan(Math.toRadians(MAXIMUM_ANGLE)) / 2;
double theta = Math.atan((b.getY() - paddle2.getY()) / x);
double phi = -Math.atan(b.getDY() / b.getDX());
double phi2;
// System.out.println("theta:"+Math.toDegrees(theta)+" phi:"+Math.toDegrees(phi));
if(theta == 0)
phi2 = phi;
else if(theta > 0)
{
if(phi >= theta)
phi2 = phi;
else
phi2 = (phi+theta)/2;
}
else
{
if(phi <= theta)
phi2 = phi;
else
phi2 = (phi+theta)/2;
}
// System.out.println("phi2: "+Math.toDegrees(phi2));
double v = Math.sqrt(Math.pow(b.getDX(), 2)+Math.pow(b.getDY(), 2));
b.setDX(-Math.cos(phi2)*v);
b.setDY(Math.sin(phi2)*v);
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| false | true | public void run() {
// TODO Auto-generated method stub
Ball b;
while (true) {
for (int i = 0; i < ballList.size(); i++) {
b = ballList.get(i);
b.setX(b.getX() + b.getDX());
b.setY(b.getY() + b.getDY());
// TODO Remove X Bounce
/*
* X Bounce
*/
if (b.getX() - b.getRadius() < 0
|| b.getX() + b.getRadius() > gui.getGUIWidth()) {
b.setDX(-b.getDX());
}
/*
* Y Bounce
*/
if (b.getY() - b.getRadius() < 0
|| b.getY() + b.getRadius() > gui.getGUIHeight()) {
b.setDY(-b.getDY());
}
/*
* Paddle1 Bounce
*/
Paddle paddle1 = gui.getPaddle1();
if (b.getX() - b.getRadius() <= paddle1.getX()
+ paddle1.getThick()
&& b.getX() - b.getRadius() > paddle1.getX()
- paddle1.getThick()
&& paddle1.isRangeY(b.getY()) && b.getDX() < 0) {
double x = paddle1.getLength() / Math.tan(Math.toRadians(MAXIMUM_ANGLE)) / 2;
double theta = Math.atan((b.getY() - paddle1.getY()) / x);
double phi = -Math.atan(b.getDY() / b.getDX());
double phi2;
// System.out.println("theta:"+Math.toDegrees(theta)+" phi:"+Math.toDegrees(phi));
if(theta == 0)
phi2 = phi;
else if(theta > 0)
{
if(phi >= theta)
phi2 = (Math.toRadians(90) + phi)/2;
else
phi2 = (phi+theta)/2;
}
else
{
if(phi <= theta)
phi2 = (Math.toRadians(-90) + phi)/2;
else
phi2 = (phi+theta)/2;
}
// System.out.println("phi2: "+Math.toDegrees(phi2));
double v = Math.sqrt(Math.pow(b.getDX(), 2)+Math.pow(b.getDY(), 2));
b.setDX(Math.cos(phi2)*v);
b.setDY(Math.sin(phi2)*v);
}
/*
* Paddle2 Bounce
*/
Paddle paddle2 = gui.getPaddle2();
if (b.getX() + b.getRadius() <= paddle2.getX()
+ paddle2.getThick()
&& b.getX() + b.getRadius() > paddle2.getX()
- paddle2.getThick()
&& paddle2.isRangeY(b.getY()) && b.getDX() > 0) {
double x = paddle2.getLength() / Math.tan(Math.toRadians(MAXIMUM_ANGLE)) / 2;
double theta = Math.atan((b.getY() - paddle2.getY()) / x);
double phi = -Math.atan(b.getDY() / b.getDX());
double phi2;
// System.out.println("theta:"+Math.toDegrees(theta)+" phi:"+Math.toDegrees(phi));
if(theta == 0)
phi2 = phi;
else if(theta > 0)
{
if(phi >= theta)
phi2 = phi;
else
phi2 = (phi+theta)/2;
}
else
{
if(phi <= theta)
phi2 = phi;
else
phi2 = (phi+theta)/2;
}
// System.out.println("phi2: "+Math.toDegrees(phi2));
double v = Math.sqrt(Math.pow(b.getDX(), 2)+Math.pow(b.getDY(), 2));
b.setDX(-Math.cos(phi2)*v);
b.setDY(Math.sin(phi2)*v);
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| public void run() {
// TODO Auto-generated method stub
Ball b;
while (true) {
for (int i = 0; i < ballList.size(); i++) {
b = ballList.get(i);
b.setX(b.getX() + b.getDX());
b.setY(b.getY() + b.getDY());
// TODO Remove X Bounce
/*
* X Bounce
*/
if (b.getX() - b.getRadius() < 0
|| b.getX() + b.getRadius() > gui.getGUIWidth()) {
b.setDX(-b.getDX());
}
/*
* Y Bounce
*/
if (b.getY() - b.getRadius() < 0 && b.getDY() < 0
|| b.getY() + b.getRadius() > gui.getGUIHeight() && b.getDY() > 0) {
b.setDY(-b.getDY());
}
/*
* Paddle1 Bounce
*/
Paddle paddle1 = gui.getPaddle1();
if (b.getX() - b.getRadius() <= paddle1.getX()
+ paddle1.getThick()
&& b.getX() - b.getRadius() > paddle1.getX()
- paddle1.getThick()
&& paddle1.isRangeY(b.getY()) && b.getDX() < 0) {
double x = paddle1.getLength() / Math.tan(Math.toRadians(MAXIMUM_ANGLE)) / 2;
double theta = Math.atan((b.getY() - paddle1.getY()) / x);
double phi = -Math.atan(b.getDY() / b.getDX());
double phi2;
// System.out.println("theta:"+Math.toDegrees(theta)+" phi:"+Math.toDegrees(phi));
if(theta == 0)
phi2 = phi;
else if(theta > 0)
{
if(phi >= theta)
phi2 = (Math.toRadians(90) + phi)/2;
else
phi2 = (phi+theta)/2;
}
else
{
if(phi <= theta)
phi2 = (Math.toRadians(-90) + phi)/2;
else
phi2 = (phi+theta)/2;
}
if(phi > Math.toRadians(MAXIMUM_ANGLE))
phi = Math.toRadians(MAXIMUM_ANGLE);
if(phi < Math.toRadians(-MAXIMUM_ANGLE))
phi = Math.toRadians(-MAXIMUM_ANGLE);
if(Math.abs(phi) < Math.toRadians(5))
phi = Math.random()*10-5;
// System.out.println("phi2: "+Math.toDegrees(phi2));
double v = Math.sqrt(Math.pow(b.getDX(), 2)+Math.pow(b.getDY(), 2));
b.setDX(Math.cos(phi2)*v);
b.setDY(Math.sin(phi2)*v);
}
/*
* Paddle2 Bounce
*/
Paddle paddle2 = gui.getPaddle2();
if (b.getX() + b.getRadius() <= paddle2.getX()
+ paddle2.getThick()
&& b.getX() + b.getRadius() > paddle2.getX()
- paddle2.getThick()
&& paddle2.isRangeY(b.getY()) && b.getDX() > 0) {
double x = paddle2.getLength() / Math.tan(Math.toRadians(MAXIMUM_ANGLE)) / 2;
double theta = Math.atan((b.getY() - paddle2.getY()) / x);
double phi = -Math.atan(b.getDY() / b.getDX());
double phi2;
// System.out.println("theta:"+Math.toDegrees(theta)+" phi:"+Math.toDegrees(phi));
if(theta == 0)
phi2 = phi;
else if(theta > 0)
{
if(phi >= theta)
phi2 = phi;
else
phi2 = (phi+theta)/2;
}
else
{
if(phi <= theta)
phi2 = phi;
else
phi2 = (phi+theta)/2;
}
// System.out.println("phi2: "+Math.toDegrees(phi2));
double v = Math.sqrt(Math.pow(b.getDX(), 2)+Math.pow(b.getDY(), 2));
b.setDX(-Math.cos(phi2)*v);
b.setDY(Math.sin(phi2)*v);
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
diff --git a/src/com/modcrafting/diablodrops/items/Socket.java b/src/com/modcrafting/diablodrops/items/Socket.java
index 88b882c..3187064 100644
--- a/src/com/modcrafting/diablodrops/items/Socket.java
+++ b/src/com/modcrafting/diablodrops/items/Socket.java
@@ -1,69 +1,69 @@
package com.modcrafting.diablodrops.items;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.material.MaterialData;
import com.modcrafting.diablodrops.DiabloDrops;
public class Socket extends ItemStack
{
public enum SkullType {
SKELETON(0), WITHER(1), ZOMBIE(2), PLAYER(3), CREEPER(4);
public int type;
private SkullType(final int i) {
type = i;
}
public byte getData() {
return (byte) type;
}
}
public Socket(final Material mat)
{
super(mat);
ChatColor color = null;
switch (DiabloDrops.getInstance().gen.nextInt(3))
{
case 1:
color = ChatColor.RED;
break;
case 2:
color = ChatColor.BLUE;
break;
default:
color = ChatColor.GREEN;
}
ItemMeta meta = this.getItemMeta();
meta.setDisplayName(color + "Socket Enhancement");
List<String> list = new ArrayList<String>();
list.add(ChatColor.GOLD + "Put in the bottom of a furnace");
list.add(ChatColor.GOLD + "with another item in the top");
list.add(ChatColor.GOLD + "to add socket enhancements.");
if (mat.equals(Material.SKULL_ITEM))
{
SkullMeta sk = (SkullMeta) meta;
SkullType type = SkullType.values()[DiabloDrops.getInstance().gen
.nextInt(SkullType.values().length)];
- if (type.equals(SkullType.PLAYER))
+ if (type.equals(SkullType.PLAYER)){
sk.setOwner(Bukkit.getServer().getOfflinePlayers()[DiabloDrops
.getInstance().gen.nextInt(Bukkit.getServer()
.getOfflinePlayers().length)].getName());
- else{
- MaterialData md = this.getData();
- md.setData(type.getData());
- this.setData(md);
}
+ MaterialData md = this.getData();
+ md.setData(type.getData());
+ this.setData(md);
}
+ this.setItemMeta(meta);
}
}
| false | true | public Socket(final Material mat)
{
super(mat);
ChatColor color = null;
switch (DiabloDrops.getInstance().gen.nextInt(3))
{
case 1:
color = ChatColor.RED;
break;
case 2:
color = ChatColor.BLUE;
break;
default:
color = ChatColor.GREEN;
}
ItemMeta meta = this.getItemMeta();
meta.setDisplayName(color + "Socket Enhancement");
List<String> list = new ArrayList<String>();
list.add(ChatColor.GOLD + "Put in the bottom of a furnace");
list.add(ChatColor.GOLD + "with another item in the top");
list.add(ChatColor.GOLD + "to add socket enhancements.");
if (mat.equals(Material.SKULL_ITEM))
{
SkullMeta sk = (SkullMeta) meta;
SkullType type = SkullType.values()[DiabloDrops.getInstance().gen
.nextInt(SkullType.values().length)];
if (type.equals(SkullType.PLAYER))
sk.setOwner(Bukkit.getServer().getOfflinePlayers()[DiabloDrops
.getInstance().gen.nextInt(Bukkit.getServer()
.getOfflinePlayers().length)].getName());
else{
MaterialData md = this.getData();
md.setData(type.getData());
this.setData(md);
}
}
}
| public Socket(final Material mat)
{
super(mat);
ChatColor color = null;
switch (DiabloDrops.getInstance().gen.nextInt(3))
{
case 1:
color = ChatColor.RED;
break;
case 2:
color = ChatColor.BLUE;
break;
default:
color = ChatColor.GREEN;
}
ItemMeta meta = this.getItemMeta();
meta.setDisplayName(color + "Socket Enhancement");
List<String> list = new ArrayList<String>();
list.add(ChatColor.GOLD + "Put in the bottom of a furnace");
list.add(ChatColor.GOLD + "with another item in the top");
list.add(ChatColor.GOLD + "to add socket enhancements.");
if (mat.equals(Material.SKULL_ITEM))
{
SkullMeta sk = (SkullMeta) meta;
SkullType type = SkullType.values()[DiabloDrops.getInstance().gen
.nextInt(SkullType.values().length)];
if (type.equals(SkullType.PLAYER)){
sk.setOwner(Bukkit.getServer().getOfflinePlayers()[DiabloDrops
.getInstance().gen.nextInt(Bukkit.getServer()
.getOfflinePlayers().length)].getName());
}
MaterialData md = this.getData();
md.setData(type.getData());
this.setData(md);
}
this.setItemMeta(meta);
}
|
diff --git a/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2149KahaDBTest.java b/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2149KahaDBTest.java
index 4883edf01..98fc273b8 100644
--- a/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2149KahaDBTest.java
+++ b/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2149KahaDBTest.java
@@ -1,30 +1,30 @@
/**
* 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.activemq.bugs;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter;
public class AMQ2149KahaDBTest extends AMQ2149Test {
@Override
protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception {
// nothing to do as kahaDB is now the default
KahaDBPersistenceAdapter kahaDB = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter();
- kahaDB.setConcurrentStoreAndDispatchTopics(true);
+ kahaDB.setConcurrentStoreAndDispatchTopics(false);
}
}
| true | true | protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception {
// nothing to do as kahaDB is now the default
KahaDBPersistenceAdapter kahaDB = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter();
kahaDB.setConcurrentStoreAndDispatchTopics(true);
}
| protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception {
// nothing to do as kahaDB is now the default
KahaDBPersistenceAdapter kahaDB = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter();
kahaDB.setConcurrentStoreAndDispatchTopics(false);
}
|
diff --git a/bcel-additions/org/apache/bcel/Repository.java b/bcel-additions/org/apache/bcel/Repository.java
index 593fb470..9efab668 100644
--- a/bcel-additions/org/apache/bcel/Repository.java
+++ b/bcel-additions/org/apache/bcel/Repository.java
@@ -1,334 +1,344 @@
package org.apache.bcel;
/* Actually, this is the BCEL Repository, with an added facility to
* let an application know which classes are actually in the Repository.
* A class that wants this, should implement the interface "RepositoryObserver"
* (which contains one method: void notify(String classname); ).
* In addition, it should register itself with the Repository through the
* void registerObserver(RepositoryObserver n); method.
*
* Another fix: the ClassQueue object in BCEL is buggy. Don't use it.
*/
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache BCEL" 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",
* "Apache BCEL", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import org.apache.bcel.classfile.*;
import org.apache.bcel.util.*;
import java.util.HashMap;
import java.io.*;
import java.util.Vector;
/**
* Repository maintains informations about class interdependencies, e.g.
* whether a class is a sub-class of another. JavaClass objects are put
* into a cache which can be purged with clearCache().
*
* All JavaClass objects used as arguments must have been obtained via
* the repository or been added with addClass() manually. This is
* because we have to check for object identity (==).
*
* @version $Id$
* @author <A HREF="mailto:[email protected]">M. Dahm</A
*/
public abstract class Repository {
private static ClassPath class_path = new ClassPath();
private static HashMap classes;
private static JavaClass OBJECT; // should be final ...
private static Vector observers = new Vector();
static { clearCache(); }
/** Register a RepositoryObserver.
*/
public static void registerObserver(RepositoryObserver n) {
for (int i = 0; i < observers.size(); i++) {
if ((RepositoryObserver) (observers.elementAt(i)) == n) return;
}
observers.addElement(n);
}
/** Unregister a RepositoryObserver.
*/
public static void unregisterObserver(RepositoryObserver n) {
observers.removeElement(n);
}
private static void notifyObserver(String n) {
for (int i = 0; i < observers.size(); i++) {
RepositoryObserver w = (RepositoryObserver) (observers.elementAt(i));
w.notify(n);
}
}
/** @return class object for given fully qualified class name.
*/
public static JavaClass lookupClass(String class_name) {
if(class_name == null || class_name.equals(""))
throw new RuntimeException("Invalid class name");
class_name = class_name.replace('/', '.');
JavaClass clazz = (JavaClass)classes.get(class_name);
if(clazz == null) {
try {
InputStream is = class_path.getInputStream(class_name);
clazz = new ClassParser(is, class_name).parse();
class_name = clazz.getClassName();
} catch(IOException e) { return null; }
classes.put(class_name, clazz);
notifyObserver(class_name);
}
return clazz;
}
/** @return class file object for given Java class.
*/
public static ClassPath.ClassFile lookupClassFile(String class_name) {
try {
return class_path.getClassFile(class_name);
} catch(IOException e) { return null; }
}
/** Clear the repository.
*/
public static void clearCache() {
classes = new HashMap();
OBJECT = lookupClass("java.lang.Object");
if(OBJECT == null)
System.err.println("Warning: java.lang.Object not found on CLASSPATH!");
else
classes.put("java.lang.Object", OBJECT);
}
/**
* Add clazz to repository if there isn't an equally named class already in there.
*
* @return old entry in repository
*/
public static JavaClass addClass(JavaClass clazz) {
String name = clazz.getClassName();
JavaClass cl = (JavaClass)classes.get(name);
if(cl == null) {
classes.put(name, cl = clazz);
notifyObserver(name);
}
return cl;
}
/**
* Remove class with given (fully qualifid) name from repository.
*/
public static void removeClass(String clazz) {
classes.remove(clazz);
}
/**
* Remove given class from repository.
*/
public static void removeClass(JavaClass clazz) {
removeClass(clazz.getClassName());
}
private static final JavaClass getSuperClass(JavaClass clazz) {
if(clazz == OBJECT)
return null;
return lookupClass(clazz.getSuperclassName());
}
/**
* @return list of super classes of clazz in ascending order, i.e.,
* Object is always the last element
*/
public static JavaClass[] getSuperClasses(JavaClass clazz) {
ClassVector vec = new ClassVector();
for(clazz = getSuperClass(clazz); clazz != null; clazz = getSuperClass(clazz))
vec.addElement(clazz);
return vec.toArray();
}
/**
* @return list of super classes of clazz in ascending order, i.e.,
* Object is always the last element. "null", if clazz cannot be found.
*/
public static JavaClass[] getSuperClasses(String class_name) {
JavaClass jc = lookupClass(class_name);
return (jc == null? null : getSuperClasses(jc));
}
/**
* @return all interfaces implemented by class and its super
* classes and the interfaces that those interfaces extend, and so on
*/
public static JavaClass[] getInterfaces(JavaClass clazz) {
ClassVector vec = new ClassVector();
Vector queue = new Vector();
queue.addElement(clazz);
while(!queue.isEmpty()) {
clazz = (JavaClass) (queue.firstElement());
queue.remove(clazz);
String s = clazz.getSuperclassName();
String[] interfaces = clazz.getInterfaceNames();
if(clazz.isInterface())
vec.addElement(clazz);
- else if(!s.equals("java.lang.Object"))
- queue.addElement(lookupClass(s));
+ else if(!s.equals("java.lang.Object")) {
+ JavaClass cl = lookupClass(s);
+ if (cl == null) {
+ System.err.println("warning: could not find class " + s);
+ }
+ else queue.addElement(cl);
+ }
- for(int i=0; i < interfaces.length; i++)
- queue.addElement(lookupClass(interfaces[i]));
+ for(int i=0; i < interfaces.length; i++) {
+ JavaClass cl = lookupClass(interfaces[i]);
+ if (cl == null) {
+ System.err.println("warning: could not find interface " + interfaces[i]);
+ }
+ else queue.addElement(cl);
+ }
}
return vec.toArray();
}
/**
* @return all interfaces implemented by class and its super
* classes and the interfaces that extend those interfaces, and so on
*/
public static JavaClass[] getInterfaces(String class_name) {
return getInterfaces(lookupClass(class_name));
}
/**
* @return true, if clazz is an instance of super_class
*/
public static boolean instanceOf(JavaClass clazz, JavaClass super_class) {
if(clazz == super_class)
return true;
JavaClass[] super_classes = getSuperClasses(clazz);
for(int i=0; i < super_classes.length; i++)
if(super_classes[i] == super_class)
return true;
if(super_class.isInterface())
return implementationOf(clazz, super_class);
return false;
}
/**
* @return true, if clazz is an instance of super_class
*/
public static boolean instanceOf(String clazz, String super_class) {
return instanceOf(lookupClass(clazz), lookupClass(super_class));
}
/**
* @return true, if clazz is an instance of super_class
*/
public static boolean instanceOf(JavaClass clazz, String super_class) {
return instanceOf(clazz, lookupClass(super_class));
}
/**
* @return true, if clazz is an instance of super_class
*/
public static boolean instanceOf(String clazz, JavaClass super_class) {
return instanceOf(lookupClass(clazz), super_class);
}
/**
* @return true, if clazz is an implementation of interface inter
*/
public static boolean implementationOf(JavaClass clazz, JavaClass inter) {
if(clazz == inter)
return true;
JavaClass[] super_interfaces = getInterfaces(clazz);
for(int i=0; i < super_interfaces.length; i++) {
if(super_interfaces[i] == inter)
return true;
}
return false;
}
/**
* @return true, if clazz is an implementation of interface inter
*/
public static boolean implementationOf(String clazz, String inter) {
return implementationOf(lookupClass(clazz), lookupClass(inter));
}
/**
* @return true, if clazz is an implementation of interface inter
*/
public static boolean implementationOf(JavaClass clazz, String inter) {
return implementationOf(clazz, lookupClass(inter));
}
/**
* @return true, if clazz is an implementation of interface inter
*/
public static boolean implementationOf(String clazz, JavaClass inter) {
return implementationOf(lookupClass(clazz), inter);
}
}
| false | true | public static JavaClass[] getInterfaces(JavaClass clazz) {
ClassVector vec = new ClassVector();
Vector queue = new Vector();
queue.addElement(clazz);
while(!queue.isEmpty()) {
clazz = (JavaClass) (queue.firstElement());
queue.remove(clazz);
String s = clazz.getSuperclassName();
String[] interfaces = clazz.getInterfaceNames();
if(clazz.isInterface())
vec.addElement(clazz);
else if(!s.equals("java.lang.Object"))
queue.addElement(lookupClass(s));
for(int i=0; i < interfaces.length; i++)
queue.addElement(lookupClass(interfaces[i]));
}
return vec.toArray();
}
| public static JavaClass[] getInterfaces(JavaClass clazz) {
ClassVector vec = new ClassVector();
Vector queue = new Vector();
queue.addElement(clazz);
while(!queue.isEmpty()) {
clazz = (JavaClass) (queue.firstElement());
queue.remove(clazz);
String s = clazz.getSuperclassName();
String[] interfaces = clazz.getInterfaceNames();
if(clazz.isInterface())
vec.addElement(clazz);
else if(!s.equals("java.lang.Object")) {
JavaClass cl = lookupClass(s);
if (cl == null) {
System.err.println("warning: could not find class " + s);
}
else queue.addElement(cl);
}
for(int i=0; i < interfaces.length; i++) {
JavaClass cl = lookupClass(interfaces[i]);
if (cl == null) {
System.err.println("warning: could not find interface " + interfaces[i]);
}
else queue.addElement(cl);
}
}
return vec.toArray();
}
|
diff --git a/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/compiler/TestCompilerMojo.java b/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/compiler/TestCompilerMojo.java
index 684b9a661..486aee759 100644
--- a/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/compiler/TestCompilerMojo.java
+++ b/flexmojos-maven-plugin/src/main/java/org/sonatype/flexmojos/compiler/TestCompilerMojo.java
@@ -1,363 +1,363 @@
/**
* Flexmojos is a set of maven goals to allow maven users to compile, optimize and test Flex SWF, Flex SWC, Air SWF and Air SWC.
* Copyright (C) 2008-2012 Marvin Froeder <[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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sonatype.flexmojos.compiler;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.DirectoryScanner;
import org.sonatype.flexmojos.utilities.MavenUtils;
/**
* Goal to compile the Flex test sources.
*
* @author Marvin Herman Froeder ([email protected])
* @since 1.0
* @goal test-compile
* @requiresDependencyResolution
* @phase test
*/
public class TestCompilerMojo
extends ApplicationMojo
{
/**
* Set this to 'true' to bypass unit tests entirely. Its use is NOT RECOMMENDED, but quite convenient on occasion.
*
* @parameter expression="${maven.test.skip}"
*/
private boolean skipTests;
/**
* @parameter
*/
private File testRunnerTemplate;
/**
* File to be tested. If not defined assumes Test*.as and *Test.as
*
* @parameter
*/
private String[] includeTestFiles;
/**
* Files to exclude from testing. If not defined, assumes no exclusions
*
* @parameter
*/
private String[] excludeTestFiles;
/**
* @parameter expression="${project.build.testSourceDirectory}"
* @readonly
*/
private File testFolder;
/**
* Socket connect port for flex/java communication to transfer tests results
*
* @parameter default-value="13539" expression="${testPort}"
*/
private int testPort;
/**
* Socket connect port for flex/java communication to control if flashplayer is alive
*
* @parameter default-value="13540" expression="${testControlPort}"
*/
private int testControlPort;
@Override
public void execute()
throws MojoExecutionException, MojoFailureException
{
getLog().info(
"flexmojos " + MavenUtils.getFlexMojosVersion()
+ " - GNU GPL License (NO WARRANTY) - See COPYRIGHT file" );
if ( skipTests )
{
getLog().warn( "Skipping test phase." );
return;
}
else if ( !testFolder.exists() )
{
getLog().warn( "Test folder not found" + testFolder );
return;
}
setUp();
run();
tearDown();
}
@Override
public void setUp()
throws MojoExecutionException, MojoFailureException
{
isSetProjectFile = false;
linkReport = false;
loadExterns = null;
if ( includeTestFiles == null || includeTestFiles.length == 0 )
{
includeTestFiles = new String[] { "**/Test*.as", "**/*Test.as" };
}
else
{
for ( int i = 0; i < includeTestFiles.length; i++ )
{
String pattern = includeTestFiles[i];
- if ( pattern.startsWith( "/" ) )
+ if ( pattern.endsWith( ".java" ) )
{
- continue;
+ pattern = pattern.substring( 0, pattern.length() - 5 );
}
- // keeping backward compatibility with previous wildcard
- pattern = "**/" + pattern;
- includeTestFiles[i] = pattern;
+ // Allow paths delimited by '.' or '/'
+ pattern = pattern.replace( '.', '/' );
+ includeTestFiles[i] = "**/" + pattern + ".java";
}
}
File outputFolder = new File( build.getTestOutputDirectory() );
if ( !outputFolder.exists() )
{
outputFolder.mkdirs();
}
List<String> testClasses = getTestClasses();
File testSourceFile;
try
{
testSourceFile = generateTester( testClasses );
}
catch ( Exception e )
{
throw new MojoExecutionException( "Unable to generate tester class.", e );
}
sourceFile = null;
source = testSourceFile;
super.setUp();
}
private List<String> getTestClasses()
{
getLog().debug(
"Scanning for tests at " + testFolder + " for " + Arrays.toString( includeTestFiles ) + " but "
+ Arrays.toString( excludeTestFiles ) );
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes( includeTestFiles );
scanner.setExcludes( excludeTestFiles );
scanner.addDefaultExcludes();
scanner.setBasedir( testFolder );
scanner.scan();
getLog().debug( "Test files: " + scanner.getIncludedFiles() );
List<String> testClasses = new ArrayList<String>();
for ( String testClass : scanner.getIncludedFiles() )
{
int endPoint = testClass.lastIndexOf( '.' );
testClass = testClass.substring( 0, endPoint ); // remove extension
testClass = testClass.replace( '/', '.' ); // Unix OS
testClass = testClass.replace( '\\', '.' ); // Windows OS
testClasses.add( testClass );
}
getLog().debug( "Test classes: " + testClasses );
return testClasses;
}
private File generateTester( List<String> testClasses )
throws Exception
{
// can't use velocity, got:
// java.io.InvalidClassException:
// org.apache.velocity.runtime.parser.node.ASTprocess; class invalid for
// deserialization
StringBuilder imports = new StringBuilder();
for ( String testClass : testClasses )
{
imports.append( "import " );
imports.append( testClass );
imports.append( ";" );
imports.append( '\n' );
}
StringBuilder classes = new StringBuilder();
for ( String testClass : testClasses )
{
testClass = testClass.substring( testClass.lastIndexOf( '.' ) + 1 );
classes.append( "addTest( " );
classes.append( testClass );
classes.append( ");" );
classes.append( '\n' );
}
InputStream templateSource = getTemplate();
String sourceString = IOUtils.toString( templateSource );
sourceString = sourceString.replace( "$imports", imports );
sourceString = sourceString.replace( "$testClasses", classes );
sourceString = sourceString.replace( "$port", String.valueOf( testPort ) );
sourceString = sourceString.replace( "$controlPort", String.valueOf( testControlPort ) );
File testSourceFile = new File( build.getTestOutputDirectory(), "TestRunner.mxml" );
FileWriter fileWriter = new FileWriter( testSourceFile );
IOUtils.write( sourceString, fileWriter );
fileWriter.flush();
fileWriter.close();
return testSourceFile;
}
private InputStream getTemplate()
throws MojoExecutionException
{
if ( testRunnerTemplate == null )
{
return getClass().getResourceAsStream( "/templates/test/TestRunner.vm" );
}
else if ( !testRunnerTemplate.exists() )
{
throw new MojoExecutionException( "Template file not found: " + testRunnerTemplate );
}
else
{
try
{
return new FileInputStream( testRunnerTemplate );
}
catch ( FileNotFoundException e )
{
// Never should happen
throw new MojoExecutionException( "Error reading template file", e );
}
}
}
@Override
protected void configure()
throws MojoExecutionException, MojoFailureException
{
compiledLocales = getLocales();
runtimeLocales = null;
super.configure();
// test launcher is at testOutputDirectory
configuration.addSourcePath( new File[] { new File( build.getTestOutputDirectory() ) } );
configuration.addSourcePath( getValidSourceRoots( project.getTestCompileSourceRoots() ).toArray( new File[0] ) );
if ( getResource( compiledLocales[0] ) != null )
{
configuration.addSourcePath( new File[] { new File( resourceBundlePath ) } );
}
configuration.allowSourcePathOverlap( true );
configuration.enableDebugging( true, super.debugPassword );
}
private File getResource( String locale )
{
try
{
return MavenUtils.getLocaleResourcePath( resourceBundlePath, locale );
}
catch ( MojoExecutionException e )
{
return null;
}
}
@Override
protected void resolveDependencies()
throws MojoExecutionException, MojoFailureException
{
configuration.setExternalLibraryPath( getGlobalDependency() );
// Set all dependencies as merged
configuration.setLibraryPath( getDependenciesPath( "compile" ) );
configuration.addLibraryPath( getDependenciesPath( "merged" ) );
configuration.addLibraryPath( merge( getResourcesBundles( getDefaultLocale() ),
getResourcesBundles( runtimeLocales ),
getResourcesBundles( compiledLocales ) ) );
// and add test libraries
configuration.includeLibraries( merge( getDependenciesPath( "internal" ), getDependenciesPath( "test" ),
getDependenciesPath( "rsl" ), getDependenciesPath( "caching" ),
getDependenciesPath( "external" ) ) );
configuration.setTheme( getThemes() );
}
private String[] getLocales()
{
if ( runtimeLocales == null && compiledLocales == null )
{
return new String[] { getDefaultLocale() };
}
Set<String> locales = new LinkedHashSet<String>();
if ( runtimeLocales != null )
{
locales.addAll( Arrays.asList( runtimeLocales ) );
}
if ( compiledLocales != null )
{
locales.addAll( Arrays.asList( compiledLocales ) );
}
return locales.toArray( new String[0] );
}
private File[] merge( File[]... filesSets )
{
List<File> files = new ArrayList<File>();
for ( File[] fileSet : filesSets )
{
files.addAll( Arrays.asList( fileSet ) );
}
return files.toArray( new File[0] );
}
@Override
protected File getOutput()
{
return new File( build.getTestOutputDirectory(), "TestRunner.swf" );
}
@Override
protected void compileModules()
throws MojoFailureException, MojoExecutionException
{
// modules are ignored on unit tests
}
}
| false | true | public void setUp()
throws MojoExecutionException, MojoFailureException
{
isSetProjectFile = false;
linkReport = false;
loadExterns = null;
if ( includeTestFiles == null || includeTestFiles.length == 0 )
{
includeTestFiles = new String[] { "**/Test*.as", "**/*Test.as" };
}
else
{
for ( int i = 0; i < includeTestFiles.length; i++ )
{
String pattern = includeTestFiles[i];
if ( pattern.startsWith( "/" ) )
{
continue;
}
// keeping backward compatibility with previous wildcard
pattern = "**/" + pattern;
includeTestFiles[i] = pattern;
}
}
File outputFolder = new File( build.getTestOutputDirectory() );
if ( !outputFolder.exists() )
{
outputFolder.mkdirs();
}
List<String> testClasses = getTestClasses();
File testSourceFile;
try
{
testSourceFile = generateTester( testClasses );
}
catch ( Exception e )
{
throw new MojoExecutionException( "Unable to generate tester class.", e );
}
sourceFile = null;
source = testSourceFile;
super.setUp();
}
| public void setUp()
throws MojoExecutionException, MojoFailureException
{
isSetProjectFile = false;
linkReport = false;
loadExterns = null;
if ( includeTestFiles == null || includeTestFiles.length == 0 )
{
includeTestFiles = new String[] { "**/Test*.as", "**/*Test.as" };
}
else
{
for ( int i = 0; i < includeTestFiles.length; i++ )
{
String pattern = includeTestFiles[i];
if ( pattern.endsWith( ".java" ) )
{
pattern = pattern.substring( 0, pattern.length() - 5 );
}
// Allow paths delimited by '.' or '/'
pattern = pattern.replace( '.', '/' );
includeTestFiles[i] = "**/" + pattern + ".java";
}
}
File outputFolder = new File( build.getTestOutputDirectory() );
if ( !outputFolder.exists() )
{
outputFolder.mkdirs();
}
List<String> testClasses = getTestClasses();
File testSourceFile;
try
{
testSourceFile = generateTester( testClasses );
}
catch ( Exception e )
{
throw new MojoExecutionException( "Unable to generate tester class.", e );
}
sourceFile = null;
source = testSourceFile;
super.setUp();
}
|
diff --git a/src/com/dmdirc/plugins/PluginClassLoader.java b/src/com/dmdirc/plugins/PluginClassLoader.java
index 98f0ec060..fa453e13a 100644
--- a/src/com/dmdirc/plugins/PluginClassLoader.java
+++ b/src/com/dmdirc/plugins/PluginClassLoader.java
@@ -1,170 +1,170 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.plugins;
import com.dmdirc.util.resourcemanager.ResourceManager;
import java.io.IOException;
public class PluginClassLoader extends ClassLoader {
/** The plugin Info object for the plugin we are loading. */
final PluginInfo pluginInfo;
/**
* Create a new PluginClassLoader.
*
* @param info PluginInfo this classloader will be for
*/
public PluginClassLoader(final PluginInfo info) {
super();
pluginInfo = info;
}
/**
* Create a new PluginClassLoader.
*
* @param info PluginInfo this classloader will be for
* @param parent Parent ClassLoader
*/
private PluginClassLoader(final PluginInfo info, final PluginClassLoader parent) {
super(parent);
pluginInfo = info;
}
/**
* Get a PluginClassLoader that is a subclassloader of this one.
*
* @param info PluginInfo the new classloader will be for
* @return A classloader configured with this one as its parent
*/
public PluginClassLoader getSubClassLoader(final PluginInfo info) {
return (new PluginClassLoader(info, this));
}
/**
* Load the plugin with the given className
*
* @param name Class Name of plugin
* @return plugin class
* @throws ClassNotFoundException if the class to be loaded could not be found.
*/
@Override
public Class<?> loadClass(final String name) throws ClassNotFoundException {
return loadClass(name, true);
}
/**
* Have we already loaded the given class name?
*
* @param name Name to check.
* @param checkGlobal Should we check if the GCL has loaded it aswell?
* @return True if the specified class is loaded, false otherwise
*/
public boolean isClassLoaded(final String name, final boolean checkGlobal) {
// Don't duplicate a class
final Class existing = findLoadedClass(name);
final boolean gcl = (checkGlobal) ? GlobalClassLoader.getGlobalClassLoader().isClassLoaded(name) : false;
return (existing != null || gcl);
}
/**
* Load the plugin with the given className
*
* @param name Class Name of plugin
* @param askGlobal Ask the gobal class loaded for this class if we can't find it?
* @return plugin class
* @throws ClassNotFoundException if the class to be loaded could not be found.
*/
@Override
public Class<?> loadClass(final String name, final boolean askGlobal) throws ClassNotFoundException {
Class< ? > loadedClass = null;
if (getParent() instanceof PluginClassLoader) {
try {
- loadedClass = ((PluginClassLoader)getParent()).loadClass(name, askGlobal);
+ loadedClass = ((PluginClassLoader)getParent()).loadClass(name, false);
if (loadedClass != null) {
return loadedClass;
}
} catch (ClassNotFoundException cnfe) {
/* Parent doesn't have the class, load ourself */
}
}
ResourceManager res;
try {
res = pluginInfo.getResourceManager();
} catch (IOException ioe) {
throw new ClassNotFoundException("Error with resourcemanager", ioe);
}
final String fileName = name.replace('.', '/')+".class";
try {
if (pluginInfo.isPersistent(name) || !res.resourceExists(fileName)) {
if (!pluginInfo.isPersistent(name) && askGlobal) {
return GlobalClassLoader.getGlobalClassLoader().loadClass(name);
} else {
// Try to load class from previous load.
try {
if (askGlobal) {
return GlobalClassLoader.getGlobalClassLoader().loadClass(name, pluginInfo);
}
} catch (ClassNotFoundException e) {
/* Class doesn't exist, we load it ourself below */
}
}
}
} catch (NoClassDefFoundError e) {
throw new ClassNotFoundException("Error loading '"+name+"' (wanted by "+pluginInfo.getName()+") -> "+e.getMessage(), e);
}
// Don't duplicate a class
if (isClassLoaded(name, false)) { return findLoadedClass(name); }
// We are ment to be loading this one!
byte[] data = null;
if (res.resourceExists(fileName)) {
data = res.getResourceBytes(fileName);
} else {
throw new ClassNotFoundException("Resource '"+name+"' (wanted by "+pluginInfo.getName()+") does not exist.");
}
try {
if (pluginInfo.isPersistent(name)) {
GlobalClassLoader.getGlobalClassLoader().defineClass(name, data);
} else {
loadedClass = defineClass(name, data, 0, data.length);
}
} catch (NoClassDefFoundError e) {
throw new ClassNotFoundException(e.getMessage(), e);
}
if (loadedClass == null) {
throw new ClassNotFoundException("Could not load " + name);
} else {
resolveClass(loadedClass);
}
return loadedClass;
}
}
| true | true | public Class<?> loadClass(final String name, final boolean askGlobal) throws ClassNotFoundException {
Class< ? > loadedClass = null;
if (getParent() instanceof PluginClassLoader) {
try {
loadedClass = ((PluginClassLoader)getParent()).loadClass(name, askGlobal);
if (loadedClass != null) {
return loadedClass;
}
} catch (ClassNotFoundException cnfe) {
/* Parent doesn't have the class, load ourself */
}
}
ResourceManager res;
try {
res = pluginInfo.getResourceManager();
} catch (IOException ioe) {
throw new ClassNotFoundException("Error with resourcemanager", ioe);
}
final String fileName = name.replace('.', '/')+".class";
try {
if (pluginInfo.isPersistent(name) || !res.resourceExists(fileName)) {
if (!pluginInfo.isPersistent(name) && askGlobal) {
return GlobalClassLoader.getGlobalClassLoader().loadClass(name);
} else {
// Try to load class from previous load.
try {
if (askGlobal) {
return GlobalClassLoader.getGlobalClassLoader().loadClass(name, pluginInfo);
}
} catch (ClassNotFoundException e) {
/* Class doesn't exist, we load it ourself below */
}
}
}
} catch (NoClassDefFoundError e) {
throw new ClassNotFoundException("Error loading '"+name+"' (wanted by "+pluginInfo.getName()+") -> "+e.getMessage(), e);
}
// Don't duplicate a class
if (isClassLoaded(name, false)) { return findLoadedClass(name); }
// We are ment to be loading this one!
byte[] data = null;
if (res.resourceExists(fileName)) {
data = res.getResourceBytes(fileName);
} else {
throw new ClassNotFoundException("Resource '"+name+"' (wanted by "+pluginInfo.getName()+") does not exist.");
}
try {
if (pluginInfo.isPersistent(name)) {
GlobalClassLoader.getGlobalClassLoader().defineClass(name, data);
} else {
loadedClass = defineClass(name, data, 0, data.length);
}
} catch (NoClassDefFoundError e) {
throw new ClassNotFoundException(e.getMessage(), e);
}
if (loadedClass == null) {
throw new ClassNotFoundException("Could not load " + name);
} else {
resolveClass(loadedClass);
}
return loadedClass;
}
| public Class<?> loadClass(final String name, final boolean askGlobal) throws ClassNotFoundException {
Class< ? > loadedClass = null;
if (getParent() instanceof PluginClassLoader) {
try {
loadedClass = ((PluginClassLoader)getParent()).loadClass(name, false);
if (loadedClass != null) {
return loadedClass;
}
} catch (ClassNotFoundException cnfe) {
/* Parent doesn't have the class, load ourself */
}
}
ResourceManager res;
try {
res = pluginInfo.getResourceManager();
} catch (IOException ioe) {
throw new ClassNotFoundException("Error with resourcemanager", ioe);
}
final String fileName = name.replace('.', '/')+".class";
try {
if (pluginInfo.isPersistent(name) || !res.resourceExists(fileName)) {
if (!pluginInfo.isPersistent(name) && askGlobal) {
return GlobalClassLoader.getGlobalClassLoader().loadClass(name);
} else {
// Try to load class from previous load.
try {
if (askGlobal) {
return GlobalClassLoader.getGlobalClassLoader().loadClass(name, pluginInfo);
}
} catch (ClassNotFoundException e) {
/* Class doesn't exist, we load it ourself below */
}
}
}
} catch (NoClassDefFoundError e) {
throw new ClassNotFoundException("Error loading '"+name+"' (wanted by "+pluginInfo.getName()+") -> "+e.getMessage(), e);
}
// Don't duplicate a class
if (isClassLoaded(name, false)) { return findLoadedClass(name); }
// We are ment to be loading this one!
byte[] data = null;
if (res.resourceExists(fileName)) {
data = res.getResourceBytes(fileName);
} else {
throw new ClassNotFoundException("Resource '"+name+"' (wanted by "+pluginInfo.getName()+") does not exist.");
}
try {
if (pluginInfo.isPersistent(name)) {
GlobalClassLoader.getGlobalClassLoader().defineClass(name, data);
} else {
loadedClass = defineClass(name, data, 0, data.length);
}
} catch (NoClassDefFoundError e) {
throw new ClassNotFoundException(e.getMessage(), e);
}
if (loadedClass == null) {
throw new ClassNotFoundException("Could not load " + name);
} else {
resolveClass(loadedClass);
}
return loadedClass;
}
|
diff --git a/src/test/java/org/robotframework/javalib/beans/common/URLFileFactoryIntegrationTest.java b/src/test/java/org/robotframework/javalib/beans/common/URLFileFactoryIntegrationTest.java
index c914800..5d37ae1 100644
--- a/src/test/java/org/robotframework/javalib/beans/common/URLFileFactoryIntegrationTest.java
+++ b/src/test/java/org/robotframework/javalib/beans/common/URLFileFactoryIntegrationTest.java
@@ -1,86 +1,92 @@
package org.robotframework.javalib.beans.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class URLFileFactoryIntegrationTest {
private String localDirectoryPath = System.getProperty("java.io.tmpdir");
private String fileSeparator = System.getProperty("file.separator");
private String localFilePath = new File(localDirectoryPath , "network_file.txt").getPath();
private String url = FileServer.URL_BASE + "/network_file.txt";
@BeforeClass
public static void startFileServer() throws Exception {
FileServer.start();
}
@Before
public void deleteTemporaryResources() {
new File(localFilePath).delete();
}
@AfterClass
public static void stopServer() throws Exception {
FileServer.stop();
}
@Test
public void retrievesFileFromURL() throws Exception {
File localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
assertEquals(localFilePath, localFile.getAbsolutePath());
assertFileEqualsToUrl(localFile);
}
@Test
public void doesntRetrieveFileWhenLocalCopyExistsAndURLHasntChanged() throws Exception {
File localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
long lastModified = localFile.lastModified();
localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
assertEquals(lastModified, localFile.lastModified());
}
@Test
public void retrievesFileWhenURLHasChanged() throws Exception {
File localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
- localFile.setLastModified(1000);
+ try {
+ localFile.setLastModified(1000);
+ } catch (Exception e) {
+ // Hack to let windows filesystem to catch up
+ Thread.sleep(100);
+ localFile.setLastModified(1000);
+ }
long oldLastModified = localFile.lastModified();
updateURLContent();
localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
long newLastModified = localFile.lastModified();
assertTrue("Expected " + oldLastModified + " to be less than " + newLastModified, oldLastModified < newLastModified);
}
private void assertFileEqualsToUrl(File file) throws Exception {
assertStreamsEqual(new FileInputStream(file), new URL(url).openStream());
}
private void assertStreamsEqual(InputStream expectedStream, InputStream actualStream) throws IOException {
try {
assertTrue(IOUtils.contentEquals(expectedStream, actualStream));
} finally {
actualStream.close();
expectedStream.close();
}
}
private void updateURLContent() throws IOException {
FileUtils.touch(new File(FileServer.RESOURCE_BASE + fileSeparator + "network_file.txt"));
}
}
| true | true | public void retrievesFileWhenURLHasChanged() throws Exception {
File localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
localFile.setLastModified(1000);
long oldLastModified = localFile.lastModified();
updateURLContent();
localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
long newLastModified = localFile.lastModified();
assertTrue("Expected " + oldLastModified + " to be less than " + newLastModified, oldLastModified < newLastModified);
}
| public void retrievesFileWhenURLHasChanged() throws Exception {
File localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
try {
localFile.setLastModified(1000);
} catch (Exception e) {
// Hack to let windows filesystem to catch up
Thread.sleep(100);
localFile.setLastModified(1000);
}
long oldLastModified = localFile.lastModified();
updateURLContent();
localFile = new URLFileFactory(localDirectoryPath).createFileFromUrl(url);
long newLastModified = localFile.lastModified();
assertTrue("Expected " + oldLastModified + " to be less than " + newLastModified, oldLastModified < newLastModified);
}
|
diff --git a/Responder.java b/Responder.java
index 0400e5c..e6ff8ad 100644
--- a/Responder.java
+++ b/Responder.java
@@ -1,111 +1,111 @@
/* Ahmet Aktay and Nathan Griffith
* DarkChat
* CS435: Final Project
*/
import java.io.*;
import java.net.*;
import java.util.*;
class Responder implements Runnable {
private Queue<Socket> q;
private BufferedInputStream bin;
private Socket socket;
private UserList knownUsers;
private String name;
private Message pm;
User toUser;
User fromUser;
public Responder(Queue<Socket> q, UserList knownUsers, Message pm, String name){
this.q = q;
this.knownUsers = knownUsers;
this.name = name;
this.pm = pm;
}
public void run() {
try {
MyUtils.dPrintLine(String.format("Launching thread %s", name));
//Wait for an item to enter the socket queue
while(true) {
socket = null;
while (socket==null) {
synchronized(q) {
while (q.isEmpty()) {
try {
q.wait(500);
}
catch (InterruptedException e) {
MyUtils.dPrintLine("Connection interrupted");
}
}
socket = q.poll();
}
}
MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort()));
// create read stream to get input
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ln = inFromClient.readLine();
int port = socket.getPort();
if (ln.equals("ONL")) //fromUser is online
{
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String state = inFromClient.readLine();
System.out.println(String.format("'%s' is online", ln));
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (state.equals("INIT")) {
synchronized (pm) {
pm.declareOnline(fromUser, false);
}
}
}
}
}
else if (ln.equals("CHT")) //fromUser is chatting with you!
{
String fromUsername = inFromClient.readLine();
String toUsername = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
ln = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUsername,true); //only get if exists
toUser = knownUsers.get(toUsername, true);
}
synchronized (fromUser) {
- if (toUser.name != pm.localUser.name) {
+ if (!toUser.name.equals(pm.localUser.name)) {
MyUtils.dPrintLine("Recieved chat with incorrect user fields:");
MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln));
}
else if (fromUser != null) {
System.out.println(String.format("%s: %s", fromUser.name,ln));
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
}
else {
MyUtils.dPrintLine("Recieved chat from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
}
}
else
MyUtils.dPrintLine("Unrecognized message format");
socket.close();
}
}
catch (Exception e) {
MyUtils.dPrintLine(String.format("%s",e));
//some sort of exception
}
}
}
| true | true | public void run() {
try {
MyUtils.dPrintLine(String.format("Launching thread %s", name));
//Wait for an item to enter the socket queue
while(true) {
socket = null;
while (socket==null) {
synchronized(q) {
while (q.isEmpty()) {
try {
q.wait(500);
}
catch (InterruptedException e) {
MyUtils.dPrintLine("Connection interrupted");
}
}
socket = q.poll();
}
}
MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort()));
// create read stream to get input
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ln = inFromClient.readLine();
int port = socket.getPort();
if (ln.equals("ONL")) //fromUser is online
{
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String state = inFromClient.readLine();
System.out.println(String.format("'%s' is online", ln));
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (state.equals("INIT")) {
synchronized (pm) {
pm.declareOnline(fromUser, false);
}
}
}
}
}
else if (ln.equals("CHT")) //fromUser is chatting with you!
{
String fromUsername = inFromClient.readLine();
String toUsername = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
ln = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUsername,true); //only get if exists
toUser = knownUsers.get(toUsername, true);
}
synchronized (fromUser) {
if (toUser.name != pm.localUser.name) {
MyUtils.dPrintLine("Recieved chat with incorrect user fields:");
MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln));
}
else if (fromUser != null) {
System.out.println(String.format("%s: %s", fromUser.name,ln));
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
}
else {
MyUtils.dPrintLine("Recieved chat from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
}
}
else
MyUtils.dPrintLine("Unrecognized message format");
socket.close();
}
}
catch (Exception e) {
MyUtils.dPrintLine(String.format("%s",e));
//some sort of exception
}
}
| public void run() {
try {
MyUtils.dPrintLine(String.format("Launching thread %s", name));
//Wait for an item to enter the socket queue
while(true) {
socket = null;
while (socket==null) {
synchronized(q) {
while (q.isEmpty()) {
try {
q.wait(500);
}
catch (InterruptedException e) {
MyUtils.dPrintLine("Connection interrupted");
}
}
socket = q.poll();
}
}
MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort()));
// create read stream to get input
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ln = inFromClient.readLine();
int port = socket.getPort();
if (ln.equals("ONL")) //fromUser is online
{
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String state = inFromClient.readLine();
System.out.println(String.format("'%s' is online", ln));
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (state.equals("INIT")) {
synchronized (pm) {
pm.declareOnline(fromUser, false);
}
}
}
}
}
else if (ln.equals("CHT")) //fromUser is chatting with you!
{
String fromUsername = inFromClient.readLine();
String toUsername = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
ln = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUsername,true); //only get if exists
toUser = knownUsers.get(toUsername, true);
}
synchronized (fromUser) {
if (!toUser.name.equals(pm.localUser.name)) {
MyUtils.dPrintLine("Recieved chat with incorrect user fields:");
MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln));
}
else if (fromUser != null) {
System.out.println(String.format("%s: %s", fromUser.name,ln));
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
}
else {
MyUtils.dPrintLine("Recieved chat from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
}
}
else
MyUtils.dPrintLine("Unrecognized message format");
socket.close();
}
}
catch (Exception e) {
MyUtils.dPrintLine(String.format("%s",e));
//some sort of exception
}
}
|
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableReader.java b/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
index 8b4f2d05..a0b45a6b 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableReader.java
@@ -1,686 +1,686 @@
/**
* 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.cassandra.io.sstable;
import java.io.*;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.nio.ByteBuffer;
import java.util.*;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.cache.InstrumentedCache;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.io.IColumnSerializer;
import org.apache.cassandra.io.util.BufferedRandomAccessFile;
import org.apache.cassandra.io.util.FileDataInput;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.SegmentedFile;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.*;
/**
* SSTableReaders are open()ed by Table.onStart; after that they are created by SSTableWriter.renameAndOpen.
* Do not re-call open() on existing SSTable files; use the references kept by ColumnFamilyStore post-start instead.
*/
public class SSTableReader extends SSTable implements Comparable<SSTableReader>
{
private static final Logger logger = LoggerFactory.getLogger(SSTableReader.class);
// guesstimated size of INDEX_INTERVAL index entries
private static final int INDEX_FILE_BUFFER_BYTES = 16 * DatabaseDescriptor.getIndexInterval();
// `finalizers` is required to keep the PhantomReferences alive after the enclosing SSTR is itself
// unreferenced. otherwise they will never get enqueued.
private static final Set<Reference<SSTableReader>> finalizers = new HashSet<Reference<SSTableReader>>();
private static final ReferenceQueue<SSTableReader> finalizerQueue = new ReferenceQueue<SSTableReader>()
{{
Runnable runnable = new Runnable()
{
public void run()
{
while (true)
{
SSTableDeletingReference r;
try
{
r = (SSTableDeletingReference) finalizerQueue.remove();
finalizers.remove(r);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
try
{
r.cleanup();
}
catch (IOException e)
{
logger.error("Error deleting " + r.desc, e);
}
}
}
};
new Thread(runnable, "SSTABLE-DELETER").start();
}};
/**
* maxDataAge is a timestamp in local server time (e.g. System.currentTimeMilli) which represents an uppper bound
* to the newest piece of data stored in the sstable. In other words, this sstable does not contain items created
* later than maxDataAge.
*
* The field is not serialized to disk, so relying on it for more than what truncate does is not advised.
*
* When a new sstable is flushed, maxDataAge is set to the time of creation.
* When a sstable is created from compaction, maxDataAge is set to max of all merged tables.
*
* The age is in milliseconds since epoc and is local to this host.
*/
public final long maxDataAge;
// indexfile and datafile: might be null before a call to load()
private SegmentedFile ifile;
private SegmentedFile dfile;
private IndexSummary indexSummary;
private Filter bf;
private InstrumentedCache<Pair<Descriptor,DecoratedKey>, Long> keyCache;
private BloomFilterTracker bloomFilterTracker = new BloomFilterTracker();
private volatile SSTableDeletingReference phantomReference;
public static long getApproximateKeyCount(Iterable<SSTableReader> sstables)
{
long count = 0;
for (SSTableReader sstable : sstables)
{
int indexKeyCount = sstable.getKeySamples().size();
count = count + (indexKeyCount + 1) * DatabaseDescriptor.getIndexInterval();
if (logger.isDebugEnabled())
logger.debug("index size for bloom filter calc for file : " + sstable.getFilename() + " : " + count);
}
return count;
}
public static SSTableReader open(Descriptor desc) throws IOException
{
Set<Component> components = componentsFor(desc, false);
return open(desc, components, DatabaseDescriptor.getCFMetaData(desc.ksname, desc.cfname), StorageService.getPartitioner());
}
public static SSTableReader open(Descriptor descriptor, Set<Component> components, CFMetaData metadata, IPartitioner partitioner) throws IOException
{
return open(descriptor, components, Collections.<DecoratedKey>emptySet(), null, metadata, partitioner);
}
public static SSTableReader open(Descriptor descriptor, Set<Component> components, Set<DecoratedKey> savedKeys, SSTableTracker tracker, CFMetaData metadata, IPartitioner partitioner) throws IOException
{
assert partitioner != null;
long start = System.currentTimeMillis();
logger.info("Opening " + descriptor);
EstimatedHistogram rowSizes;
EstimatedHistogram columnCounts;
File statsFile = new File(descriptor.filenameFor(SSTable.COMPONENT_STATS));
if (statsFile.exists())
{
DataInputStream dis = null;
try
{
logger.debug("Load statistics for {}", descriptor);
dis = new DataInputStream(new BufferedInputStream(new FileInputStream(statsFile)));
rowSizes = EstimatedHistogram.serializer.deserialize(dis);
columnCounts = EstimatedHistogram.serializer.deserialize(dis);
}
finally
{
FileUtils.closeQuietly(dis);
}
}
else
{
logger.debug("No statistics for {}", descriptor);
rowSizes = SSTable.defaultRowHistogram();
columnCounts = SSTable.defaultColumnHistogram();
}
SSTableReader sstable = new SSTableReader(descriptor, components, metadata, partitioner, null, null, null, null, System.currentTimeMillis(), rowSizes, columnCounts);
sstable.setTrackedBy(tracker);
// versions before 'c' encoded keys as utf-16 before hashing to the filter
if (descriptor.hasStringsInBloomFilter)
{
sstable.load(true, savedKeys);
}
else
{
sstable.load(false, savedKeys);
sstable.loadBloomFilter();
}
if (logger.isDebugEnabled())
logger.debug("INDEX LOAD TIME for " + descriptor + ": " + (System.currentTimeMillis() - start) + " ms.");
if (logger.isDebugEnabled() && sstable.getKeyCache() != null)
logger.debug(String.format("key cache contains %s/%s keys", sstable.getKeyCache().getSize(), sstable.getKeyCache().getCapacity()));
return sstable;
}
/**
* Open a RowIndexedReader which already has its state initialized (by SSTableWriter).
*/
static SSTableReader internalOpen(Descriptor desc, Set<Component> components, CFMetaData metadata, IPartitioner partitioner, SegmentedFile ifile, SegmentedFile dfile, IndexSummary isummary, Filter bf, long maxDataAge, EstimatedHistogram rowsize,
EstimatedHistogram columncount) throws IOException
{
assert desc != null && partitioner != null && ifile != null && dfile != null && isummary != null && bf != null;
return new SSTableReader(desc, components, metadata, partitioner, ifile, dfile, isummary, bf, maxDataAge, rowsize, columncount);
}
private SSTableReader(Descriptor desc,
Set<Component> components,
CFMetaData metadata,
IPartitioner partitioner,
SegmentedFile ifile,
SegmentedFile dfile,
IndexSummary indexSummary,
Filter bloomFilter,
long maxDataAge,
EstimatedHistogram rowSizes,
EstimatedHistogram columnCounts)
throws IOException
{
super(desc, components, metadata, partitioner, rowSizes, columnCounts);
this.maxDataAge = maxDataAge;
this.ifile = ifile;
this.dfile = dfile;
this.indexSummary = indexSummary;
this.bf = bloomFilter;
}
public void setTrackedBy(SSTableTracker tracker)
{
if (tracker != null)
{
phantomReference = new SSTableDeletingReference(tracker, this, finalizerQueue);
finalizers.add(phantomReference);
keyCache = tracker.getKeyCache();
}
}
void loadBloomFilter() throws IOException
{
DataInputStream stream = null;
try
{
stream = new DataInputStream(new BufferedInputStream(new FileInputStream(descriptor.filenameFor(Component.FILTER))));
if (descriptor.usesOldBloomFilter)
{
bf = LegacyBloomFilter.serializer().deserialize(stream);
}
else
{
bf = BloomFilter.serializer().deserialize(stream);
}
}
finally
{
FileUtils.closeQuietly(stream);
}
}
/**
* Loads ifile, dfile and indexSummary, and optionally recreates the bloom filter.
*/
private void load(boolean recreatebloom, Set<DecoratedKey> keysToLoadInCache) throws IOException
{
boolean cacheLoading = keyCache != null && !keysToLoadInCache.isEmpty();
SegmentedFile.Builder ibuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getIndexAccessMode());
SegmentedFile.Builder dbuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getDiskAccessMode());
// we read the positions in a BRAF so we don't have to worry about an entry spanning a mmap boundary.
BufferedRandomAccessFile input = new BufferedRandomAccessFile(new File(descriptor.filenameFor(Component.PRIMARY_INDEX)),
"r",
BufferedRandomAccessFile.DEFAULT_BUFFER_SIZE,
true);
try
{
if (keyCache != null && keyCache.getCapacity() - keyCache.getSize() < keysToLoadInCache.size())
keyCache.updateCapacity(keyCache.getSize() + keysToLoadInCache.size());
long indexSize = input.length();
long estimatedKeys = SSTable.estimateRowsFromIndex(input);
indexSummary = new IndexSummary(estimatedKeys);
if (recreatebloom)
// estimate key count based on index length
bf = LegacyBloomFilter.getFilter(estimatedKeys, 15);
while (true)
{
long indexPosition = input.getFilePointer();
if (indexPosition == indexSize)
break;
boolean shouldAddEntry = indexSummary.shouldAddEntry();
ByteBuffer key = (shouldAddEntry || cacheLoading || recreatebloom)
? ByteBufferUtil.readWithShortLength(input)
: ByteBufferUtil.skipShortLength(input);
long dataPosition = input.readLong();
if (key != null)
{
DecoratedKey decoratedKey = decodeKey(partitioner, descriptor, key);
if (recreatebloom)
bf.add(decoratedKey.key);
if (shouldAddEntry)
indexSummary.addEntry(decoratedKey, indexPosition);
if (cacheLoading && keysToLoadInCache.contains(decoratedKey))
cacheKey(decoratedKey, dataPosition);
}
indexSummary.incrementRowid();
ibuilder.addPotentialBoundary(indexPosition);
dbuilder.addPotentialBoundary(dataPosition);
}
indexSummary.complete();
}
finally
{
FileUtils.closeQuietly(input);
}
// finalize the state of the reader
ifile = ibuilder.complete(descriptor.filenameFor(Component.PRIMARY_INDEX));
dfile = dbuilder.complete(descriptor.filenameFor(Component.DATA));
}
/** get the position in the index file to start scanning to find the given key (at most indexInterval keys away) */
private IndexSummary.KeyPosition getIndexScanPosition(DecoratedKey decoratedKey)
{
assert indexSummary.getIndexPositions() != null && indexSummary.getIndexPositions().size() > 0;
int index = Collections.binarySearch(indexSummary.getIndexPositions(), new IndexSummary.KeyPosition(decoratedKey, -1));
if (index < 0)
{
// binary search gives us the first index _greater_ than the key searched for,
// i.e., its insertion position
int greaterThan = (index + 1) * -1;
if (greaterThan == 0)
return null;
return indexSummary.getIndexPositions().get(greaterThan - 1);
}
else
{
return indexSummary.getIndexPositions().get(index);
}
}
/**
* For testing purposes only.
*/
public void forceFilterFailures()
{
bf = LegacyBloomFilter.alwaysMatchingBloomFilter();
}
public Filter getBloomFilter()
{
return bf;
}
/**
* @return The key cache: for monitoring purposes.
*/
public InstrumentedCache getKeyCache()
{
return keyCache;
}
/**
* @return An estimate of the number of keys in this SSTable.
*/
public long estimatedKeys()
{
return indexSummary.getIndexPositions().size() * DatabaseDescriptor.getIndexInterval();
}
/**
* @return Approximately 1/INDEX_INTERVALth of the keys in this SSTable.
*/
public Collection<DecoratedKey> getKeySamples()
{
return Collections2.transform(indexSummary.getIndexPositions(),
new Function<IndexSummary.KeyPosition, DecoratedKey>(){
public DecoratedKey apply(IndexSummary.KeyPosition kp)
{
return kp.key;
}
});
}
/**
* Determine the minimal set of sections that can be extracted from this SSTable to cover the given ranges.
* @return A sorted list of (offset,end) pairs that cover the given ranges in the datafile for this SSTable.
*/
public List<Pair<Long,Long>> getPositionsForRanges(Collection<Range> ranges)
{
// use the index to determine a minimal section for each range
List<Pair<Long,Long>> positions = new ArrayList<Pair<Long,Long>>();
for (AbstractBounds range : AbstractBounds.normalize(ranges))
{
long left = getPosition(new DecoratedKey(range.left, null), Operator.GT);
if (left == -1)
// left is past the end of the file
continue;
long right = getPosition(new DecoratedKey(range.right, null), Operator.GT);
if (right == -1 || Range.isWrapAround(range.left, range.right))
// right is past the end of the file, or it wraps
right = length();
if (left == right)
// empty range
continue;
positions.add(new Pair(Long.valueOf(left), Long.valueOf(right)));
}
return positions;
}
public void cacheKey(DecoratedKey key, Long info)
{
assert key.key != null;
// avoid keeping a permanent reference to the original key buffer
DecoratedKey copiedKey = new DecoratedKey(key.token, ByteBufferUtil.clone(key.key));
keyCache.put(new Pair<Descriptor, DecoratedKey>(descriptor, copiedKey), info);
}
public Long getCachedPosition(DecoratedKey key)
{
return getCachedPosition(new Pair<Descriptor, DecoratedKey>(descriptor, key));
}
private Long getCachedPosition(Pair<Descriptor, DecoratedKey> unifiedKey)
{
if (keyCache != null && keyCache.getCapacity() > 0)
return keyCache.get(unifiedKey);
return null;
}
/**
* @param decoratedKey The key to apply as the rhs to the given Operator.
* @param op The Operator defining matching keys: the nearest key to the target matching the operator wins.
* @return The position in the data file to find the key, or -1 if the key is not present
*/
public long getPosition(DecoratedKey decoratedKey, Operator op)
{
// first, check bloom filter
if (op == Operator.EQ)
{
assert decoratedKey.key != null; // null is ok for GE scans
if (!bf.isPresent(decoratedKey.key))
return -1;
}
// next, the key cache
if (op == Operator.EQ || op == Operator.GE)
{
Pair<Descriptor, DecoratedKey> unifiedKey = new Pair<Descriptor, DecoratedKey>(descriptor, decoratedKey);
Long cachedPosition = getCachedPosition(unifiedKey);
if (cachedPosition != null)
return cachedPosition;
}
// next, see if the sampled index says it's impossible for the key to be present
IndexSummary.KeyPosition sampledPosition = getIndexScanPosition(decoratedKey);
if (sampledPosition == null)
{
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
// we matched the -1th position: if the operator might match forward, return the 0th position
return op.apply(1) >= 0 ? 0 : -1;
}
// scan the on-disk index, starting at the nearest sampled position
Iterator<FileDataInput> segments = ifile.iterator(sampledPosition.indexPosition, INDEX_FILE_BUFFER_BYTES);
while (segments.hasNext())
{
FileDataInput input = segments.next();
try
{
while (!input.isEOF())
{
// read key & data position from index entry
DecoratedKey indexDecoratedKey = decodeKey(partitioner, descriptor, ByteBufferUtil.readWithShortLength(input));
long dataPosition = input.readLong();
int comparison = indexDecoratedKey.compareTo(decoratedKey);
int v = op.apply(comparison);
if (v == 0)
{
if (comparison == 0 && keyCache != null && keyCache.getCapacity() > 0)
{
- if (op == Operator.EQ)
- bloomFilterTracker.addTruePositive();
// store exact match for the key
if (decoratedKey.key != null)
cacheKey(decoratedKey, dataPosition);
}
+ if (op == Operator.EQ)
+ bloomFilterTracker.addTruePositive();
return dataPosition;
}
if (v < 0)
{
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
return -1;
}
}
}
catch (IOException e)
{
throw new IOError(e);
}
finally
{
FileUtils.closeQuietly(input);
}
}
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
return -1;
}
/**
* @return The length in bytes of the data file for this SSTable.
*/
public long length()
{
return dfile.length;
}
public void markCompacted()
{
if (logger.isDebugEnabled())
logger.debug("Marking " + getFilename() + " compacted");
try
{
if (!new File(descriptor.filenameFor(Component.COMPACTED_MARKER)).createNewFile())
throw new IOException("Unable to create compaction marker");
}
catch (IOException e)
{
throw new IOError(e);
}
phantomReference.deleteOnCleanup();
}
/**
* @param bufferSize Buffer size in bytes for this Scanner.
* @param filter filter to use when reading the columns
* @return A Scanner for seeking over the rows of the SSTable.
*/
public SSTableScanner getScanner(int bufferSize, QueryFilter filter)
{
return new SSTableScanner(this, filter, bufferSize);
}
/**
* Direct I/O SSTableScanner
* @param bufferSize Buffer size in bytes for this Scanner.
* @return A Scanner for seeking over the rows of the SSTable.
*/
public SSTableScanner getDirectScanner(int bufferSize)
{
return new SSTableScanner(this, bufferSize, true);
}
public FileDataInput getFileDataInput(DecoratedKey decoratedKey, int bufferSize)
{
long position = getPosition(decoratedKey, Operator.EQ);
if (position < 0)
return null;
return dfile.getSegment(position, bufferSize);
}
public int compareTo(SSTableReader o)
{
return descriptor.generation - o.descriptor.generation;
}
public AbstractType getColumnComparator()
{
return metadata.comparator;
}
public ColumnFamily createColumnFamily()
{
return ColumnFamily.create(metadata);
}
public IColumnSerializer getColumnSerializer()
{
return metadata.cfType == ColumnFamilyType.Standard
? Column.serializer()
: SuperColumn.serializer(metadata.subcolumnComparator);
}
/**
* Tests if the sstable contains data newer than the given age param (in localhost currentMilli time).
* This works in conjunction with maxDataAge which is an upper bound on the create of data in this sstable.
* @param age The age to compare the maxDataAre of this sstable. Measured in millisec since epoc on this host
* @return True iff this sstable contains data that's newer than the given age parameter.
*/
public boolean newSince(long age)
{
return maxDataAge > age;
}
public static long readRowSize(DataInput in, Descriptor d) throws IOException
{
if (d.hasIntRowSize)
return in.readInt();
return in.readLong();
}
public void createLinks(String snapshotDirectoryPath) throws IOException
{
for (Component component : components)
{
File sourceFile = new File(descriptor.filenameFor(component));
File targetLink = new File(snapshotDirectoryPath, sourceFile.getName());
CLibrary.createHardLink(sourceFile, targetLink);
}
}
/**
* Conditionally use the deprecated 'IPartitioner.convertFromDiskFormat' method.
*/
public static DecoratedKey decodeKey(IPartitioner p, Descriptor d, ByteBuffer bytes)
{
if (d.hasEncodedKeys)
return p.convertFromDiskFormat(bytes);
return p.decorateKey(bytes);
}
/**
* TODO: Move someplace reusable
*/
public abstract static class Operator
{
public static final Operator EQ = new Equals();
public static final Operator GE = new GreaterThanOrEqualTo();
public static final Operator GT = new GreaterThan();
/**
* @param comparison The result of a call to compare/compareTo, with the desired field on the rhs.
* @return less than 0 if the operator cannot match forward, 0 if it matches, greater than 0 if it might match forward.
*/
public abstract int apply(int comparison);
final static class Equals extends Operator
{
public int apply(int comparison) { return -comparison; }
}
final static class GreaterThanOrEqualTo extends Operator
{
public int apply(int comparison) { return comparison >= 0 ? 0 : -comparison; }
}
final static class GreaterThan extends Operator
{
public int apply(int comparison) { return comparison > 0 ? 0 : 1; }
}
}
public long getBloomFilterFalsePositiveCount()
{
return bloomFilterTracker.getFalsePositiveCount();
}
public long getRecentBloomFilterFalsePositiveCount()
{
return bloomFilterTracker.getRecentFalsePositiveCount();
}
public long getBloomFilterTruePositiveCount()
{
return bloomFilterTracker.getTruePositiveCount();
}
public long getRecentBloomFilterTruePositiveCount()
{
return bloomFilterTracker.getRecentTruePositiveCount();
}
}
| false | true | public long getPosition(DecoratedKey decoratedKey, Operator op)
{
// first, check bloom filter
if (op == Operator.EQ)
{
assert decoratedKey.key != null; // null is ok for GE scans
if (!bf.isPresent(decoratedKey.key))
return -1;
}
// next, the key cache
if (op == Operator.EQ || op == Operator.GE)
{
Pair<Descriptor, DecoratedKey> unifiedKey = new Pair<Descriptor, DecoratedKey>(descriptor, decoratedKey);
Long cachedPosition = getCachedPosition(unifiedKey);
if (cachedPosition != null)
return cachedPosition;
}
// next, see if the sampled index says it's impossible for the key to be present
IndexSummary.KeyPosition sampledPosition = getIndexScanPosition(decoratedKey);
if (sampledPosition == null)
{
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
// we matched the -1th position: if the operator might match forward, return the 0th position
return op.apply(1) >= 0 ? 0 : -1;
}
// scan the on-disk index, starting at the nearest sampled position
Iterator<FileDataInput> segments = ifile.iterator(sampledPosition.indexPosition, INDEX_FILE_BUFFER_BYTES);
while (segments.hasNext())
{
FileDataInput input = segments.next();
try
{
while (!input.isEOF())
{
// read key & data position from index entry
DecoratedKey indexDecoratedKey = decodeKey(partitioner, descriptor, ByteBufferUtil.readWithShortLength(input));
long dataPosition = input.readLong();
int comparison = indexDecoratedKey.compareTo(decoratedKey);
int v = op.apply(comparison);
if (v == 0)
{
if (comparison == 0 && keyCache != null && keyCache.getCapacity() > 0)
{
if (op == Operator.EQ)
bloomFilterTracker.addTruePositive();
// store exact match for the key
if (decoratedKey.key != null)
cacheKey(decoratedKey, dataPosition);
}
return dataPosition;
}
if (v < 0)
{
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
return -1;
}
}
}
catch (IOException e)
{
throw new IOError(e);
}
finally
{
FileUtils.closeQuietly(input);
}
}
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
return -1;
}
| public long getPosition(DecoratedKey decoratedKey, Operator op)
{
// first, check bloom filter
if (op == Operator.EQ)
{
assert decoratedKey.key != null; // null is ok for GE scans
if (!bf.isPresent(decoratedKey.key))
return -1;
}
// next, the key cache
if (op == Operator.EQ || op == Operator.GE)
{
Pair<Descriptor, DecoratedKey> unifiedKey = new Pair<Descriptor, DecoratedKey>(descriptor, decoratedKey);
Long cachedPosition = getCachedPosition(unifiedKey);
if (cachedPosition != null)
return cachedPosition;
}
// next, see if the sampled index says it's impossible for the key to be present
IndexSummary.KeyPosition sampledPosition = getIndexScanPosition(decoratedKey);
if (sampledPosition == null)
{
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
// we matched the -1th position: if the operator might match forward, return the 0th position
return op.apply(1) >= 0 ? 0 : -1;
}
// scan the on-disk index, starting at the nearest sampled position
Iterator<FileDataInput> segments = ifile.iterator(sampledPosition.indexPosition, INDEX_FILE_BUFFER_BYTES);
while (segments.hasNext())
{
FileDataInput input = segments.next();
try
{
while (!input.isEOF())
{
// read key & data position from index entry
DecoratedKey indexDecoratedKey = decodeKey(partitioner, descriptor, ByteBufferUtil.readWithShortLength(input));
long dataPosition = input.readLong();
int comparison = indexDecoratedKey.compareTo(decoratedKey);
int v = op.apply(comparison);
if (v == 0)
{
if (comparison == 0 && keyCache != null && keyCache.getCapacity() > 0)
{
// store exact match for the key
if (decoratedKey.key != null)
cacheKey(decoratedKey, dataPosition);
}
if (op == Operator.EQ)
bloomFilterTracker.addTruePositive();
return dataPosition;
}
if (v < 0)
{
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
return -1;
}
}
}
catch (IOException e)
{
throw new IOError(e);
}
finally
{
FileUtils.closeQuietly(input);
}
}
if (op == Operator.EQ)
bloomFilterTracker.addFalsePositive();
return -1;
}
|
diff --git a/core/jar/src/main/java/org/mobicents/slee/container/management/SbbManagement.java b/core/jar/src/main/java/org/mobicents/slee/container/management/SbbManagement.java
index 19df8324f..c0046c86f 100644
--- a/core/jar/src/main/java/org/mobicents/slee/container/management/SbbManagement.java
+++ b/core/jar/src/main/java/org/mobicents/slee/container/management/SbbManagement.java
@@ -1,520 +1,526 @@
package org.mobicents.slee.container.management;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.LinkRef;
import javax.naming.Name;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingException;
import javax.slee.facilities.AlarmFacility;
import javax.slee.facilities.Level;
import javax.slee.management.DeploymentException;
import javax.transaction.SystemException;
import org.jboss.logging.Logger;
import org.jboss.naming.NonSerializableFactory;
import org.mobicents.slee.container.SleeContainer;
import org.mobicents.slee.container.component.ComponentRepositoryImpl;
import org.mobicents.slee.container.component.ResourceAdaptorTypeComponent;
import org.mobicents.slee.container.component.SbbComponent;
import org.mobicents.slee.container.component.deployment.jaxb.descriptors.common.MEnvEntry;
import org.mobicents.slee.container.component.deployment.jaxb.descriptors.common.references.MEjbRef;
import org.mobicents.slee.container.component.deployment.jaxb.descriptors.sbb.MResourceAdaptorEntityBinding;
import org.mobicents.slee.container.component.deployment.jaxb.descriptors.sbb.MResourceAdaptorTypeBinding;
import org.mobicents.slee.container.deployment.SbbClassCodeGenerator;
import org.mobicents.slee.container.service.ServiceActivityContextInterfaceFactoryImpl;
import org.mobicents.slee.container.service.ServiceActivityFactoryImpl;
import org.mobicents.slee.resource.ResourceAdaptorEntity;
import org.mobicents.slee.runtime.facilities.SbbAlarmFacilityImpl;
import org.mobicents.slee.runtime.facilities.TimerFacilityImpl;
import org.mobicents.slee.runtime.transaction.SleeTransactionManager;
/**
* Manages sbbs in container
*
* @author martins
*
*/
public class SbbManagement {
private static final Logger logger = Logger.getLogger(SbbManagement.class);
private final SleeContainer sleeContainer;
public SbbManagement(SleeContainer sleeContainer) {
this.sleeContainer = sleeContainer;
}
/**
* Deploys an SBB. This generates the code to convert abstract to concrete
* class and registers the component in the component table and creates an
* object pool for the sbb id.
*
* @param mobicentsSbbDescriptor
* the descriptor of the sbb to install
* @throws Exception
*/
public void installSbb(SbbComponent sbbComponent)
throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Installing " + sbbComponent);
}
final SleeTransactionManager sleeTransactionManager = sleeContainer
.getTransactionManager();
sleeTransactionManager.mandateTransaction();
// change classloader
ClassLoader oldClassLoader = Thread.currentThread()
.getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(
sbbComponent.getClassLoader());
// Set up the comp/env naming context for the Sbb.
setupSbbEnvironment(sbbComponent);
// generate class code for the sbb
new SbbClassCodeGenerator().process(sbbComponent);
//FIXME: this will erase stack trace.
//} catch (Exception ex) {
// throw ex;
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
// Set 1.0 Trace to off
sleeContainer.getTraceFacility().setTraceLevelOnTransaction(
sbbComponent.getSbbID(), Level.OFF);
sleeContainer.getAlarmFacility().registerComponent(
sbbComponent.getSbbID());
}
private void setupSbbEnvironment(SbbComponent sbbComponent) throws Exception {
Context ctx = (Context) new InitialContext().lookup("java:comp");
if (logger.isDebugEnabled()) {
logger.debug("Setting up SBB env. Initial context is " + ctx);
}
Context envCtx = null;
try {
envCtx = ctx.createSubcontext("env");
} catch (NameAlreadyBoundException ex) {
envCtx = (Context) ctx.lookup("env");
}
Context sleeCtx = null;
try {
sleeCtx = envCtx.createSubcontext("slee");
} catch (NameAlreadyBoundException ex) {
sleeCtx = (Context) envCtx.lookup("slee");
}
// Do all the context binding stuff just once during init and
// just do the linking here.
Context newCtx;
String containerName = "java:slee/container/Container";
try {
newCtx = sleeCtx.createSubcontext("container");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("container");
}
try {
newCtx.bind("Container", new LinkRef(containerName));
} catch (NameAlreadyBoundException ex) {
}
String nullAciFactory = "java:slee/nullactivity/nullactivitycontextinterfacefactory";
String nullActivityFactory = "java:slee/nullactivity/nullactivityfactory";
try {
newCtx = sleeCtx.createSubcontext("nullactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("nullactivity");
}
try {
newCtx.bind("activitycontextinterfacefactory", new LinkRef(
nullAciFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("factory", new LinkRef(nullActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String serviceActivityContextInterfaceFactory = "java:slee/serviceactivity/"
+ ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME;
String serviceActivityFactory = "java:slee/serviceactivity/"
+ ServiceActivityFactoryImpl.JNDI_NAME;
try {
newCtx = sleeCtx.createSubcontext("serviceactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("serviceactivity");
}
try {
newCtx.bind(ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME,
new LinkRef(serviceActivityContextInterfaceFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind(ServiceActivityFactoryImpl.JNDI_NAME, new LinkRef(
serviceActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String timer = "java:slee/facilities/" + TimerFacilityImpl.JNDI_NAME;
String aciNaming = "java:slee/facilities/activitycontextnaming";
try {
newCtx = sleeCtx.createSubcontext("facilities");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("facilities");
}
try {
newCtx.bind("timer", new LinkRef(timer));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("activitycontextnaming", new LinkRef(aciNaming));
} catch (NameAlreadyBoundException ex) {
}
String trace = "java:slee/facilities/trace";
try {
newCtx.bind("trace", new LinkRef(trace));
} catch (NameAlreadyBoundException ex) {
}
String alarm = "java:slee/facilities/alarm";
try {
//This has to be checked, to be sure sbb have it under correct jndi binding
AlarmFacility sbbAlarmFacility = new SbbAlarmFacilityImpl(sbbComponent.getSbbID(),sleeContainer.getAlarmFacility());
newCtx.bind("alarm", sbbAlarmFacility);
} catch (NameAlreadyBoundException ex) {
}
String profile = "java:slee/facilities/profile";
try {
newCtx.bind("profile", new LinkRef(profile));
} catch (NameAlreadyBoundException ex) {
}
String profilteTableAciFactory = "java:slee/facilities/profiletableactivitycontextinterfacefactory";
try {
newCtx.bind("profiletableactivitycontextinterfacefactory",
new LinkRef(profilteTableAciFactory));
} catch (NameAlreadyBoundException ex) {
}
// For each resource that the Sbb references, bind the implementing
// object name to its comp/env
if (logger.isDebugEnabled()) {
logger.debug("Number of Resource Bindings:"
+ sbbComponent.getDescriptor().getResourceAdaptorTypeBindings());
}
ComponentRepositoryImpl componentRepository = sleeContainer.getComponentRepositoryImpl();
for (MResourceAdaptorTypeBinding raTypeBinding : sbbComponent.getDescriptor().getResourceAdaptorTypeBindings()) {
ResourceAdaptorTypeComponent raTypeComponent = componentRepository.getComponentByID(raTypeBinding.getResourceAdaptorTypeRef());
for (MResourceAdaptorEntityBinding raEntityBinding : raTypeBinding.getResourceAdaptorEntityBinding()) {
String raObjectName = raEntityBinding.getResourceAdaptorObjectName();
String linkName = raEntityBinding.getResourceAdaptorEntityLink();
/*
* The Deployment descriptor specifies Zero or more
* resource-adaptor-entity-binding elements. Each
* resource-adaptor-entity-binding element binds an object that
* implements the resource adaptor interface of the resource
* adaptor type into the JNDI comp onent environment of the SBB
* (see Section 6.13.3). Each resource- adaptorentity- binding
* element contains the following sub-elements: A description
* element. This is an optional informational element. A
* resource-adaptor-object?name element. This element specifies
* the location within the JNDI component environment to which
* the object that implements the resource adaptor interface
* will be bound. A resource-adaptor-entity-link element. This
* is an optional element. It identifies the resource adaptor
* entity that provides the object that should be bound into the
* JNDI component environment of the SBB. The identified
* resource adaptor entity must be an instance of a resource
* adaptor whose resource adaptor type is specified by the
* resourceadaptor- type-ref sub-element of the enclosing
* resource-adaptortype- binding element.
*/
ResourceManagement resourceManagement = sleeContainer.getResourceManagement();
ResourceAdaptorEntity raEntity = resourceManagement
.getResourceAdaptorEntity(resourceManagement
.getResourceAdaptorEntityName(linkName));
if (raEntity == null)
throw new Exception(
"Could not find Resource adaptor Entity for Link Name: ["
+ linkName + "] of RA Type ["
+ raTypeComponent + "]");
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(raObjectName);
int tokenCount = local.size();
Context subContext = envCtx;
for (int i = 0; i < tokenCount - 1; i++) {
String nextTok = local.get(i);
try {
subContext.lookup(nextTok);
} catch (NameNotFoundException nfe) {
subContext.createSubcontext(nextTok);
} finally {
subContext = (Context) subContext.lookup(nextTok);
}
}
String lastTok = local.get(tokenCount - 1);
// Bind the resource adaptor instance to where the Sbb expects
// to find it.
if (logger.isDebugEnabled()) {
logger
.debug("setupSbbEnvironment: Binding a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
try {
- NonSerializableFactory.rebind(subContext, lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
- //subContext.bind(lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
+ Object raSbbInterface = raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef());
+ if (raSbbInterface != null) {
+ NonSerializableFactory.rebind(subContext, lastTok,raSbbInterface);
+ //subContext.bind(lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
+ }
+ else {
+ throw new DeploymentException("Unable to retrieve the RA interface for RA entity "+raEntity.getName()+" and RAType " +raTypeBinding.getResourceAdaptorTypeRef());
+ }
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
String localFactoryName = raTypeBinding.getActivityContextInterfaceFactoryName();
if (localFactoryName != null) {
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(localFactoryName);
int nameSize = local.size();
Context tempCtx = envCtx;
for (int a = 0; a < nameSize - 1; a++) {
String temp = local.get(a);
try {
tempCtx.lookup(temp);
} catch (NameNotFoundException ne) {
tempCtx.createSubcontext(temp);
} finally {
tempCtx = (Context) tempCtx.lookup(temp);
}
}
if (logger.isDebugEnabled()) {
logger
.debug(
"setupSbbEnvironment: Binding a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
String factoryRefName = local.get(nameSize - 1);
try {
tempCtx
.bind(factoryRefName,raTypeComponent.getActivityContextInterfaceFactory());
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
}
/*
* Bind the ejb-refs
*/
try {
envCtx.createSubcontext("ejb");
} catch (NameAlreadyBoundException ex) {
envCtx.lookup("ejb");
}
if (logger.isDebugEnabled()) {
logger.debug("Created ejb local context");
}
for (MEjbRef ejbRef : sbbComponent.getDescriptor().getEjbRefs()) {
String jndiName = ejbRef.getEjbRefName();
if (logger.isDebugEnabled()) {
logger.debug("Binding ejb: " + ejbRef.getEjbRefName()
+ " with link to " + jndiName);
}
try {
envCtx.bind(ejbRef.getEjbRefName(), new LinkRef(jndiName));
} catch (NameAlreadyBoundException ex) {
}
/*
* Validate the ejb reference has the correct type and classes as
* specified in deployment descriptor
*/
/*
* TODO I think I know the problem here. It seems the ejb is loaded
* AFTER the sbb is loaded, hence the validation fails here since it
* cannot locate the ejb. We need to force the ejb to be loaded
* before the sbb
*/
/*
* Commented out for now
*
*
* Object obj = new InitialContext().lookup("java:comp/env/" +
* ejbRef.getEjbRefName());
*
* Object homeObject = null; try { Class homeClass =
* Thread.currentThread().getContextClassLoader().loadClass(home);
*
* homeObject = PortableRemoteObject.narrow(obj, homeClass);
*
* if (!homeClass.isInstance(homeObject)) { throw new
* DeploymentException("Looked up ejb home is not an instanceof " +
* home); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + home); } catch
* (ClassCastException e) { throw new DeploymentException("Failed to
* lookup ejb reference using jndi name " + jndiName); }
*
* Object ejb = null; try { Method m =
* homeObject.getClass().getMethod("create", null); Object ejbObject =
* m.invoke(home, null);
*
* Class ejbClass =
* Thread.currentThread().getContextClassLoader().loadClass(remote);
* if (!ejbClass.isInstance(ejbObject)) { throw new
* DeploymentException("Looked up ejb object is not an instanceof " +
* remote); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + remote); }
*
*/
/*
* A note on the <ejb-link> link. The semantics of ejb-link when
* used to reference a remote ejb are not defined in the SLEE spec.
* In J2EE it is defined to mean a reference to an ejb deployed in
* the same J2EE application whose <ejb-name> is the same as the
* link (optionally the ejb-jar) file is also specifed. In SLEE
* there is no J2EE application and ejbs cannot be deployed in the
* SLEE container, therefore we do nothing with <ejb-link> since I
* am not sure what should be done with it anyway! - Tim
*/
}
/* Set the environment entries */
for (MEnvEntry mEnvEntry : sbbComponent.getDescriptor().getEnvEntries()) {
Class type = null;
if (logger.isDebugEnabled()) {
logger.debug("Got an environment entry:" + mEnvEntry);
}
try {
type = Thread.currentThread().getContextClassLoader()
.loadClass(mEnvEntry.getEnvEntryType());
} catch (Exception e) {
throw new DeploymentException(mEnvEntry.getEnvEntryType()
+ " is not a valid type for an environment entry");
}
Object entry = null;
String s = mEnvEntry.getEnvEntryValue();
try {
if (type == String.class) {
entry = new String(s);
} else if (type == Character.class) {
if (s.length() != 1) {
throw new DeploymentException(
s
+ " is not a valid value for an environment entry of type Character");
}
entry = new Character(s.charAt(0));
} else if (type == Integer.class) {
entry = new Integer(s);
} else if (type == Boolean.class) {
entry = new Boolean(s);
} else if (type == Double.class) {
entry = new Double(s);
} else if (type == Byte.class) {
entry = new Byte(s);
} else if (type == Short.class) {
entry = new Short(s);
} else if (type == Long.class) {
entry = new Long(s);
} else if (type == Float.class) {
entry = new Float(s);
}
} catch (NumberFormatException e) {
throw new DeploymentException("Environment entry value " + s
+ " is not a valid value for type " + type);
}
if (logger.isDebugEnabled()) {
logger.debug("Binding environment entry with name:"
+ mEnvEntry.getEnvEntryName() + " type " + entry.getClass()
+ " with value:" + entry + ". Current classloader = "
+ Thread.currentThread().getContextClassLoader());
}
try {
envCtx.bind(mEnvEntry.getEnvEntryName(), entry);
} catch (NameAlreadyBoundException ex) {
logger.error("Name already bound ! ", ex);
}
}
}
public void uninstallSbb(SbbComponent sbbComponent)
throws SystemException, Exception, NamingException {
final SleeTransactionManager sleeTransactionManager = sleeContainer
.getTransactionManager();
sleeTransactionManager.mandateTransaction();
if (logger.isDebugEnabled())
logger.debug("Uninstalling "+sbbComponent);
// remove sbb from trace and alarm facilities
sleeContainer.getTraceFacility().unSetTraceLevel(
sbbComponent.getSbbID());
sleeContainer.getAlarmFacility().unRegisterComponent(
sbbComponent.getSbbID());
if (logger.isDebugEnabled()) {
logger.debug("Removed SBB " + sbbComponent.getSbbID()
+ " from trace and alarm facilities");
}
}
}
| true | true | private void setupSbbEnvironment(SbbComponent sbbComponent) throws Exception {
Context ctx = (Context) new InitialContext().lookup("java:comp");
if (logger.isDebugEnabled()) {
logger.debug("Setting up SBB env. Initial context is " + ctx);
}
Context envCtx = null;
try {
envCtx = ctx.createSubcontext("env");
} catch (NameAlreadyBoundException ex) {
envCtx = (Context) ctx.lookup("env");
}
Context sleeCtx = null;
try {
sleeCtx = envCtx.createSubcontext("slee");
} catch (NameAlreadyBoundException ex) {
sleeCtx = (Context) envCtx.lookup("slee");
}
// Do all the context binding stuff just once during init and
// just do the linking here.
Context newCtx;
String containerName = "java:slee/container/Container";
try {
newCtx = sleeCtx.createSubcontext("container");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("container");
}
try {
newCtx.bind("Container", new LinkRef(containerName));
} catch (NameAlreadyBoundException ex) {
}
String nullAciFactory = "java:slee/nullactivity/nullactivitycontextinterfacefactory";
String nullActivityFactory = "java:slee/nullactivity/nullactivityfactory";
try {
newCtx = sleeCtx.createSubcontext("nullactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("nullactivity");
}
try {
newCtx.bind("activitycontextinterfacefactory", new LinkRef(
nullAciFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("factory", new LinkRef(nullActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String serviceActivityContextInterfaceFactory = "java:slee/serviceactivity/"
+ ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME;
String serviceActivityFactory = "java:slee/serviceactivity/"
+ ServiceActivityFactoryImpl.JNDI_NAME;
try {
newCtx = sleeCtx.createSubcontext("serviceactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("serviceactivity");
}
try {
newCtx.bind(ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME,
new LinkRef(serviceActivityContextInterfaceFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind(ServiceActivityFactoryImpl.JNDI_NAME, new LinkRef(
serviceActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String timer = "java:slee/facilities/" + TimerFacilityImpl.JNDI_NAME;
String aciNaming = "java:slee/facilities/activitycontextnaming";
try {
newCtx = sleeCtx.createSubcontext("facilities");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("facilities");
}
try {
newCtx.bind("timer", new LinkRef(timer));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("activitycontextnaming", new LinkRef(aciNaming));
} catch (NameAlreadyBoundException ex) {
}
String trace = "java:slee/facilities/trace";
try {
newCtx.bind("trace", new LinkRef(trace));
} catch (NameAlreadyBoundException ex) {
}
String alarm = "java:slee/facilities/alarm";
try {
//This has to be checked, to be sure sbb have it under correct jndi binding
AlarmFacility sbbAlarmFacility = new SbbAlarmFacilityImpl(sbbComponent.getSbbID(),sleeContainer.getAlarmFacility());
newCtx.bind("alarm", sbbAlarmFacility);
} catch (NameAlreadyBoundException ex) {
}
String profile = "java:slee/facilities/profile";
try {
newCtx.bind("profile", new LinkRef(profile));
} catch (NameAlreadyBoundException ex) {
}
String profilteTableAciFactory = "java:slee/facilities/profiletableactivitycontextinterfacefactory";
try {
newCtx.bind("profiletableactivitycontextinterfacefactory",
new LinkRef(profilteTableAciFactory));
} catch (NameAlreadyBoundException ex) {
}
// For each resource that the Sbb references, bind the implementing
// object name to its comp/env
if (logger.isDebugEnabled()) {
logger.debug("Number of Resource Bindings:"
+ sbbComponent.getDescriptor().getResourceAdaptorTypeBindings());
}
ComponentRepositoryImpl componentRepository = sleeContainer.getComponentRepositoryImpl();
for (MResourceAdaptorTypeBinding raTypeBinding : sbbComponent.getDescriptor().getResourceAdaptorTypeBindings()) {
ResourceAdaptorTypeComponent raTypeComponent = componentRepository.getComponentByID(raTypeBinding.getResourceAdaptorTypeRef());
for (MResourceAdaptorEntityBinding raEntityBinding : raTypeBinding.getResourceAdaptorEntityBinding()) {
String raObjectName = raEntityBinding.getResourceAdaptorObjectName();
String linkName = raEntityBinding.getResourceAdaptorEntityLink();
/*
* The Deployment descriptor specifies Zero or more
* resource-adaptor-entity-binding elements. Each
* resource-adaptor-entity-binding element binds an object that
* implements the resource adaptor interface of the resource
* adaptor type into the JNDI comp onent environment of the SBB
* (see Section 6.13.3). Each resource- adaptorentity- binding
* element contains the following sub-elements: A description
* element. This is an optional informational element. A
* resource-adaptor-object?name element. This element specifies
* the location within the JNDI component environment to which
* the object that implements the resource adaptor interface
* will be bound. A resource-adaptor-entity-link element. This
* is an optional element. It identifies the resource adaptor
* entity that provides the object that should be bound into the
* JNDI component environment of the SBB. The identified
* resource adaptor entity must be an instance of a resource
* adaptor whose resource adaptor type is specified by the
* resourceadaptor- type-ref sub-element of the enclosing
* resource-adaptortype- binding element.
*/
ResourceManagement resourceManagement = sleeContainer.getResourceManagement();
ResourceAdaptorEntity raEntity = resourceManagement
.getResourceAdaptorEntity(resourceManagement
.getResourceAdaptorEntityName(linkName));
if (raEntity == null)
throw new Exception(
"Could not find Resource adaptor Entity for Link Name: ["
+ linkName + "] of RA Type ["
+ raTypeComponent + "]");
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(raObjectName);
int tokenCount = local.size();
Context subContext = envCtx;
for (int i = 0; i < tokenCount - 1; i++) {
String nextTok = local.get(i);
try {
subContext.lookup(nextTok);
} catch (NameNotFoundException nfe) {
subContext.createSubcontext(nextTok);
} finally {
subContext = (Context) subContext.lookup(nextTok);
}
}
String lastTok = local.get(tokenCount - 1);
// Bind the resource adaptor instance to where the Sbb expects
// to find it.
if (logger.isDebugEnabled()) {
logger
.debug("setupSbbEnvironment: Binding a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
try {
NonSerializableFactory.rebind(subContext, lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
//subContext.bind(lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
String localFactoryName = raTypeBinding.getActivityContextInterfaceFactoryName();
if (localFactoryName != null) {
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(localFactoryName);
int nameSize = local.size();
Context tempCtx = envCtx;
for (int a = 0; a < nameSize - 1; a++) {
String temp = local.get(a);
try {
tempCtx.lookup(temp);
} catch (NameNotFoundException ne) {
tempCtx.createSubcontext(temp);
} finally {
tempCtx = (Context) tempCtx.lookup(temp);
}
}
if (logger.isDebugEnabled()) {
logger
.debug(
"setupSbbEnvironment: Binding a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
String factoryRefName = local.get(nameSize - 1);
try {
tempCtx
.bind(factoryRefName,raTypeComponent.getActivityContextInterfaceFactory());
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
}
/*
* Bind the ejb-refs
*/
try {
envCtx.createSubcontext("ejb");
} catch (NameAlreadyBoundException ex) {
envCtx.lookup("ejb");
}
if (logger.isDebugEnabled()) {
logger.debug("Created ejb local context");
}
for (MEjbRef ejbRef : sbbComponent.getDescriptor().getEjbRefs()) {
String jndiName = ejbRef.getEjbRefName();
if (logger.isDebugEnabled()) {
logger.debug("Binding ejb: " + ejbRef.getEjbRefName()
+ " with link to " + jndiName);
}
try {
envCtx.bind(ejbRef.getEjbRefName(), new LinkRef(jndiName));
} catch (NameAlreadyBoundException ex) {
}
/*
* Validate the ejb reference has the correct type and classes as
* specified in deployment descriptor
*/
/*
* TODO I think I know the problem here. It seems the ejb is loaded
* AFTER the sbb is loaded, hence the validation fails here since it
* cannot locate the ejb. We need to force the ejb to be loaded
* before the sbb
*/
/*
* Commented out for now
*
*
* Object obj = new InitialContext().lookup("java:comp/env/" +
* ejbRef.getEjbRefName());
*
* Object homeObject = null; try { Class homeClass =
* Thread.currentThread().getContextClassLoader().loadClass(home);
*
* homeObject = PortableRemoteObject.narrow(obj, homeClass);
*
* if (!homeClass.isInstance(homeObject)) { throw new
* DeploymentException("Looked up ejb home is not an instanceof " +
* home); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + home); } catch
* (ClassCastException e) { throw new DeploymentException("Failed to
* lookup ejb reference using jndi name " + jndiName); }
*
* Object ejb = null; try { Method m =
* homeObject.getClass().getMethod("create", null); Object ejbObject =
* m.invoke(home, null);
*
* Class ejbClass =
* Thread.currentThread().getContextClassLoader().loadClass(remote);
* if (!ejbClass.isInstance(ejbObject)) { throw new
* DeploymentException("Looked up ejb object is not an instanceof " +
* remote); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + remote); }
*
*/
/*
* A note on the <ejb-link> link. The semantics of ejb-link when
* used to reference a remote ejb are not defined in the SLEE spec.
* In J2EE it is defined to mean a reference to an ejb deployed in
* the same J2EE application whose <ejb-name> is the same as the
* link (optionally the ejb-jar) file is also specifed. In SLEE
* there is no J2EE application and ejbs cannot be deployed in the
* SLEE container, therefore we do nothing with <ejb-link> since I
* am not sure what should be done with it anyway! - Tim
*/
}
/* Set the environment entries */
for (MEnvEntry mEnvEntry : sbbComponent.getDescriptor().getEnvEntries()) {
Class type = null;
if (logger.isDebugEnabled()) {
logger.debug("Got an environment entry:" + mEnvEntry);
}
try {
type = Thread.currentThread().getContextClassLoader()
.loadClass(mEnvEntry.getEnvEntryType());
} catch (Exception e) {
throw new DeploymentException(mEnvEntry.getEnvEntryType()
+ " is not a valid type for an environment entry");
}
Object entry = null;
String s = mEnvEntry.getEnvEntryValue();
try {
if (type == String.class) {
entry = new String(s);
} else if (type == Character.class) {
if (s.length() != 1) {
throw new DeploymentException(
s
+ " is not a valid value for an environment entry of type Character");
}
entry = new Character(s.charAt(0));
} else if (type == Integer.class) {
entry = new Integer(s);
} else if (type == Boolean.class) {
entry = new Boolean(s);
} else if (type == Double.class) {
entry = new Double(s);
} else if (type == Byte.class) {
entry = new Byte(s);
} else if (type == Short.class) {
entry = new Short(s);
} else if (type == Long.class) {
entry = new Long(s);
} else if (type == Float.class) {
entry = new Float(s);
}
} catch (NumberFormatException e) {
throw new DeploymentException("Environment entry value " + s
+ " is not a valid value for type " + type);
}
if (logger.isDebugEnabled()) {
logger.debug("Binding environment entry with name:"
+ mEnvEntry.getEnvEntryName() + " type " + entry.getClass()
+ " with value:" + entry + ". Current classloader = "
+ Thread.currentThread().getContextClassLoader());
}
try {
envCtx.bind(mEnvEntry.getEnvEntryName(), entry);
} catch (NameAlreadyBoundException ex) {
logger.error("Name already bound ! ", ex);
}
}
}
| private void setupSbbEnvironment(SbbComponent sbbComponent) throws Exception {
Context ctx = (Context) new InitialContext().lookup("java:comp");
if (logger.isDebugEnabled()) {
logger.debug("Setting up SBB env. Initial context is " + ctx);
}
Context envCtx = null;
try {
envCtx = ctx.createSubcontext("env");
} catch (NameAlreadyBoundException ex) {
envCtx = (Context) ctx.lookup("env");
}
Context sleeCtx = null;
try {
sleeCtx = envCtx.createSubcontext("slee");
} catch (NameAlreadyBoundException ex) {
sleeCtx = (Context) envCtx.lookup("slee");
}
// Do all the context binding stuff just once during init and
// just do the linking here.
Context newCtx;
String containerName = "java:slee/container/Container";
try {
newCtx = sleeCtx.createSubcontext("container");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("container");
}
try {
newCtx.bind("Container", new LinkRef(containerName));
} catch (NameAlreadyBoundException ex) {
}
String nullAciFactory = "java:slee/nullactivity/nullactivitycontextinterfacefactory";
String nullActivityFactory = "java:slee/nullactivity/nullactivityfactory";
try {
newCtx = sleeCtx.createSubcontext("nullactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("nullactivity");
}
try {
newCtx.bind("activitycontextinterfacefactory", new LinkRef(
nullAciFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("factory", new LinkRef(nullActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String serviceActivityContextInterfaceFactory = "java:slee/serviceactivity/"
+ ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME;
String serviceActivityFactory = "java:slee/serviceactivity/"
+ ServiceActivityFactoryImpl.JNDI_NAME;
try {
newCtx = sleeCtx.createSubcontext("serviceactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("serviceactivity");
}
try {
newCtx.bind(ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME,
new LinkRef(serviceActivityContextInterfaceFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind(ServiceActivityFactoryImpl.JNDI_NAME, new LinkRef(
serviceActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String timer = "java:slee/facilities/" + TimerFacilityImpl.JNDI_NAME;
String aciNaming = "java:slee/facilities/activitycontextnaming";
try {
newCtx = sleeCtx.createSubcontext("facilities");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("facilities");
}
try {
newCtx.bind("timer", new LinkRef(timer));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("activitycontextnaming", new LinkRef(aciNaming));
} catch (NameAlreadyBoundException ex) {
}
String trace = "java:slee/facilities/trace";
try {
newCtx.bind("trace", new LinkRef(trace));
} catch (NameAlreadyBoundException ex) {
}
String alarm = "java:slee/facilities/alarm";
try {
//This has to be checked, to be sure sbb have it under correct jndi binding
AlarmFacility sbbAlarmFacility = new SbbAlarmFacilityImpl(sbbComponent.getSbbID(),sleeContainer.getAlarmFacility());
newCtx.bind("alarm", sbbAlarmFacility);
} catch (NameAlreadyBoundException ex) {
}
String profile = "java:slee/facilities/profile";
try {
newCtx.bind("profile", new LinkRef(profile));
} catch (NameAlreadyBoundException ex) {
}
String profilteTableAciFactory = "java:slee/facilities/profiletableactivitycontextinterfacefactory";
try {
newCtx.bind("profiletableactivitycontextinterfacefactory",
new LinkRef(profilteTableAciFactory));
} catch (NameAlreadyBoundException ex) {
}
// For each resource that the Sbb references, bind the implementing
// object name to its comp/env
if (logger.isDebugEnabled()) {
logger.debug("Number of Resource Bindings:"
+ sbbComponent.getDescriptor().getResourceAdaptorTypeBindings());
}
ComponentRepositoryImpl componentRepository = sleeContainer.getComponentRepositoryImpl();
for (MResourceAdaptorTypeBinding raTypeBinding : sbbComponent.getDescriptor().getResourceAdaptorTypeBindings()) {
ResourceAdaptorTypeComponent raTypeComponent = componentRepository.getComponentByID(raTypeBinding.getResourceAdaptorTypeRef());
for (MResourceAdaptorEntityBinding raEntityBinding : raTypeBinding.getResourceAdaptorEntityBinding()) {
String raObjectName = raEntityBinding.getResourceAdaptorObjectName();
String linkName = raEntityBinding.getResourceAdaptorEntityLink();
/*
* The Deployment descriptor specifies Zero or more
* resource-adaptor-entity-binding elements. Each
* resource-adaptor-entity-binding element binds an object that
* implements the resource adaptor interface of the resource
* adaptor type into the JNDI comp onent environment of the SBB
* (see Section 6.13.3). Each resource- adaptorentity- binding
* element contains the following sub-elements: A description
* element. This is an optional informational element. A
* resource-adaptor-object?name element. This element specifies
* the location within the JNDI component environment to which
* the object that implements the resource adaptor interface
* will be bound. A resource-adaptor-entity-link element. This
* is an optional element. It identifies the resource adaptor
* entity that provides the object that should be bound into the
* JNDI component environment of the SBB. The identified
* resource adaptor entity must be an instance of a resource
* adaptor whose resource adaptor type is specified by the
* resourceadaptor- type-ref sub-element of the enclosing
* resource-adaptortype- binding element.
*/
ResourceManagement resourceManagement = sleeContainer.getResourceManagement();
ResourceAdaptorEntity raEntity = resourceManagement
.getResourceAdaptorEntity(resourceManagement
.getResourceAdaptorEntityName(linkName));
if (raEntity == null)
throw new Exception(
"Could not find Resource adaptor Entity for Link Name: ["
+ linkName + "] of RA Type ["
+ raTypeComponent + "]");
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(raObjectName);
int tokenCount = local.size();
Context subContext = envCtx;
for (int i = 0; i < tokenCount - 1; i++) {
String nextTok = local.get(i);
try {
subContext.lookup(nextTok);
} catch (NameNotFoundException nfe) {
subContext.createSubcontext(nextTok);
} finally {
subContext = (Context) subContext.lookup(nextTok);
}
}
String lastTok = local.get(tokenCount - 1);
// Bind the resource adaptor instance to where the Sbb expects
// to find it.
if (logger.isDebugEnabled()) {
logger
.debug("setupSbbEnvironment: Binding a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
try {
Object raSbbInterface = raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef());
if (raSbbInterface != null) {
NonSerializableFactory.rebind(subContext, lastTok,raSbbInterface);
//subContext.bind(lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
}
else {
throw new DeploymentException("Unable to retrieve the RA interface for RA entity "+raEntity.getName()+" and RAType " +raTypeBinding.getResourceAdaptorTypeRef());
}
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
String localFactoryName = raTypeBinding.getActivityContextInterfaceFactoryName();
if (localFactoryName != null) {
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(localFactoryName);
int nameSize = local.size();
Context tempCtx = envCtx;
for (int a = 0; a < nameSize - 1; a++) {
String temp = local.get(a);
try {
tempCtx.lookup(temp);
} catch (NameNotFoundException ne) {
tempCtx.createSubcontext(temp);
} finally {
tempCtx = (Context) tempCtx.lookup(temp);
}
}
if (logger.isDebugEnabled()) {
logger
.debug(
"setupSbbEnvironment: Binding a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
String factoryRefName = local.get(nameSize - 1);
try {
tempCtx
.bind(factoryRefName,raTypeComponent.getActivityContextInterfaceFactory());
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
}
/*
* Bind the ejb-refs
*/
try {
envCtx.createSubcontext("ejb");
} catch (NameAlreadyBoundException ex) {
envCtx.lookup("ejb");
}
if (logger.isDebugEnabled()) {
logger.debug("Created ejb local context");
}
for (MEjbRef ejbRef : sbbComponent.getDescriptor().getEjbRefs()) {
String jndiName = ejbRef.getEjbRefName();
if (logger.isDebugEnabled()) {
logger.debug("Binding ejb: " + ejbRef.getEjbRefName()
+ " with link to " + jndiName);
}
try {
envCtx.bind(ejbRef.getEjbRefName(), new LinkRef(jndiName));
} catch (NameAlreadyBoundException ex) {
}
/*
* Validate the ejb reference has the correct type and classes as
* specified in deployment descriptor
*/
/*
* TODO I think I know the problem here. It seems the ejb is loaded
* AFTER the sbb is loaded, hence the validation fails here since it
* cannot locate the ejb. We need to force the ejb to be loaded
* before the sbb
*/
/*
* Commented out for now
*
*
* Object obj = new InitialContext().lookup("java:comp/env/" +
* ejbRef.getEjbRefName());
*
* Object homeObject = null; try { Class homeClass =
* Thread.currentThread().getContextClassLoader().loadClass(home);
*
* homeObject = PortableRemoteObject.narrow(obj, homeClass);
*
* if (!homeClass.isInstance(homeObject)) { throw new
* DeploymentException("Looked up ejb home is not an instanceof " +
* home); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + home); } catch
* (ClassCastException e) { throw new DeploymentException("Failed to
* lookup ejb reference using jndi name " + jndiName); }
*
* Object ejb = null; try { Method m =
* homeObject.getClass().getMethod("create", null); Object ejbObject =
* m.invoke(home, null);
*
* Class ejbClass =
* Thread.currentThread().getContextClassLoader().loadClass(remote);
* if (!ejbClass.isInstance(ejbObject)) { throw new
* DeploymentException("Looked up ejb object is not an instanceof " +
* remote); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + remote); }
*
*/
/*
* A note on the <ejb-link> link. The semantics of ejb-link when
* used to reference a remote ejb are not defined in the SLEE spec.
* In J2EE it is defined to mean a reference to an ejb deployed in
* the same J2EE application whose <ejb-name> is the same as the
* link (optionally the ejb-jar) file is also specifed. In SLEE
* there is no J2EE application and ejbs cannot be deployed in the
* SLEE container, therefore we do nothing with <ejb-link> since I
* am not sure what should be done with it anyway! - Tim
*/
}
/* Set the environment entries */
for (MEnvEntry mEnvEntry : sbbComponent.getDescriptor().getEnvEntries()) {
Class type = null;
if (logger.isDebugEnabled()) {
logger.debug("Got an environment entry:" + mEnvEntry);
}
try {
type = Thread.currentThread().getContextClassLoader()
.loadClass(mEnvEntry.getEnvEntryType());
} catch (Exception e) {
throw new DeploymentException(mEnvEntry.getEnvEntryType()
+ " is not a valid type for an environment entry");
}
Object entry = null;
String s = mEnvEntry.getEnvEntryValue();
try {
if (type == String.class) {
entry = new String(s);
} else if (type == Character.class) {
if (s.length() != 1) {
throw new DeploymentException(
s
+ " is not a valid value for an environment entry of type Character");
}
entry = new Character(s.charAt(0));
} else if (type == Integer.class) {
entry = new Integer(s);
} else if (type == Boolean.class) {
entry = new Boolean(s);
} else if (type == Double.class) {
entry = new Double(s);
} else if (type == Byte.class) {
entry = new Byte(s);
} else if (type == Short.class) {
entry = new Short(s);
} else if (type == Long.class) {
entry = new Long(s);
} else if (type == Float.class) {
entry = new Float(s);
}
} catch (NumberFormatException e) {
throw new DeploymentException("Environment entry value " + s
+ " is not a valid value for type " + type);
}
if (logger.isDebugEnabled()) {
logger.debug("Binding environment entry with name:"
+ mEnvEntry.getEnvEntryName() + " type " + entry.getClass()
+ " with value:" + entry + ". Current classloader = "
+ Thread.currentThread().getContextClassLoader());
}
try {
envCtx.bind(mEnvEntry.getEnvEntryName(), entry);
} catch (NameAlreadyBoundException ex) {
logger.error("Name already bound ! ", ex);
}
}
}
|
diff --git a/weaver/src/org/aspectj/weaver/patterns/ExactAnnotationFieldTypePattern.java b/weaver/src/org/aspectj/weaver/patterns/ExactAnnotationFieldTypePattern.java
index ba4ebef4f..66f36a229 100644
--- a/weaver/src/org/aspectj/weaver/patterns/ExactAnnotationFieldTypePattern.java
+++ b/weaver/src/org/aspectj/weaver/patterns/ExactAnnotationFieldTypePattern.java
@@ -1,200 +1,201 @@
/* *******************************************************************
* Copyright (c) 2008 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
import org.aspectj.bridge.IMessage;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.AnnotatedElement;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.World;
/**
* Represents an attempt to bind the field of an annotation within a pointcut. For example:<br>
* <code><pre>
* before(Level lev): execution(* *(..)) && @annotation(TraceAnnotation(lev))
* </pre></code><br>
* This binding annotation type pattern will be for 'lev'.
*/
public class ExactAnnotationFieldTypePattern extends ExactAnnotationTypePattern {
UnresolvedType annotationType;
private ResolvedMember field;
public ExactAnnotationFieldTypePattern(ExactAnnotationTypePattern p, String formalName) {
super(formalName);
this.annotationType = p.annotationType;
this.copyLocationFrom(p);
}
public ExactAnnotationFieldTypePattern(UnresolvedType annotationType, String formalName) {
super(formalName);
this.annotationType = annotationType;
}
/**
* resolve one of these funky things. Need to: <br>
* (a) Check the formal is bound <br>
* (b) Check the annotation type is valid
*/
public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) {
if (resolved) return this;
resolved = true;
FormalBinding formalBinding = scope.lookupFormal(formalName);
if (formalBinding == null) {
- scope.message(IMessage.ERROR, this, "when using @annotation(<annotationType>(<annotationField>)), <annotationField> must be bound");
+ scope.message(IMessage.ERROR, this, "When using @annotation(<annotationType>(<annotationField>)), <annotationField> must be bound");
+ return this;
}
annotationType = scope.getWorld().resolve(annotationType, true);
// May not be directly found if in a package, so go looking if that is the case:
if (ResolvedType.isMissing(annotationType)) {
String cleanname = annotationType.getName();
UnresolvedType type = null;
while (ResolvedType.isMissing(type = scope.lookupType(cleanname, this))) {
int lastDot = cleanname.lastIndexOf('.');
if (lastDot == -1) break;
cleanname = cleanname.substring(0, lastDot) + "$" + cleanname.substring(lastDot + 1);
}
annotationType = scope.getWorld().resolve(type, true);
}
verifyIsAnnotationType((ResolvedType) annotationType, scope);
if (!formalBinding.getType().resolve(scope.getWorld()).isEnum()) {
scope.message(IMessage.ERROR, this, "The field within the annotation must be an Enum. '" + formalBinding.getType()
+ "' is not an Enum (compiler limitation)");
}
bindingPattern = true;
// Check that the formal is bound to a type that is represented by one field in the annotation type
ReferenceType theAnnotationType = (ReferenceType) annotationType;
ResolvedMember[] annotationFields = theAnnotationType.getDeclaredMethods();
field = null;
for (int i = 0; i < annotationFields.length; i++) {
ResolvedMember resolvedMember = annotationFields[i];
if (resolvedMember.getReturnType().equals(formalBinding.getType())) {
if (field != null) {
scope.message(IMessage.ERROR, this, "The field type '" + formalBinding.getType() + "' is ambiguous for annotation type '"
+ theAnnotationType.getName() + "'");
}
field = resolvedMember;
}
}
if (field == null) {
scope.message(IMessage.ERROR, this, "No field of type '" + formalBinding.getType() + "' exists on annotation type '"
+ theAnnotationType.getName() + "'");
}
BindingAnnotationFieldTypePattern binding = new BindingAnnotationFieldTypePattern(formalBinding.getType(), formalBinding.getIndex(),
theAnnotationType);
binding.copyLocationFrom(this);
bindings.register(binding, scope);
binding.resolveBinding(scope.getWorld());
return binding;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(AnnotationTypePattern.EXACTFIELD);
s.writeUTF(formalName);
annotationType.write(s);
writeLocation(s);
}
public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException {
ExactAnnotationFieldTypePattern ret;
String formalName = s.readUTF();
UnresolvedType annotationType = UnresolvedType.read(s);
ret = new ExactAnnotationFieldTypePattern(annotationType, formalName);
ret.readLocation(context, s);
return ret;
}
// ---
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public boolean equals(Object obj) {
if (!(obj instanceof ExactAnnotationFieldTypePattern)) return false;
ExactAnnotationFieldTypePattern other = (ExactAnnotationFieldTypePattern) obj;
return
(other.annotationType.equals(annotationType)) &&
(other.field.equals(field)) && (other.formalName.equals(this.formalName));
}
public int hashCode() {
int hashcode = annotationType.hashCode();
hashcode = hashcode * 37 + field.hashCode();
hashcode = hashcode * 37 + formalName.hashCode();
return hashcode;
}
// TODO these are currently unimplemented as I believe it resolves to a Binding form *always* and so they don't get
// called
public FuzzyBoolean fastMatches(AnnotatedElement annotated) {
throw new BCException("unimplemented");
}
public UnresolvedType getAnnotationType() {
throw new BCException("unimplemented");
}
public Map getAnnotationValues() {
throw new BCException("unimplemented");
}
public ResolvedType getResolvedAnnotationType() {
throw new BCException("unimplemented");
}
public FuzzyBoolean matches(AnnotatedElement annotated, ResolvedType[] parameterAnnotations) {
throw new BCException("unimplemented");
}
public FuzzyBoolean matches(AnnotatedElement annotated) {
throw new BCException("unimplemented");
}
public FuzzyBoolean matchesRuntimeType(AnnotatedElement annotated) {
throw new BCException("unimplemented");
}
public AnnotationTypePattern parameterizeWith(Map typeVariableMap, World w) {
throw new BCException("unimplemented");
}
public void resolve(World world) {
throw new BCException("unimplemented");
}
public String toString() {
if (!resolved && formalName != null) return formalName;
StringBuffer ret = new StringBuffer();
ret.append("@").append(annotationType.toString());
ret.append("(").append(formalName).append(")");
return ret.toString();
}
}
| true | true | public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) {
if (resolved) return this;
resolved = true;
FormalBinding formalBinding = scope.lookupFormal(formalName);
if (formalBinding == null) {
scope.message(IMessage.ERROR, this, "when using @annotation(<annotationType>(<annotationField>)), <annotationField> must be bound");
}
annotationType = scope.getWorld().resolve(annotationType, true);
// May not be directly found if in a package, so go looking if that is the case:
if (ResolvedType.isMissing(annotationType)) {
String cleanname = annotationType.getName();
UnresolvedType type = null;
while (ResolvedType.isMissing(type = scope.lookupType(cleanname, this))) {
int lastDot = cleanname.lastIndexOf('.');
if (lastDot == -1) break;
cleanname = cleanname.substring(0, lastDot) + "$" + cleanname.substring(lastDot + 1);
}
annotationType = scope.getWorld().resolve(type, true);
}
verifyIsAnnotationType((ResolvedType) annotationType, scope);
if (!formalBinding.getType().resolve(scope.getWorld()).isEnum()) {
scope.message(IMessage.ERROR, this, "The field within the annotation must be an Enum. '" + formalBinding.getType()
+ "' is not an Enum (compiler limitation)");
}
bindingPattern = true;
// Check that the formal is bound to a type that is represented by one field in the annotation type
ReferenceType theAnnotationType = (ReferenceType) annotationType;
ResolvedMember[] annotationFields = theAnnotationType.getDeclaredMethods();
field = null;
for (int i = 0; i < annotationFields.length; i++) {
ResolvedMember resolvedMember = annotationFields[i];
if (resolvedMember.getReturnType().equals(formalBinding.getType())) {
if (field != null) {
scope.message(IMessage.ERROR, this, "The field type '" + formalBinding.getType() + "' is ambiguous for annotation type '"
+ theAnnotationType.getName() + "'");
}
field = resolvedMember;
}
}
if (field == null) {
scope.message(IMessage.ERROR, this, "No field of type '" + formalBinding.getType() + "' exists on annotation type '"
+ theAnnotationType.getName() + "'");
}
BindingAnnotationFieldTypePattern binding = new BindingAnnotationFieldTypePattern(formalBinding.getType(), formalBinding.getIndex(),
theAnnotationType);
binding.copyLocationFrom(this);
bindings.register(binding, scope);
binding.resolveBinding(scope.getWorld());
return binding;
}
| public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) {
if (resolved) return this;
resolved = true;
FormalBinding formalBinding = scope.lookupFormal(formalName);
if (formalBinding == null) {
scope.message(IMessage.ERROR, this, "When using @annotation(<annotationType>(<annotationField>)), <annotationField> must be bound");
return this;
}
annotationType = scope.getWorld().resolve(annotationType, true);
// May not be directly found if in a package, so go looking if that is the case:
if (ResolvedType.isMissing(annotationType)) {
String cleanname = annotationType.getName();
UnresolvedType type = null;
while (ResolvedType.isMissing(type = scope.lookupType(cleanname, this))) {
int lastDot = cleanname.lastIndexOf('.');
if (lastDot == -1) break;
cleanname = cleanname.substring(0, lastDot) + "$" + cleanname.substring(lastDot + 1);
}
annotationType = scope.getWorld().resolve(type, true);
}
verifyIsAnnotationType((ResolvedType) annotationType, scope);
if (!formalBinding.getType().resolve(scope.getWorld()).isEnum()) {
scope.message(IMessage.ERROR, this, "The field within the annotation must be an Enum. '" + formalBinding.getType()
+ "' is not an Enum (compiler limitation)");
}
bindingPattern = true;
// Check that the formal is bound to a type that is represented by one field in the annotation type
ReferenceType theAnnotationType = (ReferenceType) annotationType;
ResolvedMember[] annotationFields = theAnnotationType.getDeclaredMethods();
field = null;
for (int i = 0; i < annotationFields.length; i++) {
ResolvedMember resolvedMember = annotationFields[i];
if (resolvedMember.getReturnType().equals(formalBinding.getType())) {
if (field != null) {
scope.message(IMessage.ERROR, this, "The field type '" + formalBinding.getType() + "' is ambiguous for annotation type '"
+ theAnnotationType.getName() + "'");
}
field = resolvedMember;
}
}
if (field == null) {
scope.message(IMessage.ERROR, this, "No field of type '" + formalBinding.getType() + "' exists on annotation type '"
+ theAnnotationType.getName() + "'");
}
BindingAnnotationFieldTypePattern binding = new BindingAnnotationFieldTypePattern(formalBinding.getType(), formalBinding.getIndex(),
theAnnotationType);
binding.copyLocationFrom(this);
bindings.register(binding, scope);
binding.resolveBinding(scope.getWorld());
return binding;
}
|
diff --git a/src/com/marakana/android/stream/db/dao/PostsDao.java b/src/com/marakana/android/stream/db/dao/PostsDao.java
index 1e92e1e..f6ee496 100644
--- a/src/com/marakana/android/stream/db/dao/PostsDao.java
+++ b/src/com/marakana/android/stream/db/dao/PostsDao.java
@@ -1,190 +1,190 @@
/* $Id: $
Copyright 2012, G. Blake Meike
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.marakana.android.stream.db.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.text.TextUtils;
import android.util.Log;
import com.marakana.android.stream.BuildConfig;
import com.marakana.android.stream.db.ProjectionMap;
import com.marakana.android.stream.db.ColumnMap;
import com.marakana.android.stream.db.DbHelper;
import com.marakana.android.stream.db.StreamContract;
/**
* Using URIs as foreign keys is really convenient, but pretty expensive, space-wise.
* Might have to fix that, at some point in the future.
*
* @version $Revision: $
* @author <a href="mailto:[email protected]">G. Blake Meike</a>
*/
public class PostsDao extends BaseDao {
private static final String TAG = "POSTS-DAO";
static final String TABLE = "posts";
static final String COL_ID = "id";
private static final String COL_URI = "uri";
private static final String COL_TITLE = "title";
private static final String COL_AUTHOR = "author";
private static final String COL_DATE = "pub_date";
private static final String COL_TAGS = "tags";
private static final String COL_SUMMARY = "summary";
private static final String COL_CONTENT = "content";
private static final String COL_TYPE = "type";
private static final String COL_THUMB = "thumb";
private static final String CREATE_TABLE
= "CREATE TABLE " + TABLE + " ("
+ COL_ID + " integer PRIMARY KEY AUTOINCREMENT,"
+ COL_URI + " text UNIQUE,"
+ COL_TITLE + " text,"
+ COL_AUTHOR + " text REFERENCES " + AuthorsDao.TABLE + "(" + AuthorsDao.COL_URI + "),"
+ COL_DATE + " integer,"
+ COL_TAGS + " text,"
+ COL_SUMMARY + " text,"
+ COL_THUMB + " text REFERENCES " + ThumbsDao.TABLE + "(" + ThumbsDao.COL_URI + "),"
+ COL_TYPE + " text,"
+ COL_CONTENT + " text)";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE;
private static final String FEED_TABLE
= TABLE + " INNER JOIN " + AuthorsDao.TABLE
+ " ON(" + TABLE + "." + COL_AUTHOR
+ "=" + AuthorsDao.TABLE + "." + AuthorsDao.COL_URI + ")"
+ " LEFT OUTER JOIN " + ThumbsDao.TABLE
+ " ON(" + TABLE + "." + COL_THUMB
+ "=" + ThumbsDao.TABLE + "." + ThumbsDao.COL_URI + ")";
private static final ProjectionMap FEED_COL_AS_MAP = new ProjectionMap.Builder()
.addColumn(StreamContract.Feed.Columns.ID, TABLE, COL_ID)
.addColumn(StreamContract.Feed.Columns.TITLE, TABLE, COL_TITLE)
.addColumn(StreamContract.Feed.Columns.AUTHOR, AuthorsDao.TABLE, AuthorsDao.COL_NAME)
.addColumn(StreamContract.Feed.Columns.PUB_DATE, TABLE, COL_DATE)
.addColumn(StreamContract.Feed.Columns.SUMMARY, TABLE, COL_SUMMARY)
.addColumn(StreamContract.Feed.Columns.TAGS, TABLE, COL_TAGS)
.addColumn(StreamContract.Feed.Columns.CONTENT, TABLE, COL_CONTENT)
.addColumn(StreamContract.Feed.Columns.THUMB, ThumbsDao.TABLE, ThumbsDao.COL_ID)
.build();
private static final String PK_CONSTRAINT = COL_ID + "=";
private static final String DEFAULT_SORT = StreamContract.Posts.Columns.PUB_DATE + " DESC";
/**
* @param context
* @param db
*/
public static void dropTable(Context context, SQLiteDatabase db) {
if (BuildConfig.DEBUG) { Log.d(TAG, "drop posts db: " + DROP_TABLE); }
db.execSQL(DROP_TABLE);
}
/**
* @param context
* @param db
*/
public static void initDb(Context context, SQLiteDatabase db) {
if (BuildConfig.DEBUG) { Log.d(TAG, "create posts db: " + CREATE_TABLE); }
db.execSQL(CREATE_TABLE);
}
/**
* @param dbHelper
*/
public PostsDao(DbHelper dbHelper) {
super(
TAG,
dbHelper,
TABLE,
COL_ID,
DEFAULT_SORT,
new ColumnMap.Builder()
.addColumn(StreamContract.Posts.Columns.ID, COL_ID, ColumnMap.Type.LONG)
.addColumn(StreamContract.Posts.Columns.LINK, COL_URI, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.TITLE, COL_TITLE, ColumnMap.Type.STRING)
- .addColumn(StreamContract.Posts.Columns.AUTHOR, COL_AUTHOR, ColumnMap.Type.LONG)
- .addColumn(StreamContract.Posts.Columns.PUB_DATE, COL_DATE, ColumnMap.Type.STRING)
+ .addColumn(StreamContract.Posts.Columns.AUTHOR, COL_AUTHOR, ColumnMap.Type.STRING)
+ .addColumn(StreamContract.Posts.Columns.PUB_DATE, COL_DATE, ColumnMap.Type.LONG)
.addColumn(StreamContract.Posts.Columns.TAGS, COL_TAGS, ColumnMap.Type.STRING)
- .addColumn(StreamContract.Posts.Columns.SUMMARY, COL_SUMMARY, ColumnMap.Type.LONG)
- .addColumn(StreamContract.Posts.Columns.LINK, COL_THUMB, ColumnMap.Type.STRING)
+ .addColumn(StreamContract.Posts.Columns.SUMMARY, COL_SUMMARY, ColumnMap.Type.STRING)
+ .addColumn(StreamContract.Posts.Columns.THUMB, COL_THUMB, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.TYPE, COL_TYPE, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.CONTENT, COL_CONTENT, ColumnMap.Type.STRING)
.build(),
new ProjectionMap.Builder()
.addColumn(StreamContract.Posts.Columns.ID, COL_ID)
.addColumn(StreamContract.Posts.Columns.TITLE, COL_TITLE)
.addColumn(StreamContract.Posts.Columns.AUTHOR, COL_AUTHOR)
.addColumn(StreamContract.Posts.Columns.PUB_DATE, COL_DATE)
.addColumn(StreamContract.Posts.Columns.SUMMARY, COL_SUMMARY)
.addColumn(StreamContract.Posts.Columns.TAGS, COL_TAGS)
.addColumn(StreamContract.Posts.Columns.CONTENT, COL_CONTENT)
.addColumn(StreamContract.Posts.Columns.THUMB, COL_THUMB)
.addColumn(
StreamContract.Posts.Columns.MAX_PUB_DATE,
"MAX(" + StreamContract.Posts.Columns.PUB_DATE + ")")
.build());
}
/**
* @param vals
* @return the count of inserted rows
*/
public int bulkInsert(ContentValues[] vals) {
int n = 0;
SQLiteDatabase db = getDb();
try {
db.beginTransaction();
for (ContentValues row: vals) {
if (0 <= insert(row)) { n++; }
}
db.setTransactionSuccessful();
}
finally { db.endTransaction(); }
return n;
}
/**
* @param proj
* @param sel
* @param args
* @param ord
* @param pk
* @return cursor
*/
public Cursor queryFeed(String[] proj, String sel, String[] args, String ord, long pk) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setStrict(true);
qb.setProjectionMap(FEED_COL_AS_MAP.getProjectionMap());
qb.setTables(FEED_TABLE);
if (0 <= pk) { qb.appendWhere(PK_CONSTRAINT + pk); }
if (TextUtils.isEmpty(ord)) { ord = DEFAULT_SORT; }
return qb.query(getDb(), proj, sel, args, null, null, ord);
}
}
| false | true | public PostsDao(DbHelper dbHelper) {
super(
TAG,
dbHelper,
TABLE,
COL_ID,
DEFAULT_SORT,
new ColumnMap.Builder()
.addColumn(StreamContract.Posts.Columns.ID, COL_ID, ColumnMap.Type.LONG)
.addColumn(StreamContract.Posts.Columns.LINK, COL_URI, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.TITLE, COL_TITLE, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.AUTHOR, COL_AUTHOR, ColumnMap.Type.LONG)
.addColumn(StreamContract.Posts.Columns.PUB_DATE, COL_DATE, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.TAGS, COL_TAGS, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.SUMMARY, COL_SUMMARY, ColumnMap.Type.LONG)
.addColumn(StreamContract.Posts.Columns.LINK, COL_THUMB, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.TYPE, COL_TYPE, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.CONTENT, COL_CONTENT, ColumnMap.Type.STRING)
.build(),
new ProjectionMap.Builder()
.addColumn(StreamContract.Posts.Columns.ID, COL_ID)
.addColumn(StreamContract.Posts.Columns.TITLE, COL_TITLE)
.addColumn(StreamContract.Posts.Columns.AUTHOR, COL_AUTHOR)
.addColumn(StreamContract.Posts.Columns.PUB_DATE, COL_DATE)
.addColumn(StreamContract.Posts.Columns.SUMMARY, COL_SUMMARY)
.addColumn(StreamContract.Posts.Columns.TAGS, COL_TAGS)
.addColumn(StreamContract.Posts.Columns.CONTENT, COL_CONTENT)
.addColumn(StreamContract.Posts.Columns.THUMB, COL_THUMB)
.addColumn(
StreamContract.Posts.Columns.MAX_PUB_DATE,
"MAX(" + StreamContract.Posts.Columns.PUB_DATE + ")")
.build());
}
| public PostsDao(DbHelper dbHelper) {
super(
TAG,
dbHelper,
TABLE,
COL_ID,
DEFAULT_SORT,
new ColumnMap.Builder()
.addColumn(StreamContract.Posts.Columns.ID, COL_ID, ColumnMap.Type.LONG)
.addColumn(StreamContract.Posts.Columns.LINK, COL_URI, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.TITLE, COL_TITLE, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.AUTHOR, COL_AUTHOR, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.PUB_DATE, COL_DATE, ColumnMap.Type.LONG)
.addColumn(StreamContract.Posts.Columns.TAGS, COL_TAGS, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.SUMMARY, COL_SUMMARY, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.THUMB, COL_THUMB, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.TYPE, COL_TYPE, ColumnMap.Type.STRING)
.addColumn(StreamContract.Posts.Columns.CONTENT, COL_CONTENT, ColumnMap.Type.STRING)
.build(),
new ProjectionMap.Builder()
.addColumn(StreamContract.Posts.Columns.ID, COL_ID)
.addColumn(StreamContract.Posts.Columns.TITLE, COL_TITLE)
.addColumn(StreamContract.Posts.Columns.AUTHOR, COL_AUTHOR)
.addColumn(StreamContract.Posts.Columns.PUB_DATE, COL_DATE)
.addColumn(StreamContract.Posts.Columns.SUMMARY, COL_SUMMARY)
.addColumn(StreamContract.Posts.Columns.TAGS, COL_TAGS)
.addColumn(StreamContract.Posts.Columns.CONTENT, COL_CONTENT)
.addColumn(StreamContract.Posts.Columns.THUMB, COL_THUMB)
.addColumn(
StreamContract.Posts.Columns.MAX_PUB_DATE,
"MAX(" + StreamContract.Posts.Columns.PUB_DATE + ")")
.build());
}
|
diff --git a/Java/src/main/java/net/decasdev/dokan/FileAccess.java b/Java/src/main/java/net/decasdev/dokan/FileAccess.java
index 44930cf..434657b 100644
--- a/Java/src/main/java/net/decasdev/dokan/FileAccess.java
+++ b/Java/src/main/java/net/decasdev/dokan/FileAccess.java
@@ -1,78 +1,78 @@
/*
JDokan : Java library for Dokan
Copyright (C) 2008 Yu Kobayashi http://yukoba.accelart.jp/
2009 Caleido AG http://www.wuala.com/
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.decasdev.dokan;
import java.util.EnumSet;
import java.util.Set;
public class FileAccess {
public enum FileAccessFlags {
// these are the observed values that are passed to onCreateFile
GENERIC_ALL(0x10000000),
GENERIC_EXECUTE(0x20000000),
GENERIC_WRITE(0x40000000),
GENERIC_READ(0x80000000);
private int value;
FileAccessFlags(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Translates a numeric status code into a Set of StatusFlag enums
* @param value
* @return EnumSet representing a documents status
*/
public static EnumSet<FileAccessFlags> getFlags(int value)
{
- EnumSet flags = EnumSet.noneOf(FileAccessFlags.class);
+ EnumSet<FileAccessFlags> flags = EnumSet.noneOf(FileAccessFlags.class);
- for (CreationDisposition disp : CreationDisposition.values()) {
- long flag = disp.getValue();
- if ((flag & value) == value)
+ for (FileAccessFlags flag: FileAccessFlags.values()) {
+ long flagValue = flag.getValue();
+ if ((flagValue & value) == value)
flags.add(flag);
}
return flags;
}
/**
* Translates a set of flags enums into a numeric status code
* @param flags if statusFlags
* @return numeric representation of the document status
*/
public static long getStatusValue(Set<FileAccessFlags> flags)
{
long value=0;
for (FileAccessFlags flag: flags) {
value |= flag.getValue();
}
return value;
}
}
| false | true | public static EnumSet<FileAccessFlags> getFlags(int value)
{
EnumSet flags = EnumSet.noneOf(FileAccessFlags.class);
for (CreationDisposition disp : CreationDisposition.values()) {
long flag = disp.getValue();
if ((flag & value) == value)
flags.add(flag);
}
return flags;
}
| public static EnumSet<FileAccessFlags> getFlags(int value)
{
EnumSet<FileAccessFlags> flags = EnumSet.noneOf(FileAccessFlags.class);
for (FileAccessFlags flag: FileAccessFlags.values()) {
long flagValue = flag.getValue();
if ((flagValue & value) == value)
flags.add(flag);
}
return flags;
}
|
diff --git a/src/main/java/com/philihp/weblabora/model/CommandConvert.java b/src/main/java/com/philihp/weblabora/model/CommandConvert.java
index 4444d1d..1529537 100644
--- a/src/main/java/com/philihp/weblabora/model/CommandConvert.java
+++ b/src/main/java/com/philihp/weblabora/model/CommandConvert.java
@@ -1,48 +1,48 @@
package com.philihp.weblabora.model;
import static com.philihp.weblabora.model.TerrainTypeEnum.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.philihp.weblabora.model.building.*;
public class CommandConvert implements MoveCommand {
@Override
public void execute(Board board, CommandParameters params)
throws WeblaboraException {
UsageParam usageParam = new UsageParam(params.get(0));
execute(board, usageParam);
System.out.println("Converting " + usageParam);
}
public static void execute(Board board, UsageParam param) throws WeblaboraException {
if(param.getPenny() % 5 != 0) {
throw new WeblaboraException("Can only convert pennies in multiples of 5. Are you sure you meant to convert "+param.getPenny()+"?");
}
Player player = board.getPlayer(board.getActivePlayer());
player.subtractGrain(param.getGrain());
player.addStraw(param.getGrain());
player.subtractBeer(param.getBeer());
player.addPenny(param.getBeer()*2);
player.subtractWine(param.getWine());
player.addPenny(param.getWine());
player.subtractNickel(param.getNickel());
- player.addPenny(param.getPenny()*5);
+ player.addPenny(param.getNickel()*5);
- player.subtractPenny(param.getPenny());
+ player.subtractCoins(param.getPenny());
player.addNickel(param.getPenny()/5);
player.addPenny(param.getPenny()%5);
}
}
| false | true | public static void execute(Board board, UsageParam param) throws WeblaboraException {
if(param.getPenny() % 5 != 0) {
throw new WeblaboraException("Can only convert pennies in multiples of 5. Are you sure you meant to convert "+param.getPenny()+"?");
}
Player player = board.getPlayer(board.getActivePlayer());
player.subtractGrain(param.getGrain());
player.addStraw(param.getGrain());
player.subtractBeer(param.getBeer());
player.addPenny(param.getBeer()*2);
player.subtractWine(param.getWine());
player.addPenny(param.getWine());
player.subtractNickel(param.getNickel());
player.addPenny(param.getPenny()*5);
player.subtractPenny(param.getPenny());
player.addNickel(param.getPenny()/5);
player.addPenny(param.getPenny()%5);
}
| public static void execute(Board board, UsageParam param) throws WeblaboraException {
if(param.getPenny() % 5 != 0) {
throw new WeblaboraException("Can only convert pennies in multiples of 5. Are you sure you meant to convert "+param.getPenny()+"?");
}
Player player = board.getPlayer(board.getActivePlayer());
player.subtractGrain(param.getGrain());
player.addStraw(param.getGrain());
player.subtractBeer(param.getBeer());
player.addPenny(param.getBeer()*2);
player.subtractWine(param.getWine());
player.addPenny(param.getWine());
player.subtractNickel(param.getNickel());
player.addPenny(param.getNickel()*5);
player.subtractCoins(param.getPenny());
player.addNickel(param.getPenny()/5);
player.addPenny(param.getPenny()%5);
}
|
diff --git a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ViewRequisition.java b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ViewRequisition.java
index f519ed99b9..e4e327cb99 100644
--- a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ViewRequisition.java
+++ b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ViewRequisition.java
@@ -1,270 +1,271 @@
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.functional;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.pageobjects.*;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.assertEquals;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class ViewRequisition extends TestCaseHelper {
public static final String STORE_IN_CHARGE = "store in-charge";
public static final String APPROVE_REQUISITION = "APPROVE_REQUISITION";
public static final String CONVERT_TO_ORDER = "CONVERT_TO_ORDER";
public static final String SUBMITTED = "SUBMITTED";
public static final String AUTHORIZED = "AUTHORIZED";
public static final String IN_APPROVAL = "IN_APPROVAL";
public static final String APPROVED = "APPROVED";
public static final String RELEASED = "RELEASED";
public static final String VIEW_ORDER = "VIEW_ORDER";
public static final String patientsOnTreatment = "100";
public static final String patientsToInitiateTreatment = "200";
public static final String patientsStoppedTreatment = "300";
public static final String remarks = "testing";
public String program, userSIC, password;
@BeforeMethod(groups = "requisition")
@Before
public void setUp() throws Exception {
super.setup();
}
@When("^I populate Regimen data as patientsOnTreatment \"([^\"]*)\" patientsToInitiateTreatment \"([^\"]*)\" patientsStoppedTreatment \"([^\"]*)\" remarks \"([^\"]*)\"$")
public void enterValuesFromDB(String patientsOnTreatment, String patientsToInitiateTreatment, String patientsStoppedTreatment, String remarks) throws IOException, SQLException {
dbWrapper.insertValuesInRegimenLineItems(patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
}
@When("^I access home page")
public void accessHomePage() throws IOException, SQLException {
InitiateRnRPage initiateRnRPage=new InitiateRnRPage(testWebDriver);
initiateRnRPage.clickHome();
}
@When("^I access view RnR screen$")
public void accessViewRnRScreen() throws IOException {
HomePage homePage = new HomePage(testWebDriver);
homePage.navigateViewRequisition();
}
@Then("^I should see elements on view requisition page$")
public void shouldSeeElementsOnViewRequisitionPage() throws IOException {
ViewRequisitionPage viewRequisitionPage = new ViewRequisitionPage(testWebDriver);
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
}
@When("^I update requisition status to \"([^\"]*)\"$")
public void updateRequisitionStatus(String status) throws IOException, SQLException {
dbWrapper.updateRequisitionStatus(status, "storeincharge", "HIV");
}
@When("^I type view search criteria$")
public void typeViewResultCriteria() throws IOException, SQLException {
ViewRequisitionPage viewRequisitionPage = new ViewRequisitionPage(testWebDriver);
viewRequisitionPage.enterViewSearchCriteria();
}
@When("^I click search$")
public void clickSearch() throws IOException, SQLException {
ViewRequisitionPage viewRequisitionPage = new ViewRequisitionPage(testWebDriver);
viewRequisitionPage.clickSearch();
}
@When("^I access regimen tab for view requisition$")
public void clickRegimenTab() throws IOException, SQLException {
ViewRequisitionPage viewRequisitionPage = new ViewRequisitionPage(testWebDriver);
viewRequisitionPage.clickRegimenTab();
}
@Then("^I should see no requisition found message$")
public void shouldSeeNoRequisitionMessage() throws IOException, SQLException {
ViewRequisitionPage viewRequisitionPage = new ViewRequisitionPage(testWebDriver);
viewRequisitionPage.verifyNoRequisitionFound();
}
@When("^I update approved quantity \"([^\"]*)\"$")
public void updateApprovedQuantity(String quantity) throws IOException, SQLException {
dbWrapper.insertApprovedQuantity(Integer.parseInt(quantity));
}
@Then("^I should see requisition status as \"([^\"]*)\"$")
public void verifyRequisitionStatus(String status) throws IOException, SQLException {
ViewRequisitionPage viewRequisitionPage = new ViewRequisitionPage(testWebDriver);
viewRequisitionPage.verifyStatus(status);
}
@When("^I click RnR List$")
public void clickRnRList() throws IOException, SQLException {
ViewRequisitionPage viewRequisitionPage = new ViewRequisitionPage(testWebDriver);
viewRequisitionPage.clickRnRList();
}
@Then("^I verify total field$")
public void verifyTotalField() throws IOException, SQLException {
ViewRequisitionPage viewRequisitionPage = new ViewRequisitionPage(testWebDriver);
viewRequisitionPage.verifyTotalFieldPostAuthorize();
}
@Then("^I verify values on regimen page as patientsOnTreatment \"([^\"]*)\" patientsToInitiateTreatment \"([^\"]*)\" patientsStoppedTreatment \"([^\"]*)\" remarks \"([^\"]*)\"$")
public void verifyValuesONRegimenPage(String patientsOnTreatment, String patientsToInitiateTreatment, String patientsStoppedTreatment, String remarks) throws IOException {
InitiateRnRPage initiateRnRPage = new InitiateRnRPage(testWebDriver);
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Including-Regimen")
public void testViewRequisitionRegimenAndEmergencyStatus(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add("CREATE_REQUISITION");
rightsList.add("VIEW_REQUISITION");
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
dbWrapper.assignRight(STORE_IN_CHARGE, APPROVE_REQUISITION);
dbWrapper.assignRight(STORE_IN_CHARGE, CONVERT_TO_ORDER);
dbWrapper.assignRight(STORE_IN_CHARGE, VIEW_ORDER);
+ dbWrapper.insertFulfilmentRoleAssignment(userSIC,STORE_IN_CHARGE,"F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
HomePage homePage1 = initiateRnRPage.clickHome();
ViewRequisitionPage viewRequisitionPage = homePage1.navigateViewRequisition();
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
dbWrapper.insertValuesInRequisition(true);
dbWrapper.insertValuesInRegimenLineItems(patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(SUBMITTED, userSIC, "HIV");
viewRequisitionPage.enterViewSearchCriteria();
viewRequisitionPage.clickSearch();
viewRequisitionPage.verifyNoRequisitionFound();
dbWrapper.insertApprovedQuantity(10);
dbWrapper.updateRequisitionStatus(AUTHORIZED, userSIC, "HIV");
viewRequisitionPage.clickSearch();
viewRequisitionPage.clickRnRList();
viewRequisitionPage.verifyTotalFieldPostAuthorize();
HomePage homePageAuthorized = viewRequisitionPage.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPage.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewRequisitionPage viewRequisitionPageAuthorized = homePageAuthorized.navigateViewRequisition();
viewRequisitionPageAuthorized.enterViewSearchCriteria();
viewRequisitionPageAuthorized.clickSearch();
viewRequisitionPageAuthorized.verifyStatus(AUTHORIZED);
viewRequisitionPageAuthorized.verifyEmergencyStatus();
viewRequisitionPageAuthorized.clickRnRList();
HomePage homePageInApproval = viewRequisitionPageAuthorized.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(IN_APPROVAL, userSIC, "HIV");
ViewRequisitionPage viewRequisitionPageInApproval = homePageInApproval.navigateViewRequisition();
viewRequisitionPageInApproval.enterViewSearchCriteria();
viewRequisitionPageInApproval.clickSearch();
viewRequisitionPageInApproval.verifyStatus(IN_APPROVAL);
viewRequisitionPageInApproval.verifyEmergencyStatus();
ApprovePage approvePageTopSNUser = homePageInApproval.navigateToApprove();
approvePageTopSNUser.verifyEmergencyStatus();
approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCostViewRequisition("20");
approvePageTopSNUser.addComments("Dummy Comments");
approvePageTopSNUser.verifyTotalFieldPostAuthorize();
approvePageTopSNUser.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
ViewRequisitionPage viewRequisitionPageApproved = homePageInApproval.navigateViewRequisition();
viewRequisitionPageApproved.enterViewSearchCriteria();
viewRequisitionPageApproved.clickSearch();
viewRequisitionPageApproved.verifyStatus(APPROVED);
viewRequisitionPageApproved.verifyEmergencyStatus();
viewRequisitionPageApproved.clickRnRList();
viewRequisitionPageApproved.verifyTotalFieldPostAuthorize();
viewRequisitionPageApproved.verifyComment("Dummy Comments", userSIC, 1);
viewRequisitionPageApproved.verifyCommentBoxNotPresent();
HomePage homePageApproved = viewRequisitionPageApproved.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ConvertOrderPage convertOrderPage = homePageApproved.navigateConvertToOrder();
convertOrderPage.verifyEmergencyStatus();
convertOrderPage.convertToOrder();
ViewRequisitionPage viewRequisitionPageOrdered = homePageApproved.navigateViewRequisition();
viewRequisitionPageOrdered.enterViewSearchCriteria();
viewRequisitionPageOrdered.clickSearch();
viewRequisitionPageOrdered.verifyStatus(RELEASED);
viewRequisitionPageOrdered.verifyEmergencyStatus();
viewRequisitionPageOrdered.clickRnRList();
viewRequisitionPageOrdered.verifyTotalFieldPostAuthorize();
viewRequisitionPageOrdered.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageOrdered.verifyApprovedQuantityFieldPresent();
viewRequisitionPageOrdered.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewOrdersPage viewOrdersPage=homePageApproved.navigateViewOrders();
viewOrdersPage.verifyEmergencyStatus();
}
private void verifyValuesOnRegimenScreen(InitiateRnRPage initiateRnRPage, String patientsontreatment, String patientstoinitiatetreatment, String patientsstoppedtreatment, String remarks) {
assertEquals(patientsontreatment, initiateRnRPage.getPatientsOnTreatmentValue());
assertEquals(patientstoinitiatetreatment, initiateRnRPage.getPatientsToInitiateTreatmentValue());
assertEquals(patientsstoppedtreatment, initiateRnRPage.getPatientsStoppedTreatmentValue());
assertEquals(remarks, initiateRnRPage.getRemarksValue());
}
@AfterMethod(groups = "requisition")
@After
public void tearDown() throws Exception {
testWebDriver.sleep(500);
if(!testWebDriver.getElementById("username").isDisplayed()) {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
}
@DataProvider(name = "Data-Provider-Function-Including-Regimen")
public Object[][] parameterIntTest() {
return new Object[][]{
{"HIV", "storeincharge", "ADULTS", "Admin123", "RegimenCode1", "RegimenName1", "RegimenCode2", "RegimenName2"}
};
}
}
| true | true | public void testViewRequisitionRegimenAndEmergencyStatus(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add("CREATE_REQUISITION");
rightsList.add("VIEW_REQUISITION");
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
dbWrapper.assignRight(STORE_IN_CHARGE, APPROVE_REQUISITION);
dbWrapper.assignRight(STORE_IN_CHARGE, CONVERT_TO_ORDER);
dbWrapper.assignRight(STORE_IN_CHARGE, VIEW_ORDER);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
HomePage homePage1 = initiateRnRPage.clickHome();
ViewRequisitionPage viewRequisitionPage = homePage1.navigateViewRequisition();
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
dbWrapper.insertValuesInRequisition(true);
dbWrapper.insertValuesInRegimenLineItems(patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(SUBMITTED, userSIC, "HIV");
viewRequisitionPage.enterViewSearchCriteria();
viewRequisitionPage.clickSearch();
viewRequisitionPage.verifyNoRequisitionFound();
dbWrapper.insertApprovedQuantity(10);
dbWrapper.updateRequisitionStatus(AUTHORIZED, userSIC, "HIV");
viewRequisitionPage.clickSearch();
viewRequisitionPage.clickRnRList();
viewRequisitionPage.verifyTotalFieldPostAuthorize();
HomePage homePageAuthorized = viewRequisitionPage.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPage.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewRequisitionPage viewRequisitionPageAuthorized = homePageAuthorized.navigateViewRequisition();
viewRequisitionPageAuthorized.enterViewSearchCriteria();
viewRequisitionPageAuthorized.clickSearch();
viewRequisitionPageAuthorized.verifyStatus(AUTHORIZED);
viewRequisitionPageAuthorized.verifyEmergencyStatus();
viewRequisitionPageAuthorized.clickRnRList();
HomePage homePageInApproval = viewRequisitionPageAuthorized.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(IN_APPROVAL, userSIC, "HIV");
ViewRequisitionPage viewRequisitionPageInApproval = homePageInApproval.navigateViewRequisition();
viewRequisitionPageInApproval.enterViewSearchCriteria();
viewRequisitionPageInApproval.clickSearch();
viewRequisitionPageInApproval.verifyStatus(IN_APPROVAL);
viewRequisitionPageInApproval.verifyEmergencyStatus();
ApprovePage approvePageTopSNUser = homePageInApproval.navigateToApprove();
approvePageTopSNUser.verifyEmergencyStatus();
approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCostViewRequisition("20");
approvePageTopSNUser.addComments("Dummy Comments");
approvePageTopSNUser.verifyTotalFieldPostAuthorize();
approvePageTopSNUser.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
ViewRequisitionPage viewRequisitionPageApproved = homePageInApproval.navigateViewRequisition();
viewRequisitionPageApproved.enterViewSearchCriteria();
viewRequisitionPageApproved.clickSearch();
viewRequisitionPageApproved.verifyStatus(APPROVED);
viewRequisitionPageApproved.verifyEmergencyStatus();
viewRequisitionPageApproved.clickRnRList();
viewRequisitionPageApproved.verifyTotalFieldPostAuthorize();
viewRequisitionPageApproved.verifyComment("Dummy Comments", userSIC, 1);
viewRequisitionPageApproved.verifyCommentBoxNotPresent();
HomePage homePageApproved = viewRequisitionPageApproved.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ConvertOrderPage convertOrderPage = homePageApproved.navigateConvertToOrder();
convertOrderPage.verifyEmergencyStatus();
convertOrderPage.convertToOrder();
ViewRequisitionPage viewRequisitionPageOrdered = homePageApproved.navigateViewRequisition();
viewRequisitionPageOrdered.enterViewSearchCriteria();
viewRequisitionPageOrdered.clickSearch();
viewRequisitionPageOrdered.verifyStatus(RELEASED);
viewRequisitionPageOrdered.verifyEmergencyStatus();
viewRequisitionPageOrdered.clickRnRList();
viewRequisitionPageOrdered.verifyTotalFieldPostAuthorize();
viewRequisitionPageOrdered.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageOrdered.verifyApprovedQuantityFieldPresent();
viewRequisitionPageOrdered.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewOrdersPage viewOrdersPage=homePageApproved.navigateViewOrders();
viewOrdersPage.verifyEmergencyStatus();
}
| public void testViewRequisitionRegimenAndEmergencyStatus(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add("CREATE_REQUISITION");
rightsList.add("VIEW_REQUISITION");
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
dbWrapper.assignRight(STORE_IN_CHARGE, APPROVE_REQUISITION);
dbWrapper.assignRight(STORE_IN_CHARGE, CONVERT_TO_ORDER);
dbWrapper.assignRight(STORE_IN_CHARGE, VIEW_ORDER);
dbWrapper.insertFulfilmentRoleAssignment(userSIC,STORE_IN_CHARGE,"F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
HomePage homePage1 = initiateRnRPage.clickHome();
ViewRequisitionPage viewRequisitionPage = homePage1.navigateViewRequisition();
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
dbWrapper.insertValuesInRequisition(true);
dbWrapper.insertValuesInRegimenLineItems(patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(SUBMITTED, userSIC, "HIV");
viewRequisitionPage.enterViewSearchCriteria();
viewRequisitionPage.clickSearch();
viewRequisitionPage.verifyNoRequisitionFound();
dbWrapper.insertApprovedQuantity(10);
dbWrapper.updateRequisitionStatus(AUTHORIZED, userSIC, "HIV");
viewRequisitionPage.clickSearch();
viewRequisitionPage.clickRnRList();
viewRequisitionPage.verifyTotalFieldPostAuthorize();
HomePage homePageAuthorized = viewRequisitionPage.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPage.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewRequisitionPage viewRequisitionPageAuthorized = homePageAuthorized.navigateViewRequisition();
viewRequisitionPageAuthorized.enterViewSearchCriteria();
viewRequisitionPageAuthorized.clickSearch();
viewRequisitionPageAuthorized.verifyStatus(AUTHORIZED);
viewRequisitionPageAuthorized.verifyEmergencyStatus();
viewRequisitionPageAuthorized.clickRnRList();
HomePage homePageInApproval = viewRequisitionPageAuthorized.verifyFieldsPreApproval("12.50", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
dbWrapper.updateRequisitionStatus(IN_APPROVAL, userSIC, "HIV");
ViewRequisitionPage viewRequisitionPageInApproval = homePageInApproval.navigateViewRequisition();
viewRequisitionPageInApproval.enterViewSearchCriteria();
viewRequisitionPageInApproval.clickSearch();
viewRequisitionPageInApproval.verifyStatus(IN_APPROVAL);
viewRequisitionPageInApproval.verifyEmergencyStatus();
ApprovePage approvePageTopSNUser = homePageInApproval.navigateToApprove();
approvePageTopSNUser.verifyEmergencyStatus();
approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCostViewRequisition("20");
approvePageTopSNUser.addComments("Dummy Comments");
approvePageTopSNUser.verifyTotalFieldPostAuthorize();
approvePageTopSNUser.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
ViewRequisitionPage viewRequisitionPageApproved = homePageInApproval.navigateViewRequisition();
viewRequisitionPageApproved.enterViewSearchCriteria();
viewRequisitionPageApproved.clickSearch();
viewRequisitionPageApproved.verifyStatus(APPROVED);
viewRequisitionPageApproved.verifyEmergencyStatus();
viewRequisitionPageApproved.clickRnRList();
viewRequisitionPageApproved.verifyTotalFieldPostAuthorize();
viewRequisitionPageApproved.verifyComment("Dummy Comments", userSIC, 1);
viewRequisitionPageApproved.verifyCommentBoxNotPresent();
HomePage homePageApproved = viewRequisitionPageApproved.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageAuthorized.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ConvertOrderPage convertOrderPage = homePageApproved.navigateConvertToOrder();
convertOrderPage.verifyEmergencyStatus();
convertOrderPage.convertToOrder();
ViewRequisitionPage viewRequisitionPageOrdered = homePageApproved.navigateViewRequisition();
viewRequisitionPageOrdered.enterViewSearchCriteria();
viewRequisitionPageOrdered.clickSearch();
viewRequisitionPageOrdered.verifyStatus(RELEASED);
viewRequisitionPageOrdered.verifyEmergencyStatus();
viewRequisitionPageOrdered.clickRnRList();
viewRequisitionPageOrdered.verifyTotalFieldPostAuthorize();
viewRequisitionPageOrdered.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageOrdered.verifyApprovedQuantityFieldPresent();
viewRequisitionPageOrdered.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage, patientsOnTreatment, patientsToInitiateTreatment, patientsStoppedTreatment, remarks);
ViewOrdersPage viewOrdersPage=homePageApproved.navigateViewOrders();
viewOrdersPage.verifyEmergencyStatus();
}
|
diff --git a/search-impl/impl/src/java/org/sakaiproject/search/index/impl/ClusterFSIndexStorage.java b/search-impl/impl/src/java/org/sakaiproject/search/index/impl/ClusterFSIndexStorage.java
index 67619ada..48b49b2d 100644
--- a/search-impl/impl/src/java/org/sakaiproject/search/index/impl/ClusterFSIndexStorage.java
+++ b/search-impl/impl/src/java/org/sakaiproject/search/index/impl/ClusterFSIndexStorage.java
@@ -1,501 +1,501 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.search.index.impl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.sakaiproject.search.index.AnalyzerFactory;
import org.sakaiproject.search.index.ClusterFilesystem;
import org.sakaiproject.search.index.IndexStorage;
/**
* Inpmelemtation of IndexStorage using a Cluster File system.
* This implementation perfoms all index write operations in a new
* temporary segment. On completion of the index operation it is
* merged with the current segment. If the current segment is larger
* than the threshold, a new segment is created. Managing the segments
* and how they relate to the cluster is delegateed to the ClusterFilesystem
* @author ieb
*/
public class ClusterFSIndexStorage implements IndexStorage
{
private static final Log log = LogFactory
.getLog(ClusterFSIndexStorage.class);
/**
* Location of the index store on local disk, passed to the underlying index store
*/
private String searchIndexDirectory = null;
/**
* The token analyzer
*/
private AnalyzerFactory analyzerFactory = null;
/**
* Maximum size of a segment
*/
private long segmentThreshold = 1024 * 1024 * 2; // Maximum Segment size
// is 2M
private ClusterFilesystem clusterFS = null;
public void init() {
clusterFS.setLocation(searchIndexDirectory);
}
public IndexReader getIndexReader() throws IOException
{
List segments = clusterFS.updateSegments();
log.debug("Found " + segments.size() + " segments ");
IndexReader[] readers = new IndexReader[segments.size()];
int j = 0;
for (Iterator i = segments.iterator(); i.hasNext();)
{
String segment = (String) i.next();
String segmentName = clusterFS.getSegmentName(segment);
try
{
if (false)
{
// this code will simulate a massive index failure, where
// evey 5th segment is dammaged beyond repair.
// only enable if you want to test the recovery mechanism
if (j % 5 == 0)
{
File f = new File(segment);
log.warn("Removing Segment for test " + f);
File[] files = f.listFiles();
for (int k = 0; k < files.length; k++)
{
files[k].delete();
}
f.delete();
}
}
if ( !clusterFS.checkSegmentValidity(segmentName) ) {
throw new Exception("checksum failed");
}
readers[j] = IndexReader.open(segment);
}
catch (Exception ex)
{
try
{
log.debug("Invalid segment ",ex);
log
.warn("Found corrupted segment ("
+ segmentName
+ ") in Local store, attempting to recover from DB");
clusterFS.recoverSegment(segmentName);
readers[j] = IndexReader.open(segment);
log
.warn("Recovery complete, resuming normal operations having restored "
+ segmentName);
}
catch (Exception e)
{
log
.error("---Failed to recover corrupted segment from the DB,\n"
+ "--- it is probably that there has been a local hardware\n"
+ "--- failure on this node or that the backup in the DB is missing\n"
+ "--- or corrupt. To recover, remove the segment from the db, and rebuild the index \n"
+ "--- eg delete from search_segments where name_ = '"
+ segmentName + "'; \n");
}
}
j++;
}
IndexReader indexReader = new MultiReader(readers);
return indexReader;
}
public IndexWriter getIndexWriter(boolean create) throws IOException
{
// to ensure that we dont dammage the index due to OutOfMemory, if it
// should ever happen
// we will open a temporary index, which will be merged on completion
File currentSegment = null;
IndexWriter indexWriter = null;
if (false)
{
List segments = clusterFS.updateSegments();
log.debug("Found " + segments.size() + " segments ");
if (segments.size() > 0)
{
currentSegment = new File((String) segments
.get(segments.size() - 1));
if (!currentSegment.exists()
|| clusterFS.getTotalSize(currentSegment) > segmentThreshold)
{
currentSegment = null;
}
}
if (currentSegment == null)
{
currentSegment = clusterFS.newSegment();
log.debug("Created new segment " + currentSegment.getName());
indexWriter = new IndexWriter(currentSegment, getAnalyzer(),
true);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
else
{
clusterFS.touchSegment(currentSegment);
indexWriter = new IndexWriter(currentSegment, getAnalyzer(),
false);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
}
else
{
File tempIndex = clusterFS.getTemporarySegment(true);
indexWriter = new IndexWriter(tempIndex, getAnalyzer(), true);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
return indexWriter;
}
public IndexSearcher getIndexSearcher() throws IOException
{
IndexSearcher indexSearcher = null;
try
{
long reloadStart = System.currentTimeMillis();
indexSearcher = new IndexSearcher(getIndexReader());
if (indexSearcher == null)
{
log.warn("No search Index exists at this time");
}
long reloadEnd = System.currentTimeMillis();
log.debug("Reload Complete " + indexSearcher.maxDoc() + " in "
+ (reloadEnd - reloadStart));
}
catch (FileNotFoundException e)
{
log.error("There has been a major poblem with the"
+ " Search Index which has become corrupted ", e);
}
catch (IOException e)
{
log.error("There has been a major poblem with the "
+ "Search Index which has become corrupted", e);
}
return indexSearcher;
}
public boolean indexExists()
{
List segments = clusterFS.updateSegments();
return (segments.size() > 0);
}
public Analyzer getAnalyzer()
{
return analyzerFactory.newAnalyzer();
}
public void setLocation(String location)
{
searchIndexDirectory = location;
if ( clusterFS != null ) {
clusterFS.setLocation(location);
}
}
public void doPreIndexUpdate() throws IOException
{
log.debug("Start Index Cycle");
// dont enable locks
FSDirectory.setDisableLocks(true);
}
public void doPostIndexUpdate() throws IOException
{
FSDirectory.setDisableLocks(true);
// get the tmp index
File tmpSegment = clusterFS.getTemporarySegment(false);
Directory[] tmpDirectory = new Directory[1];
tmpDirectory[0] = FSDirectory.getDirectory(tmpSegment, false);
List segments = clusterFS.updateSegments();
// create a size sorted list
- long[] segmentSize = new long[segments.size()-1];
- File[] segmentName = new File[segments.size()-1];
- if ( segmentSize.length > 10 ) {
- for (int i = 0; i < segments.size()-1; i++ ) {
+ if ( segments.size() > 10 ) {
+ long[] segmentSize = new long[segments.size()-1];
+ File[] segmentName = new File[segments.size()-1];
+ for (int i = 0; i < segmentSize.length; i++ ) {
segmentName[i] = new File((String)segments.get(i));
segmentSize[i] = clusterFS.getTotalSize(segmentName[i]);
}
boolean moved = true;
while (moved)
{
moved = false;
for (int i = 1; i < segmentSize.length; i++)
{
if (segmentSize[i] > segmentSize[i - 1])
{
long size = segmentSize[i];
File name = segmentName[i];
segmentSize[i] = segmentSize[i - 1];
segmentName[i] = segmentName[i - 1];
segmentSize[i - 1] = size;
segmentName[i - 1] = name;
moved = true;
}
}
}
long sizeBlock = 0;
int ninblock = 0;
int mergegroupno = 1;
int[] mergegroup = new int[segmentSize.length];
int[] groupstomerge = new int[segmentSize.length];
mergegroup[0] = mergegroupno;
{
int j = 0;
for ( int i = 0; i < segmentSize.length; i++ ) {
groupstomerge[i] = 0;
if ( ninblock == 0 ) {
sizeBlock = segmentSize[0];
ninblock = 1;
}
if ( segmentSize[i] > sizeBlock/10 ) {
ninblock++;
} else {
ninblock = 1;
mergegroupno++;
sizeBlock = segmentSize[i];
}
mergegroup[i] = mergegroupno;
if ( ninblock >= 10 ) {
if ( sizeBlock < 200L*1024L*1024L) {
// only perform merge for segments < 200M
// oterwise we risk a 2G segment.
groupstomerge[j++] = mergegroupno;
}
mergegroupno++;
ninblock = 0;
}
}
if ( j > 0 ) {
StringBuffer status = new StringBuffer();
for ( int i = 0; i < segmentSize.length; i++ ) {
status.append("Segment ").append(i).append(" n").append(segmentName[i]).append(" s").append(segmentSize[i]).append(" g").append(mergegroup[i]).append("\n");
}
for ( int i = 0; i < groupstomerge.length; i++ ) {
status.append("Merge group ").append(i).append(" m").append(groupstomerge[i]).append("\n");
}
log.info("Search Merge \n"+status);
}
}
// groups to merge contains a list of group numbers that need to be
// merged.
// mergegroup marks each segment with a group number.
for ( int i = 0; i < groupstomerge.length; i++ ) {
if ( groupstomerge[i] != 0 ) {
StringBuffer status = new StringBuffer();
status.append("Group ").append(i).append(" Merge ").append(groupstomerge[i]).append("\n");
File mergeSegment = clusterFS.newSegment();
IndexWriter mergeIndexWriter = null;
boolean mergeOk = false;
try {
mergeIndexWriter = new IndexWriter(FSDirectory.getDirectory(mergeSegment,false), getAnalyzer(), true);
mergeIndexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
mergeIndexWriter.setMaxMergeDocs(50);
mergeIndexWriter.setMergeFactor(50);
ArrayList indexes = new ArrayList();
for ( int j = 0; j < mergegroup.length; j++ ) {
if ( mergegroup[j] == groupstomerge[i]) {
Directory d = FSDirectory.getDirectory(segmentName[j],false);
if ( d.fileExists("segments") ) {
status.append(" Merge ").append(segmentName[j].getName()).append(" >> ").append(mergeSegment.getName()).append("\n");
indexes.add(d);
}
}
}
log.info("Merging \n"+status);
mergeIndexWriter.addIndexes((Directory[]) indexes.toArray(new Directory[indexes.size()]));
mergeIndexWriter.close();
log.info("Done "+groupstomerge[i]);
mergeIndexWriter = null;
// remove old segments
mergeOk = true;
} catch ( Exception ex ) {
log.error("Failed to merge search segments "+ex.getMessage());
try { mergeIndexWriter.close(); } catch ( Exception ex2 ) {}
try {
clusterFS.removeLocalSegment(mergeSegment);
} catch ( Exception ex2 ) {
log.error("Failed to remove merge segment "+mergeSegment.getName()+" "+ex2.getMessage());
}
} finally {
try {
mergeIndexWriter.close();
} catch ( Exception ex) {
}
}
if ( mergeOk ) {
for ( int j = 0; j < mergegroup.length; j++ ) {
if ( mergegroup[j] == groupstomerge[i]) {
clusterFS.removeLocalSegment(segmentName[j]);
}
}
}
}
}
}
// merge it with the current index
File currentSegment = null;
IndexWriter indexWriter = null;
log.debug("Found " + segments.size() + " segments ");
if (segments.size() > 0)
{
currentSegment = new File((String) segments
.get(segments.size() - 1));
if (!currentSegment.exists()
|| clusterFS.getTotalSize(currentSegment) > segmentThreshold)
{
currentSegment = null;
}
}
if (currentSegment == null)
{
currentSegment = clusterFS.newSegment();
log.debug("Created new segment " + currentSegment.getName());
indexWriter = new IndexWriter(FSDirectory.getDirectory(currentSegment,false), getAnalyzer(), true);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
else
{
clusterFS.touchSegment(currentSegment);
indexWriter = new IndexWriter(FSDirectory.getDirectory(currentSegment,false), getAnalyzer(), false);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
if ( tmpDirectory[0].fileExists("segments") ) {
indexWriter.addIndexes(tmpDirectory);
}
indexWriter.close();
clusterFS.removeTemporarySegment();
clusterFS.saveSegments();
log.debug("End Index Cycle");
}
/**
* @return Returns the analzyserFactory.
*/
public AnalyzerFactory getAnalyzerFactory()
{
return analyzerFactory;
}
/**
* @param analzyserFactory
* The analzyserFactory to set.
*/
public void setAnalyzerFactory(AnalyzerFactory analzyserFactory)
{
this.analyzerFactory = analzyserFactory;
}
public void setRecoverCorruptedIndex(boolean recover)
{
}
/**
* @return Returns the clusterFS.
*/
public ClusterFilesystem getClusterFS()
{
return clusterFS;
}
/**
* @param clusterFS
* The clusterFS to set.
*/
public void setClusterFS(ClusterFilesystem clusterFS)
{
this.clusterFS = clusterFS;
}
}
| true | true | public void doPostIndexUpdate() throws IOException
{
FSDirectory.setDisableLocks(true);
// get the tmp index
File tmpSegment = clusterFS.getTemporarySegment(false);
Directory[] tmpDirectory = new Directory[1];
tmpDirectory[0] = FSDirectory.getDirectory(tmpSegment, false);
List segments = clusterFS.updateSegments();
// create a size sorted list
long[] segmentSize = new long[segments.size()-1];
File[] segmentName = new File[segments.size()-1];
if ( segmentSize.length > 10 ) {
for (int i = 0; i < segments.size()-1; i++ ) {
segmentName[i] = new File((String)segments.get(i));
segmentSize[i] = clusterFS.getTotalSize(segmentName[i]);
}
boolean moved = true;
while (moved)
{
moved = false;
for (int i = 1; i < segmentSize.length; i++)
{
if (segmentSize[i] > segmentSize[i - 1])
{
long size = segmentSize[i];
File name = segmentName[i];
segmentSize[i] = segmentSize[i - 1];
segmentName[i] = segmentName[i - 1];
segmentSize[i - 1] = size;
segmentName[i - 1] = name;
moved = true;
}
}
}
long sizeBlock = 0;
int ninblock = 0;
int mergegroupno = 1;
int[] mergegroup = new int[segmentSize.length];
int[] groupstomerge = new int[segmentSize.length];
mergegroup[0] = mergegroupno;
{
int j = 0;
for ( int i = 0; i < segmentSize.length; i++ ) {
groupstomerge[i] = 0;
if ( ninblock == 0 ) {
sizeBlock = segmentSize[0];
ninblock = 1;
}
if ( segmentSize[i] > sizeBlock/10 ) {
ninblock++;
} else {
ninblock = 1;
mergegroupno++;
sizeBlock = segmentSize[i];
}
mergegroup[i] = mergegroupno;
if ( ninblock >= 10 ) {
if ( sizeBlock < 200L*1024L*1024L) {
// only perform merge for segments < 200M
// oterwise we risk a 2G segment.
groupstomerge[j++] = mergegroupno;
}
mergegroupno++;
ninblock = 0;
}
}
if ( j > 0 ) {
StringBuffer status = new StringBuffer();
for ( int i = 0; i < segmentSize.length; i++ ) {
status.append("Segment ").append(i).append(" n").append(segmentName[i]).append(" s").append(segmentSize[i]).append(" g").append(mergegroup[i]).append("\n");
}
for ( int i = 0; i < groupstomerge.length; i++ ) {
status.append("Merge group ").append(i).append(" m").append(groupstomerge[i]).append("\n");
}
log.info("Search Merge \n"+status);
}
}
// groups to merge contains a list of group numbers that need to be
// merged.
// mergegroup marks each segment with a group number.
for ( int i = 0; i < groupstomerge.length; i++ ) {
if ( groupstomerge[i] != 0 ) {
StringBuffer status = new StringBuffer();
status.append("Group ").append(i).append(" Merge ").append(groupstomerge[i]).append("\n");
File mergeSegment = clusterFS.newSegment();
IndexWriter mergeIndexWriter = null;
boolean mergeOk = false;
try {
mergeIndexWriter = new IndexWriter(FSDirectory.getDirectory(mergeSegment,false), getAnalyzer(), true);
mergeIndexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
mergeIndexWriter.setMaxMergeDocs(50);
mergeIndexWriter.setMergeFactor(50);
ArrayList indexes = new ArrayList();
for ( int j = 0; j < mergegroup.length; j++ ) {
if ( mergegroup[j] == groupstomerge[i]) {
Directory d = FSDirectory.getDirectory(segmentName[j],false);
if ( d.fileExists("segments") ) {
status.append(" Merge ").append(segmentName[j].getName()).append(" >> ").append(mergeSegment.getName()).append("\n");
indexes.add(d);
}
}
}
log.info("Merging \n"+status);
mergeIndexWriter.addIndexes((Directory[]) indexes.toArray(new Directory[indexes.size()]));
mergeIndexWriter.close();
log.info("Done "+groupstomerge[i]);
mergeIndexWriter = null;
// remove old segments
mergeOk = true;
} catch ( Exception ex ) {
log.error("Failed to merge search segments "+ex.getMessage());
try { mergeIndexWriter.close(); } catch ( Exception ex2 ) {}
try {
clusterFS.removeLocalSegment(mergeSegment);
} catch ( Exception ex2 ) {
log.error("Failed to remove merge segment "+mergeSegment.getName()+" "+ex2.getMessage());
}
} finally {
try {
mergeIndexWriter.close();
} catch ( Exception ex) {
}
}
if ( mergeOk ) {
for ( int j = 0; j < mergegroup.length; j++ ) {
if ( mergegroup[j] == groupstomerge[i]) {
clusterFS.removeLocalSegment(segmentName[j]);
}
}
}
}
}
}
// merge it with the current index
File currentSegment = null;
IndexWriter indexWriter = null;
log.debug("Found " + segments.size() + " segments ");
if (segments.size() > 0)
{
currentSegment = new File((String) segments
.get(segments.size() - 1));
if (!currentSegment.exists()
|| clusterFS.getTotalSize(currentSegment) > segmentThreshold)
{
currentSegment = null;
}
}
if (currentSegment == null)
{
currentSegment = clusterFS.newSegment();
log.debug("Created new segment " + currentSegment.getName());
indexWriter = new IndexWriter(FSDirectory.getDirectory(currentSegment,false), getAnalyzer(), true);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
else
{
clusterFS.touchSegment(currentSegment);
indexWriter = new IndexWriter(FSDirectory.getDirectory(currentSegment,false), getAnalyzer(), false);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
if ( tmpDirectory[0].fileExists("segments") ) {
indexWriter.addIndexes(tmpDirectory);
}
indexWriter.close();
clusterFS.removeTemporarySegment();
clusterFS.saveSegments();
log.debug("End Index Cycle");
}
| public void doPostIndexUpdate() throws IOException
{
FSDirectory.setDisableLocks(true);
// get the tmp index
File tmpSegment = clusterFS.getTemporarySegment(false);
Directory[] tmpDirectory = new Directory[1];
tmpDirectory[0] = FSDirectory.getDirectory(tmpSegment, false);
List segments = clusterFS.updateSegments();
// create a size sorted list
if ( segments.size() > 10 ) {
long[] segmentSize = new long[segments.size()-1];
File[] segmentName = new File[segments.size()-1];
for (int i = 0; i < segmentSize.length; i++ ) {
segmentName[i] = new File((String)segments.get(i));
segmentSize[i] = clusterFS.getTotalSize(segmentName[i]);
}
boolean moved = true;
while (moved)
{
moved = false;
for (int i = 1; i < segmentSize.length; i++)
{
if (segmentSize[i] > segmentSize[i - 1])
{
long size = segmentSize[i];
File name = segmentName[i];
segmentSize[i] = segmentSize[i - 1];
segmentName[i] = segmentName[i - 1];
segmentSize[i - 1] = size;
segmentName[i - 1] = name;
moved = true;
}
}
}
long sizeBlock = 0;
int ninblock = 0;
int mergegroupno = 1;
int[] mergegroup = new int[segmentSize.length];
int[] groupstomerge = new int[segmentSize.length];
mergegroup[0] = mergegroupno;
{
int j = 0;
for ( int i = 0; i < segmentSize.length; i++ ) {
groupstomerge[i] = 0;
if ( ninblock == 0 ) {
sizeBlock = segmentSize[0];
ninblock = 1;
}
if ( segmentSize[i] > sizeBlock/10 ) {
ninblock++;
} else {
ninblock = 1;
mergegroupno++;
sizeBlock = segmentSize[i];
}
mergegroup[i] = mergegroupno;
if ( ninblock >= 10 ) {
if ( sizeBlock < 200L*1024L*1024L) {
// only perform merge for segments < 200M
// oterwise we risk a 2G segment.
groupstomerge[j++] = mergegroupno;
}
mergegroupno++;
ninblock = 0;
}
}
if ( j > 0 ) {
StringBuffer status = new StringBuffer();
for ( int i = 0; i < segmentSize.length; i++ ) {
status.append("Segment ").append(i).append(" n").append(segmentName[i]).append(" s").append(segmentSize[i]).append(" g").append(mergegroup[i]).append("\n");
}
for ( int i = 0; i < groupstomerge.length; i++ ) {
status.append("Merge group ").append(i).append(" m").append(groupstomerge[i]).append("\n");
}
log.info("Search Merge \n"+status);
}
}
// groups to merge contains a list of group numbers that need to be
// merged.
// mergegroup marks each segment with a group number.
for ( int i = 0; i < groupstomerge.length; i++ ) {
if ( groupstomerge[i] != 0 ) {
StringBuffer status = new StringBuffer();
status.append("Group ").append(i).append(" Merge ").append(groupstomerge[i]).append("\n");
File mergeSegment = clusterFS.newSegment();
IndexWriter mergeIndexWriter = null;
boolean mergeOk = false;
try {
mergeIndexWriter = new IndexWriter(FSDirectory.getDirectory(mergeSegment,false), getAnalyzer(), true);
mergeIndexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
mergeIndexWriter.setMaxMergeDocs(50);
mergeIndexWriter.setMergeFactor(50);
ArrayList indexes = new ArrayList();
for ( int j = 0; j < mergegroup.length; j++ ) {
if ( mergegroup[j] == groupstomerge[i]) {
Directory d = FSDirectory.getDirectory(segmentName[j],false);
if ( d.fileExists("segments") ) {
status.append(" Merge ").append(segmentName[j].getName()).append(" >> ").append(mergeSegment.getName()).append("\n");
indexes.add(d);
}
}
}
log.info("Merging \n"+status);
mergeIndexWriter.addIndexes((Directory[]) indexes.toArray(new Directory[indexes.size()]));
mergeIndexWriter.close();
log.info("Done "+groupstomerge[i]);
mergeIndexWriter = null;
// remove old segments
mergeOk = true;
} catch ( Exception ex ) {
log.error("Failed to merge search segments "+ex.getMessage());
try { mergeIndexWriter.close(); } catch ( Exception ex2 ) {}
try {
clusterFS.removeLocalSegment(mergeSegment);
} catch ( Exception ex2 ) {
log.error("Failed to remove merge segment "+mergeSegment.getName()+" "+ex2.getMessage());
}
} finally {
try {
mergeIndexWriter.close();
} catch ( Exception ex) {
}
}
if ( mergeOk ) {
for ( int j = 0; j < mergegroup.length; j++ ) {
if ( mergegroup[j] == groupstomerge[i]) {
clusterFS.removeLocalSegment(segmentName[j]);
}
}
}
}
}
}
// merge it with the current index
File currentSegment = null;
IndexWriter indexWriter = null;
log.debug("Found " + segments.size() + " segments ");
if (segments.size() > 0)
{
currentSegment = new File((String) segments
.get(segments.size() - 1));
if (!currentSegment.exists()
|| clusterFS.getTotalSize(currentSegment) > segmentThreshold)
{
currentSegment = null;
}
}
if (currentSegment == null)
{
currentSegment = clusterFS.newSegment();
log.debug("Created new segment " + currentSegment.getName());
indexWriter = new IndexWriter(FSDirectory.getDirectory(currentSegment,false), getAnalyzer(), true);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
else
{
clusterFS.touchSegment(currentSegment);
indexWriter = new IndexWriter(FSDirectory.getDirectory(currentSegment,false), getAnalyzer(), false);
indexWriter.setUseCompoundFile(true);
//indexWriter.setInfoStream(System.out);
indexWriter.setMaxMergeDocs(50);
indexWriter.setMergeFactor(50);
}
if ( tmpDirectory[0].fileExists("segments") ) {
indexWriter.addIndexes(tmpDirectory);
}
indexWriter.close();
clusterFS.removeTemporarySegment();
clusterFS.saveSegments();
log.debug("End Index Cycle");
}
|
diff --git a/src/main/java/org/studentsuccessplan/ssp/web/api/SessionController.java b/src/main/java/org/studentsuccessplan/ssp/web/api/SessionController.java
index fb194abce..476577c2e 100644
--- a/src/main/java/org/studentsuccessplan/ssp/web/api/SessionController.java
+++ b/src/main/java/org/studentsuccessplan/ssp/web/api/SessionController.java
@@ -1,70 +1,70 @@
package org.studentsuccessplan.ssp.web.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.studentsuccessplan.ssp.model.Person;
import org.studentsuccessplan.ssp.security.SspUser;
import org.studentsuccessplan.ssp.service.SecurityService;
import org.studentsuccessplan.ssp.transferobject.PersonTO;
import org.studentsuccessplan.ssp.transferobject.ServiceResponse;
/**
* Allows the logged in user to get their profile.
* <p>
* Mapped to the URI path <code>/api/session/...</code>
*/
@Controller
@RequestMapping("/session")
public class SessionController {
private static final Logger LOGGER = LoggerFactory
.getLogger(SessionController.class);
@Autowired
private SecurityService service;
/**
* Gets the currently authenticated user.
* <p>
* Mapped to the URI path <code>.../getAuthenticatedPerson</code>
*
* @return The currently authenticated {@link Person} info, or null (empty)
* if not authenticated.
*/
@RequestMapping(value = "/getAuthenticatedPerson", method = RequestMethod.GET)
public @ResponseBody
PersonTO getAuthenticatedPerson() {
if (service == null) {
LOGGER.error("The security service was not wired by the Spring container correctly for the SessionController.");
return null;
}
- SspUser user = service.currentUser();
+ SspUser user = service.currentlyAuthenticatedUser();
if (user == null) {
// User not authenticated, so return an empty result, but still with
// an HTTP 200 response.
return null;
}
// Convert model to a transfer object
PersonTO pTo = new PersonTO();
pTo.fromModel(user.getPerson());
// Return authenticated person transfer object
return pTo;
}
@ExceptionHandler(Exception.class)
public @ResponseBody
ServiceResponse handle(Exception e) {
LOGGER.error("Error: ", e);
return new ServiceResponse(false, e.getMessage());
}
}
| true | true | PersonTO getAuthenticatedPerson() {
if (service == null) {
LOGGER.error("The security service was not wired by the Spring container correctly for the SessionController.");
return null;
}
SspUser user = service.currentUser();
if (user == null) {
// User not authenticated, so return an empty result, but still with
// an HTTP 200 response.
return null;
}
// Convert model to a transfer object
PersonTO pTo = new PersonTO();
pTo.fromModel(user.getPerson());
// Return authenticated person transfer object
return pTo;
}
| PersonTO getAuthenticatedPerson() {
if (service == null) {
LOGGER.error("The security service was not wired by the Spring container correctly for the SessionController.");
return null;
}
SspUser user = service.currentlyAuthenticatedUser();
if (user == null) {
// User not authenticated, so return an empty result, but still with
// an HTTP 200 response.
return null;
}
// Convert model to a transfer object
PersonTO pTo = new PersonTO();
pTo.fromModel(user.getPerson());
// Return authenticated person transfer object
return pTo;
}
|
diff --git a/freeplane/src/org/freeplane/features/mindmapnode/pattern/StylePatternPanel.java b/freeplane/src/org/freeplane/features/mindmapnode/pattern/StylePatternPanel.java
index 6e46a4b7f..ba94c9f30 100644
--- a/freeplane/src/org/freeplane/features/mindmapnode/pattern/StylePatternPanel.java
+++ b/freeplane/src/org/freeplane/features/mindmapnode/pattern/StylePatternPanel.java
@@ -1,510 +1,508 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Dimitry Polivaev in 2008.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.mindmapnode.pattern;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.HeadlessException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.JPanel;
import org.freeplane.core.modecontroller.ModeController;
import org.freeplane.core.model.MindIcon;
import org.freeplane.core.resources.ResourceController;
import org.freeplane.core.resources.ui.BooleanProperty;
import org.freeplane.core.resources.ui.ColorProperty;
import org.freeplane.core.resources.ui.ComboProperty;
import org.freeplane.core.resources.ui.FontProperty;
import org.freeplane.core.resources.ui.IPropertyControl;
import org.freeplane.core.resources.ui.IconProperty;
import org.freeplane.core.resources.ui.NextLineProperty;
import org.freeplane.core.resources.ui.PropertyBean;
import org.freeplane.core.resources.ui.SeparatorProperty;
import org.freeplane.core.resources.ui.StringProperty;
import org.freeplane.core.resources.ui.ThreeCheckBoxProperty;
import org.freeplane.features.common.edge.EdgeController;
import org.freeplane.features.common.edge.EdgeModel;
import org.freeplane.features.common.edge.EdgeStyle;
import org.freeplane.features.common.icon.IconController;
import org.freeplane.features.common.nodestyle.NodeStyleController;
import org.freeplane.features.common.nodestyle.NodeStyleModel;
import org.freeplane.features.mindmapmode.icon.MIconController;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
/**
* @author foltin
*/
public class StylePatternPanel extends JPanel implements PropertyChangeListener {
final private class EdgeWidthBackTransformer implements IValueTransformator {
public String transform(final String value) {
return transformStringToWidth(value);
}
}
final private class EdgeWidthTransformer implements IValueTransformator {
public String transform(final String value) {
return transformEdgeWidth(value);
}
}
final private class IdentityTransformer implements IValueTransformator {
public String transform(final String value) {
return value;
}
}
private interface IValueTransformator {
String transform(String value);
}
public static final class StylePatternPanelType {
public static StylePatternPanelType WITH_NAME_AND_CHILDS = new StylePatternPanelType();
public static StylePatternPanelType WITHOUT_NAME_AND_CHILDS = new StylePatternPanelType();
private StylePatternPanelType() {
}
}
private static final String CHILD_PATTERN = "childpattern";
private static final String CLEAR_ALL_SETTERS = "clear_all_setters";
private static final String EDGE_COLOR = "edgecolor";
private static final String EDGE_STYLE = "edgestyle";
private static final String[] EDGE_STYLES = new String[] { EdgeStyle.EDGESTYLE_LINEAR, EdgeStyle.EDGESTYLE_BEZIER,
EdgeStyle.EDGESTYLE_SHARP_LINEAR, EdgeStyle.EDGESTYLE_SHARP_BEZIER, EdgeStyle.EDGESTYLE_HORIZONTAL, EdgeStyle.EDGESTYLE_HIDDEN };
private static final String EDGE_WIDTH = "edgewidth";
private static final String[] EDGE_WIDTHS = new String[] { "EdgeWidth_parent", "EdgeWidth_thin", "EdgeWidth_1",
"EdgeWidth_2", "EdgeWidth_4", "EdgeWidth_8" };
private static final String ICON = "icon";
private static final String NODE_BACKGROUND_COLOR = "nodebackgroundcolor";
private static final String NODE_COLOR = "nodecolor";
private static final String NODE_FONT_BOLD = "nodefontbold";
private static final String NODE_FONT_ITALIC = "nodefontitalic";
private static final String NODE_FONT_NAME = "nodefontname";
private static final String NODE_FONT_SIZE = "nodefontsize";
private static final String NODE_NAME = "patternname";
private static final String NODE_STYLE = "nodeshape";
private static final String NODE_TEXT = "nodetext";
private static final String SCRIPT = "script";
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String SET_CHILD_PATTERN = StylePatternPanel.SET_RESOURCE;
private static final String SET_EDGE_COLOR = StylePatternPanel.SET_RESOURCE;
private static final String SET_EDGE_STYLE = StylePatternPanel.SET_RESOURCE;
private static final String SET_EDGE_WIDTH = StylePatternPanel.SET_RESOURCE;
private static final String SET_ICON = StylePatternPanel.SET_RESOURCE;
private static final String SET_NODE_BACKGROUND_COLOR = StylePatternPanel.SET_RESOURCE;
private static final String SET_NODE_COLOR = StylePatternPanel.SET_RESOURCE;
private static final String SET_NODE_FONT_BOLD = StylePatternPanel.SET_RESOURCE;
private static final String SET_NODE_FONT_ITALIC = StylePatternPanel.SET_RESOURCE;
private static final String SET_NODE_FONT_NAME = StylePatternPanel.SET_RESOURCE;
private static final String SET_NODE_FONT_SIZE = StylePatternPanel.SET_RESOURCE;
private static final String SET_NODE_STYLE = StylePatternPanel.SET_RESOURCE;
private static final String SET_NODE_TEXT = StylePatternPanel.SET_RESOURCE;
private static final String SET_RESOURCE = "set_property_text";
private static final String SET_SCRIPT = "setscript";
private ComboProperty mChildPattern;
private ThreeCheckBoxProperty mClearSetters;
private Vector mControls;
private ColorProperty mEdgeColor;
private ComboProperty mEdgeStyle;
private ComboProperty mEdgeWidth;
private IconProperty mIcon;
private Vector mIconInformationVector;
final private ModeController mMindMapController;
private StringProperty mName;
private ColorProperty mNodeBackgroundColor;
private ColorProperty mNodeColor;
private BooleanProperty mNodeFontBold;
private BooleanProperty mNodeFontItalic;
private FontProperty mNodeFontName;
private ComboProperty mNodeFontSize;
private ComboProperty mNodeStyle;
private StringProperty mNodeText;
private List mPatternList;
/**
* Denotes pairs property -> ThreeCheckBoxProperty such that the boolean
* property can be set, when the format property is changed.
*/
final private HashMap mPropertyChangePropagation = new HashMap();
private ScriptEditorProperty mScriptPattern;
private ThreeCheckBoxProperty mSetChildPattern;
private ThreeCheckBoxProperty mSetEdgeColor;
private ThreeCheckBoxProperty mSetEdgeStyle;
private ThreeCheckBoxProperty mSetEdgeWidth;
private ThreeCheckBoxProperty mSetIcon;
private ThreeCheckBoxProperty mSetNodeBackgroundColor;
private ThreeCheckBoxProperty mSetNodeColor;
private ThreeCheckBoxProperty mSetNodeFontBold;
private ThreeCheckBoxProperty mSetNodeFontItalic;
private ThreeCheckBoxProperty mSetNodeFontName;
private ThreeCheckBoxProperty mSetNodeFontSize;
private ThreeCheckBoxProperty mSetNodeStyle;
private ThreeCheckBoxProperty mSetNodeText;
private ThreeCheckBoxProperty mSetScriptPattern;
final private StylePatternPanelType mType;
final private String[] sizes = new String[] { "2", "4", "6", "8", "10", "12", "14", "16", "18", "20", "22", "24",
"30", "36", "48", "72" };
/**
* @throws HeadlessException
*/
public StylePatternPanel(final ModeController pMindMapController, final StylePatternPanelType pType)
throws HeadlessException {
super();
mMindMapController = pMindMapController;
mType = pType;
}
public void addListeners() {
for (final Iterator iter = mControls.iterator(); iter.hasNext();) {
final IPropertyControl control = (IPropertyControl) iter.next();
if (control instanceof PropertyBean) {
final PropertyBean bean = (PropertyBean) control;
bean.addPropertyChangeListener(this);
}
}
mClearSetters.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent pEvt) {
for (final Iterator iter = mPropertyChangePropagation.keySet().iterator(); iter.hasNext();) {
final ThreeCheckBoxProperty booleanProp = (ThreeCheckBoxProperty) iter.next();
booleanProp.setValue(mClearSetters.getValue());
}
}
});
}
private Vector getControls() {
final Vector controls = new Vector();
controls.add(new SeparatorProperty("OptionPanel.separator.General"));
mClearSetters = new ThreeCheckBoxProperty(StylePatternPanel.CLEAR_ALL_SETTERS);
mClearSetters.setValue(ThreeCheckBoxProperty.TRUE_VALUE);
controls.add(mClearSetters);
if (StylePatternPanelType.WITH_NAME_AND_CHILDS.equals(mType)) {
mName = new StringProperty(StylePatternPanel.NODE_NAME);
controls.add(mName);
mSetChildPattern = new ThreeCheckBoxProperty(StylePatternPanel.SET_CHILD_PATTERN);
controls.add(mSetChildPattern);
final Vector childNames = new Vector();
mChildPattern = new ComboProperty(StylePatternPanel.CHILD_PATTERN, childNames, childNames);
controls.add(mChildPattern);
}
controls.add(new NextLineProperty());
controls.add(new SeparatorProperty("OptionPanel.separator.NodeColors"));
mSetNodeColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_COLOR);
controls.add(mSetNodeColor);
mNodeColor = new ColorProperty(StylePatternPanel.NODE_COLOR, ResourceController.getResourceController()
.getDefaultProperty(NodeStyleController.RESOURCES_NODE_TEXT_COLOR));
controls.add(mNodeColor);
mSetNodeBackgroundColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_BACKGROUND_COLOR);
controls.add(mSetNodeBackgroundColor);
mNodeBackgroundColor = new ColorProperty(StylePatternPanel.NODE_BACKGROUND_COLOR, ResourceController
.getResourceController().getDefaultProperty(NODE_BACKGROUND_COLOR));
controls.add(mNodeBackgroundColor);
controls.add(new SeparatorProperty("OptionPanel.separator.NodeStyles"));
mSetNodeStyle = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_STYLE);
controls.add(mSetNodeStyle);
mNodeStyle = new ComboProperty(StylePatternPanel.NODE_STYLE, new String[] { "fork", "bubble", "as_parent",
"combined" });
controls.add(mNodeStyle);
mIconInformationVector = new Vector();
final ModeController controller = mMindMapController;
final Collection mindIcons = ((MIconController) IconController.getController(controller)).getMindIcons();
mIconInformationVector.addAll(mindIcons);
mSetIcon = new ThreeCheckBoxProperty(StylePatternPanel.SET_ICON);
controls.add(mSetIcon);
mIcon = new IconProperty(StylePatternPanel.ICON, mIconInformationVector);
controls.add(mIcon);
controls.add(new NextLineProperty());
controls.add(new SeparatorProperty("OptionPanel.separator.NodeFont"));
mSetNodeFontName = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_NAME);
controls.add(mSetNodeFontName);
mNodeFontName = new FontProperty(StylePatternPanel.NODE_FONT_NAME);
controls.add(mNodeFontName);
mSetNodeFontSize = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_SIZE);
controls.add(mSetNodeFontSize);
final Vector sizesVector = new Vector();
for (int i = 0; i < sizes.length; i++) {
sizesVector.add(sizes[i]);
}
mNodeFontSize = new ComboProperty(StylePatternPanel.NODE_FONT_SIZE, sizesVector, sizesVector);
controls.add(mNodeFontSize);
mSetNodeFontBold = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_BOLD);
controls.add(mSetNodeFontBold);
mNodeFontBold = new BooleanProperty(StylePatternPanel.NODE_FONT_BOLD);
controls.add(mNodeFontBold);
mSetNodeFontItalic = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_ITALIC);
controls.add(mSetNodeFontItalic);
mNodeFontItalic = new BooleanProperty(StylePatternPanel.NODE_FONT_ITALIC);
controls.add(mNodeFontItalic);
/* **** */
mSetNodeText = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_TEXT);
controls.add(mSetNodeText);
mNodeText = new StringProperty(StylePatternPanel.NODE_TEXT);
controls.add(mNodeText);
/* **** */
controls.add(new SeparatorProperty("OptionPanel.separator.EdgeControls"));
mSetEdgeWidth = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_WIDTH);
controls.add(mSetEdgeWidth);
- mEdgeWidth = new ComboProperty(StylePatternPanel.EDGE_WIDTH, new String[] { "EdgeWidth_parent",
- "EdgeWidth_thin", "EdgeWidth_1", "EdgeWidth_2", "EdgeWidth_4", "EdgeWidth_8" });
+ mEdgeWidth = new ComboProperty(StylePatternPanel.EDGE_WIDTH, EDGE_WIDTHS);
controls.add(mEdgeWidth);
/* **** */
mSetEdgeStyle = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_STYLE);
controls.add(mSetEdgeStyle);
- mEdgeStyle = new ComboProperty(StylePatternPanel.EDGE_STYLE, new String[] { "linear", "bezier", "sharp_linear",
- "sharp_bezier" });
+ mEdgeStyle = new ComboProperty(StylePatternPanel.EDGE_STYLE, EDGE_STYLES);
controls.add(mEdgeStyle);
/* **** */
mSetEdgeColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_COLOR);
controls.add(mSetEdgeColor);
mEdgeColor = new ColorProperty(StylePatternPanel.EDGE_COLOR, ResourceController.getResourceController()
.getDefaultProperty(EdgeController.RESOURCES_EDGE_COLOR));
controls.add(mEdgeColor);
/* **** */
controls.add(new SeparatorProperty("OptionPanel.separator.ScriptingControl"));
mSetScriptPattern = new ThreeCheckBoxProperty(StylePatternPanel.SET_SCRIPT);
controls.add(mSetScriptPattern);
mScriptPattern = new ScriptEditorProperty(StylePatternPanel.SCRIPT, mMindMapController);
controls.add(mScriptPattern);
mPropertyChangePropagation.put(mSetNodeColor, mNodeColor);
mPropertyChangePropagation.put(mSetNodeBackgroundColor, mNodeBackgroundColor);
mPropertyChangePropagation.put(mSetNodeStyle, mNodeStyle);
mPropertyChangePropagation.put(mSetNodeFontName, mNodeFontName);
mPropertyChangePropagation.put(mSetNodeFontSize, mNodeFontSize);
mPropertyChangePropagation.put(mSetNodeFontBold, mNodeFontBold);
mPropertyChangePropagation.put(mSetNodeFontItalic, mNodeFontItalic);
mPropertyChangePropagation.put(mSetNodeText, mNodeText);
mPropertyChangePropagation.put(mSetEdgeColor, mEdgeColor);
mPropertyChangePropagation.put(mSetEdgeStyle, mEdgeStyle);
mPropertyChangePropagation.put(mSetEdgeWidth, mEdgeWidth);
mPropertyChangePropagation.put(mSetIcon, mIcon);
mPropertyChangePropagation.put(mSetScriptPattern, mScriptPattern);
if (StylePatternPanelType.WITH_NAME_AND_CHILDS.equals(mType)) {
mPropertyChangePropagation.put(mSetChildPattern, mChildPattern);
}
return controls;
}
private HashMap getEdgeWidthTransformation() {
final HashMap transformator = new HashMap();
transformator.put(StylePatternPanel.EDGE_WIDTHS[0], new Integer(EdgeModel.WIDTH_PARENT));
transformator.put(StylePatternPanel.EDGE_WIDTHS[1], new Integer(EdgeModel.WIDTH_THIN));
transformator.put(StylePatternPanel.EDGE_WIDTHS[2], new Integer(1));
transformator.put(StylePatternPanel.EDGE_WIDTHS[3], new Integer(2));
transformator.put(StylePatternPanel.EDGE_WIDTHS[4], new Integer(4));
transformator.put(StylePatternPanel.EDGE_WIDTHS[5], new Integer(8));
return transformator;
}
private Vector getPatternNames() {
final Vector childNames = new Vector();
for (final Iterator iter = mPatternList.iterator(); iter.hasNext();) {
final Pattern pattern = (Pattern) iter.next();
childNames.add(pattern.getName());
}
return childNames;
}
private PatternProperty getPatternResult(final PatternProperty baseProperty,
final ThreeCheckBoxProperty threeCheckBoxProperty,
final PropertyBean property) {
final IValueTransformator transformer = new IdentityTransformer();
return getPatternResult(baseProperty, threeCheckBoxProperty, property, transformer);
}
/**
*/
private PatternProperty getPatternResult(final PatternProperty baseProperty,
final ThreeCheckBoxProperty threeCheckBoxProperty,
final PropertyBean property, final IValueTransformator transformer) {
final String checkboxResult = threeCheckBoxProperty.getValue();
if (checkboxResult == null) {
return null;
}
if (checkboxResult.equals(ThreeCheckBoxProperty.DON_T_TOUCH_VALUE)) {
return null;
}
if (checkboxResult.equals(ThreeCheckBoxProperty.FALSE_VALUE)) {
return baseProperty;
}
baseProperty.setValue(transformer.transform(property.getValue()));
return baseProperty;
}
public Pattern getResultPattern() {
final Pattern pattern = new Pattern();
return getResultPattern(pattern);
}
public Pattern getResultPattern(final Pattern pattern) {
pattern.setPatternNodeColor(getPatternResult(new PatternProperty(), mSetNodeColor, mNodeColor));
pattern.setPatternNodeBackgroundColor(getPatternResult(new PatternProperty(), mSetNodeBackgroundColor,
mNodeBackgroundColor));
pattern.setPatternNodeStyle(getPatternResult(new PatternProperty(), mSetNodeStyle, mNodeStyle));
pattern.setPatternNodeText(getPatternResult(new PatternProperty(), mSetNodeText, mNodeText));
/* edges */
pattern.setPatternEdgeColor(getPatternResult(new PatternProperty(), mSetEdgeColor, mEdgeColor));
pattern.setPatternEdgeStyle(getPatternResult(new PatternProperty(), mSetEdgeStyle, mEdgeStyle));
pattern.setPatternEdgeWidth(getPatternResult(new PatternProperty(), mSetEdgeWidth, mEdgeWidth,
new EdgeWidthBackTransformer()));
/* font */
pattern.setPatternNodeFontName(getPatternResult(new PatternProperty(), mSetNodeFontName, mNodeFontName));
pattern.setPatternNodeFontSize(getPatternResult(new PatternProperty(), mSetNodeFontSize, mNodeFontSize));
pattern.setPatternNodeFontBold(getPatternResult(new PatternProperty(), mSetNodeFontBold, mNodeFontBold));
pattern.setPatternNodeFontItalic(getPatternResult(new PatternProperty(), mSetNodeFontItalic, mNodeFontItalic));
pattern.setPatternIcon(getPatternResult(new PatternProperty(), mSetIcon, mIcon));
pattern.setPatternScript(getPatternResult(new PatternProperty(), mSetScriptPattern, mScriptPattern));
if (StylePatternPanelType.WITH_NAME_AND_CHILDS.equals(mType)) {
pattern.setName(mName.getValue());
pattern.setPatternChild(getPatternResult(new PatternProperty(), mSetChildPattern, mChildPattern));
}
return pattern;
}
/**
* Creates all controls and adds them to the frame.
*/
public void init() {
final CardLayout cardLayout = new CardLayout();
final JPanel rightStack = new JPanel(cardLayout);
final String form = "right:max(40dlu;p), 4dlu, 20dlu, 7dlu,right:max(40dlu;p), 4dlu, 80dlu, 7dlu";
final FormLayout rightLayout = new FormLayout(form, "");
final DefaultFormBuilder rightBuilder = new DefaultFormBuilder(rightLayout);
rightBuilder.setDefaultDialogBorder();
mControls = getControls();
for (final Iterator i = mControls.iterator(); i.hasNext();) {
final IPropertyControl control = (IPropertyControl) i.next();
control.layout(rightBuilder);
}
rightStack.add(rightBuilder.getPanel(), "testTab");
add(rightStack, BorderLayout.CENTER);
}
/**
* Used to enable/disable the attribute controls, if the check boxes are
* changed.
*/
public void propertyChange(final PropertyChangeEvent pEvt) {
if (mPropertyChangePropagation.containsKey(pEvt.getSource())) {
final ThreeCheckBoxProperty booleanProp = (ThreeCheckBoxProperty) pEvt.getSource();
final IPropertyControl bean = (IPropertyControl) mPropertyChangePropagation.get(booleanProp);
bean.setEnabled(ThreeCheckBoxProperty.TRUE_VALUE.equals(booleanProp.getValue()));
return;
}
}
public void setPattern(final Pattern pattern) {
setPatternControls(pattern.getPatternNodeColor(), mSetNodeColor, mNodeColor, ResourceController
.getResourceController().getDefaultProperty(NodeStyleController.RESOURCES_NODE_TEXT_COLOR));
setPatternControls(pattern.getPatternNodeBackgroundColor(), mSetNodeBackgroundColor, mNodeBackgroundColor,
ResourceController.getResourceController().getDefaultProperty(NODE_BACKGROUND_COLOR));
setPatternControls(pattern.getPatternNodeStyle(), mSetNodeStyle, mNodeStyle, NodeStyleModel.SHAPE_AS_PARENT);
setPatternControls(pattern.getPatternNodeText(), mSetNodeText, mNodeText, "");
setPatternControls(pattern.getPatternEdgeColor(), mSetEdgeColor, mEdgeColor, ResourceController
.getResourceController().getDefaultProperty(EdgeController.RESOURCES_EDGE_COLOR));
setPatternControls(pattern.getPatternEdgeStyle(), mSetEdgeStyle, mEdgeStyle, StylePatternPanel.EDGE_STYLES[0]);
setPatternControls(pattern.getPatternEdgeWidth(), mSetEdgeWidth, mEdgeWidth, StylePatternPanel.EDGE_WIDTHS[0],
new EdgeWidthTransformer());
setPatternControls(pattern.getPatternNodeFontName(), mSetNodeFontName, mNodeFontName, ResourceController
.getResourceController().getDefaultFontFamilyName());
setPatternControls(pattern.getPatternNodeFontSize(), mSetNodeFontSize, mNodeFontSize, sizes[0]);
setPatternControls(pattern.getPatternNodeFontBold(), mSetNodeFontBold, mNodeFontBold, Boolean.TRUE.toString());
setPatternControls(pattern.getPatternNodeFontItalic(), mSetNodeFontItalic, mNodeFontItalic, Boolean.TRUE
.toString());
final MindIcon firstInfo = (MindIcon) mIconInformationVector.get(0);
setPatternControls(pattern.getPatternIcon(), mSetIcon, mIcon, firstInfo.getName());
setPatternControls(pattern.getPatternScript(), mSetScriptPattern, mScriptPattern, "");
if (StylePatternPanelType.WITH_NAME_AND_CHILDS.equals(mType)) {
mName.setValue(pattern.getName());
setPatternControls(pattern.getPatternChild(), mSetChildPattern, mChildPattern,
(mPatternList.size() > 0) ? ((Pattern) mPatternList.get(0)).getName() : null);
}
for (final Iterator iter = mPropertyChangePropagation.keySet().iterator(); iter.hasNext();) {
final ThreeCheckBoxProperty prop = (ThreeCheckBoxProperty) iter.next();
propertyChange(new PropertyChangeEvent(prop, prop.getName(), null, prop.getValue()));
}
}
private void setPatternControls(final PatternProperty patternProperty, final PropertyBean threeCheckBoxProperty,
final PropertyBean property, final String defaultValue) {
setPatternControls(patternProperty, threeCheckBoxProperty, property, defaultValue, new IdentityTransformer());
}
/**
*/
private void setPatternControls(final PatternProperty patternProperty, final PropertyBean threeCheckBoxProperty,
final PropertyBean property, final String defaultValue,
final IValueTransformator transformer) {
if (patternProperty == null) {
property.setValue(defaultValue);
threeCheckBoxProperty.setValue(ThreeCheckBoxProperty.DON_T_TOUCH_VALUE);
return;
}
if (patternProperty.getValue() == null) {
property.setValue(defaultValue);
threeCheckBoxProperty.setValue(ThreeCheckBoxProperty.FALSE_VALUE);
return;
}
property.setValue(transformer.transform(patternProperty.getValue()));
threeCheckBoxProperty.setValue(ThreeCheckBoxProperty.TRUE_VALUE);
}
/**
* For the child pattern box, the list is set here.
*/
public void setPatternList(final List patternList) {
mPatternList = patternList;
final Vector childNames = getPatternNames();
mChildPattern.updateComboBoxEntries(childNames, childNames);
}
private String transformEdgeWidth(final String pEdgeWidth) {
if (pEdgeWidth == null) {
return null;
}
final int edgeWidth = ApplyPatternAction.edgeWidthStringToInt(pEdgeWidth);
final HashMap transformator = getEdgeWidthTransformation();
for (final Iterator iter = transformator.keySet().iterator(); iter.hasNext();) {
final String widthString = (String) iter.next();
final Integer width = (Integer) transformator.get(widthString);
if (edgeWidth == width.intValue()) {
return widthString;
}
}
return null;
}
private String transformStringToWidth(final String value) {
final HashMap transformator = getEdgeWidthTransformation();
final int intWidth = ((Integer) transformator.get(value)).intValue();
return ApplyPatternAction.edgeWidthIntToString(intWidth);
}
}
| false | true | private Vector getControls() {
final Vector controls = new Vector();
controls.add(new SeparatorProperty("OptionPanel.separator.General"));
mClearSetters = new ThreeCheckBoxProperty(StylePatternPanel.CLEAR_ALL_SETTERS);
mClearSetters.setValue(ThreeCheckBoxProperty.TRUE_VALUE);
controls.add(mClearSetters);
if (StylePatternPanelType.WITH_NAME_AND_CHILDS.equals(mType)) {
mName = new StringProperty(StylePatternPanel.NODE_NAME);
controls.add(mName);
mSetChildPattern = new ThreeCheckBoxProperty(StylePatternPanel.SET_CHILD_PATTERN);
controls.add(mSetChildPattern);
final Vector childNames = new Vector();
mChildPattern = new ComboProperty(StylePatternPanel.CHILD_PATTERN, childNames, childNames);
controls.add(mChildPattern);
}
controls.add(new NextLineProperty());
controls.add(new SeparatorProperty("OptionPanel.separator.NodeColors"));
mSetNodeColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_COLOR);
controls.add(mSetNodeColor);
mNodeColor = new ColorProperty(StylePatternPanel.NODE_COLOR, ResourceController.getResourceController()
.getDefaultProperty(NodeStyleController.RESOURCES_NODE_TEXT_COLOR));
controls.add(mNodeColor);
mSetNodeBackgroundColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_BACKGROUND_COLOR);
controls.add(mSetNodeBackgroundColor);
mNodeBackgroundColor = new ColorProperty(StylePatternPanel.NODE_BACKGROUND_COLOR, ResourceController
.getResourceController().getDefaultProperty(NODE_BACKGROUND_COLOR));
controls.add(mNodeBackgroundColor);
controls.add(new SeparatorProperty("OptionPanel.separator.NodeStyles"));
mSetNodeStyle = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_STYLE);
controls.add(mSetNodeStyle);
mNodeStyle = new ComboProperty(StylePatternPanel.NODE_STYLE, new String[] { "fork", "bubble", "as_parent",
"combined" });
controls.add(mNodeStyle);
mIconInformationVector = new Vector();
final ModeController controller = mMindMapController;
final Collection mindIcons = ((MIconController) IconController.getController(controller)).getMindIcons();
mIconInformationVector.addAll(mindIcons);
mSetIcon = new ThreeCheckBoxProperty(StylePatternPanel.SET_ICON);
controls.add(mSetIcon);
mIcon = new IconProperty(StylePatternPanel.ICON, mIconInformationVector);
controls.add(mIcon);
controls.add(new NextLineProperty());
controls.add(new SeparatorProperty("OptionPanel.separator.NodeFont"));
mSetNodeFontName = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_NAME);
controls.add(mSetNodeFontName);
mNodeFontName = new FontProperty(StylePatternPanel.NODE_FONT_NAME);
controls.add(mNodeFontName);
mSetNodeFontSize = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_SIZE);
controls.add(mSetNodeFontSize);
final Vector sizesVector = new Vector();
for (int i = 0; i < sizes.length; i++) {
sizesVector.add(sizes[i]);
}
mNodeFontSize = new ComboProperty(StylePatternPanel.NODE_FONT_SIZE, sizesVector, sizesVector);
controls.add(mNodeFontSize);
mSetNodeFontBold = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_BOLD);
controls.add(mSetNodeFontBold);
mNodeFontBold = new BooleanProperty(StylePatternPanel.NODE_FONT_BOLD);
controls.add(mNodeFontBold);
mSetNodeFontItalic = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_ITALIC);
controls.add(mSetNodeFontItalic);
mNodeFontItalic = new BooleanProperty(StylePatternPanel.NODE_FONT_ITALIC);
controls.add(mNodeFontItalic);
/* **** */
mSetNodeText = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_TEXT);
controls.add(mSetNodeText);
mNodeText = new StringProperty(StylePatternPanel.NODE_TEXT);
controls.add(mNodeText);
/* **** */
controls.add(new SeparatorProperty("OptionPanel.separator.EdgeControls"));
mSetEdgeWidth = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_WIDTH);
controls.add(mSetEdgeWidth);
mEdgeWidth = new ComboProperty(StylePatternPanel.EDGE_WIDTH, new String[] { "EdgeWidth_parent",
"EdgeWidth_thin", "EdgeWidth_1", "EdgeWidth_2", "EdgeWidth_4", "EdgeWidth_8" });
controls.add(mEdgeWidth);
/* **** */
mSetEdgeStyle = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_STYLE);
controls.add(mSetEdgeStyle);
mEdgeStyle = new ComboProperty(StylePatternPanel.EDGE_STYLE, new String[] { "linear", "bezier", "sharp_linear",
"sharp_bezier" });
controls.add(mEdgeStyle);
/* **** */
mSetEdgeColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_COLOR);
controls.add(mSetEdgeColor);
mEdgeColor = new ColorProperty(StylePatternPanel.EDGE_COLOR, ResourceController.getResourceController()
.getDefaultProperty(EdgeController.RESOURCES_EDGE_COLOR));
controls.add(mEdgeColor);
/* **** */
controls.add(new SeparatorProperty("OptionPanel.separator.ScriptingControl"));
mSetScriptPattern = new ThreeCheckBoxProperty(StylePatternPanel.SET_SCRIPT);
controls.add(mSetScriptPattern);
mScriptPattern = new ScriptEditorProperty(StylePatternPanel.SCRIPT, mMindMapController);
controls.add(mScriptPattern);
mPropertyChangePropagation.put(mSetNodeColor, mNodeColor);
mPropertyChangePropagation.put(mSetNodeBackgroundColor, mNodeBackgroundColor);
mPropertyChangePropagation.put(mSetNodeStyle, mNodeStyle);
mPropertyChangePropagation.put(mSetNodeFontName, mNodeFontName);
mPropertyChangePropagation.put(mSetNodeFontSize, mNodeFontSize);
mPropertyChangePropagation.put(mSetNodeFontBold, mNodeFontBold);
mPropertyChangePropagation.put(mSetNodeFontItalic, mNodeFontItalic);
mPropertyChangePropagation.put(mSetNodeText, mNodeText);
mPropertyChangePropagation.put(mSetEdgeColor, mEdgeColor);
mPropertyChangePropagation.put(mSetEdgeStyle, mEdgeStyle);
mPropertyChangePropagation.put(mSetEdgeWidth, mEdgeWidth);
mPropertyChangePropagation.put(mSetIcon, mIcon);
mPropertyChangePropagation.put(mSetScriptPattern, mScriptPattern);
if (StylePatternPanelType.WITH_NAME_AND_CHILDS.equals(mType)) {
mPropertyChangePropagation.put(mSetChildPattern, mChildPattern);
}
return controls;
}
| private Vector getControls() {
final Vector controls = new Vector();
controls.add(new SeparatorProperty("OptionPanel.separator.General"));
mClearSetters = new ThreeCheckBoxProperty(StylePatternPanel.CLEAR_ALL_SETTERS);
mClearSetters.setValue(ThreeCheckBoxProperty.TRUE_VALUE);
controls.add(mClearSetters);
if (StylePatternPanelType.WITH_NAME_AND_CHILDS.equals(mType)) {
mName = new StringProperty(StylePatternPanel.NODE_NAME);
controls.add(mName);
mSetChildPattern = new ThreeCheckBoxProperty(StylePatternPanel.SET_CHILD_PATTERN);
controls.add(mSetChildPattern);
final Vector childNames = new Vector();
mChildPattern = new ComboProperty(StylePatternPanel.CHILD_PATTERN, childNames, childNames);
controls.add(mChildPattern);
}
controls.add(new NextLineProperty());
controls.add(new SeparatorProperty("OptionPanel.separator.NodeColors"));
mSetNodeColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_COLOR);
controls.add(mSetNodeColor);
mNodeColor = new ColorProperty(StylePatternPanel.NODE_COLOR, ResourceController.getResourceController()
.getDefaultProperty(NodeStyleController.RESOURCES_NODE_TEXT_COLOR));
controls.add(mNodeColor);
mSetNodeBackgroundColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_BACKGROUND_COLOR);
controls.add(mSetNodeBackgroundColor);
mNodeBackgroundColor = new ColorProperty(StylePatternPanel.NODE_BACKGROUND_COLOR, ResourceController
.getResourceController().getDefaultProperty(NODE_BACKGROUND_COLOR));
controls.add(mNodeBackgroundColor);
controls.add(new SeparatorProperty("OptionPanel.separator.NodeStyles"));
mSetNodeStyle = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_STYLE);
controls.add(mSetNodeStyle);
mNodeStyle = new ComboProperty(StylePatternPanel.NODE_STYLE, new String[] { "fork", "bubble", "as_parent",
"combined" });
controls.add(mNodeStyle);
mIconInformationVector = new Vector();
final ModeController controller = mMindMapController;
final Collection mindIcons = ((MIconController) IconController.getController(controller)).getMindIcons();
mIconInformationVector.addAll(mindIcons);
mSetIcon = new ThreeCheckBoxProperty(StylePatternPanel.SET_ICON);
controls.add(mSetIcon);
mIcon = new IconProperty(StylePatternPanel.ICON, mIconInformationVector);
controls.add(mIcon);
controls.add(new NextLineProperty());
controls.add(new SeparatorProperty("OptionPanel.separator.NodeFont"));
mSetNodeFontName = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_NAME);
controls.add(mSetNodeFontName);
mNodeFontName = new FontProperty(StylePatternPanel.NODE_FONT_NAME);
controls.add(mNodeFontName);
mSetNodeFontSize = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_SIZE);
controls.add(mSetNodeFontSize);
final Vector sizesVector = new Vector();
for (int i = 0; i < sizes.length; i++) {
sizesVector.add(sizes[i]);
}
mNodeFontSize = new ComboProperty(StylePatternPanel.NODE_FONT_SIZE, sizesVector, sizesVector);
controls.add(mNodeFontSize);
mSetNodeFontBold = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_BOLD);
controls.add(mSetNodeFontBold);
mNodeFontBold = new BooleanProperty(StylePatternPanel.NODE_FONT_BOLD);
controls.add(mNodeFontBold);
mSetNodeFontItalic = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_FONT_ITALIC);
controls.add(mSetNodeFontItalic);
mNodeFontItalic = new BooleanProperty(StylePatternPanel.NODE_FONT_ITALIC);
controls.add(mNodeFontItalic);
/* **** */
mSetNodeText = new ThreeCheckBoxProperty(StylePatternPanel.SET_NODE_TEXT);
controls.add(mSetNodeText);
mNodeText = new StringProperty(StylePatternPanel.NODE_TEXT);
controls.add(mNodeText);
/* **** */
controls.add(new SeparatorProperty("OptionPanel.separator.EdgeControls"));
mSetEdgeWidth = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_WIDTH);
controls.add(mSetEdgeWidth);
mEdgeWidth = new ComboProperty(StylePatternPanel.EDGE_WIDTH, EDGE_WIDTHS);
controls.add(mEdgeWidth);
/* **** */
mSetEdgeStyle = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_STYLE);
controls.add(mSetEdgeStyle);
mEdgeStyle = new ComboProperty(StylePatternPanel.EDGE_STYLE, EDGE_STYLES);
controls.add(mEdgeStyle);
/* **** */
mSetEdgeColor = new ThreeCheckBoxProperty(StylePatternPanel.SET_EDGE_COLOR);
controls.add(mSetEdgeColor);
mEdgeColor = new ColorProperty(StylePatternPanel.EDGE_COLOR, ResourceController.getResourceController()
.getDefaultProperty(EdgeController.RESOURCES_EDGE_COLOR));
controls.add(mEdgeColor);
/* **** */
controls.add(new SeparatorProperty("OptionPanel.separator.ScriptingControl"));
mSetScriptPattern = new ThreeCheckBoxProperty(StylePatternPanel.SET_SCRIPT);
controls.add(mSetScriptPattern);
mScriptPattern = new ScriptEditorProperty(StylePatternPanel.SCRIPT, mMindMapController);
controls.add(mScriptPattern);
mPropertyChangePropagation.put(mSetNodeColor, mNodeColor);
mPropertyChangePropagation.put(mSetNodeBackgroundColor, mNodeBackgroundColor);
mPropertyChangePropagation.put(mSetNodeStyle, mNodeStyle);
mPropertyChangePropagation.put(mSetNodeFontName, mNodeFontName);
mPropertyChangePropagation.put(mSetNodeFontSize, mNodeFontSize);
mPropertyChangePropagation.put(mSetNodeFontBold, mNodeFontBold);
mPropertyChangePropagation.put(mSetNodeFontItalic, mNodeFontItalic);
mPropertyChangePropagation.put(mSetNodeText, mNodeText);
mPropertyChangePropagation.put(mSetEdgeColor, mEdgeColor);
mPropertyChangePropagation.put(mSetEdgeStyle, mEdgeStyle);
mPropertyChangePropagation.put(mSetEdgeWidth, mEdgeWidth);
mPropertyChangePropagation.put(mSetIcon, mIcon);
mPropertyChangePropagation.put(mSetScriptPattern, mScriptPattern);
if (StylePatternPanelType.WITH_NAME_AND_CHILDS.equals(mType)) {
mPropertyChangePropagation.put(mSetChildPattern, mChildPattern);
}
return controls;
}
|
diff --git a/src/main/java/org/jbei/ice/lib/parsers/IceGenbankParser.java b/src/main/java/org/jbei/ice/lib/parsers/IceGenbankParser.java
index 30e4948b2..924340564 100644
--- a/src/main/java/org/jbei/ice/lib/parsers/IceGenbankParser.java
+++ b/src/main/java/org/jbei/ice/lib/parsers/IceGenbankParser.java
@@ -1,825 +1,826 @@
package org.jbei.ice.lib.parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jbei.ice.lib.utils.Utils;
import org.jbei.ice.lib.vo.DNAFeature;
import org.jbei.ice.lib.vo.DNAFeatureLocation;
import org.jbei.ice.lib.vo.DNAFeatureNote;
import org.jbei.ice.lib.vo.FeaturedDNASequence;
import org.jbei.ice.lib.vo.IDNASequence;
/**
* Genbank parser and generator.
* The Genbank file format is defined in gbrel.txt located at
* ftp://ftp.ncbi.nlm.nih.gov/genbank/gbrel.txt
*
* This parser also handles some incorrectly formatted and obsolete genbank files.
*
* @author Timothy Ham
*
* */
public class IceGenbankParser extends AbstractParser {
private static final String ICE_GENBANK_PARSER = "IceGenbank";
// genbank tags
public static final String LOCUS_TAG = "LOCUS";
public static final String DEFINITION_TAG = "DEFINITION";
public static final String ACCESSION_TAG = "ACCESSION";
public static final String VERSION_TAG = "VERSION";
public static final String NID_TAG = "NID";
public static final String PROJECT_TAG = "PROJECT";
public static final String DBLINK_TAG = "DBLINK";
public static final String KEYWORDS_TAG = "KEYWORDS";
public static final String SEGMENT_TAG = "SEGMENT";
public static final String SOURCE_TAG = "SOURCE";
public static final String ORGANISM_TAG = "ORGANISM";
public static final String REFERENCE_TAG = "REFERENCE";
public static final String COMMENT_TAG = "COMMENT";
public static final String FEATURES_TAG = "FEATURES";
public static final String BASE_COUNT_TAG = "BASE COUNT";
public static final String CONTIG_TAG = "CONTIG";
public static final String ORIGIN_TAG = "ORIGIN";
public static final String END_TAG = "//";
// tags only under reference tag
public static final String AUTHORS_TAG = "AUTHORS";
public static final String CONSRTM_TAG = "CONSRTM";
public static final String TITLE_TAG = "TITLE";
public static final String JOURNAL_TAG = "JOURNAL";
public static final String MEDLINE_TAG = "MEDLINE";
public static final String PUBMED_TAG = "PUBMED";
public static final String REMARK_TAG = "REMARK";
// obsolete tags
public static final String BASE_TAG = "BASE";
private static final String[] NORMAL_TAGS = { LOCUS_TAG, DEFINITION_TAG, ACCESSION_TAG,
VERSION_TAG, NID_TAG, PROJECT_TAG, DBLINK_TAG, KEYWORDS_TAG, SEGMENT_TAG, SOURCE_TAG,
ORGANISM_TAG, REFERENCE_TAG, COMMENT_TAG, FEATURES_TAG, BASE_COUNT_TAG, CONTIG_TAG,
ORIGIN_TAG, END_TAG, BASE_TAG };
private static final String[] REFERENCE_TAGS = { AUTHORS_TAG, CONSRTM_TAG, TITLE_TAG,
JOURNAL_TAG, MEDLINE_TAG, PUBMED_TAG, REMARK_TAG };
private static final String[] IGNORE_TAGS = { BASE_TAG, };
private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
private static final Pattern startStopPattern = Pattern.compile("[<>]*(\\d+)\\.\\.[<>]*(\\d+)");
private static final Pattern startOnlyPattern = Pattern.compile("\\d+");
private Boolean hasErrors = false;
private List<String> errors = new ArrayList<String>();
@Override
public String getName() {
return ICE_GENBANK_PARSER;
}
@Override
public Boolean hasErrors() {
return hasErrors;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
@Override
public IDNASequence parse(byte[] bytes) throws InvalidFormatParserException {
return parse(new String(bytes));
}
@Override
public IDNASequence parse(File file) throws FileNotFoundException, IOException,
InvalidFormatParserException {
if (file.canRead()) {
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
while (br.ready()) {
sb.append((char) br.read());
}
br.close();
IceGenbankParser iceGenbankParser = new IceGenbankParser();
return iceGenbankParser.parse(sb.toString());
} else {
return null;
}
}
// TODO parse source feature tag with xdb_ref
@Override
public IDNASequence parse(String textSequence) throws InvalidFormatParserException {
textSequence = cleanSequence(textSequence);
FeaturedDNASequence sequence = null;
ArrayList<Tag> tags = splitTags(textSequence, NORMAL_TAGS, IGNORE_TAGS);
tags = parseTags(tags);
sequence = new FeaturedDNASequence();
for (Tag tag : tags) {
if (tag instanceof LocusTag) {
sequence.setName(((LocusTag) tag).getLocusName());
sequence.setIsCircular(((LocusTag) tag).isCircular());
} else if (tag instanceof OriginTag) {
sequence.setSequence(((OriginTag) tag).getSequence());
} else if (tag instanceof FeaturesTag) {
sequence.setFeatures(((FeaturesTag) tag).getFeatures());
}
}
return sequence;
}
private ArrayList<Tag> splitTags(String block, String[] acceptedTags, String[] ignoredTags)
throws InvalidFormatParserException {
ArrayList<Tag> result = new ArrayList<Tag>();
StringBuilder rawBlock = new StringBuilder();
String[] lines = block.split("\n");
String[] lineChunks = null;
Tag currentTag = null;
// see if first two lines contain the "LOCUS" keyword. If not, don't even bother
if (lines.length >= 1 && lines[0].indexOf("LOCUS") == -1) {
if (lines.length == 1 || lines[1].indexOf("LOCUS") == -1) {
throw new InvalidFormatParserException("Not a valid Genbank format: No Locus line.");
}
}
for (String line : lines) {
lineChunks = line.trim().split(" +");
if (lineChunks.length == 0) {
continue;
} else {
String putativeTag = lineChunks[0].trim();
if (Arrays.asList(acceptedTags).contains(putativeTag)) {
if (currentTag != null) { // flush previous tag
currentTag.setRawBody(rawBlock.toString());
if (!Arrays.asList(ignoredTags).contains(currentTag.getKey())) {
result.add(currentTag);
}
}
rawBlock = new StringBuilder();
rawBlock.append(line);
rawBlock.append("\n");
currentTag = new Tag();
currentTag.setKey(putativeTag);
} else {
rawBlock.append(line);
rawBlock.append("\n");
}
}
}
currentTag.setRawBody(rawBlock.toString());
result.add(currentTag); // push the last one
return result;
}
private ArrayList<Tag> parseTags(ArrayList<Tag> tags) throws InvalidFormatParserException {
for (int i = 0; i < tags.size(); i++) {
Tag tag = tags.get(i);
if (ORIGIN_TAG.equals(tag.getKey())) {
tags.set(i, parseOriginTag(tag));
} else if (FEATURES_TAG.equals(tag.getKey())) {
tags.set(i, parseFeaturesTag(tag));
} else if (REFERENCE_TAG.equals(tag.getKey())) {
tags.set(i, parseReferenceTag(tag));
} else if (LOCUS_TAG.equals(tag.getKey())) {
tags.set(i, parseLocusTag(tag));
} else if (SOURCE_TAG.equals(tag.getKey())) {
} else {
parseNormalTag(tag);
}
}
return tags;
}
private Tag parseNormalTag(Tag tag) {
String value = "";
String[] lines = tag.getRawBody().split("\n");
String[] firstLine = lines[0].split(" +");
if (firstLine.length == 1) {
// empty value
tag.setValue("");
} else {
firstLine[0] = "";
value = Utils.join(" ", Arrays.asList(firstLine));
lines[0] = "";
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].trim();
}
value = value + " " + Utils.join(" ", Arrays.asList(lines));
}
tag.setValue(value.trim());
return tag;
}
private OriginTag parseOriginTag(Tag tag) {
OriginTag result = new OriginTag();
String value = "";
StringBuilder sequence = new StringBuilder();
String[] lines = tag.getRawBody().split("\n");
String[] chunks;
if (lines[0].startsWith(ORIGIN_TAG)) {
if (lines[0].split(" +").length > 1) { // grab value of origin
value = lines[0].split(" +")[1];
}
}
for (int i = 1; i < lines.length; i++) {
chunks = lines[i].trim().split(" +");
if (chunks[0].matches("\\d*")) { //sometimes sequence block is un-numbered fasta
chunks[0] = "";
}
sequence.append(Utils.join("", Arrays.asList(chunks)).toLowerCase());
}
result.setKey(tag.getKey());
result.setValue(value);
result.setSequence(sequence.toString());
return result;
}
private FeaturesTag parseFeaturesTag(Tag tag) throws InvalidFormatParserException {
FeaturesTag result = new FeaturesTag();
result.setKey(tag.getKey());
result.setRawBody(tag.getRawBody());
int apparentFeatureKeyColumn = 0;
String[] lines = tag.getRawBody().split("\n");
String[] chunks;
if (lines.length == 1) {
// empty features tag
result.setValue("");
return result;
} else {
// first line should be first feature with location
chunks = lines[1].trim().split(" +");
if (chunks.length > 1) {
apparentFeatureKeyColumn = lines[1].indexOf(chunks[0]);
} else {
return result; // could not determine key/value columns
}
}
String line;
String[] chunk;
DNAFeature dnaFeature = null;
StringBuilder qualifierBlock = new StringBuilder();
String type = null;
boolean complement = false;
for (int i = 1; i < lines.length; i++) {
line = lines[i];
if (!(' ' == (line.charAt(apparentFeatureKeyColumn)))) {
// start new key
if (dnaFeature != null) {
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
}
// start a new feature
dnaFeature = new DNAFeature();
qualifierBlock = new StringBuilder();
/*
* Locations are generated differently by different implementations. Given
* the following two features:
* feature1: (1..3, 5..10) on the + strand |-|.|---->
* feature2: (1..3, 5..10) on the - strand <-|.|----|
*
* biojava follows the letter of the standard (gbrel.txt)
* feature1: join(1..3,5..10)
* feature2: complement(join(5..10,1..3))
*
* However, VectorNTI generates the following
* feature1: join(1..3,5..10)
* feature2: complement(1..3,5..10)
*
* This of course is incorrect, but we must parse them.
*
*/
// grab type, genbankStart, end, and strand
List<GenbankLocation> genbankLocations = null;
try {
chunk = line.trim().split(" +");
type = chunk[0].trim();
chunk[1] = chunk[1].trim();
boolean reversedLocations = false;
if (chunk[1].startsWith("complement(join")) {
reversedLocations = true; //standard compliant complement(join(location, location))
}
if (chunk[1].startsWith("complement")) {
complement = true;
- chunk[1] = chunk[1].substring(11, chunk[1].length() - 2).trim();
+ chunk[1] = chunk[1].trim();
+ chunk[1] = chunk[1].substring(11, chunk[1].length() - 1).trim();
}
genbankLocations = parseGenbankLocation(chunk[1]);
if (reversedLocations) {
Collections.reverse(genbankLocations);
}
} catch (NumberFormatException e) {
getErrors().add("Could not parse feature " + line);
System.out.println(line);
hasErrors = true;
continue;
}
LinkedList<DNAFeatureLocation> dnaFeatureLocations = new LinkedList<DNAFeatureLocation>();
for (GenbankLocation genbankLocation : genbankLocations) {
DNAFeatureLocation dnaFeatureLocation = new DNAFeatureLocation(
genbankLocation.getGenbankStart(), genbankLocation.getEnd());
dnaFeatureLocation.setInBetween(genbankLocation.isInbetween());
dnaFeatureLocation.setSingleResidue(genbankLocation.isSingleResidue());
dnaFeatureLocations.add(dnaFeatureLocation);
}
dnaFeature.getLocations().addAll(dnaFeatureLocations);
dnaFeature.setType(type);
if (complement) {
dnaFeature.setStrand(-1);
} else {
dnaFeature.setStrand(1);
}
} else {
qualifierBlock.append(line);
qualifierBlock.append("\n");
}
}
// last qualifier
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
return result;
}
private List<GenbankLocation> parseGenbankLocation(String input)
throws InvalidFormatParserException {
LinkedList<GenbankLocation> result = new LinkedList<GenbankLocation>();
int genbankStart = 1;
int end = 1;
if (input.startsWith("join")) {
input = input.substring(5, input.length() - 1).trim();
}
String[] chunks = input.split(",");
for (String chunk : chunks) {
chunk = chunk.trim();
Matcher startStopMatcher = startStopPattern.matcher(chunk);
if (startStopMatcher.find()) {
if (startStopMatcher.groupCount() == 2) {
genbankStart = Integer.parseInt(startStopMatcher.group(1));
end = Integer.parseInt(startStopMatcher.group(2));
result.add(new GenbankLocation(genbankStart, end));
}
} else {
Matcher startOnlyMatcher = startOnlyPattern.matcher(chunk);
if (startOnlyMatcher.find()) {
genbankStart = Integer.parseInt(startOnlyMatcher.group(0));
end = Integer.parseInt(startOnlyMatcher.group(0));
result.add(new GenbankLocation(genbankStart, end));
}
}
}
return result;
}
public class GenbankLocation {
private int genbankStart = -1;
private int end = -1;
private boolean inbetween = false;
private boolean singleResidue = false;
public GenbankLocation(int genbankStart, int end) {
super();
setGenbankStart(genbankStart);
setEnd(end);
}
public int getGenbankStart() {
return genbankStart;
}
public void setGenbankStart(int genbankStart) {
this.genbankStart = genbankStart;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public void setInbetween(boolean inbetween) {
this.inbetween = inbetween;
}
public boolean isInbetween() {
return inbetween;
}
public void setSingleResidue(boolean singleResidue) {
this.singleResidue = singleResidue;
}
public boolean isSingleResidue() {
return singleResidue;
}
}
private DNAFeature parseQualifiers(String block, DNAFeature dnaFeature) {
/*
* Qualifiers are interesting beasts. The values can be quoted
* or not quoted. They can span multiple lines. Older versions used
* backslash to indicate space ("\\" -> " "). Oh, and it uses two quotes
* in a row to ("") to indicate a literal quote (e.g. "\""). And since each
* genbank feature does not have a specified "label" field, the
* label can be anything. Some software uses "label", another uses
* "notes", and some of the examples in gbrel.txt uses "gene".
* But really, it could be anything. Qualifer "translation" must be handled
* differently from other multi-line fields, as they are expected to be
* concatenated without spaces.
*
* This parser tries to normalize to "label", and preserve quotedness.
*
*/
ArrayList<DNAFeatureNote> notes = new ArrayList<DNAFeatureNote>();
if ("".equals(block)) {
return dnaFeature;
}
DNAFeatureNote dnaFeatureNote = null;
String[] lines = block.split("\n");
String line = null;
String[] chunk;
StringBuilder qualifierItem = new StringBuilder();
String qualifierValue = null;
int apparentQualifierColumn = lines[0].indexOf("/");
for (String line2 : lines) {
line = line2;
if ('/' == line.charAt(apparentQualifierColumn)) { // new tag starts
if (dnaFeatureNote != null) { // flush previous note
qualifierValue = qualifierItem.toString();
if (qualifierValue.startsWith("\"") && qualifierValue.endsWith("\"")) {
dnaFeatureNote.setQuoted(true);
qualifierValue = qualifierValue.substring(1, qualifierValue.length() - 1);
} else {
dnaFeatureNote.setQuoted(false);
}
qualifierValue = qualifierValue.replaceAll("\\\\", " ");
qualifierValue = qualifierValue.replaceAll("\"\"", "\"");
if ("translation".equals(dnaFeatureNote.getName())) {
qualifierValue = Utils.join("", Arrays.asList(qualifierValue.split(" ")))
.trim();
}
dnaFeatureNote.setValue(qualifierValue);
notes.add(dnaFeatureNote);
}
// start a new note
dnaFeatureNote = new DNAFeatureNote();
qualifierItem = new StringBuilder();
chunk = line.split("=");
if (chunk.length < 2) {
getErrors().add("Skipping bad genbank qualifier " + line);
hasErrors = true;
dnaFeatureNote = null;
continue;
} else {
String putativeName = chunk[0].trim().substring(1);
dnaFeatureNote.setName(putativeName);
chunk[0] = "";
qualifierItem.append(Utils.join(" ", Arrays.asList(chunk)).trim());
}
} else {
qualifierItem.append(" ");
qualifierItem.append(line.trim());
}
}
// parse and add the last one
qualifierValue = qualifierItem.toString();
if (qualifierValue.startsWith("\"") && qualifierValue.endsWith("\"")) {
dnaFeatureNote.setQuoted(true);
qualifierValue = qualifierValue.substring(1, qualifierValue.length() - 1);
} else {
dnaFeatureNote.setQuoted(false);
}
qualifierValue = qualifierValue.replaceAll("\\\\", " ");
qualifierValue = qualifierValue.replaceAll("\"\"", "\"");
if ("translation".equals(dnaFeatureNote.getName())) {
qualifierValue = Utils.join("", Arrays.asList(qualifierValue.split(" "))).trim();
}
dnaFeatureNote.setValue(qualifierValue);
notes.add(dnaFeatureNote);
dnaFeature.setNotes(notes);
dnaFeature = populateName(dnaFeature);
return dnaFeature;
}
/**
* Tries to determine the feature name, from a list of possible qualifier keywords that might
* contain it.
*
* @param dnaFeature
* @return
*/
private DNAFeature populateName(DNAFeature dnaFeature) {
String LABEL_QUALIFIER = "label";
String APE_LABEL_QUALIFIER = "apeinfo_label";
String NOTE_QUALIFIER = "note";
String GENE_QUALIFIER = "gene";
String ORGANISM_QUALIFIER = "organism";
String NAME_QUALIFIER = "name";
ArrayList<DNAFeatureNote> notes = (ArrayList<DNAFeatureNote>) dnaFeature.getNotes();
String[] QUALIFIERS = { APE_LABEL_QUALIFIER, NOTE_QUALIFIER, GENE_QUALIFIER,
ORGANISM_QUALIFIER, NAME_QUALIFIER };
String newLabel = null;
if (dnaFeatureContains(notes, LABEL_QUALIFIER) == -1) {
for (String element : QUALIFIERS) {
int foundId = dnaFeatureContains(notes, element);
if (foundId != -1) {
newLabel = notes.get(foundId).getValue();
}
}
if (newLabel == null) {
newLabel = dnaFeature.getType();
}
} else {
newLabel = notes.get(dnaFeatureContains(notes, LABEL_QUALIFIER)).getValue();
}
dnaFeature.setName(newLabel);
return dnaFeature;
}
private int dnaFeatureContains(ArrayList<DNAFeatureNote> notes, String key) {
int result = -1;
for (int i = 0; i < notes.size(); i++) {
if (notes.get(i).getName().equals(key)) {
result = i;
return result;
}
}
return result;
}
// TODO
private ReferenceTag parseReferenceTag(Tag tag) throws InvalidFormatParserException {
String lines[] = tag.getRawBody().split("\n");
String putativeValue = lines[0].split(" +")[1];
tag.setValue(putativeValue);
return null;
}
private LocusTag parseLocusTag(Tag tag) {
LocusTag result = new LocusTag();
result.setRawBody(tag.getRawBody());
result.setKey(tag.getKey());
String locusLine = tag.getRawBody();
String[] locusChunks = locusLine.split(" +");
if (Arrays.asList(locusChunks).contains("circular")
|| Arrays.asList(locusChunks).contains("CIRCULAR")) {
result.setCircular(true);
} else {
result.setCircular(false);
}
String dateString = locusChunks[locusChunks.length - 1].trim();
try {
result.setDate(simpleDateFormat.parse(dateString));
} catch (ParseException e1) {
getErrors().add("Invalid date format: " + dateString + ". Setting today's date.");
hasErrors = true;
result.setDate(new Date());
}
if (Arrays.asList(locusChunks).indexOf("bp") == 3) {
result.setLocusName(locusChunks[1]);
} else {
result.setLocusName("undefined");
}
return result;
}
public static void main(String[] args) throws IOException {
/*
File file = new File(
"src/main/java/org/jbei/ice/lib/parsers/examples/AcrR_geneart_badlocus_badsequence.gb");
// "src/main/java/org/jbei/ice/lib/parsers/examples/pcI-LasI_ape_no_locusname.ape");
// "src/main/java/org/jbei/ice/lib/parsers/examples/pUC19.gb");
if (file.canRead()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
while (br.ready()) {
sb.append((char) br.read());
}
IceGenbankParser igp = new IceGenbankParser();
try {
igp.parse(sb.toString());
} catch (InvalidFormatParserException e) {
e.printStackTrace();
}
}
*/
}
private class Tag {
private String key;
private String rawBody;
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getRawBody() {
return rawBody;
}
public void setRawBody(String rawBody) {
this.rawBody = rawBody;
}
@SuppressWarnings("unused")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
private class OriginTag extends Tag {
private String sequence;
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
}
private class ReferenceTag extends Tag {
private ArrayList<Tag> references = new ArrayList<Tag>();
@SuppressWarnings("unused")
public void setReferences(ArrayList<Tag> references) {
this.references = references;
}
@SuppressWarnings("unused")
public ArrayList<Tag> getReferences() {
return references;
}
}
private class FeaturesTag extends Tag {
private List<DNAFeature> features = new ArrayList<DNAFeature>();
@SuppressWarnings("unused")
public void setFeatures(List<DNAFeature> features) {
this.features = features;
}
public List<DNAFeature> getFeatures() {
return features;
}
}
private class LocusTag extends Tag {
private String locusName = "";
private boolean isCircular = true;
private String naType = "DNA";
private String strandType = "ds";
private String divisionCode = "";
private Date date;
public String getLocusName() {
return locusName;
}
public void setLocusName(String locusName) {
this.locusName = locusName;
}
public boolean isCircular() {
return isCircular;
}
public void setCircular(boolean isCircular) {
this.isCircular = isCircular;
}
@SuppressWarnings("unused")
public String getNaType() {
return naType;
}
@SuppressWarnings("unused")
public void setNaType(String naType) {
this.naType = naType;
}
@SuppressWarnings("unused")
public String getStrandType() {
return strandType;
}
@SuppressWarnings("unused")
public void setStrandType(String strandType) {
this.strandType = strandType;
}
@SuppressWarnings("unused")
public String getDivisionCode() {
return divisionCode;
}
@SuppressWarnings("unused")
public void setDivisionCode(String divisionCode) {
this.divisionCode = divisionCode;
}
@SuppressWarnings("unused")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
}
| true | true | private FeaturesTag parseFeaturesTag(Tag tag) throws InvalidFormatParserException {
FeaturesTag result = new FeaturesTag();
result.setKey(tag.getKey());
result.setRawBody(tag.getRawBody());
int apparentFeatureKeyColumn = 0;
String[] lines = tag.getRawBody().split("\n");
String[] chunks;
if (lines.length == 1) {
// empty features tag
result.setValue("");
return result;
} else {
// first line should be first feature with location
chunks = lines[1].trim().split(" +");
if (chunks.length > 1) {
apparentFeatureKeyColumn = lines[1].indexOf(chunks[0]);
} else {
return result; // could not determine key/value columns
}
}
String line;
String[] chunk;
DNAFeature dnaFeature = null;
StringBuilder qualifierBlock = new StringBuilder();
String type = null;
boolean complement = false;
for (int i = 1; i < lines.length; i++) {
line = lines[i];
if (!(' ' == (line.charAt(apparentFeatureKeyColumn)))) {
// start new key
if (dnaFeature != null) {
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
}
// start a new feature
dnaFeature = new DNAFeature();
qualifierBlock = new StringBuilder();
/*
* Locations are generated differently by different implementations. Given
* the following two features:
* feature1: (1..3, 5..10) on the + strand |-|.|---->
* feature2: (1..3, 5..10) on the - strand <-|.|----|
*
* biojava follows the letter of the standard (gbrel.txt)
* feature1: join(1..3,5..10)
* feature2: complement(join(5..10,1..3))
*
* However, VectorNTI generates the following
* feature1: join(1..3,5..10)
* feature2: complement(1..3,5..10)
*
* This of course is incorrect, but we must parse them.
*
*/
// grab type, genbankStart, end, and strand
List<GenbankLocation> genbankLocations = null;
try {
chunk = line.trim().split(" +");
type = chunk[0].trim();
chunk[1] = chunk[1].trim();
boolean reversedLocations = false;
if (chunk[1].startsWith("complement(join")) {
reversedLocations = true; //standard compliant complement(join(location, location))
}
if (chunk[1].startsWith("complement")) {
complement = true;
chunk[1] = chunk[1].substring(11, chunk[1].length() - 2).trim();
}
genbankLocations = parseGenbankLocation(chunk[1]);
if (reversedLocations) {
Collections.reverse(genbankLocations);
}
} catch (NumberFormatException e) {
getErrors().add("Could not parse feature " + line);
System.out.println(line);
hasErrors = true;
continue;
}
LinkedList<DNAFeatureLocation> dnaFeatureLocations = new LinkedList<DNAFeatureLocation>();
for (GenbankLocation genbankLocation : genbankLocations) {
DNAFeatureLocation dnaFeatureLocation = new DNAFeatureLocation(
genbankLocation.getGenbankStart(), genbankLocation.getEnd());
dnaFeatureLocation.setInBetween(genbankLocation.isInbetween());
dnaFeatureLocation.setSingleResidue(genbankLocation.isSingleResidue());
dnaFeatureLocations.add(dnaFeatureLocation);
}
dnaFeature.getLocations().addAll(dnaFeatureLocations);
dnaFeature.setType(type);
if (complement) {
dnaFeature.setStrand(-1);
} else {
dnaFeature.setStrand(1);
}
} else {
qualifierBlock.append(line);
qualifierBlock.append("\n");
}
}
// last qualifier
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
return result;
}
| private FeaturesTag parseFeaturesTag(Tag tag) throws InvalidFormatParserException {
FeaturesTag result = new FeaturesTag();
result.setKey(tag.getKey());
result.setRawBody(tag.getRawBody());
int apparentFeatureKeyColumn = 0;
String[] lines = tag.getRawBody().split("\n");
String[] chunks;
if (lines.length == 1) {
// empty features tag
result.setValue("");
return result;
} else {
// first line should be first feature with location
chunks = lines[1].trim().split(" +");
if (chunks.length > 1) {
apparentFeatureKeyColumn = lines[1].indexOf(chunks[0]);
} else {
return result; // could not determine key/value columns
}
}
String line;
String[] chunk;
DNAFeature dnaFeature = null;
StringBuilder qualifierBlock = new StringBuilder();
String type = null;
boolean complement = false;
for (int i = 1; i < lines.length; i++) {
line = lines[i];
if (!(' ' == (line.charAt(apparentFeatureKeyColumn)))) {
// start new key
if (dnaFeature != null) {
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
}
// start a new feature
dnaFeature = new DNAFeature();
qualifierBlock = new StringBuilder();
/*
* Locations are generated differently by different implementations. Given
* the following two features:
* feature1: (1..3, 5..10) on the + strand |-|.|---->
* feature2: (1..3, 5..10) on the - strand <-|.|----|
*
* biojava follows the letter of the standard (gbrel.txt)
* feature1: join(1..3,5..10)
* feature2: complement(join(5..10,1..3))
*
* However, VectorNTI generates the following
* feature1: join(1..3,5..10)
* feature2: complement(1..3,5..10)
*
* This of course is incorrect, but we must parse them.
*
*/
// grab type, genbankStart, end, and strand
List<GenbankLocation> genbankLocations = null;
try {
chunk = line.trim().split(" +");
type = chunk[0].trim();
chunk[1] = chunk[1].trim();
boolean reversedLocations = false;
if (chunk[1].startsWith("complement(join")) {
reversedLocations = true; //standard compliant complement(join(location, location))
}
if (chunk[1].startsWith("complement")) {
complement = true;
chunk[1] = chunk[1].trim();
chunk[1] = chunk[1].substring(11, chunk[1].length() - 1).trim();
}
genbankLocations = parseGenbankLocation(chunk[1]);
if (reversedLocations) {
Collections.reverse(genbankLocations);
}
} catch (NumberFormatException e) {
getErrors().add("Could not parse feature " + line);
System.out.println(line);
hasErrors = true;
continue;
}
LinkedList<DNAFeatureLocation> dnaFeatureLocations = new LinkedList<DNAFeatureLocation>();
for (GenbankLocation genbankLocation : genbankLocations) {
DNAFeatureLocation dnaFeatureLocation = new DNAFeatureLocation(
genbankLocation.getGenbankStart(), genbankLocation.getEnd());
dnaFeatureLocation.setInBetween(genbankLocation.isInbetween());
dnaFeatureLocation.setSingleResidue(genbankLocation.isSingleResidue());
dnaFeatureLocations.add(dnaFeatureLocation);
}
dnaFeature.getLocations().addAll(dnaFeatureLocations);
dnaFeature.setType(type);
if (complement) {
dnaFeature.setStrand(-1);
} else {
dnaFeature.setStrand(1);
}
} else {
qualifierBlock.append(line);
qualifierBlock.append("\n");
}
}
// last qualifier
dnaFeature = parseQualifiers(qualifierBlock.toString(), dnaFeature);
result.getFeatures().add(dnaFeature);
return result;
}
|
diff --git a/plugins/org.bonitasoft.studio.diagram.form.properties/src/org/bonitasoft/studio/properties/form/provider/FormFieldExpressionProvider.java b/plugins/org.bonitasoft.studio.diagram.form.properties/src/org/bonitasoft/studio/properties/form/provider/FormFieldExpressionProvider.java
index 8632a1c69a..5990279c0e 100644
--- a/plugins/org.bonitasoft.studio.diagram.form.properties/src/org/bonitasoft/studio/properties/form/provider/FormFieldExpressionProvider.java
+++ b/plugins/org.bonitasoft.studio.diagram.form.properties/src/org/bonitasoft/studio/properties/form/provider/FormFieldExpressionProvider.java
@@ -1,170 +1,182 @@
/**
* Copyright (C) 2009 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.properties.form.provider;
import java.util.HashSet;
import java.util.Set;
import org.bonitasoft.studio.common.ExpressionConstants;
import org.bonitasoft.studio.common.emf.tools.ModelHelper;
import org.bonitasoft.studio.expression.editor.provider.IExpressionEditor;
import org.bonitasoft.studio.expression.editor.provider.IExpressionProvider;
import org.bonitasoft.studio.form.properties.i18n.Messages;
import org.bonitasoft.studio.model.expression.Expression;
import org.bonitasoft.studio.model.expression.ExpressionFactory;
import org.bonitasoft.studio.model.form.Form;
import org.bonitasoft.studio.model.form.FormField;
import org.bonitasoft.studio.model.form.NextFormButton;
import org.bonitasoft.studio.model.form.SubmitFormButton;
import org.bonitasoft.studio.model.form.Widget;
import org.bonitasoft.studio.model.form.WidgetDependency;
import org.bonitasoft.studio.model.process.PageFlow;
import org.bonitasoft.studio.pics.Pics;
import org.bonitasoft.studio.pics.PicsConstants;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.swt.graphics.Image;
/**
* @author Romain Bioteau
*
*/
public class FormFieldExpressionProvider implements IExpressionProvider {
private final ComposedAdapterFactory adapterFactory;
private final AdapterFactoryLabelProvider adapterLabelProvider;
public FormFieldExpressionProvider(){
adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterLabelProvider = new AdapterFactoryLabelProvider(adapterFactory) ;
}
public Set<Expression> getExpressions(EObject context) {
Set<Expression> result = new HashSet<Expression>() ;
EObject relevantParent = getRelevantParent(context) ;
if (relevantParent instanceof Widget) {
result.add(createExpression((Widget) relevantParent) ) ;
for(WidgetDependency dep : ((Widget) relevantParent).getDependOn()){
if(dep.getWidget()!=null){
result.add(createExpression(dep.getWidget())) ;
}
}
// for the Submit button only, add fields of other widgets
if(relevantParent instanceof SubmitFormButton){
if(relevantParent.eContainer()!= null && relevantParent.eContainer() instanceof Form){
Form f = ModelHelper.getParentForm(relevantParent);
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField){
result.add( createExpression(w) ) ;
}
}
}
}
//Add all widgets from the pageflow not in the same form
final PageFlow pageFlow = ModelHelper.getPageFlow((Widget) relevantParent);
if (pageFlow != null ) {
Form parentForm = ModelHelper.getParentForm(relevantParent);
for (Form f : pageFlow.getForm()){
if(!f.equals(parentForm)){
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField || w instanceof NextFormButton){
result.add( createExpression(w) ) ;
}
}
}
}
}
}else if (relevantParent instanceof Form && relevantParent.eContainer() != null) {
if(relevantParent.eContainer() instanceof PageFlow){
// get all fields from pageflow
final PageFlow pageFlow = (PageFlow) relevantParent.eContainer();
if(pageFlow != null){
for (Form f : pageFlow.getForm()){
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField){
result.add( createExpression(w) ) ;
}
}
}
}
}
- }
+ }else if(relevantParent instanceof PageFlow){
+ // get all fields from pageflow
+ final PageFlow pageFlow = (PageFlow) relevantParent;
+ if(pageFlow != null){
+ for (Form f : pageFlow.getForm()){
+ for (Widget w : f.getWidgets()) {
+ if (w instanceof FormField || w instanceof NextFormButton){
+ result.add( createExpression(w) ) ;
+ }
+ }
+ }
+ }
+ }
return result;
}
private EObject getRelevantParent(EObject context) {
EObject parent = context ;
while(parent != null && (!(parent instanceof Form) && !(parent instanceof Widget)) && !(parent instanceof PageFlow)){
parent = parent.eContainer() ;
}
return parent;
}
private Expression createExpression(Widget w) {
Expression exp = ExpressionFactory.eINSTANCE.createExpression() ;
exp.setType(getExpressionType()) ;
exp.setContent("field_"+w.getName()) ;
exp.setName("field_"+w.getName()) ;
if(w.getReturnTypeModifier() != null ){
exp.setReturnType(w.getReturnTypeModifier()) ;
}else{
exp.setReturnType(w.getAssociatedReturnType()) ;
}
exp.getReferencedElements().add(EcoreUtil.copy(w)) ;
return exp;
}
public String getExpressionType() {
return ExpressionConstants.FORM_FIELD_TYPE;
}
public Image getIcon(Expression expression) {
if(expression.getReferencedElements().isEmpty()){
return null ;
}
return adapterLabelProvider.getImage(expression.getReferencedElements().get(0)) ;
}
public String getProposalLabel(Expression expression) {
return expression.getName() ;
}
public boolean isRelevantFor(EObject context) {
return context instanceof EObject;
}
public Image getTypeIcon() {
return Pics.getImage(PicsConstants.form);
}
public String getTypeLabel() {
return Messages.formFieldTypeLabel;
}
public IExpressionEditor getExpressionEditor(Expression expression,EObject context) {
return new FormFieldExpressionEditor();
}
}
| true | true | public Set<Expression> getExpressions(EObject context) {
Set<Expression> result = new HashSet<Expression>() ;
EObject relevantParent = getRelevantParent(context) ;
if (relevantParent instanceof Widget) {
result.add(createExpression((Widget) relevantParent) ) ;
for(WidgetDependency dep : ((Widget) relevantParent).getDependOn()){
if(dep.getWidget()!=null){
result.add(createExpression(dep.getWidget())) ;
}
}
// for the Submit button only, add fields of other widgets
if(relevantParent instanceof SubmitFormButton){
if(relevantParent.eContainer()!= null && relevantParent.eContainer() instanceof Form){
Form f = ModelHelper.getParentForm(relevantParent);
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField){
result.add( createExpression(w) ) ;
}
}
}
}
//Add all widgets from the pageflow not in the same form
final PageFlow pageFlow = ModelHelper.getPageFlow((Widget) relevantParent);
if (pageFlow != null ) {
Form parentForm = ModelHelper.getParentForm(relevantParent);
for (Form f : pageFlow.getForm()){
if(!f.equals(parentForm)){
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField || w instanceof NextFormButton){
result.add( createExpression(w) ) ;
}
}
}
}
}
}else if (relevantParent instanceof Form && relevantParent.eContainer() != null) {
if(relevantParent.eContainer() instanceof PageFlow){
// get all fields from pageflow
final PageFlow pageFlow = (PageFlow) relevantParent.eContainer();
if(pageFlow != null){
for (Form f : pageFlow.getForm()){
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField){
result.add( createExpression(w) ) ;
}
}
}
}
}
}
return result;
}
| public Set<Expression> getExpressions(EObject context) {
Set<Expression> result = new HashSet<Expression>() ;
EObject relevantParent = getRelevantParent(context) ;
if (relevantParent instanceof Widget) {
result.add(createExpression((Widget) relevantParent) ) ;
for(WidgetDependency dep : ((Widget) relevantParent).getDependOn()){
if(dep.getWidget()!=null){
result.add(createExpression(dep.getWidget())) ;
}
}
// for the Submit button only, add fields of other widgets
if(relevantParent instanceof SubmitFormButton){
if(relevantParent.eContainer()!= null && relevantParent.eContainer() instanceof Form){
Form f = ModelHelper.getParentForm(relevantParent);
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField){
result.add( createExpression(w) ) ;
}
}
}
}
//Add all widgets from the pageflow not in the same form
final PageFlow pageFlow = ModelHelper.getPageFlow((Widget) relevantParent);
if (pageFlow != null ) {
Form parentForm = ModelHelper.getParentForm(relevantParent);
for (Form f : pageFlow.getForm()){
if(!f.equals(parentForm)){
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField || w instanceof NextFormButton){
result.add( createExpression(w) ) ;
}
}
}
}
}
}else if (relevantParent instanceof Form && relevantParent.eContainer() != null) {
if(relevantParent.eContainer() instanceof PageFlow){
// get all fields from pageflow
final PageFlow pageFlow = (PageFlow) relevantParent.eContainer();
if(pageFlow != null){
for (Form f : pageFlow.getForm()){
for (Widget w : ModelHelper.getAllWidgetInsideForm(f)) {
if (w instanceof FormField){
result.add( createExpression(w) ) ;
}
}
}
}
}
}else if(relevantParent instanceof PageFlow){
// get all fields from pageflow
final PageFlow pageFlow = (PageFlow) relevantParent;
if(pageFlow != null){
for (Form f : pageFlow.getForm()){
for (Widget w : f.getWidgets()) {
if (w instanceof FormField || w instanceof NextFormButton){
result.add( createExpression(w) ) ;
}
}
}
}
}
return result;
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IEmbedded.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IEmbedded.java
index 3a0c9b252..50dc9a227 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IEmbedded.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IEmbedded.java
@@ -1,149 +1,151 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.HashSet;
import java.util.Set;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
public class IEmbedded extends HTML implements Paintable {
private static String CLASSNAME = "i-embedded";
private String heigth;
private String width;
private Element browserElement;
private ApplicationConnection client;
public IEmbedded() {
setStyleName(CLASSNAME);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
if (client.updateComponent(this, uidl, true)) {
return;
}
this.client = client;
boolean clearBrowserElement = true;
if (uidl.hasAttribute("type")) {
final String type = uidl.getStringAttribute("type");
if (type.equals("image")) {
String w = uidl.getStringAttribute("width");
if (w != null) {
w = " width=\"" + w + "\" ";
} else {
w = "";
}
String h = uidl.getStringAttribute("height");
if (h != null) {
h = " height=\"" + h + "\" ";
} else {
h = "";
}
setHTML("<img src=\"" + getSrc(uidl, client) + "\"" + w + h
+ "/>");
Element el = DOM.getFirstChild(getElement());
DOM.sinkEvents(el, Event.ONLOAD);
client.addPngFix(el);
} else if (type.equals("browser")) {
if (browserElement == null) {
setHTML("<iframe width=\"100%\" height=\"100%\" frameborder=\"0\" src=\""
- + getSrc(uidl, client) + "\"></iframe>");
+ + getSrc(uidl, client)
+ + "\" name=\""
+ + uidl.getId() + "\"></iframe>");
browserElement = DOM.getFirstChild(getElement());
} else {
DOM.setElementAttribute(browserElement, "src", getSrc(uidl,
client));
}
clearBrowserElement = false;
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded type '" + type + "'");
}
} else if (uidl.hasAttribute("mimetype")) {
final String mime = uidl.getStringAttribute("mimetype");
if (mime.equals("application/x-shockwave-flash")) {
setHTML("<object width=\"" + width + "\" height=\"" + heigth
+ "\"><param name=\"movie\" value=\""
+ getSrc(uidl, client) + "\"><embed src=\""
+ getSrc(uidl, client) + "\" width=\"" + width
+ "\" height=\"" + heigth + "\"></embed></object>");
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded mimetype '" + mime + "'");
}
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded; no type or mimetype attribute");
}
if (clearBrowserElement) {
browserElement = null;
}
}
/**
* Helper to return translated src-attribute from embedded's UIDL
*
* @param uidl
* @param client
* @return
*/
private String getSrc(UIDL uidl, ApplicationConnection client) {
String url = client.translateToolkitUri(uidl.getStringAttribute("src"));
if (url == null) {
return "";
}
return url;
}
public void setWidth(String width) {
if (width == null || width.equals("")) {
width = "100%";
}
this.width = width;
super.setHeight(width);
}
public void setHeight(String height) {
if (height == null || height.equals("")) {
height = "100%";
}
heigth = height;
super.setHeight(height);
}
protected void onDetach() {
// Force browser to fire unload event when component is detached from
// the view (IE doesn't do this automatically)
if (browserElement != null) {
DOM.setElementAttribute(browserElement, "src", "javascript:false");
}
super.onDetach();
}
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (DOM.eventGetType(event) == Event.ONLOAD) {
Set<Widget> w = new HashSet<Widget>();
w.add(this);
Util.componentSizeUpdated(w);
}
}
}
| true | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
if (client.updateComponent(this, uidl, true)) {
return;
}
this.client = client;
boolean clearBrowserElement = true;
if (uidl.hasAttribute("type")) {
final String type = uidl.getStringAttribute("type");
if (type.equals("image")) {
String w = uidl.getStringAttribute("width");
if (w != null) {
w = " width=\"" + w + "\" ";
} else {
w = "";
}
String h = uidl.getStringAttribute("height");
if (h != null) {
h = " height=\"" + h + "\" ";
} else {
h = "";
}
setHTML("<img src=\"" + getSrc(uidl, client) + "\"" + w + h
+ "/>");
Element el = DOM.getFirstChild(getElement());
DOM.sinkEvents(el, Event.ONLOAD);
client.addPngFix(el);
} else if (type.equals("browser")) {
if (browserElement == null) {
setHTML("<iframe width=\"100%\" height=\"100%\" frameborder=\"0\" src=\""
+ getSrc(uidl, client) + "\"></iframe>");
browserElement = DOM.getFirstChild(getElement());
} else {
DOM.setElementAttribute(browserElement, "src", getSrc(uidl,
client));
}
clearBrowserElement = false;
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded type '" + type + "'");
}
} else if (uidl.hasAttribute("mimetype")) {
final String mime = uidl.getStringAttribute("mimetype");
if (mime.equals("application/x-shockwave-flash")) {
setHTML("<object width=\"" + width + "\" height=\"" + heigth
+ "\"><param name=\"movie\" value=\""
+ getSrc(uidl, client) + "\"><embed src=\""
+ getSrc(uidl, client) + "\" width=\"" + width
+ "\" height=\"" + heigth + "\"></embed></object>");
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded mimetype '" + mime + "'");
}
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded; no type or mimetype attribute");
}
if (clearBrowserElement) {
browserElement = null;
}
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
if (client.updateComponent(this, uidl, true)) {
return;
}
this.client = client;
boolean clearBrowserElement = true;
if (uidl.hasAttribute("type")) {
final String type = uidl.getStringAttribute("type");
if (type.equals("image")) {
String w = uidl.getStringAttribute("width");
if (w != null) {
w = " width=\"" + w + "\" ";
} else {
w = "";
}
String h = uidl.getStringAttribute("height");
if (h != null) {
h = " height=\"" + h + "\" ";
} else {
h = "";
}
setHTML("<img src=\"" + getSrc(uidl, client) + "\"" + w + h
+ "/>");
Element el = DOM.getFirstChild(getElement());
DOM.sinkEvents(el, Event.ONLOAD);
client.addPngFix(el);
} else if (type.equals("browser")) {
if (browserElement == null) {
setHTML("<iframe width=\"100%\" height=\"100%\" frameborder=\"0\" src=\""
+ getSrc(uidl, client)
+ "\" name=\""
+ uidl.getId() + "\"></iframe>");
browserElement = DOM.getFirstChild(getElement());
} else {
DOM.setElementAttribute(browserElement, "src", getSrc(uidl,
client));
}
clearBrowserElement = false;
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded type '" + type + "'");
}
} else if (uidl.hasAttribute("mimetype")) {
final String mime = uidl.getStringAttribute("mimetype");
if (mime.equals("application/x-shockwave-flash")) {
setHTML("<object width=\"" + width + "\" height=\"" + heigth
+ "\"><param name=\"movie\" value=\""
+ getSrc(uidl, client) + "\"><embed src=\""
+ getSrc(uidl, client) + "\" width=\"" + width
+ "\" height=\"" + heigth + "\"></embed></object>");
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded mimetype '" + mime + "'");
}
} else {
ApplicationConnection.getConsole().log(
"Unknown Embedded; no type or mimetype attribute");
}
if (clearBrowserElement) {
browserElement = null;
}
}
|
diff --git a/jsf-ri/src/main/java/com/sun/faces/el/ScopedAttributeELResolver.java b/jsf-ri/src/main/java/com/sun/faces/el/ScopedAttributeELResolver.java
index 4229a5fd8..f25739b25 100644
--- a/jsf-ri/src/main/java/com/sun/faces/el/ScopedAttributeELResolver.java
+++ b/jsf-ri/src/main/java/com/sun/faces/el/ScopedAttributeELResolver.java
@@ -1,261 +1,259 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.el;
import java.util.ArrayList;
import java.util.Iterator;
import java.beans.FeatureDescriptor;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.component.UIViewRoot;
import javax.el.ELException;
import javax.el.PropertyNotFoundException;
import javax.el.ELContext;
import javax.el.ELResolver;
import com.sun.faces.util.Util;
import com.sun.faces.util.MessageUtils;
import com.sun.faces.application.ApplicationAssociate;
import com.sun.faces.mgbean.BeanManager;
public class ScopedAttributeELResolver extends ELResolver {
public ScopedAttributeELResolver() {
}
public Object getValue(ELContext context, Object base, Object property)
throws ELException {
if (base != null) {
return null;
}
if ( property == null) {
String message = MessageUtils.getExceptionMessageString
(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "base and property"); // ?????
throw new PropertyNotFoundException(message);
}
context.setPropertyResolved(true);
String attribute = property.toString();
FacesContext facesContext = (FacesContext)
context.getContext(FacesContext.class);
ExternalContext ec = facesContext.getExternalContext();
// check request
Object result = ec.getRequestMap().get(attribute);
if (result != null) {
return result;
}
// check UIViewRoot
UIViewRoot root = facesContext.getViewRoot();
if (root != null) {
Map<String, Object> viewMap = root.getViewMap(false);
if (viewMap != null) {
result = viewMap.get(attribute);
}
}
if (result != null) {
return result;
}
// check session
result = ec.getSessionMap().get(attribute);
if (result != null) {
return result;
}
// check application
result = ec.getApplicationMap().get(attribute);
if (result != null) {
return result;
}
// if we get to this point, nothing was found in the standard scopes.
// If the attribute refers to an entity handled by the BeanManager
// try getting the value from there as the value may be in a custom
// scope.
ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance();
if (associate != null) {
BeanManager manager = associate.getBeanManager();
- if (manager != null) {
- if (manager.isManaged(attribute)) {
- return manager.getBeanFromScope(attribute, facesContext);
- }
+ if (manager != null && manager.isManaged(attribute)) {
+ return manager.getBeanFromScope(attribute, facesContext);
}
}
return null;
}
public Class<?> getType(ELContext context, Object base, Object property)
throws ELException {
if (base != null) {
return null;
}
if ( property == null) {
String message = MessageUtils.getExceptionMessageString
(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "base and property"); // ?????
throw new PropertyNotFoundException(message);
}
context.setPropertyResolved(true);
return Object.class;
}
public void setValue(ELContext context, Object base, Object property,
Object val) throws ELException {
if (base != null) {
return;
}
if (property == null) {
String message = MessageUtils.getExceptionMessageString
(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "base and property"); // ?????
throw new PropertyNotFoundException(message);
}
context.setPropertyResolved(true);
String attribute = (String) property;
FacesContext facesContext = (FacesContext)
context.getContext(FacesContext.class);
ExternalContext ec = facesContext.getExternalContext();
if ((ec.getRequestMap().get(attribute)) != null) {
ec.getRequestMap().put(attribute, val);
} else if ((facesContext.getViewRoot()) != null && (facesContext.getViewRoot().getViewMap().get(attribute)) != null) {
facesContext.getViewRoot().getViewMap().put(attribute, val);
} else if ((ec.getSessionMap().get(attribute)) != null) {
ec.getSessionMap().put(attribute, val);
} else if ((ec.getApplicationMap().get(attribute)) != null) {
ec.getApplicationMap().put(attribute, val);
} else {
// if the property doesn't exist in any of the scopes, put it in
// request scope.
ec.getRequestMap().put(attribute, val);
}
}
public boolean isReadOnly(ELContext context, Object base, Object property)
throws ELException {
if (base != null) {
return false;
}
if (property == null) {
String message = MessageUtils.getExceptionMessageString
(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "base and property"); // ?????
throw new PropertyNotFoundException(message);
}
context.setPropertyResolved(true);
return false;
}
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
ArrayList<FeatureDescriptor> list = new ArrayList<FeatureDescriptor>();
FacesContext facesContext = (FacesContext)
context.getContext(FacesContext.class);
ExternalContext ec = facesContext.getExternalContext();
// add attributes in request scope.
Set<Entry<String,Object>> attrs = ec.getRequestMap().entrySet();
for (Entry<String, Object> entry : attrs) {
String attrName = entry.getKey();
Object attrValue = entry.getValue();
list.add(Util.getFeatureDescriptor(attrName, attrName,
"request scope attribute", false, false, true, attrValue.getClass(),
Boolean.TRUE));
}
// add attributes in view scope.
UIViewRoot root = facesContext.getViewRoot();
if (root != null) {
Map<String, Object> viewMap = root.getViewMap(false);
if (viewMap != null && viewMap.size() != 0) {
attrs = viewMap.entrySet();
for (Entry<String, Object> entry : attrs) {
String attrName = entry.getKey();
Object attrValue = entry.getValue();
list.add(Util.getFeatureDescriptor(attrName, attrName,
"view scope attribute", false, false, true, attrValue.getClass(),
Boolean.TRUE));
}
}
}
// add attributes in session scope.
attrs = ec.getSessionMap().entrySet();
for (Entry<String, Object> entry : attrs) {
String attrName = entry.getKey();
Object attrValue = entry.getValue();
list.add(Util.getFeatureDescriptor(attrName, attrName,
"session scope attribute", false, false, true, attrValue.getClass(),
Boolean.TRUE));
}
// add attributes in application scope.
attrs = ec.getApplicationMap().entrySet();
for (Entry<String, Object> entry : attrs) {
String attrName = entry.getKey();
Object attrValue = entry.getValue();
list.add(Util.getFeatureDescriptor(attrName, attrName,
"application scope attribute", false, false, true, attrValue.getClass(),
Boolean.TRUE));
}
return list.iterator();
}
public Class<?> getCommonPropertyType(ELContext context, Object base) {
if (base != null) {
return null;
}
return Object.class;
}
}
| true | true | public Object getValue(ELContext context, Object base, Object property)
throws ELException {
if (base != null) {
return null;
}
if ( property == null) {
String message = MessageUtils.getExceptionMessageString
(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "base and property"); // ?????
throw new PropertyNotFoundException(message);
}
context.setPropertyResolved(true);
String attribute = property.toString();
FacesContext facesContext = (FacesContext)
context.getContext(FacesContext.class);
ExternalContext ec = facesContext.getExternalContext();
// check request
Object result = ec.getRequestMap().get(attribute);
if (result != null) {
return result;
}
// check UIViewRoot
UIViewRoot root = facesContext.getViewRoot();
if (root != null) {
Map<String, Object> viewMap = root.getViewMap(false);
if (viewMap != null) {
result = viewMap.get(attribute);
}
}
if (result != null) {
return result;
}
// check session
result = ec.getSessionMap().get(attribute);
if (result != null) {
return result;
}
// check application
result = ec.getApplicationMap().get(attribute);
if (result != null) {
return result;
}
// if we get to this point, nothing was found in the standard scopes.
// If the attribute refers to an entity handled by the BeanManager
// try getting the value from there as the value may be in a custom
// scope.
ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance();
if (associate != null) {
BeanManager manager = associate.getBeanManager();
if (manager != null) {
if (manager.isManaged(attribute)) {
return manager.getBeanFromScope(attribute, facesContext);
}
}
}
return null;
}
| public Object getValue(ELContext context, Object base, Object property)
throws ELException {
if (base != null) {
return null;
}
if ( property == null) {
String message = MessageUtils.getExceptionMessageString
(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "base and property"); // ?????
throw new PropertyNotFoundException(message);
}
context.setPropertyResolved(true);
String attribute = property.toString();
FacesContext facesContext = (FacesContext)
context.getContext(FacesContext.class);
ExternalContext ec = facesContext.getExternalContext();
// check request
Object result = ec.getRequestMap().get(attribute);
if (result != null) {
return result;
}
// check UIViewRoot
UIViewRoot root = facesContext.getViewRoot();
if (root != null) {
Map<String, Object> viewMap = root.getViewMap(false);
if (viewMap != null) {
result = viewMap.get(attribute);
}
}
if (result != null) {
return result;
}
// check session
result = ec.getSessionMap().get(attribute);
if (result != null) {
return result;
}
// check application
result = ec.getApplicationMap().get(attribute);
if (result != null) {
return result;
}
// if we get to this point, nothing was found in the standard scopes.
// If the attribute refers to an entity handled by the BeanManager
// try getting the value from there as the value may be in a custom
// scope.
ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance();
if (associate != null) {
BeanManager manager = associate.getBeanManager();
if (manager != null && manager.isManaged(attribute)) {
return manager.getBeanFromScope(attribute, facesContext);
}
}
return null;
}
|
diff --git a/mmstudio/src/org/micromanager/acquisition/AcquisitionManager.java b/mmstudio/src/org/micromanager/acquisition/AcquisitionManager.java
index f850ad588..787e63772 100644
--- a/mmstudio/src/org/micromanager/acquisition/AcquisitionManager.java
+++ b/mmstudio/src/org/micromanager/acquisition/AcquisitionManager.java
@@ -1,188 +1,189 @@
package org.micromanager.acquisition;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;
import mmcorej.TaggedImage;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
public class AcquisitionManager {
Hashtable<String, MMAcquisition> acqs_;
private String album_ = null;
public AcquisitionManager() {
acqs_ = new Hashtable<String, MMAcquisition>();
}
public void openAcquisition(String name, String rootDir) throws MMScriptException {
if (acquisitionExists(name))
throw new MMScriptException("The name is in use");
else {
MMAcquisition acq = new MMAcquisition(name, rootDir);
acqs_.put(name, acq);
}
}
public void openAcquisition(String name, String rootDir, boolean show) throws MMScriptException {
this.openAcquisition(name, rootDir, show, false);
}
public void openAcquisition(String name, String rootDir, boolean show, boolean diskCached) throws MMScriptException {
this.openAcquisition(name, rootDir, show, diskCached, false);
}
public void openAcquisition(String name, String rootDir, boolean show,
boolean diskCached, boolean existing) throws MMScriptException {
if (acquisitionExists(name)) {
throw new MMScriptException("The name is in use");
} else {
acqs_.put(name, new MMAcquisition(name, rootDir, show, diskCached, existing));
}
}
public void closeAcquisition(String name) throws MMScriptException {
if (!acqs_.containsKey(name))
throw new MMScriptException("The name does not exist");
else {
acqs_.get(name).close();
acqs_.remove(name);
}
}
public void closeImage5D(String name) throws MMScriptException {
if (!acquisitionExists(name))
throw new MMScriptException("The name does not exist");
else
acqs_.get(name).closeImage5D();
}
public Boolean acquisitionExists(String name) {
if (acqs_.containsKey(name)) {
if (acqs_.get(name).windowClosed()) {
acqs_.get(name).close();
acqs_.remove(name);
return false;
}
return true;
}
return false;
}
public boolean hasActiveImage5D(String name) throws MMScriptException {
if (acquisitionExists(name)) {
return ! acqs_.get(name).windowClosed();
}
return false;
}
public MMAcquisition getAcquisition(String name) throws MMScriptException {
if (acquisitionExists(name))
return acqs_.get(name);
else
throw new MMScriptException("Undefined acquisition name: " + name);
}
public void closeAll() {
for (Enumeration<MMAcquisition> e=acqs_.elements(); e.hasMoreElements(); )
e.nextElement().close();
acqs_.clear();
}
public String getUniqueAcquisitionName(String name) {
char separator = '_';
while (acquisitionExists(name)) {
int lastSeparator = name.lastIndexOf(separator);
if (lastSeparator == -1)
name += separator + "1";
else {
Integer i = Integer.parseInt(name.substring(lastSeparator + 1));
i++;
name = name.substring(0, lastSeparator) + separator + i;
}
}
return name;
}
public String getCurrentAlbum() {
if (album_ == null) {
return createNewAlbum();
} else {
return album_;
}
}
public String createNewAlbum() {
album_ = getUniqueAcquisitionName("Album");
return album_;
}
public String addToAlbum(TaggedImage image) throws MMScriptException {
boolean newNeeded = true;
MMAcquisition acq = null;
String album = getCurrentAlbum();
JSONObject tags = image.tags;
int imageWidth, imageHeight, imageDepth;
try {
imageWidth = MDUtils.getWidth(tags);
imageHeight = MDUtils.getHeight(tags);
imageDepth = MDUtils.getDepth(tags);
} catch (Exception e) {
throw new MMScriptException("Something wrong with image tags.");
}
if (acquisitionExists(album)) {
acq = acqs_.get(album);
try {
if (acq.getWidth() == imageWidth &&
acq.getHeight() == imageHeight &&
- acq.getDepth() == imageDepth)
+ acq.getDepth() == imageDepth &&
+ ! acq.getImageCache().isFinished() )
newNeeded = false;
} catch (Exception e) {
}
}
if (newNeeded) {
album = createNewAlbum();
openAcquisition(album, "", true, false);
acq = getAcquisition(album);
acq.setDimensions(2, 1, 1, 1);
acq.setImagePhysicalDimensions(imageWidth, imageHeight, imageDepth);
try {
JSONObject summary = new JSONObject();
summary.put("PixelType", tags.get("PixelType"));
acq.setSummaryProperties(summary);
} catch (JSONException ex) {
ex.printStackTrace();
}
acq.initialize();
}
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(image.tags, f);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
acq.insertImage(image);
return album;
}
public String[] getAcqusitionNames() {
Set<String> keySet = acqs_.keySet();
String keys[] = new String[keySet.size()];
return keySet.toArray(keys);
}
}
| true | true | public String addToAlbum(TaggedImage image) throws MMScriptException {
boolean newNeeded = true;
MMAcquisition acq = null;
String album = getCurrentAlbum();
JSONObject tags = image.tags;
int imageWidth, imageHeight, imageDepth;
try {
imageWidth = MDUtils.getWidth(tags);
imageHeight = MDUtils.getHeight(tags);
imageDepth = MDUtils.getDepth(tags);
} catch (Exception e) {
throw new MMScriptException("Something wrong with image tags.");
}
if (acquisitionExists(album)) {
acq = acqs_.get(album);
try {
if (acq.getWidth() == imageWidth &&
acq.getHeight() == imageHeight &&
acq.getDepth() == imageDepth)
newNeeded = false;
} catch (Exception e) {
}
}
if (newNeeded) {
album = createNewAlbum();
openAcquisition(album, "", true, false);
acq = getAcquisition(album);
acq.setDimensions(2, 1, 1, 1);
acq.setImagePhysicalDimensions(imageWidth, imageHeight, imageDepth);
try {
JSONObject summary = new JSONObject();
summary.put("PixelType", tags.get("PixelType"));
acq.setSummaryProperties(summary);
} catch (JSONException ex) {
ex.printStackTrace();
}
acq.initialize();
}
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(image.tags, f);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
acq.insertImage(image);
return album;
}
| public String addToAlbum(TaggedImage image) throws MMScriptException {
boolean newNeeded = true;
MMAcquisition acq = null;
String album = getCurrentAlbum();
JSONObject tags = image.tags;
int imageWidth, imageHeight, imageDepth;
try {
imageWidth = MDUtils.getWidth(tags);
imageHeight = MDUtils.getHeight(tags);
imageDepth = MDUtils.getDepth(tags);
} catch (Exception e) {
throw new MMScriptException("Something wrong with image tags.");
}
if (acquisitionExists(album)) {
acq = acqs_.get(album);
try {
if (acq.getWidth() == imageWidth &&
acq.getHeight() == imageHeight &&
acq.getDepth() == imageDepth &&
! acq.getImageCache().isFinished() )
newNeeded = false;
} catch (Exception e) {
}
}
if (newNeeded) {
album = createNewAlbum();
openAcquisition(album, "", true, false);
acq = getAcquisition(album);
acq.setDimensions(2, 1, 1, 1);
acq.setImagePhysicalDimensions(imageWidth, imageHeight, imageDepth);
try {
JSONObject summary = new JSONObject();
summary.put("PixelType", tags.get("PixelType"));
acq.setSummaryProperties(summary);
} catch (JSONException ex) {
ex.printStackTrace();
}
acq.initialize();
}
int f = 1 + acq.getLastAcquiredFrame();
try {
MDUtils.setFrameIndex(image.tags, f);
} catch (JSONException ex) {
ReportingUtils.showError(ex);
}
acq.insertImage(image);
return album;
}
|
diff --git a/src/sphinx4/edu/cmu/sphinx/frontend/util/FrontEndUtils.java b/src/sphinx4/edu/cmu/sphinx/frontend/util/FrontEndUtils.java
index 567d6ead..b5179a8a 100644
--- a/src/sphinx4/edu/cmu/sphinx/frontend/util/FrontEndUtils.java
+++ b/src/sphinx4/edu/cmu/sphinx/frontend/util/FrontEndUtils.java
@@ -1,88 +1,88 @@
package edu.cmu.sphinx.frontend.util;
import edu.cmu.sphinx.frontend.DataBlocker;
import edu.cmu.sphinx.frontend.DataProcessor;
import edu.cmu.sphinx.frontend.FrontEnd;
import edu.cmu.sphinx.frontend.window.RaisedCosineWindower;
/**
* Some little helper methods to ease the handling of frontend-processor chains.
*
* @author Holger Brandl
*/
public class FrontEndUtils {
/** Returns a the next <code>DataProcessor</code> of type <code>predecClass</code> which preceeds <code>dp</code> */
public static DataProcessor getDataSource(DataProcessor dp, Class<? extends DataProcessor> predecClass) {
while (!predecClass.isInstance(dp.getPredecessor())) {
dp = dp.getPredecessor();
if (dp == null)
return null;
if (dp instanceof FrontEnd)
dp = ((FrontEnd) dp).getLastDataProcessor();
}
return dp;
}
/**
* Applies several heuristics in order to determine the shift-size of the fronted a given <code>DataProcessor</code>
* belongs to.
* <p/>
* <p/>
* The shift-size is searched using the following procedure <ol> <li> Try to determine the window shift-size used by
* the <code>RaisedCosineWindower</code> which precedes the given <code>DataProcessor</code>. <li> If a data-blocker
* is found within the precding processor chain but no <code>RaisedCosineWindower</code> 0 is returned. </ol>
* <p/>
* <p/>
* If both approaches fail, an <code>AssertionError</code> becomes thrown.
*
* @param dataProc The <code>DataProcessor</code> which predecessors are searched backwards to some hints about the
* used window shift size.
* @return The found window shift size
* @throws RuntimeException If both approaches fail, an <code>AssertionError</code> becomes thrown.
*/
public static float getWindowShiftMs(DataProcessor dataProc) {
DataProcessor dp = dataProc;
while (!(dp instanceof RaisedCosineWindower)) {
dp = dp.getPredecessor();
if (dp == null) {
break;
}
if (dp instanceof FrontEnd) {
dp = ((FrontEnd) dp).getLastDataProcessor();
}
}
if (dp != null) {
return ((RaisedCosineWindower) dp).getWindowShiftInMs();
}
dp = dataProc;
while (!(dp instanceof DataBlocker)) {
dp = dp.getPredecessor();
if (dp == null) {
break;
}
if (dp instanceof FrontEnd) {
dp = ((FrontEnd) dp).getLastDataProcessor();
}
}
- if (dp != null) {
- return 0;
+ if (dp != null && dp instanceof DataBlocker) {
+ return (float) ((DataBlocker) dp).getBlockSizeMs();
}
throw new RuntimeException("Can not dermine the current shift-size of the given feature frontend.");
}
}
| true | true | public static float getWindowShiftMs(DataProcessor dataProc) {
DataProcessor dp = dataProc;
while (!(dp instanceof RaisedCosineWindower)) {
dp = dp.getPredecessor();
if (dp == null) {
break;
}
if (dp instanceof FrontEnd) {
dp = ((FrontEnd) dp).getLastDataProcessor();
}
}
if (dp != null) {
return ((RaisedCosineWindower) dp).getWindowShiftInMs();
}
dp = dataProc;
while (!(dp instanceof DataBlocker)) {
dp = dp.getPredecessor();
if (dp == null) {
break;
}
if (dp instanceof FrontEnd) {
dp = ((FrontEnd) dp).getLastDataProcessor();
}
}
if (dp != null) {
return 0;
}
throw new RuntimeException("Can not dermine the current shift-size of the given feature frontend.");
}
| public static float getWindowShiftMs(DataProcessor dataProc) {
DataProcessor dp = dataProc;
while (!(dp instanceof RaisedCosineWindower)) {
dp = dp.getPredecessor();
if (dp == null) {
break;
}
if (dp instanceof FrontEnd) {
dp = ((FrontEnd) dp).getLastDataProcessor();
}
}
if (dp != null) {
return ((RaisedCosineWindower) dp).getWindowShiftInMs();
}
dp = dataProc;
while (!(dp instanceof DataBlocker)) {
dp = dp.getPredecessor();
if (dp == null) {
break;
}
if (dp instanceof FrontEnd) {
dp = ((FrontEnd) dp).getLastDataProcessor();
}
}
if (dp != null && dp instanceof DataBlocker) {
return (float) ((DataBlocker) dp).getBlockSizeMs();
}
throw new RuntimeException("Can not dermine the current shift-size of the given feature frontend.");
}
|
diff --git a/flexodesktop/GUI/flexographicutils/src/main/java/org/openflexo/swing/CustomPopup.java b/flexodesktop/GUI/flexographicutils/src/main/java/org/openflexo/swing/CustomPopup.java
index 00fd269bf..77b1b7901 100644
--- a/flexodesktop/GUI/flexographicutils/src/main/java/org/openflexo/swing/CustomPopup.java
+++ b/flexodesktop/GUI/flexographicutils/src/main/java/org/openflexo/swing/CustomPopup.java
@@ -1,842 +1,845 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenFlexo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FocusTraversalPolicy;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.IllegalComponentStateException;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EventObject;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.FocusManager;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.openflexo.icon.UtilsIconLibrary;
import org.openflexo.toolbox.ToolBox;
/**
* Abstract widget allowing to edit a complex object with a popup
*
* @author sguerin
*
*/
public abstract class CustomPopup<T> extends JPanel implements ActionListener, MouseListener {
protected static final Logger logger = Logger.getLogger(CustomPopup.class.getPackage().getName());
public static final CustomPopupConfiguration configuration = new CustomPopupConfiguration();
private static final int BULLETS = 3;
private static final int BULLET_SPACING = 2;
private static final int BULLET_SIZE = 3;
public T _editedObject;
protected JButton _downButton;
public JComponent _frontComponent;
private final List<ApplyCancelListener> applyCancelListener;
private int posX;
private int posY;
public CustomJPopupMenu _popup;
private ResizablePanel _customPanel;
public interface ApplyCancelListener {
public void fireApplyPerformed();
public void fireCancelPerformed();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (!enabled && popupIsShown()) {
closePopup();
}
if (_frontComponent != null) {
_frontComponent.setEnabled(enabled);
}
if (_downButton != null) {
_downButton.setEnabled(enabled);
}
}
protected abstract JComponent buildFrontComponent();
public CustomPopup(T editedObject) {
super();
_editedObject = editedObject;
setLayout(new BorderLayout());
if (ToolBox.getPLATFORM() != ToolBox.MACOS) {
_downButton = new JButton(UtilsIconLibrary.CUSTOM_POPUP_BUTTON);
} else {
_downButton = new JButton(UtilsIconLibrary.CUSTOM_POPUP_DOWN);
_downButton.setDisabledIcon(UtilsIconLibrary.CUSTOM_POPUP_DOWN_DISABLED);
}
_downButton.addActionListener(this);
add(_downButton, BorderLayout.WEST);
/*Border border = getDownButtonBorder();
if (border != null) {
_downButton.setBorder(border);
}*/
setOpaque(false);
if (ToolBox.getPLATFORM() != ToolBox.MACOS) {
setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
}
_downButton.setBorder(BorderFactory.createEmptyBorder());
_frontComponent = buildFrontComponent();
add(_frontComponent, BorderLayout.CENTER);
applyCancelListener = new Vector<ApplyCancelListener>();
setFocusTraversalPolicy(new FocusTraversalPolicy() {
@Override
public Component getComponentAfter(Container arg0, Component arg1) {
return null;
}
@Override
public Component getComponentBefore(Container arg0, Component arg1) {
return null;
}
@Override
public Component getDefaultComponent(Container arg0) {
return _frontComponent;
}
@Override
public Component getFirstComponent(Container arg0) {
return _frontComponent;
}
@Override
public Component getLastComponent(Container arg0) {
return _frontComponent;
}
});
}
@Override
public void setBackground(Color bg) {
super.setBackground(bg);
if (_frontComponent != null) {
_frontComponent.setBackground(bg);
}
}
@Override
public void setForeground(Color fg) {
super.setForeground(fg);
if (_frontComponent != null) {
_frontComponent.setForeground(fg);
}
}
public JComponent getFrontComponent() {
return _frontComponent;
}
@Override
public void setFont(Font aFont) {
super.setFont(aFont);
if (_frontComponent != null) {
_frontComponent.setFont(aFont);
}
}
public static abstract class ResizablePanel extends JPanel {
public abstract Dimension getDefaultSize();
}
protected void deleteCustomPanel() {
_customPanel = null;
}
public JComponent getDownButton() {
return _downButton;
}
public ResizablePanel getCustomPanel() {
if (_customPanel == null) {
_customPanel = createCustomPanel(getEditedObject());
_customPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}
return _customPanel;
}
protected abstract ResizablePanel createCustomPanel(T editedObject);
private void makePopup() {
if (logger.isLoggable(Level.FINE)) {
logger.fine("makePopup()");
}
Point p = new Point();
try {
p = this.getLocationOnScreen();
} catch (IllegalComponentStateException e) {
e.printStackTrace();
p = getLocation();
}
// Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// Avoid popup behind dock
// dim.height = dim.height - 50;
posX = p.x;/* +getWidth()-getCustomPanel().getWidth(); */
posY = p.y + getHeight() - 1;
int newWidth = getCustomPanel().getDefaultSize().width;
int newHeight = getCustomPanel().getDefaultSize().height;
/*
* if (posX + getCustomPanel().getDefaultSize().width > dim.width) { posX = dim.width - getCustomPanel().getDefaultSize().width -
* 20; } if (posY + getCustomPanel().getDefaultSize().height > dim.height) { newHeight = dim.height - posY; }
*/
getCustomPanel().setPreferredSize(new Dimension(newWidth, newHeight));
// _customPopup = popupFactory.getPopup(this, getCustomPanel(), posX,
// posY);
_popup = new CustomJPopupMenu(this);
Rectangle popupRectangle = new Rectangle(posX, posY, newWidth, newHeight);
Rectangle thisRectangle = new Rectangle();
thisRectangle.setLocation(p);
thisRectangle.setSize(getSize());
Rectangle union = thisRectangle.union(popupRectangle);
popupLiveArea = union;
}
protected class CustomJPopupMenu extends JDialog {
protected class ParentPopupMoveListener implements ComponentListener {
private Point parentPosition;
public ParentPopupMoveListener() {
if (CustomJPopupMenu.this.getOwner().isVisible()) {
parentPosition = CustomJPopupMenu.this.getOwner().getLocationOnScreen();
}
}
@Override
public void componentHidden(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) {
updatePopupLocation();
}
@Override
public void componentResized(ComponentEvent e) {
updatePopupLocation();
}
@Override
public void componentShown(ComponentEvent e) {
parentPosition = CustomJPopupMenu.this.getOwner().getLocationOnScreen();
}
private void updatePopupLocation() {
Point newPosition = getLocation();
newPosition.x += CustomJPopupMenu.this.getOwner().getLocationOnScreen().x - parentPosition.x;
newPosition.y += CustomJPopupMenu.this.getOwner().getLocationOnScreen().y - parentPosition.y;
CustomJPopupMenu.this.setLocation(newPosition);
parentPosition = CustomJPopupMenu.this.getOwner().getLocationOnScreen();
}
}
protected List<CustomJPopupMenu> _childs;
protected boolean _popupIsShown = false;
private ParentPopupMoveListener parentListener;
public CustomJPopupMenu(CustomPopup<?> invoker) {
super((Window) SwingUtilities.getAncestorOfClass(Window.class, invoker));
_childs = new Vector<CustomJPopupMenu>();
parentListener = new ParentPopupMoveListener();
setUndecorated(true);
getRootPane().setBorder(BorderFactory.createLineBorder(Color.BLACK));
getContentPane().add(invoker.getCustomPanel());
CustomJPopupMenu parentPopupMenu = getParentPopupMenu();
if (parentPopupMenu != null) {
parentPopupMenu._childs.add(this);
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("This popup is " + this.hashCode() + " Parent popup is "
+ (parentPopupMenu == null ? "null" : parentPopupMenu.hashCode()));
// logger.info("Made new popup: "+Integer.toHexString(hashCode())+(getParentPopupMenu()!=null?" with parent: "+Integer.toHexString(getParentPopupMenu().hashCode()):""));
}
}
private void registerParentListener() {
if (getOwner() != null) {
getOwner().addComponentListener(parentListener);
}
}
private void unregisterParentListener() {
if (getOwner() != null) {
getOwner().removeComponentListener(parentListener);
}
}
protected CustomPopup<?> getCustomPopup() {
return CustomPopup.this;
}
public boolean isChildOf(Window w) {
return w instanceof CustomPopup.CustomJPopupMenu && ((CustomPopup.CustomJPopupMenu) w).isParentOf(this);
}
public boolean isParentOf(Window w) {
return w != null && (w.getOwner() == this || isParentOf(w.getOwner()));
}
@Override
public void paint(Graphics g) {
super.paint(g);
int y = getSize().height - BULLET_SPACING - 5;
for (int i = 0; i < 3; i++) {
for (int j = i; j < 3; j++) {
int x = getSize().width - BULLETS * BULLET_SIZE - (BULLETS - 1) * BULLET_SPACING + j * (BULLET_SIZE + BULLET_SPACING)
- 5;
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x, y, BULLET_SIZE, BULLET_SIZE);
}
y -= BULLET_SIZE + BULLET_SPACING;
}
}
@Override
public void setVisible(boolean aBoolean) {
// logger.info((aBoolean?"Show popup":"Hide popup")+" "+Integer.toHexString(hashCode()));
if (logger.isLoggable(Level.FINE)) {
logger.fine("setVisible " + aBoolean + " for " + this.hashCode());
}
if (aBoolean) {
_requestVisibility = true;
} else {
for (CustomJPopupMenu child : _childs) {
child.setVisible(false);
}
for (CustomJPopupMenu child : _childs) {
if (child.requestVisibility()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("setVisible " + aBoolean + " forget it");
}
return;
}
}
}
super.setVisible(aBoolean);
_popupIsShown = aBoolean;
if (aBoolean) {
registerParentListener();
_requestVisibility = false;
} else {
unregisterParentListener();
}
}
private boolean _requestVisibility;
public boolean requestVisibility() {
return _requestVisibility;
}
public CustomJPopupMenu getParentPopupMenu() {
if (getOwner() instanceof CustomPopup.CustomJPopupMenu) {
return (CustomJPopupMenu) getOwner();
}
return null;
}
}
private Rectangle popupLiveArea;
// This actionListener handles the next/prev month buttons.
@Override
public void actionPerformed(ActionEvent e) {
onEvent(e);
}
private void onEvent(EventObject e) {
if (e.getSource() == _downButton) {
if (!popupIsShown()) {
openPopup();
} else {
closePopup();
}
} else {
additionalActions();
}
}
private boolean closersAdded = false;
// Override this to add functionality on down button click
public void additionalActions() {
}
private MyWindowAdapter inspectorWindowListener;
private class MyWindowAdapter extends WindowAdapter {
private final Window parentWindow;
public MyWindowAdapter(Window parent) {
this.parentWindow = parent;
}
@Override
public void windowDeactivated(final WindowEvent e) {
// If this window is deactivated, it means that another window has been activated
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (_popup == null) {
return;
}
Window oppositeWindow = e.getOppositeWindow();
if (!(oppositeWindow instanceof CustomPopup.CustomJPopupMenu) && oppositeWindow != null
&& oppositeWindow.getOwner() instanceof CustomPopup.CustomJPopupMenu) {
oppositeWindow = oppositeWindow.getOwner();
}
if (oppositeWindow != _popup) {
if (_popup.isChildOf(oppositeWindow)) {
CustomPopup.CustomJPopupMenu w = _popup;
while (w != null && w != oppositeWindow) {
w.getCustomPopup().pointerLeavesPopup();
w = w.getParentPopupMenu();
}
} else if (oppositeWindow != parentWindow || FocusManager.getCurrentManager().getFocusOwner() != null
&& !_frontComponent.hasFocus()) {
// This test is used to detect the case of the lost of focus is performed
// Because a child popup gained the focus: in this case, nothing should be performed
if (!(oppositeWindow instanceof CustomPopup.CustomJPopupMenu)
|| !((CustomPopup.CustomJPopupMenu) oppositeWindow).isChildOf(_popup)) {
pointerLeavesPopup();
}
}
}
}
});
}
public void startListening() {
_popup.addWindowListener(this);
parentWindow.addWindowListener(this);
}
public void stopListening() {
_popup.removeWindowListener(this);
parentWindow.removeWindowListener(this);
}
}
/**
* Add mouse listeners to each component of the root container c, except this button, and the calendar popup, because mouse clicks in
* them are not supposed to close the popup.
*
* @param c
* the root container
*/
private void addPopupClosers(Container c) {
if (c == getWindow(this) && c != null) {
if (logger.isLoggable(Level.FINE)) {
logger.finer("addPopupClosers");
}
inspectorWindowListener = new MyWindowAdapter((Window) c);
// inspectorWindowListener.startListening();
}
if (c != this && c != _customPanel && c != null) {
c.addMouseListener(this);
for (int i = 0; i < c.getComponents().length; i++) {
addPopupClosers((Container) c.getComponents()[i]);
}
}
}
/**
* Removes mouse listeners to each component of the root container c, except this button, and the calendar popup, because mouse clicks
* in them are not supposed to close the popup.
*
* @param c
* the root container
*/
private void removePopupClosers(Container c) {
if (c == getWindow(this)) {
if (logger.isLoggable(Level.FINE)) {
logger.finer("removePopupClosers");
}
if (inspectorWindowListener != null) {
inspectorWindowListener.stopListening();
}
inspectorWindowListener = null;
}
if (c != this && c != _customPanel && c != null) {
c.removeMouseListener(this);
for (int i = 0; i < c.getComponents().length; i++) {
removePopupClosers((Container) c.getComponents()[i]);
}
}
}
/**
* Copied directly from BasicPopupMenuUI - PK 06-08-04
*
* @param c
* componenet of which we want to find the owning window
* @return the window that is contins after plenty of leves the component c
*/
private Window getWindow(Component c) {
return SwingUtilities.getWindowAncestor(c);
}
protected void deletePopup() {
// _customPopup = null;
_popup = null;
_customPanel = null;
}
public boolean popupIsShown() {
if (_popup != null) {
return _popup._popupIsShown;
}
return false;
}
protected void openPopup() {
if (logger.isLoggable(Level.FINE)) {
logger.fine("openPopup()");
}
makePopup();
if (!closersAdded) // only do this once.
{
if (logger.isLoggable(Level.FINE)) {
logger.fine("CALLED addPopupClosers on " + getWindow(this));
}
addPopupClosers(getWindow(this));
closersAdded = true;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (!_frontComponent.hasFocus()) {
_frontComponent.grabFocus();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (inspectorWindowListener != null) {
inspectorWindowListener.startListening();
}
}
});
}
});
if (isShowing()) {
Point p = this.getLocationOnScreen();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// Multiple screen management
if (GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length > 1) {
screenSize = new Dimension(0, 0);
boolean found = false;
for (int i = 0; !found && i < GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length; i++) {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[i];
screenSize.width = Math.max(screenSize.width, gd.getDefaultConfiguration().getBounds().x
+ gd.getDefaultConfiguration().getBounds().width);
screenSize.height = Math.max(screenSize.height, gd.getDefaultConfiguration().getBounds().y
+ gd.getDefaultConfiguration().getBounds().height);
if (gd.getDefaultConfiguration().getBounds().contains(p)) {
found = true;
}
}
}
Point position = new Point(p.x, p.y + getHeight());
if (position.x + getCustomPanel().getDefaultSize().width > screenSize.width) {
position.x = screenSize.width - getCustomPanel().getDefaultSize().width;
}
if (position.y + getCustomPanel().getDefaultSize().height > screenSize.height) {
position.y = screenSize.height - getCustomPanel().getDefaultSize().height;
}
_popup.setLocation(position);
_popup.pack();
_popup.setVisible(true);
if (ToolBox.getPLATFORM() != ToolBox.MACOS) {
_downButton.setIcon(UtilsIconLibrary.CUSTOM_POPUP_OPEN_BUTTON);
}
MouseAdapter mouseListener = new MouseAdapter() {
private Point previous;
@Override
public void mousePressed(MouseEvent e) {
if (getResizeRectangle().contains(e.getPoint())) {
previous = e.getLocationOnScreen();
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (previous != null) {
Dimension size = getCustomPanel().getSize();
Dimension aDimension = new Dimension(size.width + e.getLocationOnScreen().x - previous.x, size.height
+ e.getLocationOnScreen().y - previous.y);
getCustomPanel().setPreferredSize(aDimension);
_popup.pack();
previous = e.getLocationOnScreen();
}
}
@Override
public void mouseMoved(MouseEvent e) {
if (getResizeRectangle().contains(e.getPoint())) {
_popup.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
} else {
_popup.setCursor(Cursor.getDefaultCursor());
}
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
previous = null;
}
public Rectangle getResizeRectangle() {
+ if (_popup == null) {
+ return new Rectangle();
+ }
Rectangle r = _popup.getBounds();
int size = 3 * (BULLET_SIZE + BULLET_SPACING);
r.x = r.width - size;
r.y = r.height - size;
r.width = size;
r.height = size;
return r;
}
};
_popup.addMouseListener(mouseListener);
_popup.addMouseMotionListener(mouseListener);
} else {
logger.warning("Illegal component state: component is not showing on screen");
// _popup.show(this, 0, 0);
}
// _customPopup.show();
// _popupIsShown = true;
}
public void closePopup(boolean notifyObjectChanged) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("closePopup()");
}
if (_popup == null) {
return;
}
_popup.setVisible(false);
if (ToolBox.getPLATFORM() != ToolBox.MACOS) {
_downButton.setIcon(UtilsIconLibrary.CUSTOM_POPUP_BUTTON);
}
if (notifyObjectChanged) {
fireEditedObjectChanged();
}
if (closersAdded) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("CALLED removePopupClosers on " + getWindow(this));
}
removePopupClosers(getWindow(this));
closersAdded = false;
}
}
public void closePopup() {
closePopup(true);
}
public T getEditedObject() {
return _editedObject;
}
// WARNING: this method uses the equals(Object) method to see if a change is required or not. Therefore, if the edited object type
// overrides the equals method, some objects that are different may not be swapped and cause very unpredictable behaviour. The
// workaround for this is to clone the value when setting on the model. See bug 1004363
public void setEditedObject(T object) {
if (_editedObject == null || !_editedObject.equals(object)) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("CustomPopup setEditedObject: " + object);
}
_editedObject = object;
fireEditedObjectChanged();
}
}
public void setRevertValue(T oldValue) {
// Not implemented here, implement in sub-classes
}
public void fireEditedObjectChanged() {
updateCustomPanel(getEditedObject());
}
public abstract void updateCustomPanel(T editedObject);
@Override
public void mouseEntered(MouseEvent e) {
if (e.getSource() instanceof Component && configuration.getCloseWhenPointerLeavesPopup()) {
Component leftComponent = (Component) e.getSource();
while (leftComponent != null) {
if (leftComponent == CustomPopup.this) {
return;
}
leftComponent = leftComponent.getParent();
}
leftComponent = (Component) e.getSource();
Point p = new Point(e.getPoint());
SwingUtilities.convertPointToScreen(p, leftComponent);
if (_customPanel != null) {
if (!getCustomPanel().isAncestorOf(leftComponent) && !popupLiveArea.contains(p)) {
pointerLeavesPopup();
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() instanceof Component && !configuration.getCloseWhenPointerLeavesPopup()) {
Component leftComponent = (Component) e.getSource();
while (leftComponent != null) {
if (leftComponent == CustomPopup.this) {
return;
}
leftComponent = leftComponent.getParent();
}
leftComponent = (Component) e.getSource();
Point p = new Point(e.getPoint());
SwingUtilities.convertPointToScreen(p, leftComponent);
if (_customPanel != null) {
if (!getCustomPanel().isAncestorOf(leftComponent) && !popupLiveArea.contains(p)) {
pointerLeavesPopup();
}
}
}
onEvent(e);
}
@Override
public void mousePressed(MouseEvent e) {
// interface
}
@Override
public void mouseReleased(MouseEvent e) {
// interface
}
@Override
public void mouseExited(MouseEvent e) {
// interface
}
protected void pointerLeavesPopup() {
closePopup();
}
public void addApplyCancelListener(ApplyCancelListener l) {
applyCancelListener.add(l);
}
public void removeApplyCancelListener(ApplyCancelListener l) {
applyCancelListener.remove(l);
}
public void apply() {
if (logger.isLoggable(Level.FINE)) {
logger.fine("apply()");
}
notifyApplyPerformed();
}
public void notifyApplyPerformed() {
for (ApplyCancelListener l : applyCancelListener) {
l.fireApplyPerformed();
}
}
public void cancel() {
for (ApplyCancelListener l : applyCancelListener) {
l.fireCancelPerformed();
}
}
public static class CustomPopupConfiguration {
private boolean closeWhenPointerLeavesPopup = false;
public boolean getCloseWhenPointerLeavesPopup() {
return closeWhenPointerLeavesPopup;
}
public void setCloseWhenPointerLeavesPopup(boolean closeWhenPointerLeavesPopup) {
this.closeWhenPointerLeavesPopup = closeWhenPointerLeavesPopup;
}
}
public String localizedForKey(String aKey) {
return aKey;
}
}
| true | true | protected void openPopup() {
if (logger.isLoggable(Level.FINE)) {
logger.fine("openPopup()");
}
makePopup();
if (!closersAdded) // only do this once.
{
if (logger.isLoggable(Level.FINE)) {
logger.fine("CALLED addPopupClosers on " + getWindow(this));
}
addPopupClosers(getWindow(this));
closersAdded = true;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (!_frontComponent.hasFocus()) {
_frontComponent.grabFocus();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (inspectorWindowListener != null) {
inspectorWindowListener.startListening();
}
}
});
}
});
if (isShowing()) {
Point p = this.getLocationOnScreen();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// Multiple screen management
if (GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length > 1) {
screenSize = new Dimension(0, 0);
boolean found = false;
for (int i = 0; !found && i < GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length; i++) {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[i];
screenSize.width = Math.max(screenSize.width, gd.getDefaultConfiguration().getBounds().x
+ gd.getDefaultConfiguration().getBounds().width);
screenSize.height = Math.max(screenSize.height, gd.getDefaultConfiguration().getBounds().y
+ gd.getDefaultConfiguration().getBounds().height);
if (gd.getDefaultConfiguration().getBounds().contains(p)) {
found = true;
}
}
}
Point position = new Point(p.x, p.y + getHeight());
if (position.x + getCustomPanel().getDefaultSize().width > screenSize.width) {
position.x = screenSize.width - getCustomPanel().getDefaultSize().width;
}
if (position.y + getCustomPanel().getDefaultSize().height > screenSize.height) {
position.y = screenSize.height - getCustomPanel().getDefaultSize().height;
}
_popup.setLocation(position);
_popup.pack();
_popup.setVisible(true);
if (ToolBox.getPLATFORM() != ToolBox.MACOS) {
_downButton.setIcon(UtilsIconLibrary.CUSTOM_POPUP_OPEN_BUTTON);
}
MouseAdapter mouseListener = new MouseAdapter() {
private Point previous;
@Override
public void mousePressed(MouseEvent e) {
if (getResizeRectangle().contains(e.getPoint())) {
previous = e.getLocationOnScreen();
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (previous != null) {
Dimension size = getCustomPanel().getSize();
Dimension aDimension = new Dimension(size.width + e.getLocationOnScreen().x - previous.x, size.height
+ e.getLocationOnScreen().y - previous.y);
getCustomPanel().setPreferredSize(aDimension);
_popup.pack();
previous = e.getLocationOnScreen();
}
}
@Override
public void mouseMoved(MouseEvent e) {
if (getResizeRectangle().contains(e.getPoint())) {
_popup.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
} else {
_popup.setCursor(Cursor.getDefaultCursor());
}
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
previous = null;
}
public Rectangle getResizeRectangle() {
Rectangle r = _popup.getBounds();
int size = 3 * (BULLET_SIZE + BULLET_SPACING);
r.x = r.width - size;
r.y = r.height - size;
r.width = size;
r.height = size;
return r;
}
};
_popup.addMouseListener(mouseListener);
_popup.addMouseMotionListener(mouseListener);
} else {
logger.warning("Illegal component state: component is not showing on screen");
// _popup.show(this, 0, 0);
}
// _customPopup.show();
// _popupIsShown = true;
}
| protected void openPopup() {
if (logger.isLoggable(Level.FINE)) {
logger.fine("openPopup()");
}
makePopup();
if (!closersAdded) // only do this once.
{
if (logger.isLoggable(Level.FINE)) {
logger.fine("CALLED addPopupClosers on " + getWindow(this));
}
addPopupClosers(getWindow(this));
closersAdded = true;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (!_frontComponent.hasFocus()) {
_frontComponent.grabFocus();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (inspectorWindowListener != null) {
inspectorWindowListener.startListening();
}
}
});
}
});
if (isShowing()) {
Point p = this.getLocationOnScreen();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// Multiple screen management
if (GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length > 1) {
screenSize = new Dimension(0, 0);
boolean found = false;
for (int i = 0; !found && i < GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length; i++) {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[i];
screenSize.width = Math.max(screenSize.width, gd.getDefaultConfiguration().getBounds().x
+ gd.getDefaultConfiguration().getBounds().width);
screenSize.height = Math.max(screenSize.height, gd.getDefaultConfiguration().getBounds().y
+ gd.getDefaultConfiguration().getBounds().height);
if (gd.getDefaultConfiguration().getBounds().contains(p)) {
found = true;
}
}
}
Point position = new Point(p.x, p.y + getHeight());
if (position.x + getCustomPanel().getDefaultSize().width > screenSize.width) {
position.x = screenSize.width - getCustomPanel().getDefaultSize().width;
}
if (position.y + getCustomPanel().getDefaultSize().height > screenSize.height) {
position.y = screenSize.height - getCustomPanel().getDefaultSize().height;
}
_popup.setLocation(position);
_popup.pack();
_popup.setVisible(true);
if (ToolBox.getPLATFORM() != ToolBox.MACOS) {
_downButton.setIcon(UtilsIconLibrary.CUSTOM_POPUP_OPEN_BUTTON);
}
MouseAdapter mouseListener = new MouseAdapter() {
private Point previous;
@Override
public void mousePressed(MouseEvent e) {
if (getResizeRectangle().contains(e.getPoint())) {
previous = e.getLocationOnScreen();
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (previous != null) {
Dimension size = getCustomPanel().getSize();
Dimension aDimension = new Dimension(size.width + e.getLocationOnScreen().x - previous.x, size.height
+ e.getLocationOnScreen().y - previous.y);
getCustomPanel().setPreferredSize(aDimension);
_popup.pack();
previous = e.getLocationOnScreen();
}
}
@Override
public void mouseMoved(MouseEvent e) {
if (getResizeRectangle().contains(e.getPoint())) {
_popup.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
} else {
_popup.setCursor(Cursor.getDefaultCursor());
}
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
previous = null;
}
public Rectangle getResizeRectangle() {
if (_popup == null) {
return new Rectangle();
}
Rectangle r = _popup.getBounds();
int size = 3 * (BULLET_SIZE + BULLET_SPACING);
r.x = r.width - size;
r.y = r.height - size;
r.width = size;
r.height = size;
return r;
}
};
_popup.addMouseListener(mouseListener);
_popup.addMouseMotionListener(mouseListener);
} else {
logger.warning("Illegal component state: component is not showing on screen");
// _popup.show(this, 0, 0);
}
// _customPopup.show();
// _popupIsShown = true;
}
|
diff --git a/alvis/de.unisiegen.informatik.bs.alvis/src/de/unisiegen/informatik/bs/alvis/commands/RunCompile.java b/alvis/de.unisiegen.informatik.bs.alvis/src/de/unisiegen/informatik/bs/alvis/commands/RunCompile.java
index 0e2c8a1..a6516c5 100644
--- a/alvis/de.unisiegen.informatik.bs.alvis/src/de/unisiegen/informatik/bs/alvis/commands/RunCompile.java
+++ b/alvis/de.unisiegen.informatik.bs.alvis/src/de/unisiegen/informatik/bs/alvis/commands/RunCompile.java
@@ -1,203 +1,203 @@
package de.unisiegen.informatik.bs.alvis.commands;
import java.io.File;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.FileEditorInput;
import de.unisiegen.informatik.bs.alvis.Activator;
import de.unisiegen.informatik.bs.alvis.Run;
import de.unisiegen.informatik.bs.alvis.compiler.CompilerAccess;
import de.unisiegen.informatik.bs.alvis.tools.IO;
public class RunCompile extends AbstractHandler {
Run seri;
ExecutionEvent myEvent;
public Object execute(ExecutionEvent event) throws ExecutionException {
// NOTE: event is null when executing from run editor.
myEvent = event;
// Save all Editors
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.saveAllEditors(true);
new CloseRunPerspective().execute(event);
// Instantiate IEditorInput
IEditorInput input = null;
/*
* Register datatypes and packagenames to the compiler This is important
* for compiling
*/
CompilerAccess.getDefault().setDatatypes(
Activator.getDefault().getAllDatatypesInPlugIns());
CompilerAccess.getDefault().setDatatypePackages(
Activator.getDefault().getAllDatatypesPackagesInPlugIns());
// System.out.println(Platform.getInstanceLocation().getURL().getPath());
// CompilerAccess.getDefault().testDatatypes();
try {
// What to run? get the input (filepath)
input = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActiveEditor().getEditorInput();
} catch (NullPointerException e) {
e.printStackTrace();
}
// Instantiate a new Run object
seri = null;
/*
* GET THE RUN OBJECT
*/
// Check if the input is a FileEditorInput
if (input != null && input instanceof FileEditorInput) {
// cast to FileEditorInput
FileEditorInput fileInput = (FileEditorInput) input;
// If the user has choosen a graph to run...
if (fileInput.getFile().getFileExtension().equals("run")) { //$NON-NLS-1$
// get the path in system
String systemPath = fileInput.getPath().toString();
// and deserialize the saved run to seri
seri = (Run) IO.deserialize(systemPath);
} else {
// ask for run settings
seri = getPreferencesByDialog();
}
} else {
// ask for run settings
seri = getPreferencesByDialog();
}
// END OF GET THE RUN OBJECT
if (seri != null) {
// GET THE ALGORITHM AS STRING
try {
// Translate the PseudoCode and get the translated file
File javaCode = null;
// if the algorithm is of type ".algo" it is pseudo code and it must be compiled
// if not, it's passed on to the virtual machine
if(seri.getAlgorithmFile().endsWith(".algo")){
// try to compile with compiler
javaCode = CompilerAccess.getDefault().compile(
seri.getAlgorithmFile());
// if fails
if (null == javaCode) // compile with dummy
- throw new Exception();// TODO throw a meaningful exception
+ throw new Exception("Compilation failed");// TODO throw a meaningful exception
}
else{
javaCode = new File(Platform.getInstanceLocation().getURL().getPath() + seri.getAlgorithmFile());
}
// Kill the extension
String fileNameOfTheAlgorithm = javaCode.getCanonicalPath()
.replaceAll("\\.java$", ""); //$NON-NLS-1$
// Get the path where the translated files are saved to.
String pathToTheAlgorithm = javaCode.getParentFile()
.getCanonicalPath();
// Register Algorithm to VM
// TODO Warning, if we change the name of the translated file
// this here will crash
fileNameOfTheAlgorithm = "Algorithm";
// setJavaAlgorithmToVM has 2 parameter 1. is the path 2. is the
// filename
// if /usr/alvis/src/Algorithm.java then
// 1.: /usr/alvis/src
// 2.: Algorithm
Activator.getDefault().setJavaAlgorithmToVM(pathToTheAlgorithm,
fileNameOfTheAlgorithm,
Activator.getDefault().getAllDatatypesInPlugIns());
Activator.getDefault().setActiveRun(seri);
// Then activate command SwitchToRunPerspective
new SwitchToRunPerspective().execute(event);
} catch (Exception e) {
// Create the required Status object
Status status = new Status(IStatus.ERROR, "My Plug-in ID", 0,
e.getMessage(), null);
// Display the dialog
ErrorDialog
.openError(
Display.getCurrent().getActiveShell(),
"Error starting the Run",
"An Error has occurred. The run could not start. Read the message shown below to solve the problem.",
status);
e.printStackTrace();
} finally {
}
} else {
return null;
}
// IResource.refreshLocal();
new RefreshWorkspace().execute(event);
return null;
}
private Run getPreferencesByDialog() {
String extensions = Activator.getDefault().getFileExtensionsAsCommaSeparatedList();
Run seri = new Run();
while (seri.getAlgorithmFile().equals("") | seri.getExampleFile().equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell(), new WorkbenchLabelProvider(),
new BaseWorkbenchContentProvider());
dialog.setTitle(Messages.RunCompile_7);
dialog.setMessage(NLS.bind(Messages.RunCompile_8, "(" + extensions + ")"));
dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
dialog.open();
if (dialog.getResult() != null) {
String result = ""; //$NON-NLS-1$
for (Object o : dialog.getResult()) {
result = o.toString();
for(String fileExtension : Activator.getDefault().getFileExtensions()){
if (result.startsWith("L") && result.endsWith(fileExtension)) { //$NON-NLS-1$ //$NON-NLS-2$
result = result.substring(2); // cut the first two chars
seri.setExampleFile(result);
}
}
if (result.startsWith("L") && (result.endsWith("algo")|| result.endsWith(".java"))) { //$NON-NLS-1$ //$NON-NLS-2$
result = result.substring(2); // cut the first two chars
seri.setAlgorithmFile(result);
}
}
}
if (dialog.getReturnCode() == 1) // the user clicked cancel
return null;
}
return seri;
}
}
| true | true | public Object execute(ExecutionEvent event) throws ExecutionException {
// NOTE: event is null when executing from run editor.
myEvent = event;
// Save all Editors
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.saveAllEditors(true);
new CloseRunPerspective().execute(event);
// Instantiate IEditorInput
IEditorInput input = null;
/*
* Register datatypes and packagenames to the compiler This is important
* for compiling
*/
CompilerAccess.getDefault().setDatatypes(
Activator.getDefault().getAllDatatypesInPlugIns());
CompilerAccess.getDefault().setDatatypePackages(
Activator.getDefault().getAllDatatypesPackagesInPlugIns());
// System.out.println(Platform.getInstanceLocation().getURL().getPath());
// CompilerAccess.getDefault().testDatatypes();
try {
// What to run? get the input (filepath)
input = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActiveEditor().getEditorInput();
} catch (NullPointerException e) {
e.printStackTrace();
}
// Instantiate a new Run object
seri = null;
/*
* GET THE RUN OBJECT
*/
// Check if the input is a FileEditorInput
if (input != null && input instanceof FileEditorInput) {
// cast to FileEditorInput
FileEditorInput fileInput = (FileEditorInput) input;
// If the user has choosen a graph to run...
if (fileInput.getFile().getFileExtension().equals("run")) { //$NON-NLS-1$
// get the path in system
String systemPath = fileInput.getPath().toString();
// and deserialize the saved run to seri
seri = (Run) IO.deserialize(systemPath);
} else {
// ask for run settings
seri = getPreferencesByDialog();
}
} else {
// ask for run settings
seri = getPreferencesByDialog();
}
// END OF GET THE RUN OBJECT
if (seri != null) {
// GET THE ALGORITHM AS STRING
try {
// Translate the PseudoCode and get the translated file
File javaCode = null;
// if the algorithm is of type ".algo" it is pseudo code and it must be compiled
// if not, it's passed on to the virtual machine
if(seri.getAlgorithmFile().endsWith(".algo")){
// try to compile with compiler
javaCode = CompilerAccess.getDefault().compile(
seri.getAlgorithmFile());
// if fails
if (null == javaCode) // compile with dummy
throw new Exception();// TODO throw a meaningful exception
}
else{
javaCode = new File(Platform.getInstanceLocation().getURL().getPath() + seri.getAlgorithmFile());
}
// Kill the extension
String fileNameOfTheAlgorithm = javaCode.getCanonicalPath()
.replaceAll("\\.java$", ""); //$NON-NLS-1$
// Get the path where the translated files are saved to.
String pathToTheAlgorithm = javaCode.getParentFile()
.getCanonicalPath();
// Register Algorithm to VM
// TODO Warning, if we change the name of the translated file
// this here will crash
fileNameOfTheAlgorithm = "Algorithm";
// setJavaAlgorithmToVM has 2 parameter 1. is the path 2. is the
// filename
// if /usr/alvis/src/Algorithm.java then
// 1.: /usr/alvis/src
// 2.: Algorithm
Activator.getDefault().setJavaAlgorithmToVM(pathToTheAlgorithm,
fileNameOfTheAlgorithm,
Activator.getDefault().getAllDatatypesInPlugIns());
Activator.getDefault().setActiveRun(seri);
// Then activate command SwitchToRunPerspective
new SwitchToRunPerspective().execute(event);
} catch (Exception e) {
// Create the required Status object
Status status = new Status(IStatus.ERROR, "My Plug-in ID", 0,
e.getMessage(), null);
// Display the dialog
ErrorDialog
.openError(
Display.getCurrent().getActiveShell(),
"Error starting the Run",
"An Error has occurred. The run could not start. Read the message shown below to solve the problem.",
status);
e.printStackTrace();
} finally {
}
} else {
return null;
}
// IResource.refreshLocal();
new RefreshWorkspace().execute(event);
return null;
}
| public Object execute(ExecutionEvent event) throws ExecutionException {
// NOTE: event is null when executing from run editor.
myEvent = event;
// Save all Editors
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.saveAllEditors(true);
new CloseRunPerspective().execute(event);
// Instantiate IEditorInput
IEditorInput input = null;
/*
* Register datatypes and packagenames to the compiler This is important
* for compiling
*/
CompilerAccess.getDefault().setDatatypes(
Activator.getDefault().getAllDatatypesInPlugIns());
CompilerAccess.getDefault().setDatatypePackages(
Activator.getDefault().getAllDatatypesPackagesInPlugIns());
// System.out.println(Platform.getInstanceLocation().getURL().getPath());
// CompilerAccess.getDefault().testDatatypes();
try {
// What to run? get the input (filepath)
input = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActiveEditor().getEditorInput();
} catch (NullPointerException e) {
e.printStackTrace();
}
// Instantiate a new Run object
seri = null;
/*
* GET THE RUN OBJECT
*/
// Check if the input is a FileEditorInput
if (input != null && input instanceof FileEditorInput) {
// cast to FileEditorInput
FileEditorInput fileInput = (FileEditorInput) input;
// If the user has choosen a graph to run...
if (fileInput.getFile().getFileExtension().equals("run")) { //$NON-NLS-1$
// get the path in system
String systemPath = fileInput.getPath().toString();
// and deserialize the saved run to seri
seri = (Run) IO.deserialize(systemPath);
} else {
// ask for run settings
seri = getPreferencesByDialog();
}
} else {
// ask for run settings
seri = getPreferencesByDialog();
}
// END OF GET THE RUN OBJECT
if (seri != null) {
// GET THE ALGORITHM AS STRING
try {
// Translate the PseudoCode and get the translated file
File javaCode = null;
// if the algorithm is of type ".algo" it is pseudo code and it must be compiled
// if not, it's passed on to the virtual machine
if(seri.getAlgorithmFile().endsWith(".algo")){
// try to compile with compiler
javaCode = CompilerAccess.getDefault().compile(
seri.getAlgorithmFile());
// if fails
if (null == javaCode) // compile with dummy
throw new Exception("Compilation failed");// TODO throw a meaningful exception
}
else{
javaCode = new File(Platform.getInstanceLocation().getURL().getPath() + seri.getAlgorithmFile());
}
// Kill the extension
String fileNameOfTheAlgorithm = javaCode.getCanonicalPath()
.replaceAll("\\.java$", ""); //$NON-NLS-1$
// Get the path where the translated files are saved to.
String pathToTheAlgorithm = javaCode.getParentFile()
.getCanonicalPath();
// Register Algorithm to VM
// TODO Warning, if we change the name of the translated file
// this here will crash
fileNameOfTheAlgorithm = "Algorithm";
// setJavaAlgorithmToVM has 2 parameter 1. is the path 2. is the
// filename
// if /usr/alvis/src/Algorithm.java then
// 1.: /usr/alvis/src
// 2.: Algorithm
Activator.getDefault().setJavaAlgorithmToVM(pathToTheAlgorithm,
fileNameOfTheAlgorithm,
Activator.getDefault().getAllDatatypesInPlugIns());
Activator.getDefault().setActiveRun(seri);
// Then activate command SwitchToRunPerspective
new SwitchToRunPerspective().execute(event);
} catch (Exception e) {
// Create the required Status object
Status status = new Status(IStatus.ERROR, "My Plug-in ID", 0,
e.getMessage(), null);
// Display the dialog
ErrorDialog
.openError(
Display.getCurrent().getActiveShell(),
"Error starting the Run",
"An Error has occurred. The run could not start. Read the message shown below to solve the problem.",
status);
e.printStackTrace();
} finally {
}
} else {
return null;
}
// IResource.refreshLocal();
new RefreshWorkspace().execute(event);
return null;
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/sync/CVSCatchupReleaseViewer.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/sync/CVSCatchupReleaseViewer.java
index b6da6a200..eeaa7fd16 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/sync/CVSCatchupReleaseViewer.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/sync/CVSCatchupReleaseViewer.java
@@ -1,458 +1,458 @@
package org.eclipse.team.internal.ccvs.ui.sync;
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.structuremergeviewer.DiffContainer;
import org.eclipse.compare.structuremergeviewer.DiffElement;
import org.eclipse.compare.structuremergeviewer.IDiffElement;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.sync.IRemoteResource;
import org.eclipse.team.core.sync.IRemoteSyncElement;
import org.eclipse.team.internal.ccvs.core.CVSException;
import org.eclipse.team.internal.ccvs.core.CVSProviderPlugin;
import org.eclipse.team.internal.ccvs.core.CVSTeamProvider;
import org.eclipse.team.internal.ccvs.core.ICVSFile;
import org.eclipse.team.internal.ccvs.core.ICVSRemoteFile;
import org.eclipse.team.internal.ccvs.core.ILogEntry;
import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot;
import org.eclipse.team.internal.ccvs.core.syncinfo.ResourceSyncInfo;
import org.eclipse.team.internal.ccvs.ui.CVSDecoration;
import org.eclipse.team.internal.ccvs.ui.CVSDecorationRunnable;
import org.eclipse.team.internal.ccvs.ui.CVSDecoratorConfiguration;
import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin;
import org.eclipse.team.internal.ccvs.ui.HistoryView;
import org.eclipse.team.internal.ccvs.ui.ICVSUIConstants;
import org.eclipse.team.internal.ccvs.ui.OverlayIcon;
import org.eclipse.team.internal.ccvs.ui.OverlayIconCache;
import org.eclipse.team.internal.ccvs.ui.Policy;
import org.eclipse.team.internal.ccvs.ui.merge.OverrideUpdateMergeAction;
import org.eclipse.team.internal.ccvs.ui.merge.UpdateMergeAction;
import org.eclipse.team.internal.ccvs.ui.merge.UpdateWithForcedJoinAction;
import org.eclipse.team.internal.ui.sync.CatchupReleaseViewer;
import org.eclipse.team.internal.ui.sync.ITeamNode;
import org.eclipse.team.internal.ui.sync.MergeResource;
import org.eclipse.team.internal.ui.sync.SyncView;
import org.eclipse.team.internal.ui.sync.TeamFile;
import org.eclipse.team.ui.ISharedImages;
import org.eclipse.team.ui.TeamUIPlugin;
public class CVSCatchupReleaseViewer extends CatchupReleaseViewer {
// Actions
private UpdateSyncAction updateAction;
private ForceUpdateSyncAction forceUpdateAction;
private CommitSyncAction commitAction;
private ForceCommitSyncAction forceCommitAction;
private UpdateMergeAction updateMergeAction;
private UpdateWithForcedJoinAction updateWithJoinAction;
private OverrideUpdateMergeAction forceUpdateMergeAction;
private IgnoreAction ignoreAction;
private HistoryAction showInHistory;
private Action confirmMerge;
private AddSyncAction addAction;
private static class DiffOverlayIcon extends OverlayIcon {
private static final int HEIGHT = 16;
private static final int WIDTH = 22;
public DiffOverlayIcon(Image baseImage, ImageDescriptor[] overlays) {
super(baseImage, overlays, new Point(WIDTH, HEIGHT));
}
protected void drawOverlays(ImageDescriptor[] overlays) {
for (int i = 0; i < overlays.length; i++) {
ImageDescriptor overlay = overlays[i];
ImageData overlayData = overlay.getImageData();
drawImage(overlayData, 0, 0);
}
}
}
private static class HistoryAction extends Action implements ISelectionChangedListener {
IStructuredSelection selection;
public HistoryAction(String label) {
super(label);
}
public void run() {
if (selection.isEmpty()) {
return;
}
HistoryView view = HistoryView.openInActivePerspective();
if (view == null) {
return;
}
ITeamNode node = (ITeamNode)selection.getFirstElement();
IRemoteSyncElement remoteSyncElement = ((TeamFile)node).getMergeResource().getSyncElement();
ICVSRemoteFile remoteFile = (ICVSRemoteFile)remoteSyncElement.getRemote();
IResource local = remoteSyncElement.getLocal();
ICVSRemoteFile baseFile = (ICVSRemoteFile)remoteSyncElement.getBase();
// can only show history if remote exists or local has a base.
String currentRevision = null;
try {
currentRevision = baseFile!=null ? baseFile.getRevision(): null;
} catch(TeamException e) {
CVSUIPlugin.log(e.getStatus());
}
if(remoteFile!=null) {
view.showHistory(remoteFile, currentRevision);
} else if(baseFile!=null) {
view.showHistory(baseFile, currentRevision);
}
}
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (!(selection instanceof IStructuredSelection)) {
setEnabled(false);
return;
}
IStructuredSelection ss = (IStructuredSelection)selection;
if (ss.size() != 1) {
setEnabled(false);
return;
}
ITeamNode first = (ITeamNode)ss.getFirstElement();
if (first instanceof TeamFile) {
// can only show history on elements that have a remote file
this.selection = ss;
IRemoteSyncElement remoteSyncElement = ((TeamFile)first).getMergeResource().getSyncElement();
if(remoteSyncElement.getRemote() != null || remoteSyncElement.getBase() != null) {
setEnabled(true);
} else {
setEnabled(false);
}
} else {
this.selection = null;
setEnabled(false);
}
}
}
public CVSCatchupReleaseViewer(Composite parent, CVSSyncCompareInput model) {
super(parent, model);
initializeActions(model);
initializeLabelProvider();
}
private void initializeLabelProvider() {
final ImageDescriptor conflictDescriptor = CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_MERGEABLE_CONFLICT);
final ImageDescriptor hasRemoteDescriptor = TeamUIPlugin.getPlugin().getImageDescriptor(ISharedImages.IMG_CHECKEDIN_OVR);
final ImageDescriptor addedDescriptor = TeamUIPlugin.getPlugin().getImageDescriptor(ISharedImages.IMG_CHECKEDOUT_OVR);
final LabelProvider oldProvider = (LabelProvider)getLabelProvider();
setLabelProvider(new LabelProvider() {
private OverlayIconCache iconCache = new OverlayIconCache();
public void dispose() {
iconCache.disposeAll();
oldProvider.dispose();
}
public Image getImage(Object element) {
Image image = oldProvider.getImage(element);
if (element instanceof ITeamNode) {
ITeamNode node = (ITeamNode)element;
int kind = node.getKind();
IResource resource = node.getResource();
// use the default cvs image decorations
if(resource.exists()) {
CVSTeamProvider provider = (CVSTeamProvider)RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId());
List overlays = new ArrayList();
List stdOverlays = CVSDecorationRunnable.computeLabelOverlaysFor(node.getResource(), false, provider);
if(stdOverlays != null) {
overlays.addAll(stdOverlays);
}
if ((kind & IRemoteSyncElement.AUTOMERGE_CONFLICT) != 0) {
overlays.add(conflictDescriptor);
}
if(!overlays.isEmpty()) {
return iconCache.getImageFor(new DiffOverlayIcon(image,
(ImageDescriptor[]) overlays.toArray(
new ImageDescriptor[overlays.size()])));
} else {
return image;
}
}
}
return image;
}
public String getText(Object element) {
if (element instanceof ITeamNode) {
ITeamNode node = (ITeamNode)element;
IResource resource = node.getResource();
if (resource.exists()) {
// use the default text decoration preferences
CVSDecoration decoration = CVSDecorationRunnable.computeTextLabelFor(resource, false /*don't show dirty*/);
String format = decoration.getFormat();
Map bindings = decoration.getBindings();
// don't show the revision number, it will instead be shown in
// the label for the remote/base/local files editors
bindings.remove(CVSDecoratorConfiguration.FILE_REVISION);
bindings.put(CVSDecoratorConfiguration.RESOURCE_NAME, oldProvider.getText(element));
return CVSDecoratorConfiguration.bind(format, bindings);
}
}
return oldProvider.getText(element);
}
});
}
protected void fillContextMenu(IMenuManager manager) {
super.fillContextMenu(manager);
if (showInHistory != null) {
manager.add(showInHistory);
}
manager.add(new Separator());
switch (getSyncMode()) {
case SyncView.SYNC_INCOMING:
updateAction.update(SyncView.SYNC_INCOMING);
manager.add(updateAction);
forceUpdateAction.update(SyncView.SYNC_INCOMING);
manager.add(forceUpdateAction);
manager.add(new Separator());
manager.add(confirmMerge);
break;
case SyncView.SYNC_OUTGOING:
addAction.update(SyncView.SYNC_OUTGOING);
manager.add(addAction);
commitAction.update(SyncView.SYNC_OUTGOING);
manager.add(commitAction);
forceCommitAction.update(SyncView.SYNC_OUTGOING);
manager.add(forceCommitAction);
ignoreAction.update();
manager.add(ignoreAction);
manager.add(new Separator());
manager.add(confirmMerge);
break;
case SyncView.SYNC_BOTH:
addAction.update(SyncView.SYNC_BOTH);
manager.add(addAction);
commitAction.update(SyncView.SYNC_BOTH);
manager.add(commitAction);
updateAction.update(SyncView.SYNC_BOTH);
manager.add(updateAction);
manager.add(new Separator());
forceCommitAction.update(SyncView.SYNC_BOTH);
manager.add(forceCommitAction);
forceUpdateAction.update(SyncView.SYNC_BOTH);
manager.add(forceUpdateAction);
manager.add(new Separator());
manager.add(confirmMerge);
break;
case SyncView.SYNC_MERGE:
updateMergeAction.update(SyncView.SYNC_INCOMING);
forceUpdateMergeAction.update(SyncView.SYNC_INCOMING);
updateWithJoinAction.update(SyncView.SYNC_INCOMING);
manager.add(updateMergeAction);
manager.add(forceUpdateMergeAction);
manager.add(updateWithJoinAction);
break;
}
}
/**
* Creates the actions for this viewer.
*/
private void initializeActions(final CVSSyncCompareInput diffModel) {
Shell shell = getControl().getShell();
commitAction = new CommitSyncAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.commit"), shell); //$NON-NLS-1$
forceCommitAction = new ForceCommitSyncAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.forceCommit"), shell); //$NON-NLS-1$
updateAction = new UpdateSyncAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.update"), shell); //$NON-NLS-1$
forceUpdateAction = new ForceUpdateSyncAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.forceUpdate"), shell); //$NON-NLS-1$
updateMergeAction = new UpdateMergeAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.update"), shell); //$NON-NLS-1$
ignoreAction = new IgnoreAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.ignore"), shell); //$NON-NLS-1$
updateWithJoinAction = new UpdateWithForcedJoinAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.mergeUpdate"), shell); //$NON-NLS-1$
forceUpdateMergeAction = new OverrideUpdateMergeAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.forceUpdate"), shell); //$NON-NLS-1$
addAction = new AddSyncAction(diffModel, this, Policy.bind("CVSCatchupReleaseViewer.addAction"), shell); //$NON-NLS-1$
// Show in history view
showInHistory = new HistoryAction(Policy.bind("CVSCatchupReleaseViewer.showInHistory")); //$NON-NLS-1$
addSelectionChangedListener(showInHistory);
// confirm merge
confirmMerge = new Action(Policy.bind("CVSCatchupReleaseViewer.confirmMerge"), null) { //$NON-NLS-1$
public void run() {
ISelection s = getSelection();
if (!(s instanceof IStructuredSelection) || s.isEmpty()) {
return;
}
List needsMerge = new ArrayList();
for (Iterator it = ((IStructuredSelection)s).iterator(); it.hasNext();) {
final Object element = it.next();
if(element instanceof DiffElement) {
mergeRecursive((IDiffElement)element, needsMerge);
}
}
TeamFile[] files = (TeamFile[]) needsMerge.toArray(new TeamFile[needsMerge.size()]);
if(files.length != 0) {
try {
for (int i = 0; i < files.length; i++) {
TeamFile teamFile = (TeamFile)files[i];
CVSUIPlugin.getPlugin().getRepositoryManager().merged(new IRemoteSyncElement[] {teamFile.getMergeResource().getSyncElement()});
teamFile.merged();
}
} catch(TeamException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
}
}
refresh();
}
public boolean isEnabled() {
ISelection s = getSelection();
if (!(s instanceof IStructuredSelection) || s.isEmpty()) {
return false;
}
for (Iterator it = ((IStructuredSelection)s).iterator(); it.hasNext();) {
Object element = (Object) it.next();
if(element instanceof TeamFile) {
TeamFile file = (TeamFile)element;
if(file.hasBeenSaved()) {
int direction = file.getChangeDirection();
int type = file.getChangeType();
if(direction == IRemoteSyncElement.INCOMING ||
direction == IRemoteSyncElement.CONFLICTING) {
continue;
}
}
}
return false;
}
return true;
}
};
}
protected void mergeRecursive(IDiffElement element, List needsMerge) {
if(element instanceof DiffContainer) {
DiffContainer container = (DiffContainer)element;
IDiffElement[] children = container.getChildren();
for (int i = 0; i < children.length; i++) {
mergeRecursive(children[i], needsMerge);
}
} else if(element instanceof TeamFile) {
TeamFile file = (TeamFile)element;
needsMerge.add(file);
}
}
/**
* Provide CVS-specific labels for the editors.
*/
protected void updateLabels(MergeResource resource) {
CompareConfiguration config = getCompareConfiguration();
String name = resource.getName();
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.workspaceFile", name)); //$NON-NLS-1$
IRemoteSyncElement syncTree = resource.getSyncElement();
IRemoteResource remote = syncTree.getRemote();
if (remote != null) {
try {
final ICVSRemoteFile remoteFile = (ICVSRemoteFile)remote;
String revision = remoteFile.getRevision();
final String[] author = new String[] { "" }; //$NON-NLS-1$
try {
CVSUIPlugin.runWithProgress(getTree().getShell(), true /*cancelable*/,
new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
ILogEntry logEntry = remoteFile.getLogEntry(monitor);
author[0] = logEntry.getAuthor();
} catch (TeamException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) { // ignore cancellation
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof TeamException) {
throw (TeamException) t;
}
// should not get here
}
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.repositoryFileRevision", new Object[] {name, revision, author[0]})); //$NON-NLS-1$
} catch (TeamException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.repositoryFile", name)); //$NON-NLS-1$
}
} else {
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.noRepositoryFile")); //$NON-NLS-1$
}
IRemoteResource base = syncTree.getBase();
if (base != null) {
try {
String revision = ((ICVSRemoteFile)base).getRevision();
config.setAncestorLabel(Policy.bind("CVSCatchupReleaseViewer.commonFileRevision", new Object[] {name, revision} )); //$NON-NLS-1$
} catch (TeamException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
} else {
config.setAncestorLabel(Policy.bind("CVSCatchupReleaseViewer.noCommonFile")); //$NON-NLS-1$
}
IResource local = syncTree.getLocal();
if (local != null) {
if (!local.exists()) {
- config.setLeftLabel("No workspace file");
+ config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.No_workspace_file_1")); //$NON-NLS-1$
} else {
ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor((IFile)local);
ResourceSyncInfo info = null;
try {
info = cvsFile.getSyncInfo();
name = local.getName();
String revision = null;
if (info != null) {
revision = info.getRevision();
if (info.isAdded() || info.isDeleted()) {
revision = null;
}
}
if (revision != null) {
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFileRevision", name, revision)); //$NON-NLS-1$
} else {
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
} catch (CVSException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
}
}
}
}
| true | true | protected void updateLabels(MergeResource resource) {
CompareConfiguration config = getCompareConfiguration();
String name = resource.getName();
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.workspaceFile", name)); //$NON-NLS-1$
IRemoteSyncElement syncTree = resource.getSyncElement();
IRemoteResource remote = syncTree.getRemote();
if (remote != null) {
try {
final ICVSRemoteFile remoteFile = (ICVSRemoteFile)remote;
String revision = remoteFile.getRevision();
final String[] author = new String[] { "" }; //$NON-NLS-1$
try {
CVSUIPlugin.runWithProgress(getTree().getShell(), true /*cancelable*/,
new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
ILogEntry logEntry = remoteFile.getLogEntry(monitor);
author[0] = logEntry.getAuthor();
} catch (TeamException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) { // ignore cancellation
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof TeamException) {
throw (TeamException) t;
}
// should not get here
}
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.repositoryFileRevision", new Object[] {name, revision, author[0]})); //$NON-NLS-1$
} catch (TeamException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.repositoryFile", name)); //$NON-NLS-1$
}
} else {
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.noRepositoryFile")); //$NON-NLS-1$
}
IRemoteResource base = syncTree.getBase();
if (base != null) {
try {
String revision = ((ICVSRemoteFile)base).getRevision();
config.setAncestorLabel(Policy.bind("CVSCatchupReleaseViewer.commonFileRevision", new Object[] {name, revision} )); //$NON-NLS-1$
} catch (TeamException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
} else {
config.setAncestorLabel(Policy.bind("CVSCatchupReleaseViewer.noCommonFile")); //$NON-NLS-1$
}
IResource local = syncTree.getLocal();
if (local != null) {
if (!local.exists()) {
config.setLeftLabel("No workspace file");
} else {
ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor((IFile)local);
ResourceSyncInfo info = null;
try {
info = cvsFile.getSyncInfo();
name = local.getName();
String revision = null;
if (info != null) {
revision = info.getRevision();
if (info.isAdded() || info.isDeleted()) {
revision = null;
}
}
if (revision != null) {
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFileRevision", name, revision)); //$NON-NLS-1$
} else {
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
} catch (CVSException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
}
}
}
| protected void updateLabels(MergeResource resource) {
CompareConfiguration config = getCompareConfiguration();
String name = resource.getName();
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.workspaceFile", name)); //$NON-NLS-1$
IRemoteSyncElement syncTree = resource.getSyncElement();
IRemoteResource remote = syncTree.getRemote();
if (remote != null) {
try {
final ICVSRemoteFile remoteFile = (ICVSRemoteFile)remote;
String revision = remoteFile.getRevision();
final String[] author = new String[] { "" }; //$NON-NLS-1$
try {
CVSUIPlugin.runWithProgress(getTree().getShell(), true /*cancelable*/,
new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
ILogEntry logEntry = remoteFile.getLogEntry(monitor);
author[0] = logEntry.getAuthor();
} catch (TeamException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) { // ignore cancellation
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof TeamException) {
throw (TeamException) t;
}
// should not get here
}
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.repositoryFileRevision", new Object[] {name, revision, author[0]})); //$NON-NLS-1$
} catch (TeamException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.repositoryFile", name)); //$NON-NLS-1$
}
} else {
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.noRepositoryFile")); //$NON-NLS-1$
}
IRemoteResource base = syncTree.getBase();
if (base != null) {
try {
String revision = ((ICVSRemoteFile)base).getRevision();
config.setAncestorLabel(Policy.bind("CVSCatchupReleaseViewer.commonFileRevision", new Object[] {name, revision} )); //$NON-NLS-1$
} catch (TeamException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setRightLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
} else {
config.setAncestorLabel(Policy.bind("CVSCatchupReleaseViewer.noCommonFile")); //$NON-NLS-1$
}
IResource local = syncTree.getLocal();
if (local != null) {
if (!local.exists()) {
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.No_workspace_file_1")); //$NON-NLS-1$
} else {
ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor((IFile)local);
ResourceSyncInfo info = null;
try {
info = cvsFile.getSyncInfo();
name = local.getName();
String revision = null;
if (info != null) {
revision = info.getRevision();
if (info.isAdded() || info.isDeleted()) {
revision = null;
}
}
if (revision != null) {
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFileRevision", name, revision)); //$NON-NLS-1$
} else {
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
} catch (CVSException e) {
ErrorDialog.openError(getControl().getShell(), null, null, e.getStatus());
config.setLeftLabel(Policy.bind("CVSCatchupReleaseViewer.commonFile", name)); //$NON-NLS-1$
}
}
}
}
|
diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/QbobViewer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/QbobViewer.java
index 044bb646a..7751aa52d 100644
--- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/QbobViewer.java
+++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/QbobViewer.java
@@ -1,162 +1,162 @@
package com.badlogic.gdx.graphics.g3d.test;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.jogl.JoglApplication;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL11;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dLoader;
import com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dtLoader;
import com.badlogic.gdx.graphics.g3d.materials.Material;
import com.badlogic.gdx.graphics.g3d.materials.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.model.keyframe.KeyframedAnimation;
import com.badlogic.gdx.graphics.g3d.model.keyframe.KeyframedModel;
import com.badlogic.gdx.graphics.g3d.model.still.StillModel;
import com.badlogic.gdx.graphics.g3d.test.utils.PerspectiveCamController;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Plane;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.Ray;
public class QbobViewer implements ApplicationListener {
PerspectiveCamera cam;
KeyframedModel animModel;
KeyframedAnimation anim;
float animTime = 0;
StillModel model[] = new StillModel[4];
Texture diffuse;
Texture[] lightMaps = new Texture[4];
FPSLogger fps = new FPSLogger();
PerspectiveCamController controller;
SpriteBatch batch;
BitmapFont font;
@Override public void create () {
animModel = G3dtLoader.loadKeyframedModel(Gdx.files.internal("data/boy.g3dt"), true);
anim = animModel.getAnimations()[0];
Material material = new Material("default", new TextureAttribute(new Texture(Gdx.files.internal("data/boy.png")), 0, "tex0"));
animModel.setMaterial(material);
model[0] = G3dLoader.loadStillModel(Gdx.files.internal("data/qbob/test_section_01.dae.g3d"));
lightMaps[0] = new Texture(Gdx.files.internal("data/qbob/world_blobbie_lm_01.jpg"), Format.RGB565, true);
model[1] = G3dLoader.loadStillModel(Gdx.files.internal("data/qbob/test_section_02.dae.g3d"));
lightMaps[1] = new Texture(Gdx.files.internal("data/qbob/world_blobbie_lm_02.jpg"), Format.RGB565, true);
model[2] = G3dLoader.loadStillModel(Gdx.files.internal("data/qbob/test_section_03.dae.g3d"));
lightMaps[2] = new Texture(Gdx.files.internal("data/qbob/world_blobbie_lm_03.jpg"), Format.RGB565, true);
model[3] = G3dLoader.loadStillModel(Gdx.files.internal("data/qbob/test_section_04.dae.g3d"));
lightMaps[3] = new Texture(Gdx.files.internal("data/qbob/world_blobbie_lm_04.jpg"), Format.RGB565, true);
diffuse = new Texture(Gdx.files.internal("data/qbob/World_blobbie_blocks.png"), Format.RGB565, true);
cam = new PerspectiveCamera(60, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(30, 10, 85f);
cam.direction.set(0,0,-1);
cam.up.set(0,1,0);
cam.near = 10f;
cam.far = 1000;
controller = new PerspectiveCamController(cam);
Gdx.input.setInputProcessor(controller);
batch = new SpriteBatch();
font = new BitmapFont();
}
@Override public void resume () {
}
@Override public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
cam.apply(Gdx.gl10);
Gdx.gl.glEnable(GL10.GL_CULL_FACE);
Gdx.gl.glEnable(GL10.GL_DEPTH_TEST);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0);
Gdx.gl.glEnable(GL10.GL_TEXTURE_2D);
diffuse.bind();
- diffuse.setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
+ diffuse.setFilter(TextureFilter.MipMap, TextureFilter.Linear);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE1);
Gdx.gl.glEnable(GL10.GL_TEXTURE_2D);
lightMaps[0].bind();
lightMaps[0].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[0].render();
lightMaps[1].bind();
lightMaps[1].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[1].render();
lightMaps[2].bind();
lightMaps[2].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[2].render();
lightMaps[3].bind();
lightMaps[3].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[3].render();
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE1);
Gdx.gl.glDisable(GL10.GL_TEXTURE_2D);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0);
Gdx.gl.glDisable(GL10.GL_CULL_FACE);
Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);
Gdx.gl.glDisable(GL10.GL_BLEND);
animTime += Gdx.graphics.getDeltaTime();
if(animTime > anim.totalDuration - anim.frameDuration) animTime = 0;
animModel.setAnimation(anim.name, animTime, true);
Gdx.gl10.glPushMatrix();
Gdx.gl10.glTranslatef(cam.position.x, cam.position.y, 6);
animModel.render();
Gdx.gl10.glPopMatrix();
Gdx.gl.glDisable(GL10.GL_DEPTH_TEST);
batch.begin();
font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
fps.log();
}
private void setCombiners() {
Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_COMBINE);
Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB, GL11.GL_ADD_SIGNED);
Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_SRC0_RGB, GL11.GL_PREVIOUS);
Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB, GL11.GL_TEXTURE);
}
@Override public void resize (int width, int height) {
}
@Override public void pause () {
}
@Override public void dispose () {
}
public static void main(String[] argv) {
new JoglApplication(new QbobViewer(), "Qbob Viewer", 800, 480, false);
}
}
| true | true | @Override public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
cam.apply(Gdx.gl10);
Gdx.gl.glEnable(GL10.GL_CULL_FACE);
Gdx.gl.glEnable(GL10.GL_DEPTH_TEST);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0);
Gdx.gl.glEnable(GL10.GL_TEXTURE_2D);
diffuse.bind();
diffuse.setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE1);
Gdx.gl.glEnable(GL10.GL_TEXTURE_2D);
lightMaps[0].bind();
lightMaps[0].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[0].render();
lightMaps[1].bind();
lightMaps[1].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[1].render();
lightMaps[2].bind();
lightMaps[2].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[2].render();
lightMaps[3].bind();
lightMaps[3].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[3].render();
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE1);
Gdx.gl.glDisable(GL10.GL_TEXTURE_2D);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0);
Gdx.gl.glDisable(GL10.GL_CULL_FACE);
Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);
Gdx.gl.glDisable(GL10.GL_BLEND);
animTime += Gdx.graphics.getDeltaTime();
if(animTime > anim.totalDuration - anim.frameDuration) animTime = 0;
animModel.setAnimation(anim.name, animTime, true);
Gdx.gl10.glPushMatrix();
Gdx.gl10.glTranslatef(cam.position.x, cam.position.y, 6);
animModel.render();
Gdx.gl10.glPopMatrix();
Gdx.gl.glDisable(GL10.GL_DEPTH_TEST);
batch.begin();
font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
fps.log();
}
| @Override public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
cam.update();
cam.apply(Gdx.gl10);
Gdx.gl.glEnable(GL10.GL_CULL_FACE);
Gdx.gl.glEnable(GL10.GL_DEPTH_TEST);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0);
Gdx.gl.glEnable(GL10.GL_TEXTURE_2D);
diffuse.bind();
diffuse.setFilter(TextureFilter.MipMap, TextureFilter.Linear);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE1);
Gdx.gl.glEnable(GL10.GL_TEXTURE_2D);
lightMaps[0].bind();
lightMaps[0].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[0].render();
lightMaps[1].bind();
lightMaps[1].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[1].render();
lightMaps[2].bind();
lightMaps[2].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[2].render();
lightMaps[3].bind();
lightMaps[3].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear);
setCombiners();
model[3].render();
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE1);
Gdx.gl.glDisable(GL10.GL_TEXTURE_2D);
Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0);
Gdx.gl.glDisable(GL10.GL_CULL_FACE);
Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);
Gdx.gl.glDisable(GL10.GL_BLEND);
animTime += Gdx.graphics.getDeltaTime();
if(animTime > anim.totalDuration - anim.frameDuration) animTime = 0;
animModel.setAnimation(anim.name, animTime, true);
Gdx.gl10.glPushMatrix();
Gdx.gl10.glTranslatef(cam.position.x, cam.position.y, 6);
animModel.render();
Gdx.gl10.glPopMatrix();
Gdx.gl.glDisable(GL10.GL_DEPTH_TEST);
batch.begin();
font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
fps.log();
}
|
diff --git a/src/test/java/it/antreem/birretta/service/test/generic/Dummytest.java b/src/test/java/it/antreem/birretta/service/test/generic/Dummytest.java
index 2330766..8e1942f 100644
--- a/src/test/java/it/antreem/birretta/service/test/generic/Dummytest.java
+++ b/src/test/java/it/antreem/birretta/service/test/generic/Dummytest.java
@@ -1,54 +1,54 @@
package it.antreem.birretta.service.test.generic;
import it.antreem.birretta.service.BirrettaService;
import it.antreem.birretta.service.dao.DaoFactory;
import it.antreem.birretta.service.dto.ErrorDTO;
import it.antreem.birretta.service.dto.GenericResultDTO;
import it.antreem.birretta.service.model.Address;
import it.antreem.birretta.service.model.LocType;
import it.antreem.birretta.service.model.Location;
import it.antreem.birretta.service.util.Utils;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.junit.Test;
/**
*
* @author gmorlini
*/
public class Dummytest
{
private final static Logger log = Logger.getLogger(Dummytest.class);
@Test
public void dummytest()
{
LocType lt=new LocType();
lt.setCod("MorlinsCode");
lt.setDesc("Morlins Pub and Grill for all");
if(DaoFactory.getInstance().getLocTypeDao().findLocTypeByCod(lt.getCod())==null)
DaoFactory.getInstance().getLocTypeDao().saveLocType(lt);
BirrettaService service= new BirrettaService();
Location l= new Location();
Address a= new Address();
a.setCap("54345");
a.setNum(new Integer("46"));
a.setState("IT");
a.setStreet("Via della vittoria");
- l.setAddress(a);
+ // l.setAddress(a);
l.setUrl("mio località");
- l.setIdLocType(lt.getCod());
+ //l.setIdLocType(lt.getCod());
ArrayList<Double> pos=new ArrayList<Double>();
pos.add(new Double("10"));
pos.add(new Double("10"));
l.setPos(pos);
l.setName("MorlinsRumGrill");
Response resp= service.insertLoc(l);
log.debug("inserito: "+ l + "response. " + (resp.getEntity()));
// log.debug("inserito: "+ l + "response. " + ((ErrorDTO)resp.getEntity()).getError().getTitle()+" : " +((ErrorDTO)resp.getEntity()).getError().getDesc());
log.debug("inserito: "+ l + "response. " + ((GenericResultDTO)resp.getEntity()).getMessage());
}
}
| false | true | public void dummytest()
{
LocType lt=new LocType();
lt.setCod("MorlinsCode");
lt.setDesc("Morlins Pub and Grill for all");
if(DaoFactory.getInstance().getLocTypeDao().findLocTypeByCod(lt.getCod())==null)
DaoFactory.getInstance().getLocTypeDao().saveLocType(lt);
BirrettaService service= new BirrettaService();
Location l= new Location();
Address a= new Address();
a.setCap("54345");
a.setNum(new Integer("46"));
a.setState("IT");
a.setStreet("Via della vittoria");
l.setAddress(a);
l.setUrl("mio località");
l.setIdLocType(lt.getCod());
ArrayList<Double> pos=new ArrayList<Double>();
pos.add(new Double("10"));
pos.add(new Double("10"));
l.setPos(pos);
l.setName("MorlinsRumGrill");
Response resp= service.insertLoc(l);
log.debug("inserito: "+ l + "response. " + (resp.getEntity()));
// log.debug("inserito: "+ l + "response. " + ((ErrorDTO)resp.getEntity()).getError().getTitle()+" : " +((ErrorDTO)resp.getEntity()).getError().getDesc());
log.debug("inserito: "+ l + "response. " + ((GenericResultDTO)resp.getEntity()).getMessage());
}
| public void dummytest()
{
LocType lt=new LocType();
lt.setCod("MorlinsCode");
lt.setDesc("Morlins Pub and Grill for all");
if(DaoFactory.getInstance().getLocTypeDao().findLocTypeByCod(lt.getCod())==null)
DaoFactory.getInstance().getLocTypeDao().saveLocType(lt);
BirrettaService service= new BirrettaService();
Location l= new Location();
Address a= new Address();
a.setCap("54345");
a.setNum(new Integer("46"));
a.setState("IT");
a.setStreet("Via della vittoria");
// l.setAddress(a);
l.setUrl("mio località");
//l.setIdLocType(lt.getCod());
ArrayList<Double> pos=new ArrayList<Double>();
pos.add(new Double("10"));
pos.add(new Double("10"));
l.setPos(pos);
l.setName("MorlinsRumGrill");
Response resp= service.insertLoc(l);
log.debug("inserito: "+ l + "response. " + (resp.getEntity()));
// log.debug("inserito: "+ l + "response. " + ((ErrorDTO)resp.getEntity()).getError().getTitle()+" : " +((ErrorDTO)resp.getEntity()).getError().getDesc());
log.debug("inserito: "+ l + "response. " + ((GenericResultDTO)resp.getEntity()).getMessage());
}
|
diff --git a/Android/PrintPlugin.java b/Android/PrintPlugin.java
index 650f37a..d4b1c7e 100644
--- a/Android/PrintPlugin.java
+++ b/Android/PrintPlugin.java
@@ -1,274 +1,275 @@
package com.phonegap.plugins;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UnknownFormatConversionException;
import org.json.JSONArray;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.drawable.PictureDrawable;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.phonegap.api.PhonegapActivity;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PrintPlugn extends Plugin {
String printAppIds[] = {"kr.co.iconlab.BasicPrintingProfile",
"com.blueslib.android.app",
"com.brother.mfc.brprint",
"com.brother.ptouch.sdk",
"jp.co.canon.bsd.android.aepp.activity",
"com.pauloslf.cloudprint",
"com.dlnapr1.printer",
"com.dell.mobileprint",
"com.printjinni.app.print",
"epson.print",
"jp.co.fujixerox.prt.PrintUtil.PCL",
"jp.co.fujixerox.prt.PrintUtil.Karin",
"com.hp.android.print",
"com.blackspruce.lpd",
"com.threebirds.notesprint",
"com.xerox.mobileprint",
"com.zebra.kdu",
"net.jsecurity.printbot",
"com.dynamixsoftware.printhand",
"com.dynamixsoftware.printhand.premium",
"com.sec.print.mobileprint",
"com.rcreations.send2printer",
"com.ivc.starprint",
"com.threebirds.easyviewer",
"com.woosim.android.print",
"com.woosim.bt.app",
"com.zebra.android.zebrautilities",
};
/*
String printAppIds[] = ["Bluetooth Smart Printing" "kr.co.iconlab.BasicPrintingProfile",
"Bluetooth SPP Printer API" "com.blueslib.android.app",
"Brother iPrint&Scan" "com.brother.mfc.brprint",
"Brother Print Library" "com.brother.ptouch.sdk",
"Canon Easy-PhotoPrint" "jp.co.canon.bsd.android.aepp.activity",
"Cloud Print" "com.pauloslf.cloudprint",
"CMC DLNA Print Client" "com.dlnapr1.printer",
"Dell Mobile Print" "com.dell.mobileprint",
"PrintJinni" "com.printjinni.app.print",
"Epson iPrint" "epson.print",
"Fuji Xerox Print Utility" "jp.co.fujixerox.prt.PrintUtil.PCL",
"Fuji Xeros Print&Scan (S)" "jp.co.fujixerox.prt.PrintUtil.Karin",
"HP ePrint" "com.hp.android.print",
"Let's Print Droid" "com.blackspruce.lpd",
"NotesPrint print your notes" "com.threebirds.notesprint",
"Print Portal (Xerox)" "com.xerox.mobileprint",
"Print Station (Zebra)" "com.zebra.kdu",
"PrintBot" "net.jsecurity.printbot",
"PrintHand Mobile Print" "com.dynamixsoftware.printhand",
"PrintHand Mobile Print Premium" "com.dynamixsoftware.printhand.premium",
"Samsung Mobile Print" "com.sec.print.mobileprint",
"Send 2 Printer" "com.rcreations.send2printer",
"StarPrint, Just for Print!" "com.ivc.starprint",
"WiFi Print - EasyReader" "com.threebirds.easyviewer",
"Woosim BT printer" "com.woosim.android.print",
"WoosimPrinter" "com.woosim.bt.app",
"Zebra Utilities" "com.zebra.android.zebrautilities",
];
*/
public static File saveBitmapToTempFile( Bitmap b, Bitmap.CompressFormat format )
throws IOException, UnknownFormatConversionException
{
File tempFile = null;
// save to temporary file
File dir = new File( Environment.getExternalStorageDirectory(), "temp" );
if( dir.exists() || dir.mkdirs() )
{
FileOutputStream fos = null;
try
{
String strExt = null;
switch( format )
{
case PNG:
strExt = ".pngx";
break;
case JPEG:
strExt = ".jpgx";
break;
default:
throw new UnknownFormatConversionException( "unknown format: " + format );
}
File f = File.createTempFile( "bitmap", strExt, dir );
fos = new FileOutputStream( f );
b.compress( format, 100, fos );
tempFile = f;
}
finally
{
try
{
fos.close();
}
catch( Exception e ) {}
}
}
return tempFile;
}
@Override
public PluginResult execute(String action, final JSONArray args, final String callbackId) {
if (action.equals("scan")) {
JSONArray obj = new JSONArray();
PackageManager pm = this.ctx.getPackageManager();
for(int i = 0; i < printAppIds.length; i++)
{
try {
PackageInfo pi = pm.getPackageInfo( printAppIds[i], 0 );
if( pi != null )
{
obj.put(printAppIds[i]);
}
} catch (PackageManager.NameNotFoundException e) {}
}
return new PluginResult(PluginResult.Status.OK, obj);
}
if (action.equals("print")) {
final PhonegapActivity ctx = this.ctx;
final PrintAppScanner self = this;
Runnable runnable = new Runnable() {
public void run() {
String printIntent = "android.intent.action.SEND";
String dataType = "image/png";
String htmlData = args.optString(0, "<html></html>");
String optionalAppId = args.optString(1);
//Check for special cases that can receive HTML
if (optionalAppId.equals("com.rcreations.send2printer") ||
optionalAppId.equals("com.dynamixsoftware.printershare")) {
dataType = "text/html";
}
/*//Check for special cases that have special Intent's
if (optionalAppId.equals("com.rcreations.send2printer")) {
printIntent = "com.rcreations.send2printer.print";
} else if (optionalAppId.equals("com.dynamixsoftware.printershare")) {
printIntent = "android.intent.action.VIEW";
} else if (optionalAppId.equals("com.hp.android.print")) {
printIntent = "org.androidprinting.intent.action.PRINT";
}*/
final Intent i = new Intent( printIntent );
if (!optionalAppId.isEmpty()) {
i.setPackage(optionalAppId);
}
i.setType( dataType );
if (dataType.equals("text/html")) {
i.putExtra( Intent.EXTRA_TEXT, htmlData );
try {
ctx.startActivity( i );
self.success(new PluginResult(PluginResult.Status.OK, ""), callbackId);
} catch (Exception e) {
e.printStackTrace();
self.error(new PluginResult(PluginResult.Status.ERROR, "Couldn't start activity"), callbackId);
}
} else {
//Create WebView
WebView wv = new WebView(ctx);
wv.setVisibility(View.INVISIBLE);
wv.getSettings().setJavaScriptEnabled(false);
+ wv.getSettings().setDatabaseEnabled(true);
wv.setPictureListener(new WebView.PictureListener() {
@Deprecated
public void onNewPicture(WebView view, Picture picture) {
if(picture != null)
{
try
{
Bitmap bitmap = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
picture.draw(canvas);
File tempFile = saveBitmapToTempFile(bitmap, Bitmap.CompressFormat.PNG);
Uri uri = Uri.fromFile( tempFile );
i.putExtra(Intent.EXTRA_STREAM, uri);
ctx.startActivity( i );
self.success(new PluginResult(PluginResult.Status.OK, ""), callbackId);
}
catch(Exception e)
{
e.printStackTrace();
self.error(new PluginResult(PluginResult.Status.ERROR, "Can't save picture"), callbackId);
}
} else {
self.error(new PluginResult(PluginResult.Status.ERROR, "No picture"), callbackId);
}
ViewGroup vg = (ViewGroup)(view.getParent());
vg.removeView(view);
}
});
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
Picture picture = webview.capturePicture();
}
});
//Set base URI to the assets/www folder
String baseURL = self.webView.getUrl();
baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);
//Set content of WebView to htmlData
ctx.addContentView(wv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
wv.loadDataWithBaseURL(baseURL, htmlData, "text/html", "UTF-8", null);
}
}
};
this.ctx.runOnUiThread(runnable);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
public boolean isSynch(String action)
{
if (action.equals("print")) {
return true;
}
return false;
}
}
| true | true | public PluginResult execute(String action, final JSONArray args, final String callbackId) {
if (action.equals("scan")) {
JSONArray obj = new JSONArray();
PackageManager pm = this.ctx.getPackageManager();
for(int i = 0; i < printAppIds.length; i++)
{
try {
PackageInfo pi = pm.getPackageInfo( printAppIds[i], 0 );
if( pi != null )
{
obj.put(printAppIds[i]);
}
} catch (PackageManager.NameNotFoundException e) {}
}
return new PluginResult(PluginResult.Status.OK, obj);
}
if (action.equals("print")) {
final PhonegapActivity ctx = this.ctx;
final PrintAppScanner self = this;
Runnable runnable = new Runnable() {
public void run() {
String printIntent = "android.intent.action.SEND";
String dataType = "image/png";
String htmlData = args.optString(0, "<html></html>");
String optionalAppId = args.optString(1);
//Check for special cases that can receive HTML
if (optionalAppId.equals("com.rcreations.send2printer") ||
optionalAppId.equals("com.dynamixsoftware.printershare")) {
dataType = "text/html";
}
/*//Check for special cases that have special Intent's
if (optionalAppId.equals("com.rcreations.send2printer")) {
printIntent = "com.rcreations.send2printer.print";
} else if (optionalAppId.equals("com.dynamixsoftware.printershare")) {
printIntent = "android.intent.action.VIEW";
} else if (optionalAppId.equals("com.hp.android.print")) {
printIntent = "org.androidprinting.intent.action.PRINT";
}*/
final Intent i = new Intent( printIntent );
if (!optionalAppId.isEmpty()) {
i.setPackage(optionalAppId);
}
i.setType( dataType );
if (dataType.equals("text/html")) {
i.putExtra( Intent.EXTRA_TEXT, htmlData );
try {
ctx.startActivity( i );
self.success(new PluginResult(PluginResult.Status.OK, ""), callbackId);
} catch (Exception e) {
e.printStackTrace();
self.error(new PluginResult(PluginResult.Status.ERROR, "Couldn't start activity"), callbackId);
}
} else {
//Create WebView
WebView wv = new WebView(ctx);
wv.setVisibility(View.INVISIBLE);
wv.getSettings().setJavaScriptEnabled(false);
wv.setPictureListener(new WebView.PictureListener() {
@Deprecated
public void onNewPicture(WebView view, Picture picture) {
if(picture != null)
{
try
{
Bitmap bitmap = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
picture.draw(canvas);
File tempFile = saveBitmapToTempFile(bitmap, Bitmap.CompressFormat.PNG);
Uri uri = Uri.fromFile( tempFile );
i.putExtra(Intent.EXTRA_STREAM, uri);
ctx.startActivity( i );
self.success(new PluginResult(PluginResult.Status.OK, ""), callbackId);
}
catch(Exception e)
{
e.printStackTrace();
self.error(new PluginResult(PluginResult.Status.ERROR, "Can't save picture"), callbackId);
}
} else {
self.error(new PluginResult(PluginResult.Status.ERROR, "No picture"), callbackId);
}
ViewGroup vg = (ViewGroup)(view.getParent());
vg.removeView(view);
}
});
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
Picture picture = webview.capturePicture();
}
});
//Set base URI to the assets/www folder
String baseURL = self.webView.getUrl();
baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);
//Set content of WebView to htmlData
ctx.addContentView(wv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
wv.loadDataWithBaseURL(baseURL, htmlData, "text/html", "UTF-8", null);
}
}
};
this.ctx.runOnUiThread(runnable);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
| public PluginResult execute(String action, final JSONArray args, final String callbackId) {
if (action.equals("scan")) {
JSONArray obj = new JSONArray();
PackageManager pm = this.ctx.getPackageManager();
for(int i = 0; i < printAppIds.length; i++)
{
try {
PackageInfo pi = pm.getPackageInfo( printAppIds[i], 0 );
if( pi != null )
{
obj.put(printAppIds[i]);
}
} catch (PackageManager.NameNotFoundException e) {}
}
return new PluginResult(PluginResult.Status.OK, obj);
}
if (action.equals("print")) {
final PhonegapActivity ctx = this.ctx;
final PrintAppScanner self = this;
Runnable runnable = new Runnable() {
public void run() {
String printIntent = "android.intent.action.SEND";
String dataType = "image/png";
String htmlData = args.optString(0, "<html></html>");
String optionalAppId = args.optString(1);
//Check for special cases that can receive HTML
if (optionalAppId.equals("com.rcreations.send2printer") ||
optionalAppId.equals("com.dynamixsoftware.printershare")) {
dataType = "text/html";
}
/*//Check for special cases that have special Intent's
if (optionalAppId.equals("com.rcreations.send2printer")) {
printIntent = "com.rcreations.send2printer.print";
} else if (optionalAppId.equals("com.dynamixsoftware.printershare")) {
printIntent = "android.intent.action.VIEW";
} else if (optionalAppId.equals("com.hp.android.print")) {
printIntent = "org.androidprinting.intent.action.PRINT";
}*/
final Intent i = new Intent( printIntent );
if (!optionalAppId.isEmpty()) {
i.setPackage(optionalAppId);
}
i.setType( dataType );
if (dataType.equals("text/html")) {
i.putExtra( Intent.EXTRA_TEXT, htmlData );
try {
ctx.startActivity( i );
self.success(new PluginResult(PluginResult.Status.OK, ""), callbackId);
} catch (Exception e) {
e.printStackTrace();
self.error(new PluginResult(PluginResult.Status.ERROR, "Couldn't start activity"), callbackId);
}
} else {
//Create WebView
WebView wv = new WebView(ctx);
wv.setVisibility(View.INVISIBLE);
wv.getSettings().setJavaScriptEnabled(false);
wv.getSettings().setDatabaseEnabled(true);
wv.setPictureListener(new WebView.PictureListener() {
@Deprecated
public void onNewPicture(WebView view, Picture picture) {
if(picture != null)
{
try
{
Bitmap bitmap = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
picture.draw(canvas);
File tempFile = saveBitmapToTempFile(bitmap, Bitmap.CompressFormat.PNG);
Uri uri = Uri.fromFile( tempFile );
i.putExtra(Intent.EXTRA_STREAM, uri);
ctx.startActivity( i );
self.success(new PluginResult(PluginResult.Status.OK, ""), callbackId);
}
catch(Exception e)
{
e.printStackTrace();
self.error(new PluginResult(PluginResult.Status.ERROR, "Can't save picture"), callbackId);
}
} else {
self.error(new PluginResult(PluginResult.Status.ERROR, "No picture"), callbackId);
}
ViewGroup vg = (ViewGroup)(view.getParent());
vg.removeView(view);
}
});
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
Picture picture = webview.capturePicture();
}
});
//Set base URI to the assets/www folder
String baseURL = self.webView.getUrl();
baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);
//Set content of WebView to htmlData
ctx.addContentView(wv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
wv.loadDataWithBaseURL(baseURL, htmlData, "text/html", "UTF-8", null);
}
}
};
this.ctx.runOnUiThread(runnable);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
|
diff --git a/hds/src/main/uk/ac/starlink/hds/ArrayStructure.java b/hds/src/main/uk/ac/starlink/hds/ArrayStructure.java
index d1249b0ae..c6260eff3 100644
--- a/hds/src/main/uk/ac/starlink/hds/ArrayStructure.java
+++ b/hds/src/main/uk/ac/starlink/hds/ArrayStructure.java
@@ -1,246 +1,247 @@
package uk.ac.starlink.hds;
import uk.ac.starlink.array.NDShape;
import uk.ac.starlink.array.Order;
import uk.ac.starlink.array.OrderedNDShape;
/**
* Represents an array object within an HDS file, as understood by the
* Starlink ARY library. This is more than an
* HDS primitive array since it has an explicit (simple array) or
* implicit (primitive array) origin as well as a data array.
*
* <h3>Array file structure</h3>
* The structures read and written by the Starlink ARY library are not
* as far as I know documented anywhere, but are defined implicitly by
* the ARY implementation itself.
* This class currently makes assumptions about the form of ARY structures
* based on reverse engineering of HDS/NDF files found in the field.
* <ul>
* <li>An ARY structure may be PRIMITIVE or SIMPLE.
* <li>A PRIMITIVE ARY structure is any HDS primitive array
* <li>A SIMPLE ARY structure is a scalar HDS structure which conforms to the
* following conditions:
* <ul>
* <li>The structure has a type of "ARRAY"
* <li>The structure contains a primitive array called "DATA" containing
* the primitive data of the array object
* <li>The structure contains a 1-d N-element array of type _INTEGER
* for N-dimensional primitive array giving the origin
* <li>The structure may contain a _LOGICAL scalar called BAD_PIXEL
* indicating whether the data array may contain bad pixels or not
* </ul>
* </ul>
* This class should be modified if the above assumptions turn out to
* be incomplete or erroneous.
*
* @author Mark Taylor (Starlink)
* @see <a href="http://www.starlink.ac.uk/cgi-bin/htxserver/sun11.htx/">SUN/11</a>
* @see <a href="http://www.starlink.ac.uk/cgi-bin/htxserver/sgp38.htx/">SGP/38</a>
*/
public class ArrayStructure {
private final HDSObject hobj;
private final HDSObject dataObj;
private final OrderedNDShape oshape;
private final HDSType htype;
private final String storage;
private final static long[] SCALAR_DIMS = new long[ 0 ];
/**
* Creates an ArrayStructure from an existing HDS object.
*
* @param hobj the HDSObject at which the array object is to be found.
* @throws HDSException if an error occurred in traversing the HDS
* tree or <tt>hobj</tt> does not represent an array
*/
public ArrayStructure( HDSObject hobj ) throws HDSException {
this.hobj = hobj;
/* See if we appear to have a SIMPLE array. */
HDSObject dat;
if ( hobj.datStruc() &&
hobj.datShape().length == 0 &&
hobj.datType().equals( "ARRAY" ) &&
hobj.datThere( "DATA" ) &&
( ( dat = hobj.datFind( "DATA" ) ) != null ) &&
( ! dat.datStruc() ) &&
dat.datShape().length > 0 ) {
storage = "SIMPLE";
dataObj = dat;
long[] dims = dataObj.datShape();
long[] origin;
if ( hobj.datThere( "ORIGIN" ) ) {
HDSObject orgObj = hobj.datFind( "ORIGIN" );
long[] orgShape = orgObj.datShape();
if ( orgShape.length != 1 ||
orgShape[ 0 ] != dims.length ||
! orgObj.datType().equals( "_INTEGER" ) ) {
throw new HDSException(
"Format of ARY object is unexpected" );
}
origin = NDShape.intsToLongs( orgObj.datGetvi() );
}
else {
origin = new long[ dims.length ];
for ( int i = 0; i < dims.length; i++ ) {
origin[ i ] = 1L;
}
}
oshape = new OrderedNDShape( new NDShape( origin, dims ),
Order.COLUMN_MAJOR );
}
/* See if we appear to have a PRIMITIVE array. */
else if ( ! hobj.datStruc() &&
hobj.datShape().length > 0 ) {
storage = "PRIMITIVE";
dataObj = hobj.datClone();
long[] dims = dataObj.datShape();
int ndim = dims.length;
long[] origin = new long[ ndim ];
for ( int i = 0; i < ndim; i++ ) {
origin[ i ] = 1L;
}
oshape = new OrderedNDShape( new NDShape( origin, dims ),
Order.COLUMN_MAJOR );
}
else {
- throw new HDSException( "No array structure found in HDS" );
+ throw new HDSException( "No array structure found in HDS object "
+ + hobj.datRef() );
}
htype = HDSType.fromName( dataObj.datType() );
}
/**
* Creates the components of a new SIMPLE array object in a suitable
* structure. Any existing children of the structure will be removed
* and new DATA and ORIGIN children will be added describing the
* array object.
*
* @param struct an HDS structure scalar or array element of type ARRAY.
* @param shape the shape of the new array
* @param htype the HDS primitive type of the new array
* @throws HDSException if an error occurs manipulating the HDS tree
*/
public ArrayStructure( HDSObject struct, NDShape shape, HDSType htype )
throws HDSException {
/* Check we have been given a suitable location. */
if ( ! struct.datStruc() ) {
throw new HDSException( "HDS object is not a structure" );
}
if ( ! struct.datType().equals( "ARRAY" ) ) {
throw new HDSException( "HDS structure type is '"
+ struct.datType() + "' not 'ARRAY'" );
}
/* Clear out anything already there. */
for ( int i = struct.datNcomp(); i > 0; i-- ) {
HDSObject sub = struct.datIndex( i );
String subname = sub.datName();
sub.datAnnul();
struct.datErase( subname );
}
/* Create the origin and data components of a SIMPLE array. */
populateArrayStructure( struct, shape, htype );
/* Store the fields of this object. */
this.hobj = struct;
this.dataObj = struct.datFind( "DATA" );
this.oshape = new OrderedNDShape( shape, Order.COLUMN_MAJOR );
this.htype = htype;
this.storage = "SIMPLE";
}
/**
* Creates a new SIMPLE array object below the given parent HDS object.
*
* @param parent the object below which the new array structure
* will be created
* @param name the name of the new array structure
* @param htype the HDS primitive type of the new array
* @param shape the shape of the new array
* @throws HDSException if an error occurs manipulating the HDS tree
*/
public ArrayStructure( HDSObject parent, String name, HDSType htype,
NDShape shape ) throws HDSException {
parent.datNew( name, "ARRAY", SCALAR_DIMS );
HDSObject struct = parent.datFind( name );
populateArrayStructure( struct, shape, htype );
this.hobj = struct;
this.dataObj = struct.datFind( "DATA" );
this.oshape = new OrderedNDShape( shape, Order.COLUMN_MAJOR );
this.htype = htype;
this.storage = "SIMPLE";
}
/**
* Creates and populates an ORIGIN structure and creates a DATA
* structure within a given empty structure object.
*/
private static void populateArrayStructure( HDSObject struct, NDShape shape,
HDSType htype )
throws HDSException {
long[] dims = shape.getDims();
struct.datNew( "ORIGIN", "_INTEGER", new long[] { dims.length } );
struct.datFind( "ORIGIN" )
.datPutvi( NDShape.longsToInts( shape.getOrigin() ) );
struct.datNew( "DATA", htype.getName(), dims );
}
/**
* Gets the HDS object representing the data array itself.
* This will be a primitive array with dimensions given by
* <tt>getShape().getDims()</tt>.
*
* @return the primitive array containing the actual data
*/
public HDSObject getData() {
return dataObj;
}
/**
* Gets the shape of the array. This includes the origin and dimensions
* information. The pixel ordering scheme is always
* {@link uk.ac.starlink.array.Order#COLUMN_MAJOR}.
*
* @return the shape of the array
*/
public OrderedNDShape getShape() {
return oshape;
}
/**
* Gets the storage format; either "SIMPLE" or "PRIMITIVE".
*
* @return the storage format
*/
public String getStorage() {
return storage;
}
/**
* Returns the HDS object at which this array resides. This will be the
* ARRAY structure containing it for a SIMPLE array, or the
* primitive array object itself for a PRIMITIVE array.
*
* @return the HDS object holding this array object
*/
public HDSObject getHDSObject() {
return hobj;
}
/**
* Returns the HDS type of the primitives in the array.
*
* @return the primitive type of the array
*/
public HDSType getType() {
return htype;
}
}
| true | true | public ArrayStructure( HDSObject hobj ) throws HDSException {
this.hobj = hobj;
/* See if we appear to have a SIMPLE array. */
HDSObject dat;
if ( hobj.datStruc() &&
hobj.datShape().length == 0 &&
hobj.datType().equals( "ARRAY" ) &&
hobj.datThere( "DATA" ) &&
( ( dat = hobj.datFind( "DATA" ) ) != null ) &&
( ! dat.datStruc() ) &&
dat.datShape().length > 0 ) {
storage = "SIMPLE";
dataObj = dat;
long[] dims = dataObj.datShape();
long[] origin;
if ( hobj.datThere( "ORIGIN" ) ) {
HDSObject orgObj = hobj.datFind( "ORIGIN" );
long[] orgShape = orgObj.datShape();
if ( orgShape.length != 1 ||
orgShape[ 0 ] != dims.length ||
! orgObj.datType().equals( "_INTEGER" ) ) {
throw new HDSException(
"Format of ARY object is unexpected" );
}
origin = NDShape.intsToLongs( orgObj.datGetvi() );
}
else {
origin = new long[ dims.length ];
for ( int i = 0; i < dims.length; i++ ) {
origin[ i ] = 1L;
}
}
oshape = new OrderedNDShape( new NDShape( origin, dims ),
Order.COLUMN_MAJOR );
}
/* See if we appear to have a PRIMITIVE array. */
else if ( ! hobj.datStruc() &&
hobj.datShape().length > 0 ) {
storage = "PRIMITIVE";
dataObj = hobj.datClone();
long[] dims = dataObj.datShape();
int ndim = dims.length;
long[] origin = new long[ ndim ];
for ( int i = 0; i < ndim; i++ ) {
origin[ i ] = 1L;
}
oshape = new OrderedNDShape( new NDShape( origin, dims ),
Order.COLUMN_MAJOR );
}
else {
throw new HDSException( "No array structure found in HDS" );
}
htype = HDSType.fromName( dataObj.datType() );
}
| public ArrayStructure( HDSObject hobj ) throws HDSException {
this.hobj = hobj;
/* See if we appear to have a SIMPLE array. */
HDSObject dat;
if ( hobj.datStruc() &&
hobj.datShape().length == 0 &&
hobj.datType().equals( "ARRAY" ) &&
hobj.datThere( "DATA" ) &&
( ( dat = hobj.datFind( "DATA" ) ) != null ) &&
( ! dat.datStruc() ) &&
dat.datShape().length > 0 ) {
storage = "SIMPLE";
dataObj = dat;
long[] dims = dataObj.datShape();
long[] origin;
if ( hobj.datThere( "ORIGIN" ) ) {
HDSObject orgObj = hobj.datFind( "ORIGIN" );
long[] orgShape = orgObj.datShape();
if ( orgShape.length != 1 ||
orgShape[ 0 ] != dims.length ||
! orgObj.datType().equals( "_INTEGER" ) ) {
throw new HDSException(
"Format of ARY object is unexpected" );
}
origin = NDShape.intsToLongs( orgObj.datGetvi() );
}
else {
origin = new long[ dims.length ];
for ( int i = 0; i < dims.length; i++ ) {
origin[ i ] = 1L;
}
}
oshape = new OrderedNDShape( new NDShape( origin, dims ),
Order.COLUMN_MAJOR );
}
/* See if we appear to have a PRIMITIVE array. */
else if ( ! hobj.datStruc() &&
hobj.datShape().length > 0 ) {
storage = "PRIMITIVE";
dataObj = hobj.datClone();
long[] dims = dataObj.datShape();
int ndim = dims.length;
long[] origin = new long[ ndim ];
for ( int i = 0; i < ndim; i++ ) {
origin[ i ] = 1L;
}
oshape = new OrderedNDShape( new NDShape( origin, dims ),
Order.COLUMN_MAJOR );
}
else {
throw new HDSException( "No array structure found in HDS object "
+ hobj.datRef() );
}
htype = HDSType.fromName( dataObj.datType() );
}
|
diff --git a/src/game/AbstractGameScreenState.java b/src/game/AbstractGameScreenState.java
index 5dccae5..a9e73f4 100644
--- a/src/game/AbstractGameScreenState.java
+++ b/src/game/AbstractGameScreenState.java
@@ -1,786 +1,786 @@
package game;
import game.Car.CarType;
import physics.BMWM3Properties;
import physics.CarProperties;
import physics.EnginePhysics;
import physics.tools.Conversion;
import physics.tools.MathTools;
import save.ProfilCurrent;
import audio.AudioRender;
import audio.EngineSoundStore;
import audio.SoundStore;
import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.input.ChaseCamera;
import com.jme3.input.InputManager;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.AnalogListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Matrix3f;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.plugins.blender.BlenderLoader;
import com.jme3.shadow.PssmShadowRenderer;
import com.jme3.terrain.geomipmap.TerrainLodControl;
import com.jme3.terrain.geomipmap.TerrainQuad;
import com.jme3.terrain.heightmap.AbstractHeightMap;
import com.jme3.terrain.heightmap.ImageBasedHeightMap;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapMode;
import com.jme3.util.SkyFactory;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.screen.Screen;
/**
* This class contains the common points between all games, such as the controls
* of the car, initializing sounds, maps...
*
* @author TANGUY Arnaud
*
*/
public abstract class AbstractGameScreenState extends AbstractScreenController
implements ActionListener, AnalogListener, PhysicsCollisionListener {
protected ViewPort viewPort;
protected Node rootNode;
protected AssetManager assetManager;
protected InputManager inputManager;
protected BulletAppState bulletAppState;
protected SoundStore<String> soundStore;
protected EngineSoundStore engineSoundStore;
protected Car player;
protected CarProperties playerCarProperties;
protected EnginePhysics playerEnginePhysics;
protected boolean runIsOn;
protected boolean runFinish;
protected boolean playerStartKickDone;
protected ChaseCamera chaseCam;
protected TerrainQuad terrain;
protected Material mat_terrain;
protected RigidBodyControl terrainPhys;
protected PssmShadowRenderer pssmRenderer;
protected long startTime = 0;
protected long countDown = 0;
protected boolean soudIsActive = true;
protected AppStateManager stateManager;
protected DigitalDisplay digitalTachometer;
protected DigitalDisplay digitalSpeed;
protected DigitalDisplay digitalGear;
protected DigitalDisplay digitalStart;
protected ShiftlightLed shiftlight;
protected boolean isBreaking;
protected long rpmTimer;
protected boolean needReset;
protected boolean needJump = false;
protected long timerJump = 0;
protected long timerRedZone = 0;
protected long timerCrashSound = 0;
protected boolean playerFinish;
protected long timePlayer = 0;
protected boolean playerStoped = false;
private Vector3f jumpForce = new Vector3f(0, 15000, 0);
boolean zeroSec;
boolean oneSec;
boolean twoSec;
boolean threeSec;
protected AudioRender<String> audioRender;
public AbstractGameScreenState() {
super();
}
/***** Initialize Nifty gui ****/
@Override
public void stateAttached(AppStateManager stateManager) {
}
@Override
public void stateDetached(AppStateManager stateManager) {
}
@Override
public void bind(Nifty nifty, Screen screen) {
super.bind(nifty, screen);
// nifty.setDebugOptionPanelColors(true);
}
@Override
public void onEndScreen() {
audioRender.mute();
stateManager.detach(this);
}
@Override
public void onStartScreen() {
}
/******* Initialize game ******/
@Override
public void initialize(AppStateManager stateManager, Application a) {
/** init the screen */
super.initialize(stateManager, a);
this.rootNode = app.getRootNode();
this.viewPort = app.getViewPort();
this.assetManager = app.getAssetManager();
this.inputManager = app.getInputManager();
assetManager.registerLoader(BlenderLoader.class, "blend");
}
protected void initGame() throws Exception {
app.setDisplayStatView(false);
bulletAppState = new BulletAppState();
stateManager = app.getStateManager();
stateManager.attach(bulletAppState);
runIsOn = false;
runFinish = false;
this.isBreaking = false;
this.needReset = false;
zeroSec = false;
oneSec = false;
twoSec = false;
threeSec = false;
playerStartKickDone = false;
initAudio();
initGround();
buildPlayer();
setupKeys();
// Active skybox
Spatial sky = SkyFactory.createSky(assetManager,
"Textures/Skysphere.jpg", true);
rootNode.attachChild(sky);
// Enable a chase cam
chaseCam = new ChaseCamera(app.getCamera(), player.getNode(),
inputManager);
chaseCam.setSmoothMotion(true);
chaseCam.setMaxDistance(100);
// Set up light
DirectionalLight dl = new DirectionalLight();
dl.setDirection(new Vector3f(-0.5f, -1f, -0.3f).normalizeLocal());
rootNode.addLight(dl);
AmbientLight al = new AmbientLight();
al.setColor(ColorRGBA.White.mult(1.3f));
rootNode.addLight(al);
// Set up shadow
pssmRenderer = new PssmShadowRenderer(assetManager, 1024, 3);
pssmRenderer.setDirection(new Vector3f(0.5f, -0.1f, 0.3f)
.normalizeLocal()); // light direction
viewPort.addProcessor(pssmRenderer);
rootNode.setShadowMode(ShadowMode.Off); // reset all
player.getNode().setShadowMode(ShadowMode.CastAndReceive); // normal
// map.setShadowMode(ShadowMode.Receive);
terrain.setShadowMode(ShadowMode.Receive);
getPhysicsSpace().addCollisionListener(this);
digitalTachometer = new DigitalDisplay(nifty, screen,
"digital_tachometer", 80);
digitalSpeed = new DigitalDisplay(nifty, screen, "digital_speed", 50);
digitalGear = new DigitalDisplay(nifty, screen, "digital_gear", 50);
digitalStart = new DigitalDisplay(nifty, screen, "startTimer", 50);
shiftlight = new ShiftlightLed(nifty, screen, playerCarProperties,
playerEnginePhysics);
}
protected void initAudio() throws Exception {
// Init audio
soundStore = SoundStore.getInstance();
soundStore.setAssetManager(assetManager);
engineSoundStore = engineSoundStore.getInstance();
engineSoundStore.setAssetManager(assetManager);
engineSoundStore.addSound(1000, "Models/Default/1052_P.wav");
// channels.put(1126, "Models/Default/1126_P.wav");
// channels.put(1205, "Models/Default/1205_P.wav");
// channels.put(1289, "Models/Default/1289_P.wav");
// channels.put(1380, "Models/Default/1380_P.wav");
// channels.put(1476, "Models/Default/1476_P.wav");
// channels.put(1579, "Models/Default/1579_P.wav");
// channels.put(1690, "Models/Default/1690_P.wav");
// channels.put(1808, "Models/Default/1808_P.wav");
// channels.put(1935, "Models/Default/1935_P.wav");
// channels.put(2070, "Models/Default/2070_P.wav");
// channels.put(2215, "Models/Default/2215_P.wav");
// channels.put(2370, "Models/Default/2370_P.wav");
// channels.put(2536, "Models/Default/2536_P.wav");
engineSoundStore.addSound(2714, "Models/Default/2714_P.wav");
// channels.put(2904, "Models/Default/2904_P.wav");
// channels.put(3107, "Models/Default/3107_P.wav");
// channels.put(3324, "Models/Default/3324_P.wav");
// channels.put(3557, "Models/Default/3557_P.wav");
// channels.put(3806, "Models/Default/3806_P.wav");
// channels.put(4073, "Models/Default/4073_P.wav");
engineSoundStore.addSound(4358, "Models/Default/4358_P.wav");
// channels.put(4663, "Models/Default/4663_P.wav");
// channels.put(4989, "Models/Default/4989_P.wav");
// channels.put(5338, "Models/Default/5338_P.wav");
// channels.put(5712, "Models/Default/5712_P.wav");
// channels.put(6112, "Models/Default/6112_P.wav");
engineSoundStore.addSound(8540, "Models/Default/6540_P.wav");
soundStore.addSound("start", "Models/Default/start.wav");
soundStore.addSound("up", "Models/Default/up.wav");
soundStore.addSound("lost", "Sound/lost.wav");
soundStore.addSound("win", "Sound/win.wav");
soundStore.addSound("start_low", "Sound/start_low.wav");
soundStore.addSound("start_high", "Sound/start_high.wav");
soundStore.addSound("burst", "Sound/explosion.wav");
soundStore.addSound("crash", "Sound/car_crash.wav");
audioRender = new AudioRender<String>(rootNode, soundStore);
}
protected void buildPlayer() {
//playerCarProperties = new F430Properties();
//playerCarProperties = (ProfilCurrent.getInstance() == null) ? new CarProperties () :
//ProfilCurrent.getInstance().getCar().get(ProfilCurrent.getInstance().getChoixCar());
//XXX
playerCarProperties = (ProfilCurrent.getInstance() == null) ? new BMWM3Properties () :
ProfilCurrent.getInstance().getCar().get(ProfilCurrent.getInstance().getChoixCar());
// Create a vehicle control
player = new Car(assetManager, playerCarProperties, "ferrari red");
// player = new Car(assetManager, playerCarProperties, "corvette.j3o");
player.setType(CarType.PLAYER);
player.setDriverName("Player");
player.getNode().addControl(player);
player.setPhysicsLocation(new Vector3f(0, 27, 700));
player.setNosCharge(1);
playerCarProperties = player.getProperties();
playerEnginePhysics = player.getEnginePhysics();
rootNode.attachChild(player.getNode());
getPhysicsSpace().add(player);
}
public void initGround() {
/** 1. Create terrain material and load four textures into it. */
mat_terrain = new Material(assetManager,
"Common/MatDefs/Terrain/Terrain.j3md");
/** 1.1) Add ALPHA map (for red-blue-green coded splat textures) */
mat_terrain.setTexture("Alpha",
assetManager.loadTexture("Textures/alphamap.png"));
/** 1.2) Add GRASS texture into the red layer (Tex1). */
Texture grass = assetManager.loadTexture("Textures/grass.jpg");
grass.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("Tex1", grass);
mat_terrain.setFloat("Tex1Scale", 64f);
/** 1.3) Add DIRT texture into the green layer (Tex2) */
Texture dirt = assetManager.loadTexture("Textures/carreau.jpg");
dirt.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("Tex2", dirt);
mat_terrain.setFloat("Tex2Scale", 64f);
/** 1.4) Add ROAD texture into the blue layer (Tex3) */
Texture rock = assetManager.loadTexture("Textures/road2.jpg");
rock.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("Tex3", rock);
mat_terrain.setFloat("Tex3Scale", 128f);
/** 2. Create the height map */
AbstractHeightMap heightmap = null;
Texture heightMapImage = assetManager
.loadTexture("Textures/mountains512.png");
heightmap = new ImageBasedHeightMap(heightMapImage.getImage());
heightmap.load();
/**
* 3. We have prepared material and heightmap. Now we create the actual
* terrain: 3.1) Create a TerrainQuad and name it "my terrain". 3.2) A
* good value for terrain tiles is 64x64 -- so we supply 64+1=65. 3.3)
* We prepared a heightmap of size 512x512 -- so we supply 512+1=513.
* 3.4) As LOD step scale we supply Vector3f(1,1,1). 3.5) We supply the
* prepared heightmap itself.
*/
int patchSize = 65;
terrain = new TerrainQuad("my terrain", patchSize, 513,
heightmap.getHeightMap());
/**
* 4. We give the terrain its material, position & scale it, and attach
* it.
*/
terrain.setMaterial(mat_terrain);
terrain.setLocalTranslation(0, -100, 0);
terrain.setLocalScale(2f, 1f, 2f);
rootNode.attachChild(terrain);
/** 5. The LOD (level of detail) depends on were the camera is: */
TerrainLodControl control = new TerrainLodControl(terrain,
app.getCamera());
terrain.addControl(control);
// Rendre le terrain physique
terrain.setLocalScale(3f, 2f, 4f);
terrainPhys = new RigidBodyControl(0.0f);
terrain.addControl(terrainPhys);
bulletAppState.getPhysicsSpace().add(terrainPhys);
bulletAppState.getPhysicsSpace()
.setGravity(new Vector3f(0, -19.81f, 0));
terrainPhys.setFriction(0.5f);
bulletAppState.getPhysicsSpace().enableDebug(assetManager);
}
protected void setupKeys() {
inputManager.addMapping("Lefts", new KeyTrigger(KeyInput.KEY_Q));
inputManager.addMapping("Rights", new KeyTrigger(KeyInput.KEY_D));
inputManager.addMapping("GearUp", new KeyTrigger(KeyInput.KEY_Z));
inputManager.addMapping("GearDown", new KeyTrigger(KeyInput.KEY_S));
inputManager.addMapping("Space", new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addMapping("Reset", new KeyTrigger(KeyInput.KEY_RETURN));
inputManager.addMapping("Mute", new KeyTrigger(KeyInput.KEY_M));
inputManager.addMapping("GearUp", new KeyTrigger(KeyInput.KEY_A));
inputManager.addMapping("GearDown", new KeyTrigger(KeyInput.KEY_E));
inputManager.addMapping("GearUp", new KeyTrigger(KeyInput.KEY_UP));
inputManager.addMapping("GearDown", new KeyTrigger(KeyInput.KEY_DOWN));
inputManager.addMapping("Throttle", new KeyTrigger(
KeyInput.KEY_RCONTROL));
inputManager.addMapping("Lefts", new KeyTrigger(KeyInput.KEY_LEFT));
inputManager.addMapping("Rights", new KeyTrigger(KeyInput.KEY_RIGHT));
inputManager.addMapping("NOS", new KeyTrigger(KeyInput.KEY_RSHIFT));
inputManager.addMapping("Jump", new KeyTrigger(KeyInput.KEY_J));
// inputManager.addMapping("Menu", new KeyTrigger(KeyInput.KEY_ESCAPE));
inputManager.addListener(this, "Lefts");
inputManager.addListener(this, "Rights");
inputManager.addListener(this, "Ups");
inputManager.addListener(this, "Downs");
inputManager.addListener(this, "Space");
inputManager.addListener(this, "Reset");
inputManager.addListener(this, "Mute");
inputManager.addListener(this, "GearUp");
inputManager.addListener(this, "GearDown");
inputManager.addListener(this, "Throttle");
inputManager.addListener(this, "NOS");
inputManager.addListener(this, "Jump");
}
@Override
public void update(float tpf) {
int playerRpm = player.getEnginePhysics().getFreeRpm();
int playerSpeed = (int) Math.abs(player.getCurrentVehicleSpeedKmHour());
/** Stops 1 second after the finish line */
if (playerFinish && !playerStoped) {
player.stop(1000);
playerStoped = true;
}
if (runIsOn) {
// XXX why the hell is it needed !!
digitalStart.setText(" ");
if (!player.getBurstEnabled() && !playerFinish) {
if (playerStartKickDone) {
playerRpm = player.getEnginePhysics().getRpm();
} else {
playerStartKickDone = true;
}
playerEnginePhysics.setSpeed(Math.abs(Conversion
.kmToMiles(playerSpeed)));
float force = -(float) playerEnginePhysics.getForce() / 5;
player.accelerate(2, force * 2);
player.accelerate(3, force * 2);
if (needJump) {
player.applyImpulse(jumpForce, Vector3f.ZERO);
needJump = false;
}
} else if (player.getBurstEnabled()) {
audioRender.mute();
playerRpm = 0;
}
} else {
if (!runFinish) {
countDown();
}
// Baisser le régime moteur à l'arrêt
playerEnginePhysics.setRpm(playerEnginePhysics.getFreeRpm() - 100);
}
// Traiter le cas du sur-régime
if (playerRpm > (playerCarProperties.getRedline() - 500)) {
if (!player.getBurstEnabled()) {
// Déclencher le timer s'il n'est pas activé
if (timerRedZone == 0) {
timerRedZone = System.currentTimeMillis();
} else {
if (System.currentTimeMillis() - timerRedZone > 3000) {
player.explode();
audioRender.mute();
playerFinish = true;
timePlayer = 0;
}
}
}
} else {
timerRedZone = 0;
}
// Update audio
if (soudIsActive) {
if (!player.getBurstEnabled()) {
player.updateSound(playerRpm);
} else {
player.mute();
}
app.getListener().setLocation(
player.getNode().getWorldTranslation());
}
if (player.getNosActivity()) {
player.controlNos();
}
// particule_motor.controlBurst();
digitalTachometer.setText(((Integer) playerRpm).toString());
digitalSpeed.setText(((Integer) playerSpeed).toString());
digitalGear.setText(((Integer) playerEnginePhysics.getGear())
.toString());
shiftlight.setRpm(playerRpm);
}
/**
* Displays a countdown
*/
protected void countDown() {
/*
* long ellapsedTime = System.currentTimeMillis() - countDown;
*
* if (ellapsedTime < time) { screen.findElementByName("startTimer")
* .getRenderer(TextRenderer.class) .setText( ((Long) ((time -
* ellapsedTime + 1000) / 1000)) .toString()); } else if (ellapsedTime
* >= time && ellapsedTime < time + 500) {
* screen.findElementByName("startTimer")
* .getRenderer(TextRenderer.class).setText(""); runIsOn = true;
* audio_motor.playStartBeepHigh();
* playerEnginePhysics.setRpm(initialRev); startTime =
* System.currentTimeMillis(); countDown = 0; }
*/
if (countDown != 0) {
long time = System.currentTimeMillis() - countDown;
if (time > 5000) {
if (!zeroSec) {
audioRender.play("start_high");
zeroSec = true;
}
digitalStart.setText(" ");
runIsOn = true;
startTime = System.currentTimeMillis();
} else if (time > 4000) {
if (!oneSec) {
audioRender.play("start_low");
oneSec = true;
}
digitalStart.setText("1");
} else if (time > 3000) {
if (!twoSec) {
audioRender.play("start_low");
twoSec = true;
}
digitalStart.setText("2");
} else if (time > 2000) {
if (!threeSec) {
audioRender.play("start_low");
threeSec = true;
}
digitalStart.setText("3");
}
}
}
protected void reset() {
player.setPhysicsLocation(new Vector3f(0, 27, 700));
player.setPhysicsRotation(new Matrix3f());
player.setLinearVelocity(Vector3f.ZERO);
player.setAngularVelocity(Vector3f.ZERO);
player.setNosCharge(1);
playerEnginePhysics.setGear(1);
player.resetSuspension();
player.steer(0);
audioRender.play("start");
player.accelerate(0);
player.setLife(100);
playerEnginePhysics.setSpeed(0);
playerEnginePhysics.setRpm(1000);
if (player.getBurstEnabled()) {
player.removeExplosion();
}
player.stopNos();
timerRedZone = 0;
playerFinish = false;
playerStoped = false;
runIsOn = false;
playerStartKickDone = false;
needReset = false;
runFinish = false;
needJump = false;
startTime = 0;
countDown = 0;
threeSec = false;
twoSec = false;
oneSec = false;
zeroSec = false;
digitalStart.setText("Ready ?");
}
protected PhysicsSpace getPhysicsSpace() {
return bulletAppState.getPhysicsSpace();
}
public void onAction(String binding, boolean value, float tpf) {
if (binding.equals("Lefts")) {
// XXX: Needs analog controller for releasing the wheels too!
if (!value) {
player.setSteeringValue(0.f);
player.steer(player.getSteeringValue());
}
} else if (binding.equals("Rights")) {
if (!value) {
player.setSteeringValue(0);
player.steer(0);
}
} else if (binding.equals("Space")) {
if (value) {
player.brake(700f);
} else {
player.brake(0f);
}
} else if (binding.equals("Reset")) {
if (value) {
System.out.println("Reset");
needReset = true;
}
} else if (binding.equals("GearUp")) {
if (value) {
audioRender.play("up");
playerEnginePhysics.incrementGear();
}
} else if (binding.equals("GearDown")) {
if (value) {
playerEnginePhysics.decrementGear();
}
} else if (binding.equals("NOS")) {
if (value) {
if (!player.getNosActivity()) {
player.addNos();
}
}
} else if (binding.equals("Jump")) {
if (value) {
if (System.currentTimeMillis() - timerJump > 2000
&& !player.getBurstEnabled() && runIsOn) {
needJump = true;
timerJump = System.currentTimeMillis();
}
}
} else if (binding.equals("Menu")) {
app.gotoStart();
}
}
@Override
public void onAnalog(String binding, float value, float tpf) {
if (binding.equals("Throttle")) {
if (!player.getBurstEnabled()) {
// Start countdown
if (countDown == 0) {
countDown = System.currentTimeMillis();
}
playerEnginePhysics
.setRpm(playerEnginePhysics.getFreeRpm() + 400);
}
} else if (binding.equals("Rights")) {
float val = player.getSteeringValue();
val = val - value;
if (val < -0.5)
val = -0.5f;
player.setSteeringValue(val);
player.steer(player.getSteeringValue());
} else if (binding.equals("Lefts")) {
float val = player.getSteeringValue();
val = val + value;
if (val > 0.5)
val = 0.5f;
player.setSteeringValue(val);
player.steer(player.getSteeringValue());
}
}
@Override
public void collision(PhysicsCollisionEvent event) {
Car car1 = null;
Car car2 = null;
Car car = null;
if (event.getObjectA() instanceof Car) {
car1 = (Car) event.getObjectA();
}
if (event.getObjectB() instanceof Car) {
car2 = (Car) event.getObjectB();
}
// Two cars collide
if (car1 != null && car2 != null) {
// Trigger crash sound
if (car1.getType().equals(CarType.PLAYER)
|| car2.getType().equals(CarType.PLAYER)) {
// Trigger only if the sound is not playing
if (timerCrashSound == 0
|| System.currentTimeMillis() - timerCrashSound > 2000) {
- audioRender.play("crash");
+ audioRender.play("crash", 20f);
timerCrashSound = System.currentTimeMillis();
}
}
float speed1 = Math.abs(car1.getCurrentVehicleSpeedKmHour());
float speed2 = Math.abs(car2.getCurrentVehicleSpeedKmHour());
float appliedImpulse = event.getAppliedImpulse();
// Impact, reduce friction
float damageForce = (appliedImpulse - event.getCombinedFriction() / 10) / 10000;
/*
* System.out.println("Collision between " + car1.getType() + " " +
* car1.getDriverName() + " and " + car2.getType() + " " +
* car2.getDriverName()); System.out.println("Lateral 1 impulse " +
* event.getAppliedImpulseLateral1());
* System.out.println("Lateral 2 impulse " +
* event.getAppliedImpulseLateral2());
* System.out.println("Combined friction " +
* event.getCombinedFriction()); System.out.println("Force " +
* appliedImpulse);
*/
Vector3f forward1 = new Vector3f(0, 0, 0).subtract(
car1.getForwardVector(null)).normalize();
Vector3f forward2 = new Vector3f(0, 0, 0).subtract(
car2.getForwardVector(null)).normalize();
Vector2f f1 = new Vector2f(forward1.x, forward1.z);
Vector2f f2 = new Vector2f(forward2.x, forward2.z);
float angle = Math.abs(MathTools.orientedAngle(f1, f2));
// Frontal collision
if (angle >= Math.PI - Math.PI / 4
&& angle <= Math.PI + Math.PI / 4) {
float speedPercent1 = speed1 / (speed1 + speed2);
float life1 = 10 * speedPercent1 * damageForce;
life1 = (life1 <= 50) ? life1 : 50;
float life2 = 10 * (1 - speedPercent1) * damageForce;
life2 = (life2 <= 50) ? life2 : 50;
car1.decreaseLife(life1);
car2.decreaseLife(life2);
} else {
/*
* back collision if (angle <= Math.PI / 4) the car in front
* will have 75% of the damages 25% for the car in back
*/
double speedDifferenceDamage = Math.abs(speed2 - speed1)
* damageForce / 2;
if (car1.inFront(car2)) {
car1.decreaseLife(0.75 * speedDifferenceDamage);
car2.decreaseLife(0.25 * speedDifferenceDamage);
} else {
car1.decreaseLife(0.25 * speedDifferenceDamage);
car2.decreaseLife(0.75 * speedDifferenceDamage);
}
}
} else {
RigidBodyControl control = null;
if (car1 != null) {
car = car1;
try {
control = (RigidBodyControl) event.getObjectB();
} catch (Exception e) {
control = null;
}
} else if (car2 != null) {
car = car2;
try {
control = (RigidBodyControl) event.getObjectA();
} catch (Exception e) {
control = null;
}
}
if (car != null && control != null) {
float speed = Math.abs(car.getCurrentVehicleSpeedKmHour());
if (control.getUserObject().equals("Tree")) {
car.decreaseLife(speed / 10);
}
}
}
}
}
| true | true | public void collision(PhysicsCollisionEvent event) {
Car car1 = null;
Car car2 = null;
Car car = null;
if (event.getObjectA() instanceof Car) {
car1 = (Car) event.getObjectA();
}
if (event.getObjectB() instanceof Car) {
car2 = (Car) event.getObjectB();
}
// Two cars collide
if (car1 != null && car2 != null) {
// Trigger crash sound
if (car1.getType().equals(CarType.PLAYER)
|| car2.getType().equals(CarType.PLAYER)) {
// Trigger only if the sound is not playing
if (timerCrashSound == 0
|| System.currentTimeMillis() - timerCrashSound > 2000) {
audioRender.play("crash");
timerCrashSound = System.currentTimeMillis();
}
}
float speed1 = Math.abs(car1.getCurrentVehicleSpeedKmHour());
float speed2 = Math.abs(car2.getCurrentVehicleSpeedKmHour());
float appliedImpulse = event.getAppliedImpulse();
// Impact, reduce friction
float damageForce = (appliedImpulse - event.getCombinedFriction() / 10) / 10000;
/*
* System.out.println("Collision between " + car1.getType() + " " +
* car1.getDriverName() + " and " + car2.getType() + " " +
* car2.getDriverName()); System.out.println("Lateral 1 impulse " +
* event.getAppliedImpulseLateral1());
* System.out.println("Lateral 2 impulse " +
* event.getAppliedImpulseLateral2());
* System.out.println("Combined friction " +
* event.getCombinedFriction()); System.out.println("Force " +
* appliedImpulse);
*/
Vector3f forward1 = new Vector3f(0, 0, 0).subtract(
car1.getForwardVector(null)).normalize();
Vector3f forward2 = new Vector3f(0, 0, 0).subtract(
car2.getForwardVector(null)).normalize();
Vector2f f1 = new Vector2f(forward1.x, forward1.z);
Vector2f f2 = new Vector2f(forward2.x, forward2.z);
float angle = Math.abs(MathTools.orientedAngle(f1, f2));
// Frontal collision
if (angle >= Math.PI - Math.PI / 4
&& angle <= Math.PI + Math.PI / 4) {
float speedPercent1 = speed1 / (speed1 + speed2);
float life1 = 10 * speedPercent1 * damageForce;
life1 = (life1 <= 50) ? life1 : 50;
float life2 = 10 * (1 - speedPercent1) * damageForce;
life2 = (life2 <= 50) ? life2 : 50;
car1.decreaseLife(life1);
car2.decreaseLife(life2);
} else {
/*
* back collision if (angle <= Math.PI / 4) the car in front
* will have 75% of the damages 25% for the car in back
*/
double speedDifferenceDamage = Math.abs(speed2 - speed1)
* damageForce / 2;
if (car1.inFront(car2)) {
car1.decreaseLife(0.75 * speedDifferenceDamage);
car2.decreaseLife(0.25 * speedDifferenceDamage);
} else {
car1.decreaseLife(0.25 * speedDifferenceDamage);
car2.decreaseLife(0.75 * speedDifferenceDamage);
}
}
} else {
RigidBodyControl control = null;
if (car1 != null) {
car = car1;
try {
control = (RigidBodyControl) event.getObjectB();
} catch (Exception e) {
control = null;
}
} else if (car2 != null) {
car = car2;
try {
control = (RigidBodyControl) event.getObjectA();
} catch (Exception e) {
control = null;
}
}
if (car != null && control != null) {
float speed = Math.abs(car.getCurrentVehicleSpeedKmHour());
if (control.getUserObject().equals("Tree")) {
car.decreaseLife(speed / 10);
}
}
}
}
| public void collision(PhysicsCollisionEvent event) {
Car car1 = null;
Car car2 = null;
Car car = null;
if (event.getObjectA() instanceof Car) {
car1 = (Car) event.getObjectA();
}
if (event.getObjectB() instanceof Car) {
car2 = (Car) event.getObjectB();
}
// Two cars collide
if (car1 != null && car2 != null) {
// Trigger crash sound
if (car1.getType().equals(CarType.PLAYER)
|| car2.getType().equals(CarType.PLAYER)) {
// Trigger only if the sound is not playing
if (timerCrashSound == 0
|| System.currentTimeMillis() - timerCrashSound > 2000) {
audioRender.play("crash", 20f);
timerCrashSound = System.currentTimeMillis();
}
}
float speed1 = Math.abs(car1.getCurrentVehicleSpeedKmHour());
float speed2 = Math.abs(car2.getCurrentVehicleSpeedKmHour());
float appliedImpulse = event.getAppliedImpulse();
// Impact, reduce friction
float damageForce = (appliedImpulse - event.getCombinedFriction() / 10) / 10000;
/*
* System.out.println("Collision between " + car1.getType() + " " +
* car1.getDriverName() + " and " + car2.getType() + " " +
* car2.getDriverName()); System.out.println("Lateral 1 impulse " +
* event.getAppliedImpulseLateral1());
* System.out.println("Lateral 2 impulse " +
* event.getAppliedImpulseLateral2());
* System.out.println("Combined friction " +
* event.getCombinedFriction()); System.out.println("Force " +
* appliedImpulse);
*/
Vector3f forward1 = new Vector3f(0, 0, 0).subtract(
car1.getForwardVector(null)).normalize();
Vector3f forward2 = new Vector3f(0, 0, 0).subtract(
car2.getForwardVector(null)).normalize();
Vector2f f1 = new Vector2f(forward1.x, forward1.z);
Vector2f f2 = new Vector2f(forward2.x, forward2.z);
float angle = Math.abs(MathTools.orientedAngle(f1, f2));
// Frontal collision
if (angle >= Math.PI - Math.PI / 4
&& angle <= Math.PI + Math.PI / 4) {
float speedPercent1 = speed1 / (speed1 + speed2);
float life1 = 10 * speedPercent1 * damageForce;
life1 = (life1 <= 50) ? life1 : 50;
float life2 = 10 * (1 - speedPercent1) * damageForce;
life2 = (life2 <= 50) ? life2 : 50;
car1.decreaseLife(life1);
car2.decreaseLife(life2);
} else {
/*
* back collision if (angle <= Math.PI / 4) the car in front
* will have 75% of the damages 25% for the car in back
*/
double speedDifferenceDamage = Math.abs(speed2 - speed1)
* damageForce / 2;
if (car1.inFront(car2)) {
car1.decreaseLife(0.75 * speedDifferenceDamage);
car2.decreaseLife(0.25 * speedDifferenceDamage);
} else {
car1.decreaseLife(0.25 * speedDifferenceDamage);
car2.decreaseLife(0.75 * speedDifferenceDamage);
}
}
} else {
RigidBodyControl control = null;
if (car1 != null) {
car = car1;
try {
control = (RigidBodyControl) event.getObjectB();
} catch (Exception e) {
control = null;
}
} else if (car2 != null) {
car = car2;
try {
control = (RigidBodyControl) event.getObjectA();
} catch (Exception e) {
control = null;
}
}
if (car != null && control != null) {
float speed = Math.abs(car.getCurrentVehicleSpeedKmHour());
if (control.getUserObject().equals("Tree")) {
car.decreaseLife(speed / 10);
}
}
}
}
|
diff --git a/src-datatype/org/seasr/datatypes/core/BasicDataTypesTools.java b/src-datatype/org/seasr/datatypes/core/BasicDataTypesTools.java
index 6ab607df..9d87370f 100644
--- a/src-datatype/org/seasr/datatypes/core/BasicDataTypesTools.java
+++ b/src-datatype/org/seasr/datatypes/core/BasicDataTypesTools.java
@@ -1,533 +1,533 @@
/**
*
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2008, NCSA. All rights reserved.
*
* Developed by:
* The Automated Learning Group
* University of Illinois at Urbana-Champaign
* http://www.seasr.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal with 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:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimers in
* the documentation and/or other materials provided with the distribution.
*
* Neither the names of The Automated Learning Group, University of
* Illinois at Urbana-Champaign, nor the names of its contributors may
* be used to endorse or promote products derived from this Software
* without specific prior written permission.
*
* 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
*
*/
package org.seasr.datatypes.core;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.seasr.datatypes.core.BasicDataTypes.Bytes;
import org.seasr.datatypes.core.BasicDataTypes.BytesMap;
import org.seasr.datatypes.core.BasicDataTypes.Integers;
import org.seasr.datatypes.core.BasicDataTypes.IntegersMap;
import org.seasr.datatypes.core.BasicDataTypes.Longs;
import org.seasr.datatypes.core.BasicDataTypes.LongsMap;
import org.seasr.datatypes.core.BasicDataTypes.Floats;
import org.seasr.datatypes.core.BasicDataTypes.FloatsMap;
import org.seasr.datatypes.core.BasicDataTypes.Doubles;
import org.seasr.datatypes.core.BasicDataTypes.DoublesMap;
import org.seasr.datatypes.core.BasicDataTypes.Strings;
import org.seasr.datatypes.core.BasicDataTypes.StringsArray;
import org.seasr.datatypes.core.BasicDataTypes.StringsMap;
import org.seasr.datatypes.core.exceptions.UnsupportedDataTypeException;
import com.google.protobuf.ByteString;
/**
* Tools to help dealing with the basic types
*
* @author Xavier Llorà
* @author Boris Capitanu
* @author Mike Haberman
* @author Ian Wood
*
*/
public abstract class BasicDataTypesTools {
enum NumberTypes {INTEGER, LONG, FLOAT, DOUBLE};
/**
* Creates a Integers object out of a regular Integer.
*
* @param i The integer to use
* @return THe new object produced
*/
public static Integers integerToIntegers( Integer i ) {
org.seasr.datatypes.core.BasicDataTypes.Integers.Builder res = BasicDataTypes.Integers.newBuilder();
res.addValue(i);
return res.build();
}
/**
* Creates a Doubles object out of a regular Double.
*
* @param d The double to use
* @return THe new object produced
*/
public static Doubles doubleToDoubles( Double d ) {
org.seasr.datatypes.core.BasicDataTypes.Doubles.Builder res = BasicDataTypes.Doubles.newBuilder();
res.addValue(d);
return res.build();
}
/**
* Create a integer array out of the Integers contents.
*
* @param i The integers to process
* @return The array of integers
*/
public static Integer[] integersToIntegerArray( Integers i ) {
Integer[] iaRes = new Integer[i.getValueCount()];
iaRes = i.getValueList().toArray(iaRes);
return iaRes;
}
/**
* Create a Integers object out of an array of Java integers
*
* @param ints The array of Java integers
* @return The new object produced
*/
public static Integers integerArrayToIntegers(int[] ints) {
org.seasr.datatypes.core.BasicDataTypes.Integers.Builder res = BasicDataTypes.Integers.newBuilder();
for (int i : ints) res.addValue(i);
return res.build();
}
/**
* Creates a Strings object out of a regular String.
*
* @param s The string to use
* @return The new object produced
*/
public static Strings stringToStrings ( String s ){
org.seasr.datatypes.core.BasicDataTypes.Strings.Builder res = BasicDataTypes.Strings.newBuilder();
res.addValue(s);
return res.build();
}
/**
* Creates a Strings object out of an array of String.
*
* @param s The string to use
* @return The new object produced
*/
public static Strings stringToStrings ( String [] sa ){
org.seasr.datatypes.core.BasicDataTypes.Strings.Builder res = BasicDataTypes.Strings.newBuilder();
for (String s:sa) {
if (s != null) res.addValue(s);
}
return res.build();
}
/**
* Create a string array out of the Strings contents.
*
* @param s The strings to process
* @return The array of strings
*/
public static String [] stringsToStringArray ( Strings s ) {
String [] saRes = new String[s.getValueCount()];
saRes = s.getValueList().toArray(saRes);
return saRes;
}
//
// Array Types
//
/**
* Create a StringsArray out of the Strings[] contents.
*
* @param The strings to process
* @return The StringsArray
*/
public static StringsArray javaArrayToStringsArray(Strings[] sa)
{
org.seasr.datatypes.core.BasicDataTypes.StringsArray.Builder res = BasicDataTypes.StringsArray.newBuilder();
for(Strings s: sa) res.addValue(s);
return res.build();
}
/**
* Create a Strings[] from a StringsArray content.
*
* @param The StringsArray to process
* @return The Strings[] array
*/
public static Strings[] stringsArrayToJavaArray(StringsArray sa)
{
Strings[] out = new Strings[sa.getValueCount()];
out = sa.getValueList().toArray(out);
return out;
}
/**
* Creates an empty string map.
*
* @return The empty strings map created
*/
public static StringsMap buildEmptyStringsMap () {
org.seasr.datatypes.core.BasicDataTypes.StringsMap.Builder res = BasicDataTypes.StringsMap.newBuilder();
return res.build();
}
/**
* Creates an empty strings.
*
* @return The empty strings map created
*/
public static Strings buildEmptyStrings () {
org.seasr.datatypes.core.BasicDataTypes.Strings.Builder res = BasicDataTypes.Strings.newBuilder();
return res.build();
}
/**
* Creates an empty integer maps.
*
* @return The empty integer map created
*/
public static IntegersMap buildEmptyIntegersMap () {
org.seasr.datatypes.core.BasicDataTypes.IntegersMap.Builder res = BasicDataTypes.IntegersMap.newBuilder();
return res.build();
}
/**
* Builds the integer map and sorts it if needed.
*
* @param htCounts The token counts
* @param bOrdered Should the counts be ordered?
* @return The IntegerMap
*/
@SuppressWarnings("unchecked")
public static IntegersMap mapToIntegerMap(Map<String, Integer> htCounts, boolean bOrdered) {
Set<Entry<String, Integer>> setCnts = htCounts.entrySet();
Entry<String, Integer>[] esa = new Entry[setCnts.size()];
esa = setCnts.toArray(esa);
// Sort if needed
if ( bOrdered ) {
Arrays.sort(esa, new Comparator<Entry<String,Integer>>(){
public int compare(Entry<String, Integer> o1,Entry<String, Integer> o2) {
return o2.getValue()-o1.getValue();
}} );
}
org.seasr.datatypes.core.BasicDataTypes.IntegersMap.Builder res = BasicDataTypes.IntegersMap.newBuilder();
for ( Entry<String, Integer> entry:esa ) {
res.addKey(entry.getKey());
res.addValue(BasicDataTypes.Integers.newBuilder().addValue(entry.getValue()));
}
return res.build();
}
/**
* Converts a protocol buffer string integer map to the equivalent java map
*
* @param im The integer map to convert
* @return The converted map
*/
public static Map<String,Integer> IntegerMapToMap ( IntegersMap im ) {
Hashtable<String,Integer> ht = new Hashtable<String,Integer>(im.getValueCount());
for ( int i=0,iMax=im.getValueCount() ; i<iMax ; i++ )
ht.put(im.getKey(i), im.getValue(i).getValue(0));
return ht;
}
/**
* Converts a protocol buffer string integer/long/float/double map to a java Number map
*
* @param im The numerical map to convert
* @return The converted map
*/
public static Map<String,Number> NumberMapToMap ( Object im ) throws UnsupportedDataTypeException {
NumberTypes type;
int size;
if (im instanceof IntegersMap) {
type = NumberTypes.INTEGER;
size = ((IntegersMap)im).getKeyCount();
} else
if (im instanceof LongsMap) {
type = NumberTypes.LONG;
size = ((LongsMap)im).getKeyCount();
} else
if (im instanceof FloatsMap) {
type = NumberTypes.FLOAT;
size = ((FloatsMap)im).getKeyCount();
} else
if (im instanceof DoublesMap) {
type = NumberTypes.DOUBLE ;
size = ((DoublesMap)im).getKeyCount();
} else
throw new UnsupportedDataTypeException(im.getClass().getName());
Hashtable<String,Number> ht = new Hashtable<String,Number>(size);
for ( int i=0,iMax=size ; i<iMax ; i++ )
switch (type) {
- case INTEGER: ht.put (((IntegersMap)im).getKey(i), (Number) ((IntegersMap)im).getValue(i).getValue(0));
- case LONG: ht.put (((LongsMap)im).getKey(i), (Number) ((LongsMap)im).getValue(i).getValue(0));
- case FLOAT: ht.put (((FloatsMap)im).getKey(i), (Number) ((FloatsMap)im).getValue(i).getValue(0));
- case DOUBLE: ht.put (((DoublesMap)im).getKey(i), (Number) ((DoublesMap)im).getValue(i).getValue(0));
+ case INTEGER: ht.put (((IntegersMap)im).getKey(i), (Number) ((IntegersMap)im).getValue(i).getValue(0)); break;
+ case LONG: ht.put (((LongsMap)im).getKey(i), (Number) ((LongsMap)im).getValue(i).getValue(0)); break;
+ case FLOAT: ht.put (((FloatsMap)im).getKey(i), (Number) ((FloatsMap)im).getValue(i).getValue(0)); break;
+ case DOUBLE: ht.put (((DoublesMap)im).getKey(i), (Number) ((DoublesMap)im).getValue(i).getValue(0)); break;
}
return ht;
}
/**
* Builds the long map and sorts it if needed.
*
* @param htCounts The token counts
* @param bOrdered Should the counts be ordered?
* @return The LongMap
*/
@SuppressWarnings("unchecked")
public static LongsMap mapToLongMap(Map<String, Long> htCounts, boolean bOrdered) {
Set<Entry<String, Long>> setCnts = htCounts.entrySet();
Entry<String, Long>[] esa = new Entry[setCnts.size()];
esa = setCnts.toArray(esa);
// Sort if needed
if ( bOrdered ) {
Arrays.sort(esa, new Comparator<Entry<String,Long>>(){
public int compare(Entry<String, Long> o1,Entry<String, Long> o2) {
return (int) (o2.getValue()-o1.getValue());
}} );
}
org.seasr.datatypes.core.BasicDataTypes.LongsMap.Builder res = BasicDataTypes.LongsMap.newBuilder();
for ( Entry<String, Long> entry:esa ) {
res.addKey(entry.getKey());
res.addValue(BasicDataTypes.Longs.newBuilder().addValue(entry.getValue()));
}
return res.build();
}
/**
* Converts a protocol buffer string long map to the equivalent java map
*
* @param im The long map to convert
* @return The converted map
*/
public static Map<String,Long> LongMapToMap ( LongsMap im ) {
Hashtable<String,Long> ht = new Hashtable<String,Long>(im.getValueCount());
for ( int i=0,iMax=im.getValueCount() ; i<iMax ; i++ )
ht.put(im.getKey(i), im.getValue(i).getValue(0));
return ht;
}
/**
* Builds the float map and sorts it if needed.
*
* @param htCounts The token counts
* @param bOrdered Should the counts be ordered?
* @return The FloatMap
*/
@SuppressWarnings("unchecked")
public static FloatsMap mapToFloatMap(Map<String, Float> htCounts, boolean bOrdered) {
Set<Entry<String, Float>> setCnts = htCounts.entrySet();
Entry<String, Float>[] esa = new Entry[setCnts.size()];
esa = setCnts.toArray(esa);
// Sort if needed
if ( bOrdered ) {
Arrays.sort(esa, new Comparator<Entry<String,Float>>(){
public int compare(Entry<String, Float> o1,Entry<String, Float> o2) {
return (int) (o2.getValue()-o1.getValue());
}} );
}
org.seasr.datatypes.core.BasicDataTypes.FloatsMap.Builder res = BasicDataTypes.FloatsMap.newBuilder();
for ( Entry<String, Float> entry:esa ) {
res.addKey(entry.getKey());
res.addValue(BasicDataTypes.Floats.newBuilder().addValue(entry.getValue()));
}
return res.build();
}
/**
* Converts a protocol buffer string float map to the equivalent java map
*
* @param im The float map to convert
* @return The converted map
*/
public static Map<String,Float> FloatMapToMap ( FloatsMap im ) {
Hashtable<String,Float> ht = new Hashtable<String,Float>(im.getValueCount());
for ( int i=0,iMax=im.getValueCount() ; i<iMax ; i++ )
ht.put(im.getKey(i), im.getValue(i).getValue(0));
return ht;
}
/**
* Builds the doubles map and sorts it if needed.
*
* @param htDoubles The token values as doubles
* @param bOrdered Should the values be ordered?
* @return The DoublesMap
*/
@SuppressWarnings("unchecked")
public static DoublesMap mapToDoubleMap(Map<String, Double> htDoubles, boolean bOrdered) {
Set<Entry<String,Double>> setCnts = htDoubles.entrySet();
Entry<String, Double>[] esa = new Entry[setCnts.size()];
esa = setCnts.toArray(esa);
// Sort if needed
if ( bOrdered ) {
Arrays.sort(esa, new Comparator<Entry<String,Double>>(){
public int compare(Entry<String, Double> o1,Entry<String, Double> o2) {
return (int) (o2.getValue()-o1.getValue());
}} );
}
org.seasr.datatypes.core.BasicDataTypes.DoublesMap.Builder res = BasicDataTypes.DoublesMap.newBuilder();
for ( Entry<String, Double> entry:esa ) {
res.addKey(entry.getKey());
res.addValue(BasicDataTypes.Doubles.newBuilder().addValue(entry.getValue()));
}
return res.build();
}
/**
* Converts a protocol buffer string double map to the equivalent java map
*
* @param im The double map to convert
* @return The converted map
*/
public static Map<String,Double> DoubleMapToMap ( DoublesMap im ) {
Hashtable<String,Double> ht = new Hashtable<String,Double>(im.getValueCount());
for ( int i=0,iMax=im.getValueCount() ; i<iMax ; i++ )
ht.put(im.getKey(i), im.getValue(i).getValue(0));
return ht;
}
/**
* Builds a strings map
*
* @param htSentences The tokenized sentences
* @return The StringsMap
*/
public static StringsMap mapToStringMap(Map<String, String[]> htSentences) {
org.seasr.datatypes.core.BasicDataTypes.StringsMap.Builder res = BasicDataTypes.StringsMap.newBuilder();
for (Entry<String, String[]> entry : htSentences.entrySet()) {
res.addKey(entry.getKey());
res.addValue(stringToStrings(entry.getValue()));
}
return res.build();
}
/**
* Converts a protocol buffer string string map to the equivalent java map
*
* @param sm The string map to convert
* @return The converted map
*/
public static Map<String, String[]> StringMapToMap ( StringsMap sm ) {
Hashtable<String, String[]> ht = new Hashtable<String, String[]>(sm.getValueCount());
for ( int i = 0, iMax = sm.getValueCount(); i < iMax; i++ )
ht.put(sm.getKey(i), stringsToStringArray(sm.getValue(i)));
return ht;
}
/**
* Converts a protocol buffer Bytes to a byte array
*
* @param bytes The Bytes object to convert
* @return The byte array
*/
public static byte[] bytestoByteArray(Bytes bytes) {
ByteString bs = bytes.getValue(0);
byte[] barr = new byte[bs.size()];
bs.copyTo(barr, 0);
return barr;
}
/**
* Converts a byte array to a protocol buffer Bytes object
*
* @param barr The byte array
* @return The Bytes object
*/
public static Bytes byteArrayToBytes(byte[] barr) {
org.seasr.datatypes.core.BasicDataTypes.Bytes.Builder res = BasicDataTypes.Bytes.newBuilder();
res.addValue(ByteString.copyFrom(barr));
return res.build();
}
/**
* Converts a protocol buffer string byte map to the equivalent java map
*
* @param bm The byte map to convert
* @return The converted map
*/
public static Map<String,byte[]> ByteMapToMap ( BytesMap bm ) {
Map<String,byte[]> ht = new Hashtable<String,byte[]>(bm.getValueCount());
for ( int i=0,iMax=bm.getValueCount() ; i<iMax ; i++ )
ht.put(bm.getKey(i), bytestoByteArray(bm.getValue(i)));
return ht;
}
/**
* Builds the byte map
*
* @param htCounts The token counts
* @param bOrdered Should the counts be ordered?
* @return The ByteMap
*/
public static BytesMap mapToByteMap(Map<String, byte[]> htBytes) {
org.seasr.datatypes.core.BasicDataTypes.BytesMap.Builder res = BasicDataTypes.BytesMap.newBuilder();
for ( Entry<String, byte[]> entry:htBytes.entrySet() ) {
res.addKey(entry.getKey());
res.addValue(byteArrayToBytes(entry.getValue()));
}
return res.build();
}
}
| true | true | public static Map<String,Number> NumberMapToMap ( Object im ) throws UnsupportedDataTypeException {
NumberTypes type;
int size;
if (im instanceof IntegersMap) {
type = NumberTypes.INTEGER;
size = ((IntegersMap)im).getKeyCount();
} else
if (im instanceof LongsMap) {
type = NumberTypes.LONG;
size = ((LongsMap)im).getKeyCount();
} else
if (im instanceof FloatsMap) {
type = NumberTypes.FLOAT;
size = ((FloatsMap)im).getKeyCount();
} else
if (im instanceof DoublesMap) {
type = NumberTypes.DOUBLE ;
size = ((DoublesMap)im).getKeyCount();
} else
throw new UnsupportedDataTypeException(im.getClass().getName());
Hashtable<String,Number> ht = new Hashtable<String,Number>(size);
for ( int i=0,iMax=size ; i<iMax ; i++ )
switch (type) {
case INTEGER: ht.put (((IntegersMap)im).getKey(i), (Number) ((IntegersMap)im).getValue(i).getValue(0));
case LONG: ht.put (((LongsMap)im).getKey(i), (Number) ((LongsMap)im).getValue(i).getValue(0));
case FLOAT: ht.put (((FloatsMap)im).getKey(i), (Number) ((FloatsMap)im).getValue(i).getValue(0));
case DOUBLE: ht.put (((DoublesMap)im).getKey(i), (Number) ((DoublesMap)im).getValue(i).getValue(0));
}
return ht;
}
| public static Map<String,Number> NumberMapToMap ( Object im ) throws UnsupportedDataTypeException {
NumberTypes type;
int size;
if (im instanceof IntegersMap) {
type = NumberTypes.INTEGER;
size = ((IntegersMap)im).getKeyCount();
} else
if (im instanceof LongsMap) {
type = NumberTypes.LONG;
size = ((LongsMap)im).getKeyCount();
} else
if (im instanceof FloatsMap) {
type = NumberTypes.FLOAT;
size = ((FloatsMap)im).getKeyCount();
} else
if (im instanceof DoublesMap) {
type = NumberTypes.DOUBLE ;
size = ((DoublesMap)im).getKeyCount();
} else
throw new UnsupportedDataTypeException(im.getClass().getName());
Hashtable<String,Number> ht = new Hashtable<String,Number>(size);
for ( int i=0,iMax=size ; i<iMax ; i++ )
switch (type) {
case INTEGER: ht.put (((IntegersMap)im).getKey(i), (Number) ((IntegersMap)im).getValue(i).getValue(0)); break;
case LONG: ht.put (((LongsMap)im).getKey(i), (Number) ((LongsMap)im).getValue(i).getValue(0)); break;
case FLOAT: ht.put (((FloatsMap)im).getKey(i), (Number) ((FloatsMap)im).getValue(i).getValue(0)); break;
case DOUBLE: ht.put (((DoublesMap)im).getKey(i), (Number) ((DoublesMap)im).getValue(i).getValue(0)); break;
}
return ht;
}
|
diff --git a/src/DerpyAI/Driver.java b/src/DerpyAI/Driver.java
index f0939f3..0448bb6 100644
--- a/src/DerpyAI/Driver.java
+++ b/src/DerpyAI/Driver.java
@@ -1,20 +1,19 @@
package DerpyAI;
public class Driver {
public static void main(String[] args) {
// October 22, 2012 - Makes 20 random moves and prints the board each
// time. Pieces should be functional at this point.
DerpyBoard db = new DerpyBoard();
DerpyAI aiOne = new DerpyAI(true);
DerpyAI aiTwo = new DerpyAI(false);
for (int i = 0; i < 20; i++) {
db = aiOne.makeMove(db);
- db = aiTwo.makeMove(db);
System.out.println();
}
}
}
| true | true | public static void main(String[] args) {
// October 22, 2012 - Makes 20 random moves and prints the board each
// time. Pieces should be functional at this point.
DerpyBoard db = new DerpyBoard();
DerpyAI aiOne = new DerpyAI(true);
DerpyAI aiTwo = new DerpyAI(false);
for (int i = 0; i < 20; i++) {
db = aiOne.makeMove(db);
db = aiTwo.makeMove(db);
System.out.println();
}
}
| public static void main(String[] args) {
// October 22, 2012 - Makes 20 random moves and prints the board each
// time. Pieces should be functional at this point.
DerpyBoard db = new DerpyBoard();
DerpyAI aiOne = new DerpyAI(true);
DerpyAI aiTwo = new DerpyAI(false);
for (int i = 0; i < 20; i++) {
db = aiOne.makeMove(db);
System.out.println();
}
}
|
diff --git a/src/main/java/nu/wasis/stunden/plugins/StundenSTDOutPlugin.java b/src/main/java/nu/wasis/stunden/plugins/StundenSTDOutPlugin.java
index d5bbaa0..a0383b8 100644
--- a/src/main/java/nu/wasis/stunden/plugins/StundenSTDOutPlugin.java
+++ b/src/main/java/nu/wasis/stunden/plugins/StundenSTDOutPlugin.java
@@ -1,79 +1,78 @@
package nu.wasis.stunden.plugins;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import nu.wasis.stunden.model.Day;
import nu.wasis.stunden.model.Entry;
import nu.wasis.stunden.model.WorkPeriod;
import nu.wasis.stunden.plugin.OutputPlugin;
import nu.wasis.stunden.plugins.stdout.config.StundenSTDOutPluginConfig;
import nu.wasis.stunden.util.DateUtils;
import org.joda.time.Duration;
import org.joda.time.Interval;
@PluginImplementation
public class StundenSTDOutPlugin implements OutputPlugin {
// private static final Logger LOG = Logger.getLogger(StundenSTDOutPlugin.class);
private static final void p(final String message) {
System.out.println(message);
}
@Override
public void output(final WorkPeriod workPeriod, final Object config) {
List<String> noWork = null;
if (null != config) {
final StundenSTDOutPluginConfig myConfig = (StundenSTDOutPluginConfig) config;
noWork = myConfig.getNoWork();
}
p("Start of period\t: " + workPeriod.getBegin().toString(DateUtils.DATE_FORMATTER));
p("End of period\t: " + workPeriod.getEnd().toString(DateUtils.DATE_FORMATTER));
p("============================");
if (workPeriod.getDays().isEmpty()) {
p("[Period contains no entries.]");
return;
}
for (final Day day : workPeriod.getDays()) {
p("");
p(day.getDate().toString(DateUtils.DATE_FORMATTER));
p("==========");
final Map<String, Duration> durations = new HashMap<>();
Duration totalDuration = null;
for (final Entry entry : day.getEntries()) {
- p(entry.getBegin().toString(DateUtils.TIME_FORMATTER) + " - " + entry.getEnd().toString(DateUtils.TIME_FORMATTER) + ": "
- + entry.getProject().getName());
+ p(entry.getBegin().toString(DateUtils.TIME_FORMATTER) + " - " + entry.getEnd().toString(DateUtils.TIME_FORMATTER) + ": " + entry.getProject().getName());
final Duration newDuration = new Interval(entry.getBegin(), entry.getEnd()).toDuration();
if (null == totalDuration) {
totalDuration = new Duration(newDuration);
} else {
if (!noWork.contains(entry.getProject().getName())) {
totalDuration = totalDuration.plus(newDuration);
}
}
if (!durations.containsKey(entry.getProject().getName())) {
durations.put(entry.getProject().getName(), newDuration);
} else {
final Duration originalPeriod = durations.get(entry.getProject().getName());
durations.put(entry.getProject().getName(), originalPeriod.plus(newDuration));
}
}
p("Summary:");
for (final Map.Entry<String, Duration> entry : durations.entrySet()) {
p("\t" + entry.getKey() + ": " + entry.getValue().toPeriod().toString(DateUtils.PERIOD_FORMATTER));
}
p("\tTotal: " + totalDuration.toPeriod().normalizedStandard().toString(DateUtils.PERIOD_FORMATTER));
}
}
@Override
public Class<StundenSTDOutPluginConfig> getConfigurationClass() {
return StundenSTDOutPluginConfig.class;
}
}
| true | true | public void output(final WorkPeriod workPeriod, final Object config) {
List<String> noWork = null;
if (null != config) {
final StundenSTDOutPluginConfig myConfig = (StundenSTDOutPluginConfig) config;
noWork = myConfig.getNoWork();
}
p("Start of period\t: " + workPeriod.getBegin().toString(DateUtils.DATE_FORMATTER));
p("End of period\t: " + workPeriod.getEnd().toString(DateUtils.DATE_FORMATTER));
p("============================");
if (workPeriod.getDays().isEmpty()) {
p("[Period contains no entries.]");
return;
}
for (final Day day : workPeriod.getDays()) {
p("");
p(day.getDate().toString(DateUtils.DATE_FORMATTER));
p("==========");
final Map<String, Duration> durations = new HashMap<>();
Duration totalDuration = null;
for (final Entry entry : day.getEntries()) {
p(entry.getBegin().toString(DateUtils.TIME_FORMATTER) + " - " + entry.getEnd().toString(DateUtils.TIME_FORMATTER) + ": "
+ entry.getProject().getName());
final Duration newDuration = new Interval(entry.getBegin(), entry.getEnd()).toDuration();
if (null == totalDuration) {
totalDuration = new Duration(newDuration);
} else {
if (!noWork.contains(entry.getProject().getName())) {
totalDuration = totalDuration.plus(newDuration);
}
}
if (!durations.containsKey(entry.getProject().getName())) {
durations.put(entry.getProject().getName(), newDuration);
} else {
final Duration originalPeriod = durations.get(entry.getProject().getName());
durations.put(entry.getProject().getName(), originalPeriod.plus(newDuration));
}
}
p("Summary:");
for (final Map.Entry<String, Duration> entry : durations.entrySet()) {
p("\t" + entry.getKey() + ": " + entry.getValue().toPeriod().toString(DateUtils.PERIOD_FORMATTER));
}
p("\tTotal: " + totalDuration.toPeriod().normalizedStandard().toString(DateUtils.PERIOD_FORMATTER));
}
}
| public void output(final WorkPeriod workPeriod, final Object config) {
List<String> noWork = null;
if (null != config) {
final StundenSTDOutPluginConfig myConfig = (StundenSTDOutPluginConfig) config;
noWork = myConfig.getNoWork();
}
p("Start of period\t: " + workPeriod.getBegin().toString(DateUtils.DATE_FORMATTER));
p("End of period\t: " + workPeriod.getEnd().toString(DateUtils.DATE_FORMATTER));
p("============================");
if (workPeriod.getDays().isEmpty()) {
p("[Period contains no entries.]");
return;
}
for (final Day day : workPeriod.getDays()) {
p("");
p(day.getDate().toString(DateUtils.DATE_FORMATTER));
p("==========");
final Map<String, Duration> durations = new HashMap<>();
Duration totalDuration = null;
for (final Entry entry : day.getEntries()) {
p(entry.getBegin().toString(DateUtils.TIME_FORMATTER) + " - " + entry.getEnd().toString(DateUtils.TIME_FORMATTER) + ": " + entry.getProject().getName());
final Duration newDuration = new Interval(entry.getBegin(), entry.getEnd()).toDuration();
if (null == totalDuration) {
totalDuration = new Duration(newDuration);
} else {
if (!noWork.contains(entry.getProject().getName())) {
totalDuration = totalDuration.plus(newDuration);
}
}
if (!durations.containsKey(entry.getProject().getName())) {
durations.put(entry.getProject().getName(), newDuration);
} else {
final Duration originalPeriod = durations.get(entry.getProject().getName());
durations.put(entry.getProject().getName(), originalPeriod.plus(newDuration));
}
}
p("Summary:");
for (final Map.Entry<String, Duration> entry : durations.entrySet()) {
p("\t" + entry.getKey() + ": " + entry.getValue().toPeriod().toString(DateUtils.PERIOD_FORMATTER));
}
p("\tTotal: " + totalDuration.toPeriod().normalizedStandard().toString(DateUtils.PERIOD_FORMATTER));
}
}
|
diff --git a/examples/WebImageList/src/com/wrapp/android/webimagelist/WebImageListAdapter.java b/examples/WebImageList/src/com/wrapp/android/webimagelist/WebImageListAdapter.java
index 80efc3e..5be2eae 100644
--- a/examples/WebImageList/src/com/wrapp/android/webimagelist/WebImageListAdapter.java
+++ b/examples/WebImageList/src/com/wrapp/android/webimagelist/WebImageListAdapter.java
@@ -1,107 +1,107 @@
/*
* Copyright (c) 2011 Bohemian Wrappsody AB
*
* 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.wrapp.android.webimagelist;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.wrapp.android.webimage.WebImageView;
public class WebImageListAdapter extends BaseAdapter {
private static final boolean USE_NUMBER_IMAGES = true;
private static final boolean USE_AWESOME_IMAGES = true;
private static final int NUM_IMAGES = 100;
private static final int IMAGE_SIZE = 100;
private WebImageView.Listener listener;
private boolean shouldCacheImagesInMemory = true;
private boolean shouldRestrictMemoryUsage = false;
private static BitmapFactory.Options options = new BitmapFactory.Options();
public WebImageListAdapter(WebImageView.Listener listener) {
this.listener = listener;
}
public int getCount() {
return NUM_IMAGES;
}
private String getImageUrl(int i) {
if(USE_NUMBER_IMAGES) {
// Numbers with random backgrounds. More useful for testing correct listview behavior
- return "http://c539576.r76.cf2.rackcdn.com/numbers/" + i + ".png";
+ return "http://static.nikreiman.com/numbers/" + i + ".png";
}
else {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
}
public Object getItem(int i) {
return getImageUrl(i);
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View convertView, ViewGroup parentViewGroup) {
WebImageContainerView containerView;
if(convertView != null) {
containerView = (WebImageContainerView)convertView;
}
else {
containerView = new WebImageContainerView(parentViewGroup.getContext());
}
containerView.setImageUrl(getImageUrl(i), listener, shouldCacheImagesInMemory, options);
containerView.setImageText("Image #" + i);
return containerView;
}
public boolean getShouldCacheImagesInMemory() {
return shouldCacheImagesInMemory;
}
public void setShouldCacheImagesInMemory(boolean shouldCacheImagesInMemory) {
this.shouldCacheImagesInMemory = shouldCacheImagesInMemory;
}
public boolean getShouldRestrictMemoryUsage() {
return shouldRestrictMemoryUsage;
}
public void setShouldRestrictMemoryUsage(boolean shouldRestrictMemoryUsage) {
this.shouldRestrictMemoryUsage = shouldRestrictMemoryUsage;
options.inInputShareable = shouldRestrictMemoryUsage;
options.inPurgeable = shouldRestrictMemoryUsage;
options.inSampleSize = shouldRestrictMemoryUsage ? 2 : 1;
options.inDither = shouldRestrictMemoryUsage;
}
}
| true | true | private String getImageUrl(int i) {
if(USE_NUMBER_IMAGES) {
// Numbers with random backgrounds. More useful for testing correct listview behavior
return "http://c539576.r76.cf2.rackcdn.com/numbers/" + i + ".png";
}
else {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
}
| private String getImageUrl(int i) {
if(USE_NUMBER_IMAGES) {
// Numbers with random backgrounds. More useful for testing correct listview behavior
return "http://static.nikreiman.com/numbers/" + i + ".png";
}
else {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
}
|
diff --git a/src/main/java/org/atlasapi/media/entity/Described.java b/src/main/java/org/atlasapi/media/entity/Described.java
index 0cc9d059..ecbbd42c 100644
--- a/src/main/java/org/atlasapi/media/entity/Described.java
+++ b/src/main/java/org/atlasapi/media/entity/Described.java
@@ -1,283 +1,286 @@
/* Copyright 2010 Meta Broadcast Ltd
Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License. */
package org.atlasapi.media.entity;
import java.util.Set;
import org.atlasapi.content.rdf.annotations.RdfProperty;
import org.atlasapi.media.channel.Channel;
import org.atlasapi.media.vocabulary.DC;
import org.atlasapi.media.vocabulary.PLAY_USE_IN_RDF_FOR_BACKWARD_COMPATIBILITY;
import org.atlasapi.media.vocabulary.PO;
import org.joda.time.DateTime;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.metabroadcast.common.text.MoreStrings;
public abstract class Described extends Identified {
private String title;
private String shortDescription;
private String mediumDescription;
private String longDescription;
private String description;
private MediaType mediaType = MediaType.VIDEO;
private Specialization specialization;
private ImmutableSet<String> genres = ImmutableSet.of();
private Set<String> tags = Sets.newHashSet();
protected Publisher publisher;
private String image;
private Set<Image> images;
private String thumbnail;
private DateTime firstSeen;
private DateTime lastFetched;
private DateTime thisOrChildLastUpdated;
private boolean scheduleOnly = false;
private boolean activelyPublished = true;
private String presentationChannel;
protected Set<RelatedLink> relatedLinks = ImmutableSet.of();
public Described(String uri, String curie, Publisher publisher) {
super(uri, curie);
this.publisher = publisher;
}
public Described(String uri, String curie) {
this(uri, curie, null);
}
public Described(String uri) {
super(uri);
}
public Described() { /* some legacy code still requires a default constructor */ }
public DateTime getLastFetched() {
return lastFetched;
}
public void setLastFetched(DateTime lastFetched) {
this.lastFetched = lastFetched;
}
public DateTime getFirstSeen() {
return this.firstSeen;
}
public void setFirstSeen(DateTime firstSeen) {
this.firstSeen = firstSeen;
}
public void setGenres(Iterable<String> genres) {
this.genres = ImmutableSet.copyOf(genres);
}
@RdfProperty(relation = true, namespace=PO.NS, uri = "genre")
public Set<String> getGenres() {
return this.genres;
}
public void setTitle(String title) {
this.title = title;
}
@RdfProperty(namespace = DC.NS)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
@RdfProperty(namespace = DC.NS)
public String getShortDescription() {
return this.shortDescription;
}
@RdfProperty(namespace = DC.NS)
public String getMediumDescription() {
return this.mediumDescription;
}
@RdfProperty(namespace = DC.NS)
public String getLongDescription() {
return this.longDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public void setMediumDescription(String mediumDescription) {
this.mediumDescription = mediumDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
public Set<String> getTags() {
return tags;
}
public void setTags(Set<String> tags) {
if (tags != null && ! tags.isEmpty()) {
this.tags = Sets.newHashSet(Iterables.transform(tags, MoreStrings.TO_LOWER));
} else {
this.tags = tags;
}
}
@RdfProperty(namespace = DC.NS)
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
@RdfProperty(namespace = PLAY_USE_IN_RDF_FOR_BACKWARD_COMPATIBILITY.NS)
public String getImage() {
return image;
}
@RdfProperty(namespace = PLAY_USE_IN_RDF_FOR_BACKWARD_COMPATIBILITY.NS)
public String getThumbnail() {
return thumbnail;
}
public void setImage(String image) {
this.image = image;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
@RdfProperty(namespace = DC.NS)
public String getTitle() {
return this.title;
}
public DateTime getThisOrChildLastUpdated() {
return thisOrChildLastUpdated;
}
public void setThisOrChildLastUpdated(DateTime thisOrChildLastUpdated) {
this.thisOrChildLastUpdated = thisOrChildLastUpdated;
}
public boolean isActivelyPublished() {
return activelyPublished;
}
public void setActivelyPublished(boolean activelyPublished) {
this.activelyPublished = activelyPublished;
}
public void setMediaType(MediaType mediaType) {
this.mediaType = mediaType;
}
public MediaType getMediaType() {
return this.mediaType;
}
public Specialization getSpecialization() {
return specialization;
}
public void setSpecialization(Specialization specialization) {
this.specialization = specialization;
}
public void setScheduleOnly(boolean scheduleOnly) {
this.scheduleOnly = scheduleOnly;
}
public boolean isScheduleOnly() {
return scheduleOnly;
}
public void setPresentationChannel(Channel channel) {
setPresentationChannel(channel.getKey());
}
public void setPresentationChannel(String channel) {
this.presentationChannel = channel;
}
public String getPresentationChannel() {
return this.presentationChannel;
}
public void setImages(Iterable<Image> images) {
this.images = ImmutableSet.copyOf(images);
}
public Set<Image> getImages() {
return images;
}
public Image getPrimaryImage() {
return Iterables.getOnlyElement(Iterables.filter(images, Image.IS_PRIMARY), null);
}
public Set<RelatedLink> getRelatedLinks() {
return relatedLinks;
}
public void setRelatedLinks(Iterable<RelatedLink> links) {
relatedLinks = ImmutableSet.copyOf(links);
}
public void addRelatedLink(RelatedLink link) {
relatedLinks = ImmutableSet.<RelatedLink>builder().add(link).addAll(relatedLinks).build();
}
public static void copyTo(Described from, Described to) {
Identified.copyTo(from, to);
to.description = from.description;
to.firstSeen = from.firstSeen;
to.genres = ImmutableSet.copyOf(from.genres);
to.image = from.image;
to.lastFetched = from.lastFetched;
to.mediaType = from.mediaType;
to.publisher = from.publisher;
to.specialization = from.specialization;
to.tags = Sets.newHashSet(from.tags);
to.thisOrChildLastUpdated = from.thisOrChildLastUpdated;
to.thumbnail = from.thumbnail;
to.title = from.title;
to.scheduleOnly = from.scheduleOnly;
to.presentationChannel = from.presentationChannel;
to.images = from.images;
+ to.shortDescription = from.shortDescription;
+ to.mediumDescription = from.mediumDescription;
+ to.longDescription = from.longDescription;
}
public abstract Described copy();
}
| true | true | public static void copyTo(Described from, Described to) {
Identified.copyTo(from, to);
to.description = from.description;
to.firstSeen = from.firstSeen;
to.genres = ImmutableSet.copyOf(from.genres);
to.image = from.image;
to.lastFetched = from.lastFetched;
to.mediaType = from.mediaType;
to.publisher = from.publisher;
to.specialization = from.specialization;
to.tags = Sets.newHashSet(from.tags);
to.thisOrChildLastUpdated = from.thisOrChildLastUpdated;
to.thumbnail = from.thumbnail;
to.title = from.title;
to.scheduleOnly = from.scheduleOnly;
to.presentationChannel = from.presentationChannel;
to.images = from.images;
}
| public static void copyTo(Described from, Described to) {
Identified.copyTo(from, to);
to.description = from.description;
to.firstSeen = from.firstSeen;
to.genres = ImmutableSet.copyOf(from.genres);
to.image = from.image;
to.lastFetched = from.lastFetched;
to.mediaType = from.mediaType;
to.publisher = from.publisher;
to.specialization = from.specialization;
to.tags = Sets.newHashSet(from.tags);
to.thisOrChildLastUpdated = from.thisOrChildLastUpdated;
to.thumbnail = from.thumbnail;
to.title = from.title;
to.scheduleOnly = from.scheduleOnly;
to.presentationChannel = from.presentationChannel;
to.images = from.images;
to.shortDescription = from.shortDescription;
to.mediumDescription = from.mediumDescription;
to.longDescription = from.longDescription;
}
|
diff --git a/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java b/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java
index 4d9c87dc6..992e35223 100644
--- a/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java
+++ b/luni/src/test/java/libcore/java/text/DateFormatSymbolsTest.java
@@ -1,144 +1,145 @@
/*
* 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 libcore.java.text;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
public class DateFormatSymbolsTest extends junit.framework.TestCase {
private void assertLocaleIsEquivalentToRoot(Locale locale) {
DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale);
assertEquals(DateFormatSymbols.getInstance(Locale.ROOT), dfs);
}
/** http://b/3056586 */
public void test_getInstance_unknown_locale() throws Exception {
// TODO: we fail this test. on Android, the root locale uses GMT offsets as names.
// see the invalid locale test below. on the RI, the root locale uses English names.
assertLocaleIsEquivalentToRoot(new Locale("xx", "XX"));
}
public void test_getInstance_invalid_locale() throws Exception {
assertLocaleIsEquivalentToRoot(new Locale("not exist language", "not exist country"));
}
public void testSerialization() throws Exception {
// The Polish language needs stand-alone month and weekday names.
Locale pl = new Locale("pl");
DateFormatSymbols originalDfs = new DateFormatSymbols(pl);
// Serialize...
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(originalDfs);
byte[] bytes = out.toByteArray();
// Deserialize...
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
DateFormatSymbols deserializedDfs = (DateFormatSymbols) in.readObject();
assertEquals(-1, in.read());
// The two objects should claim to be equal, even though they aren't really.
assertEquals(originalDfs, deserializedDfs);
// The original differentiates between regular month names and stand-alone month names...
assertEquals("stycznia", formatDate(pl, "MMMM", originalDfs));
assertEquals("stycze\u0144", formatDate(pl, "LLLL", originalDfs));
- // Whereas the deserialized object can't, because it lost the strings...
+ // But the deserialized object is screwed because the RI's serialized form doesn't
+ // contain the locale or the necessary strings. Don't serialize DateFormatSymbols, folks!
assertEquals("stycznia", formatDate(pl, "MMMM", deserializedDfs));
- assertEquals("stycznia", formatDate(pl, "LLLL", deserializedDfs));
+ assertEquals("January", formatDate(pl, "LLLL", deserializedDfs));
}
private String formatDate(Locale l, String fmt, DateFormatSymbols dfs) {
SimpleDateFormat sdf = new SimpleDateFormat(fmt, l);
sdf.setDateFormatSymbols(dfs);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(new Date(0));
}
public void test_getZoneStrings_cloning() throws Exception {
// Check that corrupting our array doesn't affect other callers.
// Kill a row.
{
String[][] originalZoneStrings = DateFormatSymbols.getInstance(Locale.US).getZoneStrings();
assertNotNull(originalZoneStrings[0]);
originalZoneStrings[0] = null;
String[][] currentZoneStrings = DateFormatSymbols.getInstance(Locale.US).getZoneStrings();
assertNotNull(currentZoneStrings[0]);
}
// Kill an element.
{
String[][] originalZoneStrings = DateFormatSymbols.getInstance(Locale.US).getZoneStrings();
assertNotNull(originalZoneStrings[0][0]);
originalZoneStrings[0][0] = null;
String[][] currentZoneStrings = DateFormatSymbols.getInstance(Locale.US).getZoneStrings();
assertNotNull(currentZoneStrings[0][0]);
}
}
public void test_getZoneStrings_UTC() throws Exception {
HashMap<String, String[]> zoneStrings = new HashMap<String, String[]>();
for (String[] row : DateFormatSymbols.getInstance(Locale.US).getZoneStrings()) {
zoneStrings.put(row[0], row);
}
assertUtc(zoneStrings.get("Etc/UCT"));
assertUtc(zoneStrings.get("Etc/UTC"));
assertUtc(zoneStrings.get("Etc/Universal"));
assertUtc(zoneStrings.get("Etc/Zulu"));
assertUtc(zoneStrings.get("UCT"));
assertUtc(zoneStrings.get("UTC"));
assertUtc(zoneStrings.get("Universal"));
assertUtc(zoneStrings.get("Zulu"));
}
private static void assertUtc(String[] row) {
// Element 0 is the Olson id. The short names should be "UTC".
// On the RI, the long names are localized. ICU doesn't have those, so we just use UTC.
assertEquals(Arrays.toString(row), "UTC", row[2]);
assertEquals(Arrays.toString(row), "UTC", row[4]);
}
// http://b/8128460
// If icu4c doesn't actually have a name, we arrange to return null from native code rather
// that use icu4c's probably-out-of-date time zone transition data.
// getZoneStrings has to paper over this.
public void test_getZoneStrings_no_nulls() throws Exception {
String[][] array = DateFormatSymbols.getInstance(Locale.US).getZoneStrings();
int failCount = 0;
for (String[] row : array) {
for (String element : row) {
if (element == null) {
System.err.println(Arrays.toString(row));
++failCount;
}
}
}
assertEquals(0, failCount);
}
}
| false | true | public void testSerialization() throws Exception {
// The Polish language needs stand-alone month and weekday names.
Locale pl = new Locale("pl");
DateFormatSymbols originalDfs = new DateFormatSymbols(pl);
// Serialize...
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(originalDfs);
byte[] bytes = out.toByteArray();
// Deserialize...
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
DateFormatSymbols deserializedDfs = (DateFormatSymbols) in.readObject();
assertEquals(-1, in.read());
// The two objects should claim to be equal, even though they aren't really.
assertEquals(originalDfs, deserializedDfs);
// The original differentiates between regular month names and stand-alone month names...
assertEquals("stycznia", formatDate(pl, "MMMM", originalDfs));
assertEquals("stycze\u0144", formatDate(pl, "LLLL", originalDfs));
// Whereas the deserialized object can't, because it lost the strings...
assertEquals("stycznia", formatDate(pl, "MMMM", deserializedDfs));
assertEquals("stycznia", formatDate(pl, "LLLL", deserializedDfs));
}
| public void testSerialization() throws Exception {
// The Polish language needs stand-alone month and weekday names.
Locale pl = new Locale("pl");
DateFormatSymbols originalDfs = new DateFormatSymbols(pl);
// Serialize...
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(originalDfs);
byte[] bytes = out.toByteArray();
// Deserialize...
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
DateFormatSymbols deserializedDfs = (DateFormatSymbols) in.readObject();
assertEquals(-1, in.read());
// The two objects should claim to be equal, even though they aren't really.
assertEquals(originalDfs, deserializedDfs);
// The original differentiates between regular month names and stand-alone month names...
assertEquals("stycznia", formatDate(pl, "MMMM", originalDfs));
assertEquals("stycze\u0144", formatDate(pl, "LLLL", originalDfs));
// But the deserialized object is screwed because the RI's serialized form doesn't
// contain the locale or the necessary strings. Don't serialize DateFormatSymbols, folks!
assertEquals("stycznia", formatDate(pl, "MMMM", deserializedDfs));
assertEquals("January", formatDate(pl, "LLLL", deserializedDfs));
}
|
diff --git a/project-set/extensions/api-validator/src/main/java/org/openrepose/components/apivalidator/filter/ApiValidatorFilter.java b/project-set/extensions/api-validator/src/main/java/org/openrepose/components/apivalidator/filter/ApiValidatorFilter.java
index 2e438ad155..020cdda933 100644
--- a/project-set/extensions/api-validator/src/main/java/org/openrepose/components/apivalidator/filter/ApiValidatorFilter.java
+++ b/project-set/extensions/api-validator/src/main/java/org/openrepose/components/apivalidator/filter/ApiValidatorFilter.java
@@ -1,61 +1,57 @@
package org.openrepose.components.apivalidator.filter;
import com.rackspace.papi.filter.FilterConfigHelper;
import com.rackspace.papi.filter.logic.impl.FilterLogicHandlerDelegate;
import com.rackspace.papi.service.config.ConfigurationService;
import com.rackspace.papi.service.context.ServletContextHelper;
import com.rackspace.papi.servlet.InitParameter;
import org.openrepose.components.apivalidator.servlet.config.BaseValidatorConfiguration;
import org.openrepose.components.apivalidator.servlet.config.ValidatorConfiguration1;
import org.openrepose.components.apivalidator.servlet.config.ValidatorConfiguration2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import java.io.IOException;
import java.net.URL;
public class ApiValidatorFilter implements Filter {
private static final Logger LOG = LoggerFactory.getLogger(ApiValidatorFilter.class);
private static final String DEFAULT_CONFIG = "validator.cfg.xml";
private String config;
private ApiValidatorHandlerFactory handlerFactory;
private ConfigurationService configurationManager;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
ApiValidatorHandler handler = handlerFactory.newHandler();
if (handler == null) {
throw new ServletException("Unable to build validator handler");
}
handler.setFilterChain(chain);
new FilterLogicHandlerDelegate(request, response, chain).doFilter(handler);
}
@Override
public void destroy() {
configurationManager.unsubscribeFrom(config, handlerFactory);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
final String configProp = InitParameter.POWER_API_CONFIG_DIR.getParameterName();
final ServletContext ctx = filterConfig.getServletContext();
final String configurationRoot = System.getProperty(configProp, ctx.getInitParameter(configProp));
configurationManager = ServletContextHelper.getInstance(filterConfig.getServletContext()).getPowerApiContext()
.configurationService();
config = new FilterConfigHelper(filterConfig).getFilterConfig(DEFAULT_CONFIG);
LOG.info("Initializing filter using config " + config);
handlerFactory = new ApiValidatorHandlerFactory(configurationManager, configurationRoot, config);
URL xsdURL = getClass().getResource("/META-INF/schema/config/validator-configuration.xsd");
configurationManager.subscribeTo(filterConfig.getFilterName(), config, xsdURL, handlerFactory,
- BaseValidatorConfiguration.class);
- configurationManager.subscribeTo(filterConfig.getFilterName(), config, xsdURL, handlerFactory,
- ValidatorConfiguration1.class);
- configurationManager.subscribeTo(filterConfig.getFilterName(), config, xsdURL, handlerFactory,
- ValidatorConfiguration2.class);
+ BaseValidatorConfiguration.class);
}
}
| true | true | public void init(FilterConfig filterConfig) throws ServletException {
final String configProp = InitParameter.POWER_API_CONFIG_DIR.getParameterName();
final ServletContext ctx = filterConfig.getServletContext();
final String configurationRoot = System.getProperty(configProp, ctx.getInitParameter(configProp));
configurationManager = ServletContextHelper.getInstance(filterConfig.getServletContext()).getPowerApiContext()
.configurationService();
config = new FilterConfigHelper(filterConfig).getFilterConfig(DEFAULT_CONFIG);
LOG.info("Initializing filter using config " + config);
handlerFactory = new ApiValidatorHandlerFactory(configurationManager, configurationRoot, config);
URL xsdURL = getClass().getResource("/META-INF/schema/config/validator-configuration.xsd");
configurationManager.subscribeTo(filterConfig.getFilterName(), config, xsdURL, handlerFactory,
BaseValidatorConfiguration.class);
configurationManager.subscribeTo(filterConfig.getFilterName(), config, xsdURL, handlerFactory,
ValidatorConfiguration1.class);
configurationManager.subscribeTo(filterConfig.getFilterName(), config, xsdURL, handlerFactory,
ValidatorConfiguration2.class);
}
| public void init(FilterConfig filterConfig) throws ServletException {
final String configProp = InitParameter.POWER_API_CONFIG_DIR.getParameterName();
final ServletContext ctx = filterConfig.getServletContext();
final String configurationRoot = System.getProperty(configProp, ctx.getInitParameter(configProp));
configurationManager = ServletContextHelper.getInstance(filterConfig.getServletContext()).getPowerApiContext()
.configurationService();
config = new FilterConfigHelper(filterConfig).getFilterConfig(DEFAULT_CONFIG);
LOG.info("Initializing filter using config " + config);
handlerFactory = new ApiValidatorHandlerFactory(configurationManager, configurationRoot, config);
URL xsdURL = getClass().getResource("/META-INF/schema/config/validator-configuration.xsd");
configurationManager.subscribeTo(filterConfig.getFilterName(), config, xsdURL, handlerFactory,
BaseValidatorConfiguration.class);
}
|
diff --git a/src/test/java/npanday/its/NPandayIT0012VBWebAppTest.java b/src/test/java/npanday/its/NPandayIT0012VBWebAppTest.java
index dd383eb..1f51734 100644
--- a/src/test/java/npanday/its/NPandayIT0012VBWebAppTest.java
+++ b/src/test/java/npanday/its/NPandayIT0012VBWebAppTest.java
@@ -1,61 +1,61 @@
package npanday.its;
/*
* Copyright 2009
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.maven.it.Verifier;
import org.apache.maven.it.util.ResourceExtractor;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipFile;
public class NPandayIT0012VBWebAppTest
extends AbstractNPandayIntegrationTestCase
{
public NPandayIT0012VBWebAppTest()
{
super( "[1.2,)" );
}
public void testWebAppInstall()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/NPandayIT0012VBWebAppTest" );
Verifier verifier = getVerifier( testDir );
verifier.executeGoal( "install" );
File zipFile = new File( testDir, getAssemblyFile( "VBWebAppTest", "1.0.0", "zip" ) );
verifier.assertFilePresent( zipFile.getAbsolutePath() );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
List<String> expectedEntries = Arrays.asList( "bin/VBWebAppTest.dll", "Default.aspx",
"My Project/Application.myapp", "My Project/Resources.resx",
"My Project/Settings.settings", "Web.config" );
assertZipEntries( zipFile, expectedEntries );
- String assembly = new File( testDir, "target/bin/VBWebAppTest.dll" ).getAbsolutePath();
+ String assembly = new File( testDir, "target/VBWebAppTest/bin/VBWebAppTest.dll" ).getAbsolutePath();
assertResourcePresent( assembly, "VBWebAppTest.Resources.resources" );
assertClassPresent( assembly, "VBWebAppTest._Default" );
}
}
| true | true | public void testWebAppInstall()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/NPandayIT0012VBWebAppTest" );
Verifier verifier = getVerifier( testDir );
verifier.executeGoal( "install" );
File zipFile = new File( testDir, getAssemblyFile( "VBWebAppTest", "1.0.0", "zip" ) );
verifier.assertFilePresent( zipFile.getAbsolutePath() );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
List<String> expectedEntries = Arrays.asList( "bin/VBWebAppTest.dll", "Default.aspx",
"My Project/Application.myapp", "My Project/Resources.resx",
"My Project/Settings.settings", "Web.config" );
assertZipEntries( zipFile, expectedEntries );
String assembly = new File( testDir, "target/bin/VBWebAppTest.dll" ).getAbsolutePath();
assertResourcePresent( assembly, "VBWebAppTest.Resources.resources" );
assertClassPresent( assembly, "VBWebAppTest._Default" );
}
| public void testWebAppInstall()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/NPandayIT0012VBWebAppTest" );
Verifier verifier = getVerifier( testDir );
verifier.executeGoal( "install" );
File zipFile = new File( testDir, getAssemblyFile( "VBWebAppTest", "1.0.0", "zip" ) );
verifier.assertFilePresent( zipFile.getAbsolutePath() );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
List<String> expectedEntries = Arrays.asList( "bin/VBWebAppTest.dll", "Default.aspx",
"My Project/Application.myapp", "My Project/Resources.resx",
"My Project/Settings.settings", "Web.config" );
assertZipEntries( zipFile, expectedEntries );
String assembly = new File( testDir, "target/VBWebAppTest/bin/VBWebAppTest.dll" ).getAbsolutePath();
assertResourcePresent( assembly, "VBWebAppTest.Resources.resources" );
assertClassPresent( assembly, "VBWebAppTest._Default" );
}
|
diff --git a/enough-polish-j2me/source/src/de/enough/polish/ui/Container.java b/enough-polish-j2me/source/src/de/enough/polish/ui/Container.java
index a181bc0..7fc3e22 100644
--- a/enough-polish-j2me/source/src/de/enough/polish/ui/Container.java
+++ b/enough-polish-j2me/source/src/de/enough/polish/ui/Container.java
@@ -1,4751 +1,4756 @@
//#condition polish.usePolishGui
/*
* Created on 01-Mar-2004 at 09:45:32.
*
* Copyright (c) 2004-2005 Robert Virkus / Enough Software
*
* This file is part of J2ME Polish.
*
* J2ME Polish 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.
*
* J2ME Polish 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 J2ME Polish; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Commercial licenses are also available, please
* refer to the accompanying LICENSE.txt or visit
* http://www.j2mepolish.org for details.
*/
package de.enough.polish.ui;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import de.enough.polish.util.ArrayList;
//#if polish.blackberry
//# import de.enough.polish.blackberry.ui.BaseScreen;
//#endif
/**
* <p>Contains a number of items.</p>
* <p>Main purpose is to manage all items of a Form or similar canvases.</p>
* <p>Containers support following additional CSS attributes:
* </p>
* <ul>
* <li><b>columns</b>: The number of columns. If defined a table will be drawn.</li>
* <li><b>columns-width</b>: The width of the columns. "equals" for an equal width
* of each column, "normal" for a column width which depends on
* the items. One can also specify the used widths directly with
* a comma separated list of integers, e.g.
* <pre>
* columns: 2;
* columns-width: 15,5;
* </pre>
* </li>
* <li><b>scroll-mode</b>: Either "smooth" (=default) or "normal".</li>
* <li><b>and many more...</b>: compare the visual guide to J2ME Polish</li>
* </ul>
* <p>Copyright Enough Software 2004 - 2011</p>
* @author Robert Virkus, [email protected]
*/
public class Container extends Item {
//#if polish.css.columns || polish.useTable
//#define tmp.useTable
//#endif
/** constant for normal scrolling (0) */
public static final int SCROLL_DEFAULT = 0;
/** constant for smooth scrolling (1) */
public static final int SCROLL_SMOOTH = 1;
protected ArrayList itemsList;
//protected Item[] items;
/**
* defines whether a child item should be automatically focused. Please do no set directly, instead use setAutoFocusEnabled(boolean).
* @see #setAutoFocusEnabled(boolean)
*/
protected boolean autoFocusEnabled;
protected int autoFocusIndex;
protected Style itemStyle;
protected Item focusedItem;
/** the index of the currently focused item - please use only for reading, not for setting, unless you know what you are doing */
public int focusedIndex = -1;
protected boolean enableScrolling;
//#if polish.Container.allowCycling != false
/** specifies whether this container is allowed to cycle to the beginning when the last item has been reached */
public boolean allowCycling = true;
//#else
//# public boolean allowCycling = false;
//#endif
protected int yOffset;
protected int targetYOffset;
private int focusedTopMargin;
//#if polish.css.view-type || polish.css.columns
//#define tmp.supportViewType
protected ContainerView containerView;
//#endif
//#ifdef polish.css.scroll-mode
protected boolean scrollSmooth = true;
//#endif
//#if polish.css.expand-items
protected boolean isExpandItems;
//#endif
//#ifdef polish.hasPointerEvents
/** vertical pointer position when it was pressed the last time */
protected int lastPointerPressY;
/** scrolloffset when this container was pressed the last time */
protected int lastPointerPressYOffset;
/** time in ms when this container was pressed the last time */
protected long lastPointerPressTime;
//#endif
//#if polish.css.focused-style-first
protected Style focusedStyleFirst;
//#endif
//#if polish.css.focused-style-last
protected Style focusedStyleLast;
//#endif
private boolean isScrollRequired;
/** The height available for scrolling, ignore when set to -1 */
protected int scrollHeight = -1;
private Item[] containerItems;
private boolean showCommandsHasBeenCalled;
private Item scrollItem;
protected Style plainStyle;
private static final String KEY_ORIGINAL_STYLE = "os";
//#if polish.css.focus-all
private boolean isFocusAllChildren;
//#endif
//#if polish.css.focus-all-style
protected Style focusAllStyle;
//#endif
//#if polish.css.press-all
private boolean isPressAllChildren;
//#endif
private boolean isIgnoreMargins;
//private int availableContentWidth;
//#if polish.css.show-delay
private int showDelay;
private int showDelayIndex;
private long showNotifyTime;
//#endif
//#if polish.css.child-style
private Style childStyle;
//#endif
boolean appearanceModeSet;
private int scrollDirection;
private int scrollSpeed;
private int scrollDamping;
//#ifdef tmp.supportFocusItemsInVisibleContentArea
private boolean needsCheckItemInVisibleContent = false;
//#endif
private long lastAnimationTime;
private boolean isScrolling;
//#if polish.css.bounce && !(polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false)
//#define tmp.checkBouncing
private boolean allowBouncing = true;
//#endif
private FocusListener focusListener;
private long scrollStartTime;
private int scrollStartYOffset;
private long scrollDuration = 300; // ms
//#if !polish.Container.selectEntriesWhileTouchScrolling
/**
* the minimum drag distance before the focus is cleared while dragging
*/
private static int minimumDragDistance;
//#endif
/**
* Creates a new empty container.
*/
public Container() {
this( null, false, null, -1 );
}
/**
* Creates a new empty container with the specified style.
*
* @param style the style for this container
*/
public Container(Style style) {
this( null, false, style, -1 );
}
/**
* Creates a new empty container.
*
* @param focusFirstElement true when the first focussable element should be focused automatically.
*/
public Container( boolean focusFirstElement ) {
this( null, focusFirstElement, null, -1 );
}
/**
* Creates a new empty container.
*
* @param focusFirstElement true when the first focussable element should be focused automatically.
* @param style the style for this container
*/
public Container(boolean focusFirstElement, Style style) {
this( null, focusFirstElement, style, -1 );
}
/**
* Creates a new empty container.
*
* @param label the label of this container
* @param focusFirstElement true when the first focusable element should be focused automatically.
* @param style the style for this container
* @param height the vertical space available for this container, set to -1 when scrolling should not be activated
* @see #setScrollHeight( int )
*/
public Container(String label, boolean focusFirstElement, Style style, int height ) {
super( label, LAYOUT_DEFAULT, INTERACTIVE, style );
this.itemsList = new ArrayList();
setAutoFocusEnabled( focusFirstElement );
this.layout |= Item.LAYOUT_NEWLINE_BEFORE;
setScrollHeight( height );
}
/**
* Sets the height available for scrolling of this item.
*
* @param height available height for this item including label, padding, margin and border, -1 when scrolling should not be done.
*/
public void setScrollHeight( int height ) {
//#debug
System.out.println("Setting scroll height to " + height + " for " + this);
boolean scrollAutomatic = (this.scrollHeight != -1) && (height != -1) && (height != this.scrollHeight) && isInitialized();
this.scrollHeight = height;
this.enableScrolling = (height != -1);
Item item = this.scrollItem != null ? this.scrollItem : (this.isFocused ? this.focusedItem : null);
if (scrollAutomatic && item != null) {
//#debug
System.out.println("setScrollHeight(): scrolling to item=" + item + " with y=" + item.relativeY + ", height=" + height);
scroll( 0, item, true);
synchronized(this.itemsList) {
this.isScrollRequired = false;
}
}
}
/**
* Returns the available height for scrolling either from this container or from it's parent container.
* Note that the height available for this container might differ from the returned value.
*
* @return the available vertical space or -1 when it is not known.
* @see #getContentScrollHeight()
*/
public int getScrollHeight() {
if (this.scrollHeight == -1 && this.parent instanceof Container) {
return ((Container)this.parent).getScrollHeight();
} else {
return this.scrollHeight;
}
}
// /**
// * Returns the available height for scrolling either from this container or from it's parent container.
// *
// * @return the available vertical space for this container or -1 when it is not known.
// * @see #getContentScrollHeight()
// */
// public int getRelativeScrollHeight() {
// if (this.scrollHeight == -1 && this.parent instanceof Container) {
// return ((Container)this.parent).getRelativeScrollHeight() - this.relativeY - this.targetYOffset;
// } else {
// return this.scrollHeight - this.targetYOffset;
// }
// }
/**
* Retrieves the available height available for the content of this container
*
* @return the available vertical space minus paddings/margins etc or -1 when it is not known.
* @see #getScrollHeight()
*/
int getContentScrollHeight() {
return getScrollHeight() - (this.contentY + getBorderWidthTop() + getBorderWidthBottom() + this.paddingBottom + this.marginBottom );
}
/**
* Adds an StringItem with the given text to this container.
*
* @param text the text
* @throws IllegalArgumentException when the given item is null
*/
public void add(String text)
{
add(new StringItem(null,text));
}
/**
* Adds an StringItem with the given text to this container.
*
* @param text the text
* @param textAddStyle the style for the text
* @throws IllegalArgumentException when the given item is null
*/
public void add(String text,Style textAddStyle)
{
add(new StringItem(null,text),textAddStyle);
}
/**
* Adds an item to this container.
*
* @param item the item which should be added.
* @throws IllegalArgumentException when the given item is null
*/
public void add( Item item ) {
//#debug
System.out.println("adding " + item + " to " + this);
synchronized (this.itemsList) {
item.relativeY = 0;
item.internalX = Item.NO_POSITION_SET;
item.parent = this;
this.itemsList.add( item );
if (isInitialized()) {
requestInit();
}
}
if (this.isShown) {
item.showNotify();
}
//#if polish.css.focus-all
if (this.isFocused && this.isFocusAllChildren && !item.isFocused) {
Style itemFocusedStyle = item.getFocusedStyle();
if (itemFocusedStyle != this.style && itemFocusedStyle != StyleSheet.focusedStyle) {
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.focus(itemFocusedStyle, 0);
}
}
//#endif
if (this.isShown) {
repaint();
}
notifyValueChanged(item);
}
/**
* Adds an item to this container.
*
* @param item the item which should be added.
* @param itemAddStyle the style for the item
* @throws IllegalArgumentException when the given item is null
*/
public void add( Item item, Style itemAddStyle ) {
add( item );
if (itemAddStyle != null) {
// by setting the style field instead of calling setStyle(itemStyle), the style will not be resolved immediately but only when needed
item.style = itemAddStyle;
item.isStyleInitialized = false;
}
//#if polish.css.child-style
else if (item.style == null && this.childStyle != null) {
item.setStyle( this.childStyle );
}
//#endif
}
/**
* Inserts the given item at the defined position.
* Any following elements are shifted one position to the back.
*
* @param index the position at which the element should be inserted,
* use 0 when the element should be inserted in the front of this list.
* @param item the item which should be inserted
* @throws IllegalArgumentException when the given item is null
* @throws IndexOutOfBoundsException when the index < 0 || index >= size()
*/
public void add( int index, Item item ) {
synchronized (this.itemsList) {
item.relativeY = 0;
item.internalX = NO_POSITION_SET;
item.parent = this;
this.itemsList.add( index, item );
if (index <= this.focusedIndex) {
this.focusedIndex++;
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.focusedIndex = this.focusedIndex;
}
//#endif
}
if (this.isShown) {
requestInit();
}
// set following items to relativeY=0, so that they will be scrolled correctly:
for (int i= index + 1; i < this.itemsList.size(); i++ ) {
Item followingItem = get(i);
followingItem.relativeY = 0;
}
if (this.isShown) {
item.showNotify();
}
//#if polish.css.focus-all
if (this.isFocused && this.isFocusAllChildren) {
Style itemFocusedStyle = item.getFocusedStyle();
if (itemFocusedStyle != this.style && itemFocusedStyle != StyleSheet.focusedStyle) {
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.focus(itemFocusedStyle, 0);
}
}
//#endif
}
if (this.isShown) {
repaint();
}
}
//#if polish.LibraryBuild
/**
* Adds an item
* @param item the item to be added
*/
public void add( javax.microedition.lcdui.Item item ) {
// ignore
}
/**
* Inserts an item
* @param index the index
* @param item the item
*/
public void add( int index, javax.microedition.lcdui.Item item ) {
// ignore
}
/**
* Replaces an item
* @param index the index
* @param item the item to be added
*/
public void set( int index, javax.microedition.lcdui.Item item ) {
// ignore
}
//#endif
/**
* Replaces the item at the specified position in this list with the given item.
*
* @param index the position of the element, the first element has the index 0.
* @param item the item which should be set
* @return the replaced item
* @throws IndexOutOfBoundsException when the index < 0 || index >= size()
*/
public Item set( int index, Item item ) {
return set( index, item, null );
}
/**
* Replaces the item at the specified position in this list with the given item.
*
* @param index the position of the element, the first element has the index 0.
* @param item the item which should be set
* @param itemStyle the new style for the item
* @return the replaced item
* @throws IndexOutOfBoundsException when the index < 0 || index >= size()
*/
public Item set( int index, Item item, Style itemStyle ) {
//#debug
System.out.println("Container: setting item " + index + " " + item.toString() );
Item last = get( index );
if (last == item && (itemStyle == null || itemStyle == item.style)) {
// ignore, the same item is set over again:
//#debug
System.out.println("set: ignoring re-setting of the same item");
return last;
}
item.parent = this;
boolean focusNewItem = (index == this.focusedIndex) && (last.isFocused);
this.itemsList.set(index, item);
if (itemStyle != null) {
item.setStyle(itemStyle);
}
if (index == this.focusedIndex) {
if ( item.appearanceMode != PLAIN ) {
if (focusNewItem) {
this.focusedItem = null;
focusChild( index, item, 0, true );
} else {
this.focusedItem = item;
}
} else {
focusChild( -1 );
}
}
if (this.enableScrolling && (this.focusedIndex == -1 || index <= this.focusedIndex )) {
int offset = getScrollYOffset() + last.itemHeight;
if (offset > 0) {
offset = 0;
}
setScrollYOffset(offset, true);
}
//#if polish.css.focus-all
if (this.isFocused && this.isFocusAllChildren && !item.isFocused) {
Style itemFocusedStyle = item.getFocusedStyle();
if (itemFocusedStyle != this.style && itemFocusedStyle != StyleSheet.focusedStyle) {
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.focus(itemFocusedStyle, 0);
}
}
//#endif
//requestInit();
// set following items to relativeY=0, so that they will be scrolled correctly:
for (int i= index + 1; i < this.itemsList.size(); i++ ) {
Item followingItem = get(i);
followingItem.relativeY = 0;
}
requestInit();
repaint();
if (this.isShown) {
item.showNotify();
}
notifyValueChanged(item);
return last;
}
/**
* Returns the item at the specified position of this container.
*
* @param index the position of the desired item.
* @return the item stored at the given position
* @throws IndexOutOfBoundsException when the index < 0 || index >= size()
*/
public Item get( int index ) {
return (Item) this.itemsList.get( index );
}
/**
* Removes the item at the specified position of this container.
*
* @param index the position of the desired item.
* @return the item stored at the given position
* @throws IndexOutOfBoundsException when the index < 0 || index >= size()
*/
public Item remove( int index ) {
Item removedItem = null;
//#if polish.blackberry
// when the currently focused item is removed and this contains a native blackberry field,
// this can cause deadlocks with Container.initContent().
synchronized (de.enough.polish.blackberry.midlet.MIDlet.getEventLock()) {
//#endif
synchronized (this.itemsList) {
removedItem = (Item) this.itemsList.remove(index);
if (removedItem == this.scrollItem) {
this.scrollItem = null;
}
//#debug
System.out.println("Container: removing item " + index + " " + removedItem.toString() );
// adjust y-positions of following items:
//this.items = null;
Object[] myItems = this.itemsList.getInternalArray();
int removedItemHeight = removedItem.itemHeight + this.paddingVertical;
//#if tmp.supportViewType
if (this.containerView == null) {
//#endif
for (int i = index; i < myItems.length; i++) {
Item item = (Item) myItems[i];
if (item == null) {
break;
}
item.relativeY -= removedItemHeight;
}
//#if tmp.supportViewType
}
//#endif
// check if the currenlty focused item has been removed:
if (index == this.focusedIndex) {
this.focusedItem = null;
removedItem.defocus(this.itemStyle);
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.focusedIndex = -1;
this.containerView.focusedItem = null;
}
//#endif
// remove any item commands:
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(removedItem);
}
// focus the first possible item:
if (index >= this.itemsList.size()) {
index = this.itemsList.size() - 1;
}
if (index != -1) {
Item item = (Item) myItems[ index ];
if (item.appearanceMode != PLAIN) {
focusChild( index, item, Canvas.DOWN, true );
} else {
focusClosestItem(index);
}
} else {
this.focusedIndex = -1;
setAutoFocusEnabled( true );
this.autoFocusIndex = 0;
}
} else if (index < this.focusedIndex) {
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.focusedIndex--;
} else {
//#endif
int offset = getScrollYOffset() + removedItemHeight;
//System.out.println("new container offset: from " + this.yOffset + " to " + (offset > 0 ? 0 : offset));
setScrollYOffset( offset > 0 ? 0 : offset, false );
//#if tmp.supportViewType
}
//#endif
this.focusedIndex--;
}
setInitialized(false);
if (this.parent != null) {
this.parent.setInitialized(false);
}
if (this.isShown) {
removedItem.hideNotify();
}
}
//#if polish.blackberry
}
//#endif
repaint();
notifyValueChanged(removedItem);
return removedItem;
}
/**
* Focuses the next focussable item starting at the specified index + 1.
* @param index the index of the item that should be used as a starting point for the search of a new possible focussable item
* @return true when the focus could be set, when false is returned autofocus will be enabled instead
*/
public boolean focusClosestItemAbove( int index) {
//#debug
System.out.println("focusClosestItemAbove(" + index + ")");
Item[] myItems = getItems();
Item newFocusedItem = null;
int newFocusedIndex = -1;
for (int i = index -1; i >= 0; i--) {
Item item = myItems[i];
if (item.appearanceMode != PLAIN) {
newFocusedIndex = i;
newFocusedItem = item;
break;
}
}
if (newFocusedItem == null) {
for (int i = index + 1; i < myItems.length; i++) {
Item item = myItems[i];
if (item.appearanceMode != PLAIN) {
newFocusedIndex = i;
newFocusedItem = item;
break;
}
}
}
if (newFocusedItem != null) {
int direction = Canvas.DOWN;
if (newFocusedIndex < index) {
direction = Canvas.UP;
}
focusChild( newFocusedIndex, newFocusedItem, direction, true );
} else {
setAutoFocusEnabled( true );
this.focusedItem = null;
this.focusedIndex = -1;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.focusedIndex = -1;
this.containerView.focusedItem = null;
}
//#endif
}
return (newFocusedItem != null);
}
/**
* Focuses the next focussable item starting at the specified index +/- 1.
* @param index the index of the item that should be used as a starting point for the search of a new possible focussable item
* @return true when the focus could be set, when false is returned autofocus will be enabled instead
*/
public boolean focusClosestItem( int index) {
//#debug
System.out.println("focusClosestItem(" + index + ")");
int i = 1;
Item newFocusedItem = null;
Item item;
boolean continueFocus = true;
Object[] myItems = this.itemsList.getInternalArray();
int size = this.itemsList.size();
while (continueFocus) {
continueFocus = false;
int testIndex = index + i;
if (testIndex < size) {
item = (Item) myItems[ testIndex ];
if (item == null) {
break;
}
if (item.appearanceMode != Item.PLAIN) {
newFocusedItem = item;
i = testIndex;
break;
}
continueFocus = true;
}
testIndex = index - i;
if (testIndex >= 0) {
item = (Item) myItems[ testIndex ];
if (item.appearanceMode != Item.PLAIN) {
i = testIndex;
newFocusedItem = item;
break;
}
continueFocus = true;
}
i++;
}
if (newFocusedItem != null) {
int direction = Canvas.DOWN;
if (i < index) {
direction = Canvas.UP;
}
focusChild( i, newFocusedItem, direction, true );
} else {
setAutoFocusEnabled( true );
this.focusedItem = null;
this.focusedIndex = -1;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.focusedIndex = -1;
this.containerView.focusedItem = null;
}
//#endif
}
return (newFocusedItem != null);
}
/**
* Removes the given item.
*
* @param item the item which should be removed.
* @return true when the item was found in this list.
* @throws IllegalArgumentException when the given item is null
*/
public boolean remove( Item item ) {
int index = this.itemsList.indexOf(item);
if (index != -1) {
remove( index );
return true;
} else {
return false;
}
}
/**
* Removes all items from this container.
*/
public void clear() {
//System.out.println("CLEARING CONTAINER " + this);
synchronized (this.itemsList) {
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.focusedIndex = -1;
this.containerView.focusedItem = null;
}
//#endif
//System.out.println("clearing container - focusedItem=" + this.focusedItem + ", isFocused=" + this.isFocused + ", focusedIndex=" + this.focusedIndex + ", size=" + this.size() + ", itemStyle=" + this.itemStyle );
this.scrollItem = null;
if (this.isShown) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++) {
Item item = (Item) myItems[i];
if (item == null) {
break;
}
item.hideNotify();
}
}
this.itemsList.clear();
this.containerItems = new Item[0];
//this.items = new Item[0];
if (this.focusedIndex != -1) {
setAutoFocusEnabled( this.isFocused );
//#if polish.Container.clearResetsFocus != false
this.autoFocusIndex = 0;
//#else
this.autoFocusIndex = this.focusedIndex;
//#endif
this.focusedIndex = -1;
if (this.focusedItem != null) {
if (this.itemStyle != null) {
//System.out.println("Container.clear(): defocusing current item " + this.focusedItem);
this.focusedItem.defocus(this.itemStyle);
}
if (this.focusedItem.commands != null) {
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this.focusedItem);
}
}
}
this.focusedItem = null;
}
this.yOffset = 0;
this.targetYOffset = 0;
if (this.internalX != NO_POSITION_SET) {
this.internalX = NO_POSITION_SET;
this.internalY = 0;
}
// adjust scrolling:
if ( this.isFocused && this.parent instanceof Container ) {
Container parentContainer = (Container) this.parent;
int scrollOffset = - parentContainer.getScrollYOffset();
if (scrollOffset > this.relativeY) {
int diff = scrollOffset - this.relativeY;
parentContainer.setScrollYOffset( diff - scrollOffset, false );
}
}
//}
this.contentHeight = 0;
this.contentWidth = 0;
this.itemHeight = this.marginTop + this.paddingTop + this.paddingBottom + this.marginBottom;
this.itemWidth = this.marginLeft + this.paddingLeft + this.paddingRight + this.marginRight;
if (isInitialized()) {
setInitialized(false);
//this.yBottom = this.yTop = 0;
repaint();
}
}
}
/**
* Retrieves the number of items stored in this container.
*
* @return The number of items stored in this container.
*/
public int size() {
return this.itemsList.size();
}
/**
* Retrieves all items which this container holds.
* The items might not have been intialised.
*
* @return an array of all items, can be empty but not null.
*/
public Item[] getItems() {
if (!isInitialized() || this.containerItems == null) {
this.containerItems = (Item[]) this.itemsList.toArray( new Item[ this.itemsList.size() ]);
}
return this.containerItems;
}
/**
* Sets the focus listener.
* @param listener the new listener, use null to remove an existing listener.
* @see #getFocusListener()
*/
public void setFocusListener( FocusListener listener ) {
this.focusListener = listener;
}
/**
* Retrieves the focus listener
* @return the listener, may be null
* @see #setFocusListener(FocusListener)
*/
public FocusListener getFocusListener() {
return this.focusListener;
}
/**
* Focuses the specified item.
*
* @param index the index of the item. The first item has the index 0,
* when -1 is given, the focus will be removed altogether
* @return true when the specified item could be focused.
* It needs to have an appearanceMode which is not Item.PLAIN to
* be focusable.
*/
public boolean focusChild(int index) {
if (index == -1) {
this.focusedIndex = -1;
Item item = this.focusedItem;
if (item != null && this.itemStyle != null && item.isFocused) {
item.defocus( this.itemStyle );
}
this.focusedItem = null;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.focusedIndex = -1;
this.containerView.focusedItem = null;
}
//#endif
//#if polish.blackberry
if (this.isFocused) {
if(getScreen() != null) {
getScreen().notifyFocusSet(this);
} else {
Display.getInstance().notifyFocusSet(this);
}
}
//#endif
if (this.focusListener != null) {
this.focusListener.onFocusChanged(this, null, -1);
}
return true;
}
if (!this.isFocused) {
setAutoFocusEnabled( true );
}
Item item = get(index );
if (item.appearanceMode != Item.PLAIN) {
int direction = 0;
if (this.isFocused) {
if (this.focusedIndex == -1) {
// nothing
} else if (this.focusedIndex < index ) {
direction = Canvas.DOWN;
} else if (this.focusedIndex > index) {
direction = Canvas.UP;
}
}
focusChild( index, item, direction, true);
return true;
}
return false;
}
//#if polish.hasPointerEvents
//#ifdef tmp.supportFocusItemsInVisibleContentArea
/**
* Checks if an item in the visible range is
*
* @param item the Item to check
* @return true if item is in visible content area else false
*/
private boolean isItemInVisibleContentArea(Item item){
if(item == null) {
return false;
}
int relY = (item.getAbsoluteY() + this.getCurrentScrollYOffset() - this.getScrollYOffset());
if(relY <= this.getAvailableContentHeight() && relY >= 0){
return true;
}
return false;
}
/**
* Find the position of first item in visible area
*
* @param isInteractive true to check only interactive items else false
* @return the position of the first item in visible area or -1 if no item was found
*/
private int getFirstItemInVisibleContentArea(boolean isInteractive){
Item[] items = this.getItems();
for(int i = 0; i < items.length; i++){
Item item = items[i];
if((!isInteractive || item.isInteractive()) && isItemInVisibleContentArea(item)) {
return i;
}
}
return -1;
}
/**
* Find the position of last item in visible area
*
* @param isInteractive true to check only interactive items else false
* @return the position of the last item in visible area or -1 if no item was found
*/
private int getLastItemInVisibleContentArea(boolean isInteractive){
Item[] items = this.getItems();
for(int i = items.length-1; i > 0 ; i--){
Item item = items[i];
if((!isInteractive || item.isInteractive()) && isItemInVisibleContentArea(item)) {
return i;
}
}
return -1;
}
//#endif
//#endif
/**
* Sets the focus to the given item.
*
* @param index the position
* @param item the item which should be focused
* @param direction the direction, either Canvas.DOWN, Canvas.RIGHT, Canvas.UP, Canvas.LEFT or 0.
* @param force true when the child should be focused again even though is has been focused before
*/
public void focusChild( int index, Item item, int direction, boolean force ) {
//#debug
System.out.println("Container (" + this + "): Focusing child item " + index + " (" + item + "), isInitialized=" + this.isInitialized + ", autoFocusEnabled=" + this.autoFocusEnabled );
//System.out.println("focus: yOffset=" + this.yOffset + ", targetYOffset=" + this.targetYOffset + ", enableScrolling=" + this.enableScrolling + ", isInitialized=" + this.isInitialized );
if (!isInitialized() && this.autoFocusEnabled) {
// setting the index for automatically focusing the appropriate item
// during the initialization:
//#debug
System.out.println("Container: Setting autofocus-index to " + index );
this.autoFocusIndex = index;
}
if (this.isFocused) {
setAutoFocusEnabled( false );
}
if (index == this.focusedIndex && item.isFocused && item == this.focusedItem) {
//#debug
System.out.println("Container: ignoring focusing of item " + index );
//#ifdef polish.css.view-type
if (this.containerView != null && this.containerView.focusedIndex != index) {
this.containerView.focusedItem = item;
this.containerView.focusedIndex = index;
}
//#endif
// ignore the focusing of the same element:
return;
}
//#if polish.blackberry
if (this.isShown) {
Display.getInstance().notifyFocusSet(item);
}
//#endif
// indicating if either the former focusedItem or the new focusedItem has changed it's size or it's layout by losing/gaining the focus,
// of course this can only work if this container is already initialized:
boolean isReinitializationRequired = false;
// first defocus the last focused item:
Item previouslyFocusedItem = this.focusedItem;
if (previouslyFocusedItem != null) {
int wBefore = previouslyFocusedItem.itemWidth;
int hBefore = previouslyFocusedItem.itemHeight;
int layoutBefore = previouslyFocusedItem.layout;
if (this.itemStyle != null) {
previouslyFocusedItem.defocus(this.itemStyle);
} else {
//#debug error
System.out.println("Container: Unable to defocus item - no previous style found.");
previouslyFocusedItem.defocus( StyleSheet.defaultStyle );
}
if (isInitialized()) {
//fix 2008-11-11: width given to an item can be different from availableContentWidth on ContainerViews:
//int wAfter = previouslyFocusedItem.getItemWidth( this.availableContentWidth, this.availableContentWidth, this.availableHeight );
//fix 2008-12-10: on some ContainerViews it can happen, that not all items have been initialized before:
//int wAfter = item.getItemWidth( item.availableWidth, item.availableWidth, item.availableHeight );
int wAfter = getChildWidth(item);
int hAfter = previouslyFocusedItem.itemHeight;
int layoutAfter = previouslyFocusedItem.layout;
if (wAfter != wBefore || hAfter != hBefore || layoutAfter != layoutBefore ) {
//#debug
System.out.println("dimension changed from " + wBefore + "x" + hBefore + " to " + wAfter + "x" + hAfter + " for previous " + previouslyFocusedItem);
isReinitializationRequired = true;
//#if tmp.supportViewType
if (this.containerView != null) {
previouslyFocusedItem.setInitialized(false); // could be that a container view poses restrictions on the possible size, i.e. within a table
}
//#endif
}
}
}
int wBefore = item.itemWidth;
int hBefore = item.itemHeight;
int layoutBefore = item.layout;
Style newStyle = getFocusedStyle( index, item);
boolean isDownwards = (direction == Canvas.DOWN) || (direction == Canvas.RIGHT) || (direction == 0 && index > this.focusedIndex);
int previousIndex = this.focusedIndex; // need to determine whether the user has scrolled from the bottom to the top
this.focusedIndex = index;
this.focusedItem = item;
int scrollOffsetBeforeScroll = getScrollYOffset();
//#if tmp.supportViewType
if ( this.containerView != null ) {
this.itemStyle = this.containerView.focusItem( index, item, direction, newStyle );
} else {
//#endif
this.itemStyle = item.focus( newStyle, direction );
//#if tmp.supportViewType
}
//#endif
//#ifdef polish.debug.error
if (this.itemStyle == null) {
//#debug error
System.out.println("Container: Unable to retrieve style of item " + item.getClass().getName() );
}
//#endif
//System.out.println("focus - still initialized=" + this.isInitialized + " for " + this);
if (isInitialized()) {
// this container has been initialized already,
// so the dimensions are known.
//System.out.println("focus: contentWidth=" + this.contentWidth + ", of container " + this);
//int wAfter = item.getItemWidth( this.availableContentWidth, this.availableContentWidth, this.availableHeight );
// fix 2008-11-11: availableContentWidth can be different from the width granted to items in a ContainerView:
int wAfter = getChildWidth( item );
int hAfter = item.itemHeight;
int layoutAfter = item.layout;
if (wAfter != wBefore || hAfter != hBefore || layoutAfter != layoutBefore ) {
//#debug
System.out.println("dimension changed from " + wBefore + "x" + hBefore + " to " + wAfter + "x" + hAfter + " for next " + item);
isReinitializationRequired = true;
//#if tmp.supportViewType
if (this.containerView != null) {
item.setInitialized(false); // could be that a container view poses restrictions on the possible size, i.e. within a table
}
//#endif
}
updateInternalPosition(item);
if (getScrollHeight() != -1) {
// Now adjust the scrolling:
Item nextItem;
if ( isDownwards && index < this.itemsList.size() - 1 ) {
nextItem = get( index + 1 );
//#debug
System.out.println("Focusing downwards, nextItem.relativY = [" + nextItem.relativeY + "], focusedItem.relativeY=[" + item.relativeY + "], this.yOffset=" + this.yOffset + ", this.targetYOffset=" + this.targetYOffset);
} else if ( !isDownwards && index > 0 ) {
nextItem = get( index - 1 );
//#debug
System.out.println("Focusing upwards, nextItem.yTopPos = " + nextItem.relativeY + ", focusedItem.relativeY=" + item.relativeY );
} else {
//#debug
System.out.println("Focusing last or first item.");
nextItem = item;
}
if (getScrollYOffset() == scrollOffsetBeforeScroll) {
- if ( this.enableScrolling && ((isDownwards && (index < previousIndex) || (previousIndex == -1))) ) {
+ if ( this.enableScrolling
+ && (isDownwards && (index < previousIndex)
+ //#if polish.Container.selectEntriesWhileTouchScrolling
+ || (previousIndex == -1)
+ //#endif
+ ) ) {
// either the first item or the first selectable item has been focused, so scroll to the very top:
//#if tmp.supportViewType
if (this.containerView == null || !this.containerView.isVirtualContainer())
//#endif
{
setScrollYOffset(0, true);
}
} else {
int itemYTop = isDownwards ? item.relativeY : nextItem.relativeY;
int itemYBottom = isDownwards ? nextItem.relativeY + nextItem.itemHeight : item.relativeY + item.itemHeight;
int height = itemYBottom - itemYTop;
//System.out.println("scrolling for item " + item + ", nextItem=" + nextItem + " in " + this + " with relativeY=" + this.relativeY + ", itemYTop=" + itemYTop);
scroll( direction, this.relativeX, itemYTop, item.internalWidth, height, force );
}
}
}
} else if (getScrollHeight() != -1) { // if (this.enableScrolling) {
//#debug
System.out.println("focus: postpone scrolling to initContent() for " + this + ", item " + item);
this.isScrollRequired = true;
}
if (isInitialized()) {
setInitialized(!isReinitializationRequired);
} else if (this.contentWidth != 0) {
updateInternalPosition(item);
}
//#if polish.Container.notifyFocusChange
notifyStateChanged();
//#endif
if (this.focusListener != null) {
this.focusListener.onFocusChanged(this, this.focusedItem, this.focusedIndex);
}
}
/**
* Queries the width of an child item of this container.
* This allows subclasses to control the possible re-initialization that is happening here.
* Also ContainerViews can override the re-initialization in their respective getChildWidth() method.
* @param item the child item
* @return the width of the child item
* @see #getChildHeight(Item)
* @see ContainerView#getChildWidth(Item)
*/
protected int getChildWidth(Item item) {
//#if tmp.supportViewType
ContainerView contView = this.containerView;
if (contView != null) {
return contView.getChildWidth(item);
}
//#endif
int w;
if (item.availableWidth > 0) {
w = item.getItemWidth( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
w = item.getItemWidth( this.availContentWidth, this.availContentWidth, this.availContentHeight );
}
return w;
}
/**
* Queries the height of an child item of this container.
* This allows subclasses to control the possible re-initialization that is happening here.
* Also ContainerViews can override the re-initialization in their respective getChildHeight() method.
* @param item the child item
* @return the height of the child item
* @see #getChildHeight(Item)
* @see ContainerView#getChildHeight(Item)
*/
protected int getChildHeight(Item item) {
//#if tmp.supportViewType
ContainerView contView = this.containerView;
if (contView != null) {
return contView.getChildHeight(item);
}
//#endif
int h;
if (item.availableWidth > 0) {
h = item.getItemHeight( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
h = item.getItemHeight( this.availContentWidth, this.availContentWidth, this.availContentHeight );
}
return h;
}
/**
* Retrieves the best matching focus style for the given item
* @param index the index of the item
* @param item the item
* @return the matching focus style
*/
protected Style getFocusedStyle(int index, Item item)
{
Style newStyle = item.getFocusedStyle();
//#if polish.css.focused-style-first
if (index == 0 && this.focusedStyleFirst != null) {
newStyle = this.focusedStyleFirst;
}
//#endif
//#if polish.css.focused-style-last
if (this.focusedStyleLast != null && index == this.itemsList.size() - 1) {
newStyle = this.focusedStyleLast;
}
//#endif
return newStyle;
}
/**
* Scrolls this container so that the (internal) area of the given item is best seen.
* This is used when a GUI even has been consumed by the currently focused item.
* The call is fowarded to scroll( direction, x, y, w, h ).
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param item the item for which the scrolling should be adjusted
* @return true when the container was scrolled
*/
public boolean scroll(int direction, Item item, boolean force) {
//#debug
System.out.println("scroll: scrolling for item " + item + ", item.internalX=" + item.internalX +", relativeInternalY=" + ( item.relativeY + item.contentY + item.internalY ) + ", relativeY=" + item.relativeY + ", contentY=" + item.contentY + ", internalY=" + item.internalY);
if ( (item.internalX != NO_POSITION_SET)
&& ( (item.itemHeight > getScrollHeight()) || ( (item.internalY + item.internalHeight) > item.contentHeight ) )
) {
// use internal position of item for scrolling:
//System.out.println("using internal area for scrolling");
int relativeInternalX = item.relativeX + item.contentX + item.internalX;
int relativeInternalY = item.relativeY + item.contentY + item.internalY;
return scroll( direction, relativeInternalX, relativeInternalY, item.internalWidth, item.internalHeight, force );
} else {
if (!isInitialized() && item.relativeY == 0) {
// defer scrolling to init at a later stage:
//System.out.println( this + ": setting scrollItem to " + item);
synchronized(this.itemsList) {
this.scrollItem = item;
}
return true;
} else {
// use item dimensions for scrolling:
//System.out.println("use item area for scrolling");
return scroll( direction, item.relativeX, item.relativeY, item.itemWidth, item.itemHeight, force );
}
}
}
/**
* Adjusts the yOffset or the targetYOffset so that the given relative values are inside of the visible area.
* The call is forwarded to a parent container when scrolling is not enabled for this item.
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param x the horizontal position of the area relative to this content's left edge, is ignored in the current version
* @param y the vertical position of the area relative to this content's top edge
* @param width the width of the area
* @param height the height of the area
* @return true when the scroll request changed the internal scroll offsets
*/
protected boolean scroll( int direction, int x, int y, int width, int height ) {
return scroll( direction, x, y, width, height, false );
}
/**
* Adjusts the yOffset or the targetYOffset so that the given relative values are inside of the visible area.
* The call is forwarded to a parent container when scrolling is not enabled for this item.
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param x the horizontal position of the area relative to this content's left edge, is ignored in the current version
* @param y the vertical position of the area relative to this content's top edge
* @param width the width of the area
* @param height the height of the area
* @param force true when the area should be shown regardless where the the current scrolloffset is located
* @return true when the scroll request changed the internal scroll offsets
*/
protected boolean scroll( int direction, int x, int y, int width, int height, boolean force ) {
//#debug
System.out.println("scroll: direction=" + direction + ", y=" + y + ", availableHeight=" + this.scrollHeight + ", height=" + height + ", focusedIndex=" + this.focusedIndex + ", yOffset=" + this.yOffset + ", targetYOffset=" + this.targetYOffset +", numberOfItems=" + this.itemsList.size() + ", in " + this + ", downwards=" + (direction == Canvas.DOWN || direction == Canvas.RIGHT || direction == 0));
if (!this.enableScrolling) {
if (this.parent instanceof Container) {
x += this.contentX + this.relativeX;
y += this.contentY + this.relativeY;
//#debug
System.out.println("Forwarding scroll request to parent now with y=" + y);
return ((Container)this.parent).scroll(direction, x, y, width, height, force );
}
return false;
}
if ( height == 0) {
return false;
}
// assume scrolling down when the direction is not known:
boolean isDownwards = (direction == Canvas.DOWN || direction == Canvas.RIGHT || direction == 0);
boolean isUpwards = (direction == Canvas.UP );
int currentYOffset = this.targetYOffset; // yOffset starts at 0 and grows to -contentHeight + lastItem.itemHeight
//#if polish.css.scroll-mode
if (!this.scrollSmooth) {
currentYOffset = this.yOffset;
}
//#endif
int originalYOffset = currentYOffset;
int verticalSpace = this.scrollHeight - (this.contentY + this.marginBottom + this.paddingBottom + getBorderWidthBottom()); // the available height for this container
int yTopAdjust = 0;
Screen scr = this.screen;
boolean isCenterOrBottomLayout = (this.layout & LAYOUT_VCENTER) == LAYOUT_VCENTER || (this.layout & LAYOUT_BOTTOM) == LAYOUT_BOTTOM;
if (isCenterOrBottomLayout && (scr != null && this == scr.container && this.relativeY > scr.contentY)) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
yTopAdjust = this.relativeY - scr.contentY;
}
if ( y + height + currentYOffset + yTopAdjust > verticalSpace ) {
// the area is too low, so scroll down (= increase the negative yOffset):
//#debug
System.out.println("scroll: item too low: verticalSpace=" + verticalSpace + " y=" + y + ", height=" + height + ", yOffset=" + currentYOffset + ", yTopAdjust=" + yTopAdjust + ", relativeY=" + this.relativeY + ", screen.contentY=" + scr.contentY + ", scr=" + scr);
//currentYOffset += verticalSpace - (y + height + currentYOffset + yTopAdjust);
int newYOffset = verticalSpace - (y + height + yTopAdjust);
// check if the top of the area is still visible when scrolling downwards:
if ( !isUpwards && y + newYOffset < 0) {
newYOffset = -y;
}
if (isDownwards) {
// check if we scroll down more than one page:
int difference = Math.max(Math.abs(currentYOffset), Math.abs(newYOffset)) -
Math.min(Math.abs(currentYOffset), Math.abs(newYOffset));
if (difference > verticalSpace && !force ) {
newYOffset = currentYOffset - verticalSpace;
}
}
currentYOffset = newYOffset;
} else if ( y + currentYOffset < 0 ) {
//#debug
System.out.println("scroll: item too high: , y=" + y + ", current=" + currentYOffset + ", target=" + (-y) );
int newYOffset = -y;
// check if the bottom of the area is still visible when scrolling upwards:
if (isUpwards && newYOffset + y + height > verticalSpace) { // && height < verticalSpace) {
//2008-12-10: scrolling upwards resulted in too large jumps when we have big items, so
// adjust the offset in any case, not only when height is smaller than the vertical space (height < verticalSpace):
newYOffset = -(y + height) + verticalSpace;
}
int difference = Math.max(Math.abs(currentYOffset), Math.abs(newYOffset)) -
Math.min(Math.abs(currentYOffset), Math.abs(newYOffset));
if (difference > verticalSpace && !force ) {
newYOffset = currentYOffset + verticalSpace;
}
currentYOffset = newYOffset;
} else {
//#debug
System.out.println("scroll: do nothing");
return false;
}
if (currentYOffset != originalYOffset) {
setScrollYOffset(currentYOffset, true);
return true;
} else {
//#debug
System.out.println("scroll: no change");
return false;
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setAppearanceMode(int)
*/
public void setAppearanceMode(int appearanceMode)
{
super.setAppearanceMode(appearanceMode);
// this is used in initContent() to circumvent the
// reversal of the previously set appearance mode
synchronized(this.itemsList) {
this.appearanceModeSet = true;
}
}
protected void initLayout(Style style, int availWidth) {
//#ifdef polish.css.view-type
if (this.containerView != null) {
this.containerView.initPadding(style, availWidth);
} else
//#endif
{
initPadding(style, availWidth);
}
//#ifdef polish.css.view-type
if (this.containerView != null) {
this.containerView.initMargin(style, availWidth);
} else
//#endif
{
initMargin(style, availWidth);
}
}
/**
* Retrieves the synchronization lock for this container.
* As a lock either the internal ArrayList for items is used or the paint lock of the screen when this container is associated with a screen.
* The lock can be used manipulate a Container that is currently displayed
* @return the synchronization lock
* @see Screen#getPaintLock()
* @see #add(Item)
*/
public Object getSynchronizationLock() {
Object lock = this.itemsList;
Screen scr = getScreen();
if (scr != null) {
lock = scr.getPaintLock();
}
return lock;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#initItem( int, int )
*/
protected void initContent(int firstLineWidth, int availWidth, int availHeight) {
//#debug
System.out.println("Container: intialising content for " + this + ": autofocus=" + this.autoFocusEnabled + ", autoFocusIndex=" + this.autoFocusIndex + ", isFocused=" + this.isFocused + ", firstLineWidth=" + firstLineWidth + ", availWidth=" + availWidth + ", availHeight=" + availHeight + ", size=" + this.itemsList.size() );
//this.availableContentWidth = firstLineWidth;
//#if polish.css.focused-style
if (this.focusedStyle != null) {
this.focusedTopMargin = this.focusedStyle.getMarginTop(availWidth) + this.focusedStyle.getPaddingTop(availWidth);
if (this.focusedStyle.border != null) {
this.focusedTopMargin += this.focusedStyle.border.borderWidthTop;
}
if (this.focusedStyle.background != null) {
this.focusedTopMargin += this.focusedStyle.background.borderWidth;
}
}
//#endif
synchronized (this.itemsList) {
int myContentWidth = 0;
int myContentHeight = 0;
Item[] myItems;
if (this.containerItems == null || this.containerItems.length != this.itemsList.size()) {
myItems = (Item[]) this.itemsList.toArray( new Item[ this.itemsList.size() ]);
this.containerItems = myItems;
} else {
myItems = (Item[]) this.itemsList.toArray(this.containerItems);
}
//#if (polish.css.child-style-first || polish.css.child-style-last) && polish.css.child-style
if (this.style != null && this.childStyle != null) {
Style firstStyle = null;
//#if polish.css.child-style-first
firstStyle = (Style) this.style.getObjectProperty("child-style-first");
//#endif
Style lastStyle = null;
//#if polish.css.child-style-last
lastStyle = (Style) this.style.getObjectProperty("child-style-last");
//#endif
if (firstStyle != null || lastStyle != null) {
int lastIndex = myItems.length - 1;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.style == null) {
item.setStyle( this.childStyle );
}
if (i != 0 && item.style == firstStyle) {
item.setStyle( this.childStyle );
}
if (i != lastIndex && item.style == lastStyle) {
item.setStyle( this.childStyle );
}
if (i == 0 && firstStyle != null && item.style != firstStyle) {
item.setStyle( firstStyle );
}
if (i == lastIndex && lastStyle != null && item.style != lastStyle) {
item.setStyle( lastStyle );
}
}
}
}
//#endif
if (this.autoFocusEnabled && this.autoFocusIndex >= myItems.length ) {
this.autoFocusIndex = 0;
}
//#if polish.Container.allowCycling != false
if (this.focusedItem instanceof Container && ((Container)this.focusedItem).allowCycling && getNumberOfInteractiveItems() > 1) {
((Container)this.focusedItem).allowCycling = false;
}
Item ancestor = this.parent;
while (this.allowCycling && ancestor != null) {
if ( (ancestor instanceof Container) && ((Container)ancestor).getNumberOfInteractiveItems()>1 ) {
this.allowCycling = false;
break;
}
ancestor = ancestor.parent;
}
//#endif
//#if tmp.supportViewType
if (this.containerView != null) {
// additional initialization is necessary when a view is used for this container:
boolean requireScrolling = this.isScrollRequired && this.isFocused;
// System.out.println("ABOUT TO CALL INIT CONTENT - focusedIndex of Container=" + this.focusedIndex);
this.containerView.parentItem = this;
this.containerView.parentContainer = this;
this.containerView.init( this, firstLineWidth, availWidth, availHeight);
if (this.defaultCommand != null || (this.commands != null && this.commands.size() > 0)) {
this.appearanceMode = INTERACTIVE;
} else if(!this.appearanceModeSet){
this.appearanceMode = this.containerView.appearanceMode;
}
if (this.isFocused && this.autoFocusEnabled) {
//#debug
System.out.println("Container/View: autofocusing element starting at " + this.autoFocusIndex);
if (this.autoFocusIndex >= 0 && this.appearanceMode != Item.PLAIN) {
for (int i = this.autoFocusIndex; i < myItems.length; i++) {
Item item = myItems[i];
if (item.appearanceMode != Item.PLAIN) {
// make sure that the item has applied it's own style first (not needed since it has been initialized by the container view already):
//item.getItemHeight( firstLineWidth, lineWidth );
// now focus the item:
setAutoFocusEnabled( false );
requireScrolling = (this.autoFocusIndex != 0);
// int heightBeforeFocus = item.itemHeight;
focusChild( i, item, 0, true);
// outcommented on 2008-07-09 because this results in a wrong
// available width for items with subsequent wrong getAbsoluteX() coordinates
// int availableWidth = item.itemWidth;
// if (availableWidth < this.minimumWidth) {
// availableWidth = this.minimumWidth;
// }
// if (item.getItemHeight( availableWidth, availableWidth ) > heightBeforeFocus) {
// item.isInitialized = false;
// this.containerView.initContent( this, firstLineWidth, lineWidth);
// }
this.isScrollRequired = this.isScrollRequired && requireScrolling; // override setting in focus()
//this.containerView.focusedIndex = i; is done within focus(i, item, 0) already
//this.containerView.focusedItem = item;
//System.out.println("autofocus: found item " + i );
break;
}
}
// when deactivating the auto focus the container won't initialize correctly after it has
// been cleared and items are added subsequently one after another (e.g. like within the Browser).
// } else {
// this.autoFocusEnabled = false;
}
}
this.contentWidth = this.containerView.contentWidth;
this.contentHeight = this.containerView.contentHeight;
if (requireScrolling && this.focusedItem != null) {
//#debug
System.out.println("initContent(): scrolling autofocused or scroll-required item for view, focused=" + this.focusedItem);
Item item = this.focusedItem;
scroll( 0, item.relativeX, item.relativeY, item.itemWidth, item.itemHeight, true );
}
else if (this.scrollItem != null) {
//System.out.println("initContent(): scrolling scrollItem=" + this.scrollItem);
boolean scrolled = scroll( 0, this.scrollItem, true );
if (scrolled) {
this.scrollItem = null;
}
}
if (this.focusedItem != null) {
updateInternalPosition(this.focusedItem);
}
return;
}
//#endif
boolean isLayoutShrink = (this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK;
boolean hasFocusableItem = false;
int numberOfVerticalExpandItems = 0;
Item lastVerticalExpandItem = null;
int lastVerticalExpandItemIndex = 0;
boolean hasCenterOrRightItems = false;
boolean hasVerticalExpandItems = false;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.isLayoutVerticalExpand()) {
hasVerticalExpandItems = true;
break;
}
}
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (hasVerticalExpandItems && item.isLayoutVerticalExpand()) {
// re-initialize items when we have vertical-expand items, so that relativeY and itemHeight is correctly calculated
// with each run:
item.setInitialized(false);
}
//System.out.println("initalising " + item.getClass().getName() + ":" + i);
int width = item.getItemWidth( availWidth, availWidth, availHeight );
int height = item.itemHeight; // no need to call getItemHeight() since the item is now initialised...
// now the item should have a style, so it can be safely focused
// without loosing the style information:
//String toString = item.toString();
//System.out.println("init of item " + i + ": height=" + height + " of item " + toString.substring( 19, Math.min(120, toString.length() ) ));
//if (item.isInvisible && height != 0) {
// System.out.println("*** item.height != 0 even though it is INVISIBLE - isInitialized=" + item.isInitialized );
//}
if (item.appearanceMode != PLAIN) {
hasFocusableItem = true;
}
if (this.isFocused && this.autoFocusEnabled && (i >= this.autoFocusIndex ) && (item.appearanceMode != Item.PLAIN)) {
setAutoFocusEnabled( false );
//System.out.println("Container.initContent: auto-focusing " + i + ": " + item );
focusChild( i, item, 0, true );
this.isScrollRequired = (this.isScrollRequired || hasFocusableItem) && (this.autoFocusIndex != 0); // override setting in focus()
height = item.getItemHeight(availWidth, availWidth, availHeight);
if (!isLayoutShrink) {
width = item.itemWidth; // no need to call getItemWidth() since the item is now initialised...
} else {
width = 0;
}
if (this.enableScrolling && this.autoFocusIndex != 0) {
//#debug
System.out.println("initContent(): scrolling autofocused item, autofocus-index=" + this.autoFocusIndex + ", i=" + i );
scroll( 0, 0, myContentHeight, width, height, true );
}
} else if (i == this.focusedIndex) {
if (isLayoutShrink) {
width = 0;
}
if (this.isScrollRequired) {
//#debug
System.out.println("initContent(): scroll is required - scrolling to y=" + myContentHeight + ", height=" + height);
scroll( 0, 0, myContentHeight, width, height, true );
this.isScrollRequired = false;
// } else if (item.internalX != NO_POSITION_SET ) {
// // ensure that lines of textfields etc are within the visible area:
// scroll(0, item );
}
}
if (item.isLayoutVerticalExpand()) {
numberOfVerticalExpandItems++;
lastVerticalExpandItem = item;
lastVerticalExpandItemIndex = i;
}
if (width > myContentWidth) {
myContentWidth = width;
}
item.relativeY = myContentHeight;
if (item.isLayoutCenter || item.isLayoutRight) {
hasCenterOrRightItems = true;
if (this.parent == null) {
myContentWidth = availWidth;
}
} else {
item.relativeX = 0;
}
myContentHeight += height != 0 ? height + this.paddingVertical : 0;
//System.out.println( i + ": height=" + height + ", myContentHeight=" + myContentHeight + ", item=" + item + ", style=" + (this.style == null ? "<none>" : this.style.name));
//System.out.println("item.yTopPos=" + item.yTopPos);
} // cycling through all items
if (numberOfVerticalExpandItems > 0 && myContentHeight < availHeight) {
int diff = availHeight - myContentHeight;
if (numberOfVerticalExpandItems == 1) {
// this is a simple case:
lastVerticalExpandItem.setItemHeight( lastVerticalExpandItem.itemHeight + diff );
for (int i = lastVerticalExpandItemIndex+1; i < myItems.length; i++)
{
Item item = myItems[i];
item.relativeY += diff;
}
} else {
// okay, there are several items that would like to be expanded vertically:
// System.out.println("having " + numberOfVerticalExpandItems + ", diff: " + diff + "=>" + (diff / numberOfVerticalExpandItems) + "=>" + ((diff / numberOfVerticalExpandItems) * numberOfVerticalExpandItems));
diff = diff / numberOfVerticalExpandItems;
int relYAdjust = 0;
for (int i = 0; i < myItems.length; i++)
{
Item item = myItems[i];
// System.out.println("changing relativeY from " + item.relativeY + " to " + (item.relativeY + relYAdjust) + ", relYAdjust=" + relYAdjust + " for " + item );
item.relativeY += relYAdjust;
if (item.isLayoutVerticalExpand()) {
// System.out.println("changing itemHeight from " + item.itemHeight + " to " + (item.itemHeight + diff) + " for " + item);
item.setItemHeight(item.itemHeight + diff );
relYAdjust += diff;
}
}
}
myContentHeight = availHeight;
}
if (this.minimumWidth != null && this.minimumWidth.getValue(firstLineWidth) > myContentWidth) {
myContentWidth = this.minimumWidth.getValue(firstLineWidth) - (getBorderWidthLeft() + getBorderWidthRight() + this.marginLeft + this.paddingLeft + this.marginRight + this.paddingRight);
}
//#if polish.css.expand-items
if (this.isExpandItems) {
for (int i = 0; i < myItems.length; i++)
{
Item item = myItems[i];
if (!item.isLayoutExpand && item.itemWidth < myContentWidth) {
item.setItemWidth( myContentWidth );
}
}
}
//#endif
if (!hasFocusableItem) {
if (this.defaultCommand != null || (this.commands != null && this.commands.size() > 0)) {
this.appearanceMode = INTERACTIVE;
} else if(!this.appearanceModeSet){
this.appearanceMode = PLAIN;
}
} else {
this.appearanceMode = INTERACTIVE;
Item item = this.focusedItem;
if (item == null) {
this.internalX = NO_POSITION_SET;
} else {
updateInternalPosition(item);
if (isLayoutShrink) {
//System.out.println("container has shrinking layout and contains focused item " + item);
boolean doExpand = item.isLayoutExpand;
int width;
if (doExpand) {
item.setInitialized(false);
item.isLayoutExpand = false;
width = item.getItemWidth( availWidth, availWidth, availHeight );
item.setInitialized(false);
item.isLayoutExpand = true;
if (width > myContentWidth) {
myContentWidth = width;
}
}
if ( this.minimumWidth != null && myContentWidth < this.minimumWidth.getValue(availWidth) ) {
myContentWidth = this.minimumWidth.getValue(availWidth);
}
if (doExpand) {
item.init(myContentWidth, myContentWidth, availHeight);
}
//myContentHeight += item.getItemHeight( lineWidth, lineWidth );
}
}
}
if (hasCenterOrRightItems) {
int width;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
width = item.itemWidth;
if (item.isLayoutCenter) {
item.relativeX = (myContentWidth - width) / 2;
} else if (item.isLayoutRight) {
item.relativeX = (myContentWidth - width);
}
}
}
if (this.scrollItem != null) {
boolean scrolled = scroll( 0, this.scrollItem, true );
//System.out.println( this + ": scrolled scrollItem " + this.scrollItem + ": " + scrolled);
if (scrolled) {
this.scrollItem = null;
}
}
this.contentHeight = myContentHeight;
this.contentWidth = myContentWidth;
//#debug
System.out.println("initContent(): Container " + this + " has a content-width of " + this.contentWidth + ", parent=" + this.parent);
}
}
/**
* Enables or disables the auto focus of this container
* @param enable true when autofocus should be enabled
*/
protected void setAutoFocusEnabled( boolean enable) {
// if (enable) {
// try { throw new RuntimeException("for autofocus, previous=" + this.autoFocusEnabled + ", index=" + this.autoFocusIndex ); } catch (Exception e) { e.printStackTrace(); }
// }
this.autoFocusEnabled = enable;
}
/**
* Updates the internal position of this container according to the specified item's one
* @param item the (assumed focused) item
*/
protected void updateInternalPosition(Item item) {
//#debug
System.out.println("updating internal position of " + this + " for child " + item);
if (item == null) {
return;
}
int prevX = this.internalX;
int prevY = this.internalY;
int prevWidth = this.internalWidth;
int prevHeight = this.internalHeight;
if (item.internalX != NO_POSITION_SET) { // && (item.itemHeight > getScrollHeight() || (item.contentY + item.internalY + item.internalHeight > item.itemHeight) ) ) {
// adjust internal settings for root container:
this.internalX = item.relativeX + item.contentX + item.internalX;
if (this.enableScrolling) {
this.internalY = getScrollYOffset() + item.relativeY + item.contentY + item.internalY;
} else {
this.internalY = item.relativeY + item.contentY + item.internalY;
}
this.internalWidth = item.internalWidth;
this.internalHeight = item.internalHeight;
//#debug
System.out.println(this + ": Adjusted internal area by internal area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
} else {
this.internalX = item.relativeX;
if (this.enableScrolling) {
this.internalY = getScrollYOffset() + item.relativeY;
} else {
this.internalY = item.relativeY;
}
this.internalWidth = item.itemWidth;
this.internalHeight = item.itemHeight;
//#debug
System.out.println(this + ": Adjusted internal area by full area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
}
if (this.isFocused
&& this.parent instanceof Container
&& (prevY != this.internalY || prevX != this.internalX || prevWidth != this.itemWidth || prevHeight != this.internalHeight)
) {
((Container)this.parent).updateInternalPosition( this );
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setContentWidth(int)
*/
protected void setContentWidth(int width)
{
if (width < this.contentWidth) {
initContent( width, width, this.availContentHeight);
} else {
super.setContentWidth(width);
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.setContentWidth( width );
}
//#endif
if (this.focusedItem != null && (this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK) {
this.focusedItem.init(width, width, this.contentHeight);
}
}
}
//#ifdef tmp.supportViewType
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#setContentHeight(int)
*/
protected void setContentHeight(int height) {
super.setContentHeight(height);
if(this.containerView != null) {
this.containerView.setContentHeight( height );
}
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setItemWidth(int)
*/
public void setItemWidth(int width) {
int prevContentX = this.contentX;
int myContentWidth = this.contentWidth + width - this.itemWidth;
super.setItemWidth(width);
//#ifdef tmp.supportViewType
if (this.containerView == null) {
//#endif
boolean hasCenterOrRightAlignedItems = false;
Item[] myItems = this.containerItems;
if (myItems != null) {
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
width = item.itemWidth;
if (item.isLayoutCenter) {
item.relativeX = (myContentWidth - width) / 2;
hasCenterOrRightAlignedItems = true;
} else if (item.isLayoutRight) {
item.relativeX = (myContentWidth - width);
hasCenterOrRightAlignedItems = true;
}
}
}
if (hasCenterOrRightAlignedItems) {
this.contentWidth = myContentWidth;
this.contentX = prevContentX;
}
//#ifdef tmp.supportViewType
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#paintContent(int, int, int, int, javax.microedition.lcdui.Graphics)
*/
protected void paintContent(int x, int y, int leftBorder, int rightBorder, Graphics g) {
//System.out.println("paintContent, size=" + this.itemsList.size() + ", isInitialized=" + this.isInitialized);
// System.out.println("paintContent with implicit width " + (rightBorder - leftBorder) + ", itemWidth=" + this.itemWidth + " of " + this ) ;
// paints all items,
// the layout will be done according to this containers'
// layout or according to the items layout, when specified.
// adjust vertical start for scrolling:
//#if polish.debug.debug
if (this.enableScrolling) {
// g.setColor( 0xFFFF00 );
// g.drawLine( leftBorder, y, rightBorder, y + getContentScrollHeight() );
// g.drawLine( rightBorder, y, leftBorder, y + + getContentScrollHeight() );
// g.drawString( "" + this.availableHeight, x, y, Graphics.TOP | Graphics.LEFT );
//#debug
System.out.println("Container: drawing " + this + " with yOffset=" + this.yOffset );
}
//#endif
boolean setClipping = ( this.enableScrolling && (this.yOffset != 0 || this.itemHeight > this.scrollHeight) ); //( this.yOffset != 0 && (this.marginTop != 0 || this.paddingTop != 0) );
int clipX = 0;
int clipY = 0;
int clipWidth = 0;
int clipHeight = 0;
if (setClipping) {
clipX = g.getClipX();
clipY = g.getClipY();
clipWidth = g.getClipWidth();
clipHeight = g.getClipHeight();
Screen scr = this.screen;
if (scr != null && scr.container == this && this.relativeY > scr.contentY ) {
int diff = this.relativeY - scr.contentY;
g.clipRect(clipX, y - diff, clipWidth, clipHeight - (y - clipY) + diff );
} else {
//g.clipRect(clipX, y, clipWidth, clipHeight - (y - clipY) );
// in this way we also clip the padding area at the bottom of the container (padding-bottom):
g.clipRect(clipX, y, clipWidth, this.scrollHeight - this.paddingTop - this.paddingBottom );
}
}
//x = leftBorder;
y += this.yOffset;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
//#debug
System.out.println("forwarding paint call to " + this.containerView );
this.containerView.paintContent( this, x, y, leftBorder, rightBorder, g);
if (setClipping) {
g.setClip(clipX, clipY, clipWidth, clipHeight);
}
} else {
//#endif
Item[] myItems = this.containerItems;
int startY = g.getClipY();
int endY = startY + g.getClipHeight();
Item focItem = this.focusedItem;
int focIndex = this.focusedIndex;
int itemX;
//int originalY = y;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
// currently the NEWLINE_AFTER and NEWLINE_BEFORE layouts will be ignored,
// since after every item a line break will be done. Use view-type: midp2; to place several items into a single row.
int itemY = y + item.relativeY;
if (i != focIndex && itemY + item.itemHeight >= startY && itemY < endY ){
//item.paint(x, y, leftBorder, rightBorder, g);
itemX = x + item.relativeX;
item.paint(itemX, itemY, itemX, itemX + item.itemWidth, g);
}
// if (item.itemHeight != 0) {
// y += item.itemHeight + this.paddingVertical;
// }
}
boolean paintFocusedItemOutside = false;
if (focItem != null) {
paintFocusedItemOutside = setClipping && (focItem.internalX != NO_POSITION_SET);
if (!paintFocusedItemOutside) {
itemX = x + focItem.relativeX;
focItem.paint(itemX, y + focItem.relativeY, itemX, itemX + focItem.itemWidth, g);
}
}
if (setClipping) {
g.setClip(clipX, clipY, clipWidth, clipHeight);
}
// paint the currently focused item outside of the clipping area when it has an internal area. This is
// for example useful for popup items that extend the actual container area.
if (paintFocusedItemOutside) {
//System.out.println("Painting focusedItem " + this.focusedItem + " with width=" + this.focusedItem.itemWidth + " and with increased colwidth of " + (focusedRightBorder - focusedX) );
itemX = x + focItem.relativeX;
focItem.paint(itemX, y + focItem.relativeY, itemX, itemX + focItem.itemWidth, g);
}
//#ifdef tmp.supportViewType
}
//#endif
// if (this.internalX != NO_POSITION_SET) {
// g.setColor(0xff00);
// g.drawRect( x + this.internalX, y + this.internalY, this.internalWidth, this.internalHeight );
// }
}
//#if tmp.supportViewType
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#paintBackgroundAndBorder(int, int, int, int, javax.microedition.lcdui.Graphics)
*/
protected void paintBackgroundAndBorder(int x, int y, int width, int height, Graphics g) {
if (this.containerView == null) {
super.paintBackgroundAndBorder(x, y, width, height, g);
} else {
// this is only necessary since ContainerViews are integrated differently from
// normal ItemViews - we should consider abonding this approach!
//#if polish.css.bgborder
if (this.bgBorder != null) {
int bgX = x - this.bgBorder.borderWidthLeft;
int bgW = width + this.bgBorder.borderWidthLeft + this.bgBorder.borderWidthRight;
int bgY = y - this.bgBorder.borderWidthTop;
int bgH = height + this.bgBorder.borderWidthTop + this.bgBorder.borderWidthBottom;
this.containerView.paintBorder( this.bgBorder, bgX, bgY, bgW, bgH, g );
}
//#endif
if ( this.background != null ) {
int bWidthL = getBorderWidthLeft();
int bWidthR = getBorderWidthRight();
int bWidthT = getBorderWidthTop();
int bWidthB = getBorderWidthBottom();
if ( this.border != null ) {
x += bWidthL;
y += bWidthT;
width -= bWidthL + bWidthR;
height -= bWidthT + bWidthB;
}
this.containerView.paintBackground( this.background, x, y, width, height, g );
if (this.border != null) {
x -= bWidthL;
y -= bWidthT;
width += bWidthL + bWidthR;
height += bWidthT + bWidthB;
}
}
if ( this.border != null ) {
this.containerView.paintBorder( this.border, x, y, width, height, g );
}
}
}
//#endif
//#ifdef polish.useDynamicStyles
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getCssSelector()
*/
protected String createCssSelector() {
return "container";
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyPressed(int, int)
*/
protected boolean handleKeyPressed(int keyCode, int gameAction) {
//#debug
System.out.println("handleKeyPressed( " + keyCode + ", " + gameAction + " ) for " + this + ", focusedItem=" + this.focusedItem);
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return super.handleKeyPressed(keyCode, gameAction);
}
Item item = this.focusedItem;
//looking for the next focusable Item if the focusedItem is not in
//the visible content area
//#ifdef tmp.supportFocusItemsInVisibleContentArea
//#if polish.hasPointerEvents
if(this.needsCheckItemInVisibleContent && item != null && !isItemInVisibleContentArea(item)
&& (gameAction == Canvas.DOWN || gameAction == Canvas.UP || gameAction == Canvas.LEFT || gameAction == Canvas.RIGHT)){
int next = -1;
int offset = 0;
//System.out.println("tmp.supportFocusItemsInVisibleContentArea is set");
if(gameAction == Canvas.DOWN ){
next = getFirstItemInVisibleContentArea(true);
offset = getScrollYOffset()-(this.getAvailableContentHeight());
}else if(gameAction == Canvas.UP ){
next = getLastItemInVisibleContentArea(true);
offset = getScrollYOffset()+(this.getAvailableContentHeight());
}
if(next != -1){
focusChild( next, this.get(next), gameAction, false );
item = get(next);
}
else{
if(gameAction == Canvas.DOWN || gameAction == Canvas.UP ){
boolean smooth = true;
//#ifdef polish.css.scroll-mode
smooth = this.scrollSmooth;
//#endif
setScrollYOffset(offset, smooth);
}
return true;
}
}else{
this.needsCheckItemInVisibleContent = false;
}
//#endif
//#endif
if (item != null) {
if (!item.isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
} else if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
int startY = getScrollYOffset() + item.relativeY + item.contentY + item.internalY;
if ( (
(startY < 0 && gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2)
|| (startY + item.internalHeight > this.scrollHeight && gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8)
)
&& (scroll(gameAction, item, false))
){
//System.out.println("scrolling instead of forwwarding key to child " + item + ", item.internalY=" + item.internalY + ", item.internalHeight=" + item.internalHeight + ", item.focused=" + (item instanceof Container ? item.relativeY + ((Container)item).focusedItem.relativeY : -1) );
return true;
}
}
int scrollOffset = getScrollYOffset();
if ( item.handleKeyPressed(keyCode, gameAction) ) {
//if (item.internalX != NO_POSITION_SET) {
if (this.enableScrolling) {
if (getScrollYOffset() == scrollOffset) {
//#debug
System.out.println("scrolling focused item that has handled key pressed, item=" + item + ", item.internalY=" + item.internalY);
scroll(gameAction, item, false);
}
} else {
updateInternalPosition(item);
}
//}
//#debug
System.out.println("Container(" + this + "): handleKeyPressed consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
return handleNavigate(keyCode, gameAction) || super.handleKeyPressed(keyCode, gameAction);
}
/**
* Handles a keyPressed or keyRepeated event for navigating in the container.
*
* @param keyCode the code of the keypress/keyrepeat event
* @param gameAction the associated game action
* @return true when the key was handled
*/
protected boolean handleNavigate(int keyCode, int gameAction) {
// now allow a navigation within the container:
boolean processed = false;
int offset = getRelativeScrollYOffset();
int availableScrollHeight = getScrollHeight();
Item focItem = this.focusedItem;
int y = 0;
int h = 0;
if (focItem != null && availableScrollHeight != -1) {
if (focItem.internalX == NO_POSITION_SET || (focItem.relativeY + focItem.contentY + focItem.internalY + focItem.internalHeight < availableScrollHeight)) {
y = focItem.relativeY;
h = focItem.itemHeight;
//System.out.println("normal item has focus: y=" + y + ", h=" + h + ", item=" + focItem);
} else {
y = focItem.relativeY + focItem.contentY + focItem.internalY;
h = focItem.internalHeight;
//System.out.println("internal item has focus: y=" + y + ", h=" + h + ", item=" + focItem);
}
//System.out.println("offset=" + offset + ", scrollHeight=" + availableScrollHeight + ", offset + y + h=" + (offset + y + h) + ", focusedItem=" + focItem);
}
if (
//#if polish.blackberry && !polish.hasTrackballEvents
(gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) ||
//#endif
(gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8))
{
if (focItem != null
&& (availableScrollHeight != -1 && offset + y + h > availableScrollHeight)
) {
//System.out.println("offset=" + offset + ", foc.relativeY=" + this.focusedItem.relativeY + ", foc.height=" + this.focusedItem.itemHeight + ", available=" + this.availableHeight);
// keep the focus do scroll downwards:
//#debug
System.out.println("Container(" + this + "): scrolling down: keeping focus, focusedIndex=" + this.focusedIndex + ", y=" + y + ", h=" + h + ", offset=" + offset );
} else {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
} else {
//#endif
processed = shiftFocus( true, 0 );
//#ifdef tmp.supportViewType
}
//#endif
}
//#debug
System.out.println("Container(" + this + "): forward shift by one item succeded: " + processed + ", focusedIndex=" + this.focusedIndex + ", enableScrolling=" + this.enableScrolling);
if ((!processed)
&& (
(availableScrollHeight != -1 && offset + y + h > availableScrollHeight)
|| (this.enableScrolling && offset + this.itemHeight > availableScrollHeight)
)
) {
int containerHeight = Math.max( this.contentHeight, this.backgroundHeight );
int availScrollHeight = getContentScrollHeight();
int scrollOffset = getScrollYOffset();
// scroll downwards:
int difference =
//#if polish.Container.ScrollDelta:defined
//#= ${polish.Container.ScrollDelta};
//#else
((containerHeight + scrollOffset) - availScrollHeight);
if(difference > (availScrollHeight / 2))
{
difference = availScrollHeight / 2;
}
//#endif
if(difference == 0)
{
return false;
}
offset = scrollOffset - difference;
if (offset > 0) {
offset = 0;
}
setScrollYOffset( offset, true );
processed = true;
//#debug
System.out.println("Down/Right: Decreasing (target)YOffset to " + offset);
}
} else if (
//#if polish.blackberry && !polish.hasTrackballEvents
(gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) ||
//#endif
(gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) )
{
if (focItem != null
&& availableScrollHeight != -1
&& offset + focItem.relativeY < 0 ) // this.focusedItem.yTopPos < this.yTop )
{
// keep the focus do scroll upwards:
//#debug
System.out.println("Container(" + this + "): scrolling up: keeping focus, relativeScrollOffset=" + offset + ", scrollHeight=" + availableScrollHeight + ", focusedIndex=" + this.focusedIndex + ", focusedItem.relativeY=" + this.focusedItem.relativeY + ", this.availableHeight=" + this.scrollHeight + ", targetYOffset=" + this.targetYOffset);
} else {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
} else {
//#endif
processed = shiftFocus( false, 0 );
//#ifdef tmp.supportViewType
}
//#endif
}
//#debug
System.out.println("Container(" + this + "): upward shift by one item succeded: " + processed + ", focusedIndex=" + this.focusedIndex );
if ((!processed)
&& ( (this.enableScrolling && offset < 0)
|| (availableScrollHeight != -1 && focItem != null && offset + focItem.relativeY < 0) )
) {
// scroll upwards:
int difference =
//#if polish.Container.ScrollDelta:defined
//#= ${polish.Container.ScrollDelta};
//#else
getScreen() != null ? getScreen().contentHeight / 2 : 30;
//#endif
offset = getScrollYOffset() + difference;
if (offset > 0) {
offset = 0;
}
setScrollYOffset(offset, true);
//#debug
System.out.println("Up/Left: Increasing (target)YOffset to " + offset);
processed = true;
}
}
//#ifdef tmp.supportViewType
else if (this.containerView != null)
{
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
}
//#endif
return processed;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyReleased(int, int)
*/
protected boolean handleKeyReleased(int keyCode, int gameAction) {
//#debug
System.out.println("handleKeyReleased( " + keyCode + ", " + gameAction + " ) for " + this);
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return super.handleKeyReleased(keyCode, gameAction);
}
Item item = this.focusedItem;
if (item != null) {
int scrollOffset = getScrollYOffset();
if ( item.handleKeyReleased( keyCode, gameAction ) ) {
if (item.isShown) { // could be that the item or its screen has been removed in the meantime...
if (this.enableScrolling) {
if (getScrollYOffset() == scrollOffset) {
//#debug
System.out.println("scrolling focused item that has handled key released, item=" + item + ", item.internalY=" + item.internalY);
scroll(gameAction, item, false);
}
} else {
updateInternalPosition(item);
}
}
// 2009-06-10:
// if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
// scroll(gameAction, item);
// }
// if (this.enableScrolling) {
// if (getScrollYOffset() == scrollOffset) {
// // #debug
// System.out.println("scrolling focused item that has handled key pressed, item=" + item + ", item.internalY=" + item.internalY);
// scroll(gameAction, item);
// }
// } else {
// if (item.itemHeight > getScrollHeight() && item.internalX != NO_POSITION_SET) {
// // adjust internal settings for root container:
// this.internalX = item.relativeX + item.contentX + item.internalX;
// this.internalY = item.relativeY + item.contentY + item.internalY;
// this.internalWidth = item.internalWidth;
// this.internalHeight = item.internalHeight;
// // #debug
// System.out.println(this + ": Adjusted internal area by internal area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
// } else {
// this.internalX = item.relativeX;
// this.internalY = item.relativeY;
// this.internalWidth = item.itemWidth;
// this.internalHeight = item.itemHeight;
// // #debug
// System.out.println(this + ": Adjusted internal area by full area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
// }
// }
//#debug
System.out.println("Container(" + this + "): handleKeyReleased consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handleKeyReleased(keyCode, gameAction) ) {
return true;
}
}
//#endif
return super.handleKeyReleased(keyCode, gameAction);
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyRepeated(int, int)
*/
protected boolean handleKeyRepeated(int keyCode, int gameAction) {
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return false;
}
if (this.focusedItem != null) {
Item item = this.focusedItem;
if ( item.handleKeyRepeated( keyCode, gameAction ) ) {
if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
scroll(gameAction, item, false);
}
//#debug
System.out.println("Container(" + this + "): handleKeyRepeated consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
return handleNavigate(keyCode, gameAction);
// note: in previous versions a keyRepeat event was just re-asigned to a keyPressed event. However, this resulted
// in non-logical behavior when an item wants to ignore keyRepeat events and only press "real" keyPressed events.
// So now events are ignored by containers when they are ignored by their currently focused item...
//return super.handleKeyRepeated(keyCode, gameAction);
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
/**
* Focuses the first visible item in the given vertical minimum and maximum offsets.
*
* @param container
* the container
* @param verticalMin
* the vertical minimum offset
* @param verticalMax
* the vertical maximum offset
* @return
* the newly focused item
*/
Item focusVisible(Container container, int verticalMin, int verticalMax) {
Item[] items = container.getItems();
Item focusedItem = null;
for (int index = 0; index < items.length; index++) {
Item item = items[index];
int itemTop= item.getAbsoluteY();
int itemBottom = itemTop + item.itemHeight;
int itemAppearanceMode = item.getAppearanceMode();
// if item is interactive ...
if(itemAppearanceMode == Item.INTERACTIVE || itemAppearanceMode == Item.HYPERLINK || itemAppearanceMode == Item.BUTTON) {
// ... and is a container and not fully visible ...
if(item instanceof Container && !isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, true)) {
// ... but partially visible ...
if(isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, false)) {
focusedItem = focusVisible((Container)item, verticalMin, verticalMax);
// if a child item was focused ...
if(focusedItem != null) {
focusIndex(index);
return item;
}
}
} else if(isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, true)) {
return focusIndex(index);
}
}
}
return null;
}
/**
* Returns true if the given item top and bottom offset is inside the given vertical minimum and maximum offset.
*
* @param verticalMin
* the vertical minimum offset
* @param verticalMax
* the vertical maximum offset
* @param itemTop
* the item top offset
* @param itemBottom
* the item bottom offset
* @param full
* true if the item must fit completly into the given vertical offsets otherwise false
* @return true
* if the item fits into the given vertical offsets otherwise false
*/
protected boolean isItemVisible(int verticalMin, int verticalMax, int itemTop, int itemBottom, boolean full) {
if(full) {
return itemTop >= verticalMin && itemBottom <= verticalMax;
} else {
return !(itemBottom <= verticalMin || itemTop >= verticalMax);
}
}
/**
* Focuses the child at the given index while preserving the scroll offset.
*
* @param index
* the index
* @return the focused item
*/
Item focusIndex(int index) {
int scrollOffset = getScrollYOffset();
setInitialized(false);
focusChild(index);
setInitialized(true);
setScrollYOffset(scrollOffset);
return getFocusedChild();
}
//#endif
/**
* Shifts the focus to the next or the previous item.
*
* @param forwardFocus true when the next item should be focused, false when
* the previous item should be focused.
* @param steps how many steps forward or backward the search for the next focusable item should be started,
* 0 for the current item, negative values go backwards.
* @return true when the focus could be moved to either the next or the previous item.
*/
private boolean shiftFocus(boolean forwardFocus, int steps ) {
Item[] items = getItems();
if ( items == null || items.length <= 1) {
//#debug
System.out.println("shiftFocus fails: this.items==null or items.length <= 0");
return false;
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
if(this.focusedIndex == -1) {
int verticalMin = getAbsoluteY();
int verticalMax = verticalMin + getScrollHeight();
Item newFocusedItem = focusVisible(this, verticalMin, verticalMax);
if(newFocusedItem != null) {
return true;
}
}
//#endif
//System.out.println("|");
Item focItem = this.focusedItem;
//#if polish.css.colspan
int i = this.focusedIndex;
if (steps != 0) {
//System.out.println("ShiftFocus: steps=" + steps + ", forward=" + forwardFocus);
int doneSteps = 0;
steps = Math.abs( steps ) + 1;
Item item = items[i];
while( doneSteps <= steps) {
doneSteps += item.colSpan;
if (doneSteps >= steps) {
//System.out.println("bailing out at too many steps: focusedIndex=" + this.focusedIndex + ", startIndex=" + i + ", steps=" + steps + ", doneSteps=" + doneSteps);
break;
}
if (forwardFocus) {
i++;
if (i == items.length - 1 ) {
i = items.length - 2;
break;
} else if (i == items.length) {
i = items.length - 1;
break;
}
} else {
i--;
if (i < 0) {
i = 1;
break;
}
}
item = items[i];
//System.out.println("focusedIndex=" + this.focusedIndex + ", startIndex=" + i + ", steps=" + steps + ", doneSteps=" + doneSteps);
}
if (doneSteps >= steps && item.colSpan != 1) {
if (forwardFocus) {
i--;
if (i < 0) {
i = items.length - 1;
}
//System.out.println("forward: Adjusting startIndex to " + i );
} else {
i = (i + 1) % items.length;
//System.out.println("backward: Adjusting startIndex to " + i );
}
}
}
//#else
//# int i = this.focusedIndex + steps;
if (i > items.length) {
i = items.length - 2;
}
if (i < 0) {
i = 1;
}
//#endif
Item item = null;
boolean allowCycle = this.allowCycling;
if (allowCycle) {
if (forwardFocus) {
// when you scroll to the bottom and
// there is still space, do
// scroll first before cycling to the
// first item:
allowCycle = (getScrollYOffset() + this.itemHeight <= getScrollHeight() + 1);
//System.out.println("allowCycle-calculation ( forward non-smoothScroll): yOffset=" + this.yOffset + ", itemHeight=" + this.itemHeight + " (together="+ (this.yOffset + this.itemHeight));
} else {
// when you scroll to the top and
// there is still space, do
// scroll first before cycling to the
// last item:
allowCycle = (getScrollYOffset() == 0);
}
}
//#debug
System.out.println("shiftFocus of " + this + ": allowCycle(local)=" + allowCycle + ", allowCycle(global)=" + this.allowCycling + ", isFoward=" + forwardFocus + ", enableScrolling=" + this.enableScrolling + ", targetYOffset=" + this.targetYOffset + ", yOffset=" + this.yOffset + ", focusedIndex=" + this.focusedIndex + ", start=" + i );
while (true) {
if (forwardFocus) {
i++;
if (i >= items.length) {
if (allowCycle) {
if (!fireContinueCycle(CycleListener.DIRECTION_BOTTOM_TO_TOP)) {
return false;
}
allowCycle = false;
i = 0;
//#debug
System.out.println("allowCycle: Restarting at the beginning");
} else {
break;
}
}
} else {
i--;
if (i < 0) {
if (allowCycle) {
if (!fireContinueCycle(CycleListener.DIRECTION_TOP_TO_BOTTOM)) {
return false;
}
allowCycle = false;
i = items.length - 1;
//#debug
System.out.println("allowCycle: Restarting at the end");
} else {
break;
}
}
}
item = items[i];
if (item.appearanceMode != Item.PLAIN) {
break;
}
}
if (item == null || item.appearanceMode == Item.PLAIN || item == focItem) {
//#debug
System.out.println("got original focused item: " + (item == focItem) + ", item==null:" + (item == null) + ", mode==PLAIN:" + (item == null ? false:(item.appearanceMode == PLAIN)) );
return false;
}
int direction = Canvas.UP;
if (forwardFocus) {
direction = Canvas.DOWN;
}
focusChild(i, item, direction, false );
return true;
}
/**
* Retrieves the index of the item which is currently focused.
*
* @return the index of the focused item, -1 when none is focused.
*/
public int getFocusedIndex() {
return this.focusedIndex;
}
/**
* Retrieves the currently focused item.
*
* @return the currently focused item, null when there is no focusable item in this container.
*/
public Item getFocusedItem() {
return this.focusedItem;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setStyle(de.enough.polish.ui.Style)
*/
public void setStyle(Style style) {
//#if polish.debug.debug
if (this.parent == null) {
//#debug
System.out.println("Container.setStyle without boolean parameter for container " + toString() );
}
//#endif
setStyleWithBackground(style, false);
}
/**
* Sets the style of this container.
*
* @param style the style
* @param ignoreBackground when true is given, the background and border-settings
* will be ignored.
*/
public void setStyleWithBackground( Style style, boolean ignoreBackground) {
super.setStyle(style);
if (ignoreBackground) {
this.background = null;
this.border = null;
this.marginTop = 0;
this.marginBottom = 0;
this.marginLeft = 0;
this.marginRight = 0;
}
this.isIgnoreMargins = ignoreBackground;
//#if polish.css.focused-style-first
Style firstFocusStyleObj = (Style) style.getObjectProperty("focused-style-first");
if (firstFocusStyleObj != null) {
this.focusedStyleFirst = firstFocusStyleObj;
}
//#endif
//#if polish.css.focused-style-last
Style lastFocusStyleObj = (Style) style.getObjectProperty("focused-style-last");
if (lastFocusStyleObj != null) {
this.focusedStyleLast = lastFocusStyleObj;
}
//#endif
//#if polish.css.focus-all-style
Style focusAllStyleObj = (Style) style.getObjectProperty("focus-all-style");
if (focusAllStyleObj != null) {
this.focusAllStyle = focusAllStyleObj;
}
//#endif
//#ifdef polish.css.view-type
// ContainerView viewType = (ContainerView) style.getObjectProperty("view-type");
// if (this instanceof ChoiceGroup) {
// System.out.println("SET.STYLE / CHOICEGROUP: found view-type (1): " + (viewType != null) + " for " + this);
// }
if (this.view != null && this.view instanceof ContainerView) {
ContainerView viewType = (ContainerView) this.view; // (ContainerView) style.getObjectProperty("view-type");
this.containerView = viewType;
this.view = null; // set to null so that this container can control the view completely. This is necessary for scrolling, for example.
viewType.parentContainer = this;
viewType.focusFirstElement = this.autoFocusEnabled;
viewType.allowCycling = this.allowCycling;
if (this.focusedItem != null) {
viewType.focusItem(this.focusedIndex, this.focusedItem, 0 );
}
} else if (!this.preserveViewType && style.getObjectProperty("view-type") == null && !this.setView) {
this.containerView = null;
}
//#endif
//#ifdef polish.css.columns
if (this.containerView == null) {
Integer columns = style.getIntProperty("columns");
if (columns != null) {
if (columns.intValue() > 1) {
//System.out.println("Container: Using default container view for displaying table");
this.containerView = new ContainerView();
this.containerView.parentContainer = this;
this.containerView.focusFirstElement = this.autoFocusEnabled;
this.containerView.allowCycling = this.allowCycling;
}
}
}
//#endif
//#if polish.css.scroll-mode
Integer scrollModeInt = style.getIntProperty("scroll-mode");
if ( scrollModeInt != null ) {
this.scrollSmooth = (scrollModeInt.intValue() == SCROLL_SMOOTH);
}
//#endif
//#ifdef polish.css.scroll-duration
Integer scrollDurationInt = style.getIntProperty("scroll-duration");
if (scrollDurationInt != null) {
this.scrollDuration = scrollDurationInt.intValue();
}
//#endif
//#if tmp.checkBouncing
Boolean allowBounceBool = style.getBooleanProperty("bounce");
if (allowBounceBool != null) {
this.allowBouncing = allowBounceBool.booleanValue();
}
//#endif
//#if polish.css.expand-items
synchronized(this.itemsList) {
Boolean expandItemsBool = style.getBooleanProperty("expand-items");
if (expandItemsBool != null) {
this.isExpandItems = expandItemsBool.booleanValue();
}
}
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.setStyle(style);
}
//#endif
//#if polish.css.focus-all
Boolean focusAllBool = style.getBooleanProperty("focus-all");
if (focusAllBool != null) {
this.isFocusAllChildren = focusAllBool.booleanValue();
}
//#endif
//#if polish.css.press-all
Boolean pressAllBool = style.getBooleanProperty("press-all");
if (pressAllBool != null) {
this.isPressAllChildren = pressAllBool.booleanValue();
}
//#endif
//#if polish.css.change-styles
String changeStyles = style.getProperty("change-styles");
if (changeStyles != null) {
int splitPos = changeStyles.indexOf('>');
if (splitPos != -1) {
String oldStyle = changeStyles.substring(0, splitPos ).trim();
String newStyle = changeStyles.substring(splitPos+1).trim();
try {
changeChildStyles(oldStyle, newStyle);
} catch (Exception e) {
//#debug error
System.out.println("Unable to apply change-styles \"" + changeStyles + "\"" + e );
}
}
}
//#endif
//#ifdef polish.css.show-delay
Integer showDelayInt = style.getIntProperty("show-delay");
if (showDelayInt != null) {
this.showDelay = showDelayInt.intValue();
}
//#endif
//#if polish.css.child-style
Style childStyleObj = (Style) style.getObjectProperty("child-style");
if (childStyleObj != null) {
this.childStyle = childStyleObj;
}
//#endif
}
//#ifdef tmp.supportViewType
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setStyle(de.enough.polish.ui.Style, boolean)
*/
public void setStyle(Style style, boolean resetStyle)
{
super.setStyle(style, resetStyle);
if (this.containerView != null) {
this.containerView.setStyle(style, resetStyle);
}
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#resetStyle(boolean)
*/
public void resetStyle(boolean recursive) {
super.resetStyle(recursive);
if (recursive) {
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++) {
Item item = (Item) items[i];
if (item == null) {
break;
}
item.resetStyle(recursive);
}
}
}
/**
* Changes the style of all children that are currently using the specified oldChildStyle with the given newChildStyle.
*
* @param oldChildStyleName the name of the style of child items that should be exchanged
* @param newChildStyleName the name of the new style for child items that were using the specified oldChildStyle before
* @throws IllegalArgumentException if no corresponding newChildStyle could be found
* @see StyleSheet#getStyle(String)
*/
public void changeChildStyles( String oldChildStyleName, String newChildStyleName) {
Style newChildStyle = StyleSheet.getStyle(newChildStyleName);
if (newChildStyle == null) {
throw new IllegalArgumentException("for " + newChildStyleName );
}
Style oldChildStyle = StyleSheet.getStyle(oldChildStyleName);
changeChildStyles(oldChildStyle, newChildStyle);
}
/**
* Changes the style of all children that are currently using the specified oldChildStyle with the given newChildStyle.
*
* @param oldChildStyle the style of child items that should be exchanged
* @param newChildStyle the new style for child items that were using the specified oldChildStyle before
* @throws IllegalArgumentException if newChildStyle is null
*/
public void changeChildStyles( Style oldChildStyle, Style newChildStyle) {
if (newChildStyle == null) {
throw new IllegalArgumentException();
}
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++)
{
Item child = (Item) children[i];
if (child == null) {
break;
}
if (child.style == oldChildStyle) {
child.setStyle( newChildStyle );
}
}
}
/**
* Parses the given URL and includes the index of the item, when there is an "%INDEX%" within the given url.
* @param url the resource URL which might include the substring "%INDEX%"
* @param item the item to which the URL belongs to. The item must be
* included in this container.
* @return the URL in which the %INDEX% is substituted by the index of the
* item in this container. The url "icon%INDEX%.png" is resolved
* to "icon1.png" when the item is the second item in this container.
* @throws NullPointerException when the given url or item is null
*/
public String parseIndexUrl(String url, Item item) {
int pos = url.indexOf("%INDEX%");
if (pos != -1) {
int index = this.itemsList.indexOf( item );
//TODO rob check if valid, when url ends with %INDEX%
url = url.substring(0, pos) + index + url.substring( pos + 7 );
}
return url;
}
/**
* Retrieves the position of the specified item.
*
* @param item the item
* @return the position of the item, or -1 when it is not defined
*/
public int getPosition( Item item ) {
return this.itemsList.indexOf( item );
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#focus(de.enough.polish.ui.Style, int)
*/
protected Style focus(Style focusStyle, int direction ) {
//#debug
System.out.println("focusing container " + this + " from " + (this.style != null ? this.style.name : "<no style>") + " to " + getFocusedStyle().name);
if (this.isFocused) {
return this.style;
}
this.plainStyle = null;
if ( this.itemsList.size() == 0) {
return super.focus(focusStyle, direction );
} else {
focusStyle = getFocusedStyle();
//#if polish.css.focus-all
if (this.isFocusAllChildren) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemFocusedStyle = item.getFocusedStyle();
if (itemFocusedStyle != focusStyle && itemFocusedStyle != StyleSheet.focusedStyle) {
if (!item.isFocused) {
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.focus(itemFocusedStyle, direction);
}
}
}
}
//#endif
//#if polish.css.focus-all-style
if (this.focusAllStyle != null) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.setStyle(this.focusAllStyle);
}
}
//#endif
Style result = this.style;
if ((focusStyle != null && focusStyle != StyleSheet.focusedStyle && (this.parent == null || (this.parent.getFocusedStyle() != focusStyle)))
//#if polish.css.include-label
|| (this.includeLabel && focusStyle != null)
//#endif
) {
result = super.focus( focusStyle, direction );
this.plainStyle = result;
}
if (!this.isStyleInitialized && result != null) {
//#debug
System.out.println("setting original style for container " + this + " with style " + result.name);
setStyle( result );
}
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.focus(focusStyle, direction);
//this.isInitialised = false; not required
}
//#endif
this.isFocused = true;
int newFocusIndex = this.focusedIndex;
//#if tmp.supportViewType
if ( this.containerView == null || this.containerView.allowsAutoTraversal ) {
//#endif
Item[] myItems = getItems();
if (this.autoFocusEnabled && this.autoFocusIndex < myItems.length && (myItems[this.autoFocusIndex].appearanceMode != PLAIN)) {
//#debug
System.out.println("focus(Style, direction): autofocusing " + this + ", focusedIndex=" + this.focusedIndex + ", autofocus=" + this.autoFocusIndex);
newFocusIndex = this.autoFocusIndex;
setAutoFocusEnabled( false );
} else {
// focus the first interactive item...
if (direction == Canvas.UP || direction == Canvas.LEFT ) {
//System.out.println("Container: direction UP with " + myItems.length + " items");
for (int i = myItems.length; --i >= 0; ) {
Item item = myItems[i];
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
} else {
//System.out.println("Container: direction DOWN");
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
}
}
this.focusedIndex = newFocusIndex;
if (newFocusIndex == -1) {
//System.out.println("DID NOT FIND SUITEABLE ITEM - current style=" + this.style.name);
// this container has only non-focusable items!
if (this.plainStyle != null) {
// this will result in plainStyle being returned in the super.focus() call:
this.style = this.plainStyle;
}
return super.focus( focusStyle, direction );
}
//#if tmp.supportViewType
} else if (this.focusedIndex == -1) {
Object[] myItems = this.itemsList.getInternalArray();
//System.out.println("Container: direction DOWN through view type " + this.view);
for (int i = 0; i < myItems.length; i++) {
Item item = (Item) myItems[i];
if (item == null) {
break;
}
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
this.focusedIndex = newFocusIndex;
if (newFocusIndex == -1) {
//System.out.println("DID NOT FIND SUITEABLE ITEM (2)");
// this container has only non-focusable items!
if (this.plainStyle != null) {
this.style = this.plainStyle;
}
return super.focus( focusStyle, direction );
}
}
//#endif
Item item = get( this.focusedIndex );
// Style previousStyle = item.style;
// if (previousStyle == null) {
// previousStyle = StyleSheet.defaultStyle;
// }
this.showCommandsHasBeenCalled = false;
//#if polish.css.focus-all
if (item.isFocused) {
Style orStyle = (Style) item.getAttribute(KEY_ORIGINAL_STYLE);
if (orStyle != null) {
//#debug
System.out.println("re-setting to plain style " + orStyle.name + " for item " + item);
item.style = orStyle;
}
}
//#endif
focusChild( this.focusedIndex, item, direction, true );
// item command handling is now done within showCommands and handleCommand
if (!this.showCommandsHasBeenCalled && this.commands != null) {
showCommands();
}
// if (item.commands == null && this.commands != null) {
// Screen scr = getScreen();
// if (scr != null) {
// scr.setItemCommands(this);
// }
// }
// change the label-style of this container:
//#ifdef polish.css.label-style
if (this.label != null && focusStyle != null) {
Style labStyle = (Style) focusStyle.getObjectProperty("label-style");
if (labStyle != null) {
this.labelStyle = this.label.style;
this.label.setStyle( labStyle );
}
}
//#endif
return result;
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#defocus(de.enough.polish.ui.Style)
*/
public void defocus(Style originalStyle) {
//#debug
System.out.println("defocus container " + this + " with style " + (originalStyle != null ? originalStyle.name : "<no style>"));
//#if polish.css.focus-all
if (this.isFocusAllChildren) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemPlainStyle = (Style) item.removeAttribute( KEY_ORIGINAL_STYLE );
if (itemPlainStyle != null) {
item.defocus(itemPlainStyle);
}
}
}
//#endif
Style originalItemStyle = this.itemStyle;
//#if polish.css.focus-all-style
if (this.focusAllStyle != null) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemPlainStyle = (Style) item.removeAttribute( KEY_ORIGINAL_STYLE );
if (itemPlainStyle != null) {
if (item == this.focusedItem) {
originalItemStyle = itemPlainStyle;
} else {
item.setStyle(itemPlainStyle);
}
}
}
}
//#endif
if ( this.itemsList.size() == 0 || this.focusedIndex == -1 ) {
super.defocus( originalStyle );
} else {
if (this.plainStyle != null) {
super.defocus( this.plainStyle );
if (originalStyle == null) {
originalStyle = this.plainStyle;
}
this.plainStyle = null;
} else if (this.isPressed) {
notifyItemPressedEnd();
}
this.isFocused = false;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.defocus( originalStyle );
setInitialized(false);
}
//#endif
Item item = this.focusedItem;
if (item != null) {
//#if polish.css.focus-all
if (item.isFocused) {
//#endif
item.defocus( originalItemStyle );
//#if polish.css.focus-all
}
//#endif
this.isFocused = false;
// now remove any commands which are associated with this item:
if (item.commands == null && this.commands != null) {
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
}
}
// change the label-style of this container:
//#ifdef polish.css.label-style
Style tmpLabelStyle = null;
if ( originalStyle != null) {
tmpLabelStyle = (Style) originalStyle.getObjectProperty("label-style");
}
if (tmpLabelStyle == null) {
tmpLabelStyle = StyleSheet.labelStyle;
}
if (this.label != null && tmpLabelStyle != null && this.label.style != tmpLabelStyle) {
this.label.setStyle( tmpLabelStyle );
}
//#endif
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#showCommands()
*/
public void showCommands() {
this.showCommandsHasBeenCalled = true;
super.showCommands();
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleCommand(javax.microedition.lcdui.Command)
*/
protected boolean handleCommand(Command cmd) {
boolean handled = super.handleCommand(cmd);
if (!handled && this.focusedItem != null) {
return this.focusedItem.handleCommand(cmd);
}
return handled;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#animate(long, de.enough.polish.ui.ClippingRegion)
*/
public void animate(long currentTime, ClippingRegion repaintRegion) {
super.animate(currentTime, repaintRegion);
boolean addFullRepaintRegion = false;
// scroll the container:
int target = this.targetYOffset;
int current = this.yOffset;
int diff = 0;
if (target != current) {
long passedTime = (currentTime - this.scrollStartTime);
int nextOffset = CssAnimation.calculatePointInRange(this.scrollStartYOffset, target, passedTime, this.scrollDuration , CssAnimation.FUNCTION_EXPONENTIAL_OUT );
this.yOffset = nextOffset;
addFullRepaintRegion = true;
}
int speed = this.scrollSpeed;
if (speed != 0) {
speed = (speed * (100 - this.scrollDamping)) / 100;
if (speed <= 0) {
speed = 0;
}
this.scrollSpeed = speed;
long timeDelta = currentTime - this.lastAnimationTime;
if (timeDelta > 1000) {
timeDelta = AnimationThread.ANIMATION_INTERVAL;
}
speed = (int) ((speed * timeDelta) / 1000);
if (speed == 0) {
this.scrollSpeed = 0;
}
int offset = this.yOffset;
if (this.scrollDirection == Canvas.UP) {
offset += speed;
target = offset;
if (offset > 0) {
this.scrollSpeed = 0;
target = 0;
//#if tmp.checkBouncing
if (!this.allowBouncing) {
offset = 0;
}
//#elif polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false
offset = 0;
//#endif
}
} else {
offset -= speed;
target = offset;
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
// Style myStyle = this.style;
// if (myStyle != null) {
// maxItemHeight -= myStyle.getPaddingTop(this.availableHeight) + myStyle.getPaddingBottom(this.availableHeight) + myStyle.getMarginTop(this.availableHeight) + myStyle.getMarginBottom(this.availableHeight);
// }
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (offset + maxItemHeight < this.scrollHeight) {
this.scrollSpeed = 0;
target = this.scrollHeight - maxItemHeight;
//#if tmp.checkBouncing
if (!this.allowBouncing) {
offset = target;
}
//#elif polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false
offset = target;
//#endif
}
}
this.yOffset = offset;
this.targetYOffset = target;
addFullRepaintRegion = true;
}
// add repaint region:
if (addFullRepaintRegion) {
int x, y, width, height;
Screen scr = getScreen();
height = getItemAreaHeight();
if (this.parent == null && (this.scrollHeight > height || this.enableScrolling)) { // parent==null is required for example when a commands container is scrolled.
x = scr.contentX;
y = scr.contentY;
height = scr.contentHeight;
width = scr.contentWidth + scr.getScrollBarWidth();
} else {
x = getAbsoluteX();
y = getAbsoluteY();
width = this.itemWidth;
//#if polish.useScrollBar || polish.classes.ScrollBar:defined
width += scr.getScrollBarWidth();
//#endif
}
repaintRegion.addRegion( x, y, width, height + diff + 1 );
}
this.lastAnimationTime = currentTime;
Item focItem = this.focusedItem;
if (focItem != null) {
focItem.animate(currentTime, repaintRegion);
}
//#ifdef tmp.supportViewType
ContainerView contView = this.containerView;
if ( contView != null ) {
contView.animate(currentTime, repaintRegion);
}
//#endif
//#if polish.css.show-delay
if (this.showDelay != 0 && this.showDelayIndex != 0) {
int index = Math.min( (int)((currentTime - this.showNotifyTime) / this.showDelay), this.itemsList.size());
if (index > this.showDelayIndex) {
for (int i=this.showDelayIndex; i<index; i++) {
try {
//System.out.println("calling show notify on item " + i + " at " + (currentTime - this.showNotifyTime) + ", show-delay=" + this.showDelay);
Item item = get(i);
item.showNotify();
} catch (Exception e) {
//#debug error
System.out.println("Unable to notify");
}
}
if (index == this.itemsList.size()) {
this.showDelayIndex = 0;
} else {
this.showDelayIndex = index;
}
}
}
//#endif
//#if polish.css.focus-all
if (this.isFocusAllChildren && this.isFocused) {
Item[] items = this.getItems();
for (int i = 0; i < items.length; i++) {
Item item = items[i];
item.animate(currentTime, repaintRegion);
}
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#addRepaintArea(de.enough.polish.ui.ClippingRegion)
*/
public void addRepaintArea(ClippingRegion repaintRegion) {
if (this.enableScrolling) {
Screen scr = getScreen();
int x = scr.contentX;
int y = scr.contentY;
int height = scr.contentHeight;
int width = scr.contentWidth + scr.getScrollBarWidth();
repaintRegion.addRegion(x, y, width, height);
} else {
super.addRepaintArea(repaintRegion);
}
}
/**
* Called by the system to notify the item that it is now at least
* partially visible, when it previously had been completely invisible.
* The item may receive <code>paint()</code> calls after
* <code>showNotify()</code> has been called.
*
* <p>The container implementation calls showNotify() on the embedded items.</p>
*/
protected void showNotify()
{
super.showNotify();
if (this.style != null && !this.isStyleInitialized) {
setStyle( this.style );
}
//#ifdef polish.useDynamicStyles
else if (this.style == null) {
initStyle();
}
//#else
else if (this.style == null && !this.isStyleInitialized) {
//#debug
System.out.println("Setting default style for container " + this );
setStyle( StyleSheet.defaultStyle );
}
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.showNotify();
}
//#endif
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.style != null && !item.isStyleInitialized) {
item.setStyle( item.style );
}
//#ifdef polish.useDynamicStyles
else if (item.style == null) {
initStyle();
}
//#else
else if (item.style == null && !item.isStyleInitialized) {
//#debug
System.out.println("Setting default style for item " + item );
item.setStyle( StyleSheet.defaultStyle );
}
//#endif
//#if polish.css.show-delay
if (this.showDelay == 0 || i == 0) {
//#endif
item.showNotify();
//#if polish.css.show-delay
}
//#endif
}
//#if polish.css.show-delay
this.showDelayIndex = (myItems.length > 1 ? 1 : 0);
this.showNotifyTime = System.currentTimeMillis();
//#endif
//#if !polish.Container.selectEntriesWhileTouchScrolling
if (minimumDragDistance == 0) {
minimumDragDistance = Math.min(Display.getScreenWidth(),Display.getScreenHeight())/10;
}
//#endif
}
/**
* Called by the system to notify the item that it is now completely
* invisible, when it previously had been at least partially visible. No
* further <code>paint()</code> calls will be made on this item
* until after a <code>showNotify()</code> has been called again.
*
* <p>The container implementation calls hideNotify() on the embedded items.</p>
*/
protected void hideNotify()
{
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.hideNotify();
}
//#endif
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
item.hideNotify();
}
}
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerPressed(int, int)
*/
protected boolean handlePointerPressed(int relX, int relY) {
//#debug
System.out.println("Container.handlePointerPressed(" + relX + ", " + relY + ") for " + this );
//System.out.println("Container.handlePointerPressed( x=" + x + ", y=" + y + "): adjustedY=" + (y - (this.yOffset + this.marginTop + this.paddingTop )) );
// an item within this container was selected:
this.lastPointerPressY = relY;
this.lastPointerPressYOffset = getScrollYOffset();
this.lastPointerPressTime = System.currentTimeMillis();
int origRelX = relX;
int origRelY = relY;
relY -= this.yOffset;
relY -= this.contentY;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
//System.out.println("Container.handlePointerPressed: adjusted to (" + relX + ", " + relY + ") for " + this );
boolean eventHandled = false;
Item item = this.focusedItem;
if (item != null) {
// the focused item can extend the parent container, e.g. subcommands,
// so give it a change to process the event itself:
int itemLayout = item.layout;
boolean processed = item.handlePointerPressed(relX - item.relativeX, relY - item.relativeY );
if (processed) {
//#debug
System.out.println("pointerPressed at " + relX + "," + relY + " consumed by focusedItem " + item);
// layout could have been changed:
if (item.layout != itemLayout && isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
if (item.isLayoutLeft()) {
item.relativeX = 0;
} else if (item.isLayoutCenter()) {
item.relativeX = (this.contentWidth - item.itemWidth)/2;
} else {
item.relativeX = this.contentWidth - item.itemWidth;
}
}
notifyItemPressedStart();
return true;
} else if (item.isPressed) {
eventHandled = notifyItemPressedStart();
}
}
//#ifdef tmp.supportViewType
if (contView != null) {
relX += viewXOffset;
if ( contView.handlePointerPressed(relX + this.contentX, relY + this.contentY) ) {
//System.out.println("ContainerView " + contView + " consumed pointer press event");
notifyItemPressedStart();
return true;
}
relX -= viewXOffset;
}
if (!isInItemArea(origRelX, origRelY - this.yOffset) || (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) ) {
//System.out.println("Container.handlePointerPressed(): out of range, relativeX=" + this.relativeX + ", relativeY=" + this.relativeY + ", contentHeight=" + this.contentHeight );
return ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
}
//#else
if (!isInItemArea(origRelX, origRelY) || (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) ) {
//System.out.println("Container.handlePointerPressed(): out of range, relativeX=" + this.relativeX + ", relativeY=" + this.relativeY + ", contentHeight=" + this.contentHeight );
return super.handlePointerPressed(origRelX, origRelY) || eventHandled;
}
//#endif
Screen scr = this.screen;
if ( ((origRelY < 0) && (scr == null || origRelY + this.relativeY - scr.contentY < 0))
|| (this.enableScrolling && origRelY > this.scrollHeight)
){
return ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
}
Item nextItem = getChildAt( origRelX, origRelY );
if (nextItem != null && nextItem != item) {
int index = this.itemsList.indexOf(nextItem);
//#debug
System.out.println("Container.handlePointerPressed(" + relX + "," + relY + "): found item " + index + "=" + item + " at relative " + relX + "," + relY + ", itemHeight=" + item.itemHeight);
// only focus the item when it has not been focused already:
int offset = getScrollYOffset();
focusChild(index, nextItem, 0, true);
setScrollYOffset( offset, false ); // don't move the UI while handling the press event:
// let the item also handle the pointer-pressing event:
nextItem.handlePointerPressed( relX - nextItem.relativeX , relY - nextItem.relativeY );
if (!this.isFocused) {
setAutoFocusEnabled( true );
this.autoFocusIndex = index;
}
notifyItemPressedStart();
return true;
}
// Item[] myItems = getItems();
// int itemRelX, itemRelY;
// for (int i = 0; i < myItems.length; i++) {
// item = myItems[i];
// itemRelX = relX - item.relativeX;
// itemRelY = relY - item.relativeY;
// //System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
// if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// // this item is not in the range or not suitable:
// continue;
// }
// // the pressed item has been found:
// //#debug
// System.out.println("Container.handlePointerPressed(" + relX + "," + relY + "): found item " + i + "=" + item + " at relative " + itemRelX + "," + itemRelY + ", itemHeight=" + item.itemHeight);
// // only focus the item when it has not been focused already:
// int offset = getScrollYOffset();
// focusChild(i, item, 0, true);
// setScrollYOffset( offset, false ); // don't move the UI while handling the press event:
// // let the item also handle the pointer-pressing event:
// item.handlePointerPressed( itemRelX , itemRelY );
// if (!this.isFocused) {
// this.autoFocusEnabled = true;
// this.autoFocusIndex = i;
// }
// return true;
// }
boolean handledBySuperImplementation = ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
//#if polish.android
if (!handledBySuperImplementation && (item != null) && (item._androidView != null) && (!item._androidView.isFocused())) {
item.defocus(this.itemStyle);
handledBySuperImplementation = true;
}
//#endif
return handledBySuperImplementation;
}
//#endif
//#ifdef polish.hasPointerEvents
/**
* Allows subclasses to check if a pointer release event is used for scrolling the container.
* This method can only be called when polish.hasPointerEvents is true.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
*/
protected boolean handlePointerScrollReleased(int relX, int relY) {
if (Display.getInstance().hasPointerMotionEvents()) {
return false;
}
int yDiff = relY - this.lastPointerPressY;
int bottomY = Math.max( this.itemHeight, this.internalY + this.internalHeight );
if (this.focusedItem != null && this.focusedItem.relativeY + this.focusedItem.backgroundHeight > bottomY) {
bottomY = this.focusedItem.relativeY + this.focusedItem.backgroundHeight;
}
if ( this.enableScrolling
&& (this.itemHeight > this.scrollHeight || this.yOffset != 0)
&& ((yDiff < -5 && this.yOffset + bottomY > this.scrollHeight) // scrolling downwards
|| (yDiff > 5 && this.yOffset != 0) ) // scrolling upwards
)
{
int offset = this.yOffset + yDiff;
if (offset > 0) {
offset = 0;
}
//System.out.println("adjusting scrolloffset to " + offset);
setScrollYOffset(offset, true);
return true;
}
return false;
}
//#endif
//#if polish.hasPointerEvents
/**
* Handles the behavior of the virtual keyboard when the item is focused.
* By defaukt, the virtual keyboard is hidden. Components which need to have the virtual keyboard
* shown when they are focused can override this method.
*/
public void handleOnFocusSoftKeyboardDisplayBehavior() {
Item focItem = this.focusedItem;
if (focItem != null) {
focItem.handleOnFocusSoftKeyboardDisplayBehavior();
} else {
super.handleOnFocusSoftKeyboardDisplayBehavior();
}
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerReleased(int, int)
*/
protected boolean handlePointerReleased(int relX, int relY) {
//#debug
System.out.println("Container.handlePointerReleased(" + relX + ", " + relY + ") for " + this );
// handle keyboard behaviour
if(this.isJustFocused) {
this.isJustFocused = false;
handleOnFocusSoftKeyboardDisplayBehavior();
}
//#ifdef tmp.supportFocusItemsInVisibleContentArea
//#if polish.hasPointerEvents
this.needsCheckItemInVisibleContent=true;
//#endif
//#endif
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
Item item = this.focusedItem;
if (this.enableScrolling) {
this.isScrolling = false;
int scrollDiff = Math.abs(getScrollYOffset() - this.lastPointerPressYOffset);
if ( scrollDiff > Display.getScreenHeight()/10 || handlePointerScrollReleased(relX, relY) ) {
// we have scrolling in the meantime
boolean processed = false;
if (item != null && item.isPressed) {
processed = item.handlePointerReleased(relX - item.relativeX, relY - item.relativeY );
setInitialized(false);
}
if (!processed) {
while (item instanceof Container) {
if (item.isPressed) {
item.notifyItemPressedEnd();
}
item = ((Container)item).focusedItem;
}
// we have scrolling in the meantime
if (item != null && item.isPressed) {
item.notifyItemPressedEnd();
setInitialized(false);
}
}
// check if we should continue the scrolling:
long dragTime = System.currentTimeMillis() - this.lastPointerPressTime;
if (dragTime < 1000 && dragTime > 1) {
int direction = Canvas.DOWN;
if (this.yOffset > this.lastPointerPressYOffset) {
direction = Canvas.UP;
}
startScroll( direction, (int) ((scrollDiff * 1000 ) / dragTime), 20 );
} else if (this.yOffset > 0) {
setScrollYOffset(0, true);
} else if (this.yOffset + this.contentHeight < this.availContentHeight) {
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (this.yOffset + maxItemHeight < this.scrollHeight) {
int target = this.scrollHeight - maxItemHeight;
setScrollYOffset( target, true );
}
}
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
}
// foward event to currently focused item:
int origRelX = relX;
// //#ifdef polish.css.before
// + getBeforeWidthWithPadding()
// //#endif
// ;
int origRelY = relY;
relY -= this.yOffset;
relY -= this.contentY;
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
if (contView.handlePointerReleased(relX + this.contentX, relY + this.contentY)) {
//System.out.println("ContainerView consumed pointer release event " + contView);
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
//System.out.println("Container.handlePointerReleased: adjusted to (" + relX + ", " + relY + ") for " + this );
if (item != null) {
// the focused item can extend the parent container, e.g. subcommands,
// so give it a change to process the event itself:
int itemLayout = item.layout;
boolean processed = item.handlePointerReleased(relX - item.relativeX, relY - item.relativeY );
if (processed) {
//#debug
System.out.println("pointerReleased at " + relX + "," + relY + " consumed by focusedItem " + item);
if (this.isPressed) {
notifyItemPressedEnd();
}
// layout could have been changed:
if (item.layout != itemLayout && isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
if (item.isLayoutLeft()) {
item.relativeX = 0;
} else if (item.isLayoutCenter()) {
item.relativeX = (this.contentWidth - item.itemWidth)/2;
} else {
item.relativeX = this.contentWidth - item.itemWidth;
}
}
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
} else if ( item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) {
//#debug
System.out.println("pointerReleased not handled by focused item but within that item's area. Item=" + item + ", container=" + this);
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
}
if (!isInItemArea(origRelX, origRelY)) {
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
Item nextItem = getChildAt(origRelX, origRelY);
if (nextItem != null && nextItem != item) {
item = nextItem;
int itemRelX = relX - item.relativeX;
int itemRelY = relY - item.relativeY;
item.handlePointerReleased( itemRelX , itemRelY );
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
// Item[] myItems = getItems();
// int itemRelX, itemRelY;
// for (int i = 0; i < myItems.length; i++) {
// item = myItems[i];
// itemRelX = relX - item.relativeX;
// itemRelY = relY - item.relativeY;
// //System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
// if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// // this item is not in the range or not suitable:
// continue;
// }
// // the pressed item has been found:
// //#debug
// System.out.println("Container.handlePointerReleased(" + relX + "," + relY + "): found item " + i + "=" + item + " at relative " + itemRelX + "," + itemRelY + ", itemHeight=" + item.itemHeight);
// // only focus the item when it has not been focused already:
// //focus(i, item, 0);
// // let the item also handle the pointer-pressing event:
// item.handlePointerReleased( itemRelX , itemRelY );
// return true;
// }
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerDragged(int, int)
*/
protected boolean handlePointerDragged(int relX, int relY) {
return false;
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerDragged(int, int)
*/
protected boolean handlePointerDragged(int relX, int relY, ClippingRegion repaintRegion) {
//#debug
System.out.println("handlePointerDraggged " + relX + ", " + relY + " for " + this + ", enableScrolling=" + this.enableScrolling + ", focusedItem=" + this.focusedItem);
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
Item item = this.focusedItem;
if (item != null && item.handlePointerDragged( relX - this.contentX - item.relativeX, relY - this.yOffset - this.contentY - item.relativeY, repaintRegion)) {
return true;
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
- if(item != null) {
- int dragDistance = Math.abs(relY - this.lastPointerPressY);
- if(dragDistance > minimumDragDistance) {
- focusChild(-1);
- //#if polish.blackberry
- //# ((BaseScreen)(Object)Display.getInstance()).notifyFocusSet(null);
- //#endif
- UiAccess.init(item, item.getAvailableWidth(), item.getAvailableWidth(), item.getAvailableHeight());
- }
- }
+ if (item != null) {
+ int dragDistance = Math.abs(relY - this.lastPointerPressY);
+ if(dragDistance > minimumDragDistance) {
+ focusChild(-1);
+ //#if polish.blackberry
+ //# ((BaseScreen)(Object)Display.getInstance()).notifyFocusSet(null);
+ //#endif
+ UiAccess.init(item, item.getAvailableWidth(), item.getAvailableWidth(), item.getAvailableHeight());
+ }
+ }
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerDragged(relX, relY, repaintRegion) ) {
return true;
}
}
//#endif
if (this.enableScrolling ) {
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (maxItemHeight > this.scrollHeight || this.yOffset != 0) {
int lastOffset = getScrollYOffset();
int nextOffset = this.lastPointerPressYOffset + (relY - this.lastPointerPressY);
//#if tmp.checkBouncing
if (!this.allowBouncing) {
//#endif
//#if tmp.checkBouncing || (polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false)
if (nextOffset > 0) {
nextOffset = 0;
} else {
if (nextOffset + maxItemHeight < this.scrollHeight) {
nextOffset = this.scrollHeight - maxItemHeight;
}
}
//#endif
//#if tmp.checkBouncing
} else {
//#endif
//#if tmp.checkBouncing || !(polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false)
if (nextOffset > this.scrollHeight/3) {
nextOffset = this.scrollHeight/3;
} else {
maxItemHeight += this.scrollHeight/3;
if (nextOffset + maxItemHeight < this.scrollHeight) {
nextOffset = this.scrollHeight - maxItemHeight;
}
}
//#endif
//#if tmp.checkBouncing
}
//#endif
this.isScrolling = (nextOffset != lastOffset);
if (this.isScrolling) {
setScrollYOffset( nextOffset, false );
addRepaintArea(repaintRegion);
return true;
}
}
}
return super.handlePointerDragged(relX, relY, repaintRegion);
}
//#endif
//#if polish.hasTouchEvents
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerTouchDown(int, int)
*/
public boolean handlePointerTouchDown(int x, int y) {
if (this.enableScrolling) {
this.lastPointerPressY = y;
this.lastPointerPressYOffset = getScrollYOffset();
this.lastPointerPressTime = System.currentTimeMillis();
}
Item item = this.focusedItem;
if (item != null) {
if (item.handlePointerTouchDown(x - item.relativeX, y - item.relativeY)) {
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerTouchDown(x,y) ) {
return true;
}
}
//#endif
return super.handlePointerTouchDown(x, y);
}
//#endif
//#if polish.hasTouchEvents
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerTouchUp(int, int)
*/
public boolean handlePointerTouchUp(int x, int y) {
Item item = this.focusedItem;
if (item != null) {
if (item.handlePointerTouchUp(x - item.relativeX, y - item.relativeY)) {
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerTouchUp(x,y) ) {
return true;
}
}
//#endif
if (this.enableScrolling) {
int scrollDiff = Math.abs(getScrollYOffset() - this.lastPointerPressYOffset);
if (scrollDiff > Display.getScreenHeight()/10) {
long dragTime = System.currentTimeMillis() - this.lastPointerPressTime;
if (dragTime < 1000 && dragTime > 1) {
int direction = Canvas.DOWN;
if (this.yOffset > this.lastPointerPressYOffset) {
direction = Canvas.UP;
}
startScroll( direction, (int) ((scrollDiff * 1000 ) / dragTime), 20 );
} else if (this.yOffset > 0) {
setScrollYOffset( 0, true );
}
}
}
return super.handlePointerTouchUp(x, y);
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getItemAreaHeight()
*/
public int getItemAreaHeight()
{
int max = super.getItemAreaHeight();
Item item = this.focusedItem;
if (item != null) {
max = Math.max( max, this.contentY + item.relativeY + item.getItemAreaHeight() );
}
return max;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getItemAt(int, int)
*/
public Item getItemAt(int relX, int relY) {
relY -= this.yOffset;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relX -= this.contentX;
relY -= this.contentY;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
relX -= this.containerView.getScrollXOffset();
}
//#endif
Item item = this.focusedItem;
if (item != null) {
int itemRelX = relX - item.relativeX;
int itemRelY = relY - item.relativeY;
// if (this.label != null) {
// System.out.println("itemRelY=" + itemRelY + " of item " + item + ", parent=" + this );
// }
if (item.isInItemArea(itemRelX, itemRelY)) {
return item.getItemAt(itemRelX, itemRelY);
}
}
Item[] myItems = getItems();
int itemRelX, itemRelY;
for (int i = 0; i < myItems.length; i++) {
item = myItems[i];
itemRelX = relX - item.relativeX;
itemRelY = relY - item.relativeY;
if ( i == this.focusedIndex || !item.isInItemArea(itemRelX, itemRelY)) {
// this item is not in the range or not suitable:
continue;
}
// the pressed item has been found:
return item.getItemAt(itemRelX, itemRelY);
}
relY += this.yOffset;
relX += this.contentX;
relY += this.contentY;
return super.getItemAt(relX, relY);
}
/**
* Retrieves the child of this container at the corresponding position.
*
* @param relX the relative horizontal position
* @param relY the relatiev vertical position
* @return the item at that position, if any
*/
public Item getChildAt(int relX, int relY) {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
return this.containerView.getChildAt( relX, relY );
}
//#endif
return getChildAtImpl( relX, relY );
}
/**
* Actual implementation for finding a child, can be used by ContainerViews.
* @param relX the relative horizontal position
* @param relY the relative vertical position
* @return the child item at the specified position
*/
protected Item getChildAtImpl(int relX, int relY) {
relY -= this.yOffset;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relY -= this.contentY;
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
Item item = this.focusedItem;
if (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY)) {
return item;
}
Item[] myItems = getItems();
int itemRelX, itemRelY;
for (int i = 0; i < myItems.length; i++) {
item = myItems[i];
itemRelX = relX - item.relativeX;
itemRelY = relY - item.relativeY;
//System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// this item is not in the range or not suitable:
continue;
}
return item;
}
return null;
}
/**
* Moves the focus away from the specified item.
*
* @param item the item that currently has the focus
*/
public void requestDefocus( Item item ) {
if (item == this.focusedItem) {
boolean success = shiftFocus(true, 1);
if (!success) {
defocus(this.itemStyle);
}
}
}
/**
* Requests the initialization of this container and all of its children items.
* This was previously used for dimension changes which is now picked up automatically and not required anymore.
*/
public void requestFullInit() {
for (int i = 0; i < this.itemsList.size(); i++) {
Item item = (Item) this.itemsList.get(i);
item.setInitialized(false);
if (item instanceof Container) {
((Container)item).requestFullInit();
}
}
requestInit();
}
/**
* Retrieves the vertical scrolling offset of this item.
*
* @return either the currently used offset or the targeted offset in case the targeted one is different. This is either a negative integer or 0.
* @see #getCurrentScrollYOffset()
*/
public int getScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getScrollYOffset();
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
/**
* Retrieves the current vertical scrolling offset of this item, depending on the scroll mode this can change with every paint iteration.
*
* @return the currently used offset in pixels, either a negative integer or 0.
* @see #getScrollYOffset()
*/
public int getCurrentScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getCurrentScrollYOffset();
}
return this.yOffset;
}
/**
* Retrieves the vertical scrolling offset of this item relative to the top most container.
*
* @return either the currently used offset or the targeted offset in case the targeted one is different.
*/
public int getRelativeScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getRelativeScrollYOffset() + this.relativeY;
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
/**
* Sets the vertical scrolling offset of this item.
*
* @param offset either the new offset
*/
public void setScrollYOffset( int offset) {
setScrollYOffset( offset, false );
}
/**
* Sets the vertical scrolling offset of this item.
*
* @param offset either the new offset
* @param smooth scroll to this new offset smooth if allowed
* @see #getScrollYOffset()
*/
public void setScrollYOffset( int offset, boolean smooth) {
//#debug
System.out.println("Setting scrollYOffset to " + offset + " for " + this);
//try { throw new RuntimeException("for yOffset " + offset + " in " + this); } catch (Exception e) { e.printStackTrace(); }
if (!this.enableScrolling && this.parent instanceof Container) {
((Container)this.parent).setScrollYOffset(offset, smooth);
return;
}
this.scrollStartTime = System.currentTimeMillis();
this.scrollStartYOffset = this.yOffset;
if (!smooth
//#ifdef polish.css.scroll-mode
|| !this.scrollSmooth
//#endif
) {
this.yOffset = offset;
}
this.targetYOffset = offset;
this.scrollSpeed = 0;
}
/**
* Determines whether this container or one of its parent containers is currently being scrolled
* @return true when this container or one of its parent containers is currently being scrolled
*/
public boolean isScrolling() {
if (this.enableScrolling) {
return (this.isScrolling) || (this.targetYOffset != this.yOffset) || (this.scrollSpeed != 0);
} else if (this.parent instanceof Container) {
return ((Container)this.parent).isScrolling();
} else {
return false;
}
}
/**
* Starts to scroll in the specified direction
* @param direction either Canvas.UP or Canvas.DOWN
* @param speed the speed in pixels per second
* @param damping the damping in percent; 0 means no damping at all; 100 means the scrolling will be stopped immediately
*/
public void startScroll( int direction,int speed, int damping) {
//#debug
System.out.println("startScrolling " + (direction == Canvas.UP ? "up" : "down") + " with speed=" + speed + ", damping=" + damping + " for " + this);
if (!this.enableScrolling && this.parent instanceof Container) {
((Container)this.parent).startScroll(direction, speed, damping);
return;
}
this.scrollDirection = direction;
this.scrollDamping = damping;
this.scrollSpeed = speed;
}
/**
* Retrieves the index of the specified item.
*
* @param item the item
* @return the index of the item; -1 when the item is not part of this container
*/
public int indexOf(Item item) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++) {
Object object = myItems[i];
if (object == null) {
break;
}
if (object == item) {
return i;
}
}
return -1;
}
/**
* Checks if this container includes the specified item
* @param item the item
* @return true when this container contains the item
*/
public boolean contains( Item item ) {
return this.itemsList.contains(item);
}
//#if (polish.debug.error || polish.keepToString) && polish.debug.container.includeChildren
/**
* Generates a String representation of this item.
* This method is only implemented when the logging framework is active or the preprocessing variable
* "polish.keepToString" is set to true.
* @return a String representation of this item.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append( super.toString() ).append( ": { ");
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
//#if polish.supportInvisibleItems || polish.css.visible
if (item.isInvisible) {
buffer.append( i ).append(":invis./plain:" + ( item.appearanceMode == PLAIN ) + "=[").append( item.toString() ).append("]");
} else {
buffer.append( i ).append("=").append( item.toString() );
}
//#else
buffer.append( i ).append("=").append( item.toString() );
//#endif
if (i != myItems.length - 1 ) {
buffer.append(", ");
}
}
buffer.append( " }");
return buffer.toString();
}
//#endif
/**
* Sets a list of items for this container.
* Use this direct access only when you know what you are doing.
*
* @param itemsList the list of items to set
*/
public void setItemsList(ArrayList itemsList) {
//System.out.println("Container.setItemsList");
clear();
if (this.isFocused) {
//System.out.println("enabling auto focus for index=" + this.focusedIndex);
setAutoFocusEnabled( true );
this.autoFocusIndex = this.focusedIndex;
}
this.focusedIndex = -1;
this.focusedItem = null;
if (this.enableScrolling) {
setScrollYOffset(0, false);
}
this.itemsList = itemsList;
this.containerItems = null;
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++) {
Item item = (Item) myItems[i];
if (item == null) {
break;
}
item.parent = this;
if (this.isShown) {
item.showNotify();
}
}
requestInit();
}
/**
* Calculates the number of interactive items included in this container.
* @return the number between 0 and size()
*/
public int getNumberOfInteractiveItems()
{
int number = 0;
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++)
{
Item item = (Item) items[i];
if (item == null) {
break;
}
if (item.appearanceMode != PLAIN) {
number++;
}
}
return number;
}
/**
* Releases all (memory intensive) resources such as images or RGB arrays of this background.
*/
public void releaseResources() {
super.releaseResources();
Item[] items = getItems();
for (int i = 0; i < items.length; i++)
{
Item item = items[i];
item.releaseResources();
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.releaseResources();
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#destroy()
*/
public void destroy() {
Item[] items = getItems();
clear();
super.destroy();
for (int i = 0; i < items.length; i++)
{
Item item = items[i];
item.destroy();
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.destroy();
this.containerView = null;
}
//#endif
}
/**
* Retrieves the internal array with all managed items embedded in this container, some entries might be null.
* Use this method only if you know what you are doing and only for reading.
* @return the internal array of the managed items
*/
public Object[] getInternalArray()
{
return this.itemsList.getInternalArray();
}
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteY()
// */
// public int getAbsoluteY()
// {
// return super.getAbsoluteY() + this.yOffset;
// }
//
// //#ifdef tmp.supportViewType
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteX()
// */
// public int getAbsoluteX() {
// int xAdjust = 0;
// if (this.containerView != null) {
// xAdjust = this.containerView.getScrollXOffset();
// }
// return super.getAbsoluteX() + xAdjust;
// }
// //#endif
//
//
//
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteX()
// */
// public boolean isInItemArea(int relX, int relY, Item child) {
// relY -= this.yOffset;
// //#ifdef tmp.supportViewType
// if (this.containerView != null) {
// relX -= this.containerView.getScrollXOffset();
// }
// //#endif
// return super.isInItemArea(relX, relY, child);
// }
//
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#isInItemArea(int, int)
*/
public boolean isInItemArea(int relX, int relY) {
Item focItem = this.focusedItem;
if (focItem != null && focItem.isInItemArea(relX - focItem.relativeX, relY - focItem.relativeY)) {
return true;
}
return super.isInItemArea(relX, relY);
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#fireEvent(java.lang.String, java.lang.Object)
*/
public void fireEvent(String eventName, Object eventData)
{
super.fireEvent(eventName, eventData);
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++)
{
Item item = (Item) items[i];
if (item == null) {
break;
}
item.fireEvent(eventName, eventData);
}
}
//#ifdef polish.css.view-type
/**
* Sets the view type for this item.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
* @param view the new view, use null to remove the current view
*/
public void setView( ItemView view ) {
if (!(view instanceof ContainerView)) {
super.setView( view );
return;
}
if (!this.isStyleInitialized && this.style != null) {
setStyle( this.style );
}
if (view == null) {
this.containerView = null;
this.view = null;
} else {
ContainerView viewType = (ContainerView) view;
viewType.parentContainer = this;
viewType.focusFirstElement = this.autoFocusEnabled;
viewType.allowCycling = this.allowCycling;
this.containerView = viewType;
if (this.style != null) {
view.setStyle( this.style );
}
}
this.setView = true;
}
//#endif
//#ifdef polish.css.view-type
/**
* Retrieves the view type for this item.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
*
* @return the current view, may be null
*/
public ItemView getView() {
if (this.containerView != null) {
return this.containerView;
}
return this.view;
}
//#endif
//#ifdef polish.css.view-type
/**
* Retrieves the view type for this item or instantiates a new one.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
*
* @param viewType the view registered in the style
* @param viewStyle the style
* @return the view, may be null
*/
protected ItemView getView( ItemView viewType, Style viewStyle) {
if (viewType instanceof ContainerView) {
if (this.containerView == null || this.containerView.getClass() != viewType.getClass()) {
try {
// formerly we have used the style's instance when that instance was still free.
// However, that approach lead to GC problems, as the style is not garbage collected.
viewType = (ItemView) viewType.getClass().newInstance();
viewType.parentItem = this;
if (this.isShown) {
if (this.containerView != null) {
this.containerView.hideNotify();
}
viewType.showNotify();
}
return viewType;
} catch (Exception e) {
//#debug error
System.out.println("Container: Unable to init view-type " + e );
}
}
return this.containerView;
}
return super.getView( viewType, viewStyle );
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#initMargin(de.enough.polish.ui.Style, int)
*/
protected void initMargin(Style style, int availWidth) {
if (this.isIgnoreMargins) {
this.marginLeft = 0;
this.marginRight = 0;
this.marginTop = 0;
this.marginBottom = 0;
} else {
this.marginLeft = style.getMarginLeft( availWidth );
this.marginRight = style.getMarginRight( availWidth );
this.marginTop = style.getMarginTop( availWidth );
this.marginBottom = style.getMarginBottom(availWidth);
}
}
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#onScreenSizeChanged(int, int)
*/
public void onScreenSizeChanged(int screenWidth, int screenHeight) {
Style lastStyle = this.style;
super.onScreenSizeChanged(screenWidth, screenHeight);
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.onScreenSizeChanged(screenWidth, screenHeight);
}
//#endif
//#if polish.css.landscape-style || polish.css.portrait-style
if (this.plainStyle != null && this.style != lastStyle) {
Style newStyle = null;
if (screenWidth > screenHeight) {
if (this.landscapeStyle != null && this.style != this.landscapeStyle) {
newStyle = this.landscapeStyle;
}
} else if (this.portraitStyle != null && this.style != this.portraitStyle){
newStyle = this.portraitStyle;
}
this.plainStyle = newStyle;
}
//#endif
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++) {
Item item = (Item) items[i];
if (item == null) {
break;
}
item.onScreenSizeChanged(screenWidth, screenHeight);
}
}
/**
* Recursively returns the focused child item of this Container or of the currently focused child Container.
* @return the focused child item or this Container when there is no focused child.
*/
public Item getFocusedChild() {
Item item = getFocusedItem();
if (item == null) {
return this;
}
if (item instanceof Container) {
return ((Container)item).getFocusedChild();
}
return item;
}
//#if polish.css.press-all
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#notifyItemPressedStart()
*/
public boolean notifyItemPressedStart() {
boolean handled = super.notifyItemPressedStart();
if (this.isPressAllChildren) {
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++) {
Item child = (Item) children[i];
if (child == null) {
break;
}
handled |= child.notifyItemPressedStart();
}
}
return handled;
}
//#endif
//#if polish.css.press-all
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#notifyItemPressedEnd()
*/
public void notifyItemPressedEnd() {
super.notifyItemPressedEnd();
if (this.isPressAllChildren) {
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++) {
Item child = (Item) children[i];
if (child == null) {
break;
}
child.notifyItemPressedEnd();
}
}
}
//#endif
/**
* Resets the pointer press y offset which is used for starting scrolling processes.
* This is only applicable for touch enabled handsets.
*/
public void resetLastPointerPressYOffset() {
//#if polish.hasPointerEvents
this.lastPointerPressYOffset = this.targetYOffset;
//#endif
}
//#ifdef polish.Container.additionalMethods:defined
//#include ${polish.Container.additionalMethods}
//#endif
}
| false | true | public void focusChild( int index, Item item, int direction, boolean force ) {
//#debug
System.out.println("Container (" + this + "): Focusing child item " + index + " (" + item + "), isInitialized=" + this.isInitialized + ", autoFocusEnabled=" + this.autoFocusEnabled );
//System.out.println("focus: yOffset=" + this.yOffset + ", targetYOffset=" + this.targetYOffset + ", enableScrolling=" + this.enableScrolling + ", isInitialized=" + this.isInitialized );
if (!isInitialized() && this.autoFocusEnabled) {
// setting the index for automatically focusing the appropriate item
// during the initialization:
//#debug
System.out.println("Container: Setting autofocus-index to " + index );
this.autoFocusIndex = index;
}
if (this.isFocused) {
setAutoFocusEnabled( false );
}
if (index == this.focusedIndex && item.isFocused && item == this.focusedItem) {
//#debug
System.out.println("Container: ignoring focusing of item " + index );
//#ifdef polish.css.view-type
if (this.containerView != null && this.containerView.focusedIndex != index) {
this.containerView.focusedItem = item;
this.containerView.focusedIndex = index;
}
//#endif
// ignore the focusing of the same element:
return;
}
//#if polish.blackberry
if (this.isShown) {
Display.getInstance().notifyFocusSet(item);
}
//#endif
// indicating if either the former focusedItem or the new focusedItem has changed it's size or it's layout by losing/gaining the focus,
// of course this can only work if this container is already initialized:
boolean isReinitializationRequired = false;
// first defocus the last focused item:
Item previouslyFocusedItem = this.focusedItem;
if (previouslyFocusedItem != null) {
int wBefore = previouslyFocusedItem.itemWidth;
int hBefore = previouslyFocusedItem.itemHeight;
int layoutBefore = previouslyFocusedItem.layout;
if (this.itemStyle != null) {
previouslyFocusedItem.defocus(this.itemStyle);
} else {
//#debug error
System.out.println("Container: Unable to defocus item - no previous style found.");
previouslyFocusedItem.defocus( StyleSheet.defaultStyle );
}
if (isInitialized()) {
//fix 2008-11-11: width given to an item can be different from availableContentWidth on ContainerViews:
//int wAfter = previouslyFocusedItem.getItemWidth( this.availableContentWidth, this.availableContentWidth, this.availableHeight );
//fix 2008-12-10: on some ContainerViews it can happen, that not all items have been initialized before:
//int wAfter = item.getItemWidth( item.availableWidth, item.availableWidth, item.availableHeight );
int wAfter = getChildWidth(item);
int hAfter = previouslyFocusedItem.itemHeight;
int layoutAfter = previouslyFocusedItem.layout;
if (wAfter != wBefore || hAfter != hBefore || layoutAfter != layoutBefore ) {
//#debug
System.out.println("dimension changed from " + wBefore + "x" + hBefore + " to " + wAfter + "x" + hAfter + " for previous " + previouslyFocusedItem);
isReinitializationRequired = true;
//#if tmp.supportViewType
if (this.containerView != null) {
previouslyFocusedItem.setInitialized(false); // could be that a container view poses restrictions on the possible size, i.e. within a table
}
//#endif
}
}
}
int wBefore = item.itemWidth;
int hBefore = item.itemHeight;
int layoutBefore = item.layout;
Style newStyle = getFocusedStyle( index, item);
boolean isDownwards = (direction == Canvas.DOWN) || (direction == Canvas.RIGHT) || (direction == 0 && index > this.focusedIndex);
int previousIndex = this.focusedIndex; // need to determine whether the user has scrolled from the bottom to the top
this.focusedIndex = index;
this.focusedItem = item;
int scrollOffsetBeforeScroll = getScrollYOffset();
//#if tmp.supportViewType
if ( this.containerView != null ) {
this.itemStyle = this.containerView.focusItem( index, item, direction, newStyle );
} else {
//#endif
this.itemStyle = item.focus( newStyle, direction );
//#if tmp.supportViewType
}
//#endif
//#ifdef polish.debug.error
if (this.itemStyle == null) {
//#debug error
System.out.println("Container: Unable to retrieve style of item " + item.getClass().getName() );
}
//#endif
//System.out.println("focus - still initialized=" + this.isInitialized + " for " + this);
if (isInitialized()) {
// this container has been initialized already,
// so the dimensions are known.
//System.out.println("focus: contentWidth=" + this.contentWidth + ", of container " + this);
//int wAfter = item.getItemWidth( this.availableContentWidth, this.availableContentWidth, this.availableHeight );
// fix 2008-11-11: availableContentWidth can be different from the width granted to items in a ContainerView:
int wAfter = getChildWidth( item );
int hAfter = item.itemHeight;
int layoutAfter = item.layout;
if (wAfter != wBefore || hAfter != hBefore || layoutAfter != layoutBefore ) {
//#debug
System.out.println("dimension changed from " + wBefore + "x" + hBefore + " to " + wAfter + "x" + hAfter + " for next " + item);
isReinitializationRequired = true;
//#if tmp.supportViewType
if (this.containerView != null) {
item.setInitialized(false); // could be that a container view poses restrictions on the possible size, i.e. within a table
}
//#endif
}
updateInternalPosition(item);
if (getScrollHeight() != -1) {
// Now adjust the scrolling:
Item nextItem;
if ( isDownwards && index < this.itemsList.size() - 1 ) {
nextItem = get( index + 1 );
//#debug
System.out.println("Focusing downwards, nextItem.relativY = [" + nextItem.relativeY + "], focusedItem.relativeY=[" + item.relativeY + "], this.yOffset=" + this.yOffset + ", this.targetYOffset=" + this.targetYOffset);
} else if ( !isDownwards && index > 0 ) {
nextItem = get( index - 1 );
//#debug
System.out.println("Focusing upwards, nextItem.yTopPos = " + nextItem.relativeY + ", focusedItem.relativeY=" + item.relativeY );
} else {
//#debug
System.out.println("Focusing last or first item.");
nextItem = item;
}
if (getScrollYOffset() == scrollOffsetBeforeScroll) {
if ( this.enableScrolling && ((isDownwards && (index < previousIndex) || (previousIndex == -1))) ) {
// either the first item or the first selectable item has been focused, so scroll to the very top:
//#if tmp.supportViewType
if (this.containerView == null || !this.containerView.isVirtualContainer())
//#endif
{
setScrollYOffset(0, true);
}
} else {
int itemYTop = isDownwards ? item.relativeY : nextItem.relativeY;
int itemYBottom = isDownwards ? nextItem.relativeY + nextItem.itemHeight : item.relativeY + item.itemHeight;
int height = itemYBottom - itemYTop;
//System.out.println("scrolling for item " + item + ", nextItem=" + nextItem + " in " + this + " with relativeY=" + this.relativeY + ", itemYTop=" + itemYTop);
scroll( direction, this.relativeX, itemYTop, item.internalWidth, height, force );
}
}
}
} else if (getScrollHeight() != -1) { // if (this.enableScrolling) {
//#debug
System.out.println("focus: postpone scrolling to initContent() for " + this + ", item " + item);
this.isScrollRequired = true;
}
if (isInitialized()) {
setInitialized(!isReinitializationRequired);
} else if (this.contentWidth != 0) {
updateInternalPosition(item);
}
//#if polish.Container.notifyFocusChange
notifyStateChanged();
//#endif
if (this.focusListener != null) {
this.focusListener.onFocusChanged(this, this.focusedItem, this.focusedIndex);
}
}
/**
* Queries the width of an child item of this container.
* This allows subclasses to control the possible re-initialization that is happening here.
* Also ContainerViews can override the re-initialization in their respective getChildWidth() method.
* @param item the child item
* @return the width of the child item
* @see #getChildHeight(Item)
* @see ContainerView#getChildWidth(Item)
*/
protected int getChildWidth(Item item) {
//#if tmp.supportViewType
ContainerView contView = this.containerView;
if (contView != null) {
return contView.getChildWidth(item);
}
//#endif
int w;
if (item.availableWidth > 0) {
w = item.getItemWidth( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
w = item.getItemWidth( this.availContentWidth, this.availContentWidth, this.availContentHeight );
}
return w;
}
/**
* Queries the height of an child item of this container.
* This allows subclasses to control the possible re-initialization that is happening here.
* Also ContainerViews can override the re-initialization in their respective getChildHeight() method.
* @param item the child item
* @return the height of the child item
* @see #getChildHeight(Item)
* @see ContainerView#getChildHeight(Item)
*/
protected int getChildHeight(Item item) {
//#if tmp.supportViewType
ContainerView contView = this.containerView;
if (contView != null) {
return contView.getChildHeight(item);
}
//#endif
int h;
if (item.availableWidth > 0) {
h = item.getItemHeight( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
h = item.getItemHeight( this.availContentWidth, this.availContentWidth, this.availContentHeight );
}
return h;
}
/**
* Retrieves the best matching focus style for the given item
* @param index the index of the item
* @param item the item
* @return the matching focus style
*/
protected Style getFocusedStyle(int index, Item item)
{
Style newStyle = item.getFocusedStyle();
//#if polish.css.focused-style-first
if (index == 0 && this.focusedStyleFirst != null) {
newStyle = this.focusedStyleFirst;
}
//#endif
//#if polish.css.focused-style-last
if (this.focusedStyleLast != null && index == this.itemsList.size() - 1) {
newStyle = this.focusedStyleLast;
}
//#endif
return newStyle;
}
/**
* Scrolls this container so that the (internal) area of the given item is best seen.
* This is used when a GUI even has been consumed by the currently focused item.
* The call is fowarded to scroll( direction, x, y, w, h ).
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param item the item for which the scrolling should be adjusted
* @return true when the container was scrolled
*/
public boolean scroll(int direction, Item item, boolean force) {
//#debug
System.out.println("scroll: scrolling for item " + item + ", item.internalX=" + item.internalX +", relativeInternalY=" + ( item.relativeY + item.contentY + item.internalY ) + ", relativeY=" + item.relativeY + ", contentY=" + item.contentY + ", internalY=" + item.internalY);
if ( (item.internalX != NO_POSITION_SET)
&& ( (item.itemHeight > getScrollHeight()) || ( (item.internalY + item.internalHeight) > item.contentHeight ) )
) {
// use internal position of item for scrolling:
//System.out.println("using internal area for scrolling");
int relativeInternalX = item.relativeX + item.contentX + item.internalX;
int relativeInternalY = item.relativeY + item.contentY + item.internalY;
return scroll( direction, relativeInternalX, relativeInternalY, item.internalWidth, item.internalHeight, force );
} else {
if (!isInitialized() && item.relativeY == 0) {
// defer scrolling to init at a later stage:
//System.out.println( this + ": setting scrollItem to " + item);
synchronized(this.itemsList) {
this.scrollItem = item;
}
return true;
} else {
// use item dimensions for scrolling:
//System.out.println("use item area for scrolling");
return scroll( direction, item.relativeX, item.relativeY, item.itemWidth, item.itemHeight, force );
}
}
}
/**
* Adjusts the yOffset or the targetYOffset so that the given relative values are inside of the visible area.
* The call is forwarded to a parent container when scrolling is not enabled for this item.
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param x the horizontal position of the area relative to this content's left edge, is ignored in the current version
* @param y the vertical position of the area relative to this content's top edge
* @param width the width of the area
* @param height the height of the area
* @return true when the scroll request changed the internal scroll offsets
*/
protected boolean scroll( int direction, int x, int y, int width, int height ) {
return scroll( direction, x, y, width, height, false );
}
/**
* Adjusts the yOffset or the targetYOffset so that the given relative values are inside of the visible area.
* The call is forwarded to a parent container when scrolling is not enabled for this item.
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param x the horizontal position of the area relative to this content's left edge, is ignored in the current version
* @param y the vertical position of the area relative to this content's top edge
* @param width the width of the area
* @param height the height of the area
* @param force true when the area should be shown regardless where the the current scrolloffset is located
* @return true when the scroll request changed the internal scroll offsets
*/
protected boolean scroll( int direction, int x, int y, int width, int height, boolean force ) {
//#debug
System.out.println("scroll: direction=" + direction + ", y=" + y + ", availableHeight=" + this.scrollHeight + ", height=" + height + ", focusedIndex=" + this.focusedIndex + ", yOffset=" + this.yOffset + ", targetYOffset=" + this.targetYOffset +", numberOfItems=" + this.itemsList.size() + ", in " + this + ", downwards=" + (direction == Canvas.DOWN || direction == Canvas.RIGHT || direction == 0));
if (!this.enableScrolling) {
if (this.parent instanceof Container) {
x += this.contentX + this.relativeX;
y += this.contentY + this.relativeY;
//#debug
System.out.println("Forwarding scroll request to parent now with y=" + y);
return ((Container)this.parent).scroll(direction, x, y, width, height, force );
}
return false;
}
if ( height == 0) {
return false;
}
// assume scrolling down when the direction is not known:
boolean isDownwards = (direction == Canvas.DOWN || direction == Canvas.RIGHT || direction == 0);
boolean isUpwards = (direction == Canvas.UP );
int currentYOffset = this.targetYOffset; // yOffset starts at 0 and grows to -contentHeight + lastItem.itemHeight
//#if polish.css.scroll-mode
if (!this.scrollSmooth) {
currentYOffset = this.yOffset;
}
//#endif
int originalYOffset = currentYOffset;
int verticalSpace = this.scrollHeight - (this.contentY + this.marginBottom + this.paddingBottom + getBorderWidthBottom()); // the available height for this container
int yTopAdjust = 0;
Screen scr = this.screen;
boolean isCenterOrBottomLayout = (this.layout & LAYOUT_VCENTER) == LAYOUT_VCENTER || (this.layout & LAYOUT_BOTTOM) == LAYOUT_BOTTOM;
if (isCenterOrBottomLayout && (scr != null && this == scr.container && this.relativeY > scr.contentY)) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
yTopAdjust = this.relativeY - scr.contentY;
}
if ( y + height + currentYOffset + yTopAdjust > verticalSpace ) {
// the area is too low, so scroll down (= increase the negative yOffset):
//#debug
System.out.println("scroll: item too low: verticalSpace=" + verticalSpace + " y=" + y + ", height=" + height + ", yOffset=" + currentYOffset + ", yTopAdjust=" + yTopAdjust + ", relativeY=" + this.relativeY + ", screen.contentY=" + scr.contentY + ", scr=" + scr);
//currentYOffset += verticalSpace - (y + height + currentYOffset + yTopAdjust);
int newYOffset = verticalSpace - (y + height + yTopAdjust);
// check if the top of the area is still visible when scrolling downwards:
if ( !isUpwards && y + newYOffset < 0) {
newYOffset = -y;
}
if (isDownwards) {
// check if we scroll down more than one page:
int difference = Math.max(Math.abs(currentYOffset), Math.abs(newYOffset)) -
Math.min(Math.abs(currentYOffset), Math.abs(newYOffset));
if (difference > verticalSpace && !force ) {
newYOffset = currentYOffset - verticalSpace;
}
}
currentYOffset = newYOffset;
} else if ( y + currentYOffset < 0 ) {
//#debug
System.out.println("scroll: item too high: , y=" + y + ", current=" + currentYOffset + ", target=" + (-y) );
int newYOffset = -y;
// check if the bottom of the area is still visible when scrolling upwards:
if (isUpwards && newYOffset + y + height > verticalSpace) { // && height < verticalSpace) {
//2008-12-10: scrolling upwards resulted in too large jumps when we have big items, so
// adjust the offset in any case, not only when height is smaller than the vertical space (height < verticalSpace):
newYOffset = -(y + height) + verticalSpace;
}
int difference = Math.max(Math.abs(currentYOffset), Math.abs(newYOffset)) -
Math.min(Math.abs(currentYOffset), Math.abs(newYOffset));
if (difference > verticalSpace && !force ) {
newYOffset = currentYOffset + verticalSpace;
}
currentYOffset = newYOffset;
} else {
//#debug
System.out.println("scroll: do nothing");
return false;
}
if (currentYOffset != originalYOffset) {
setScrollYOffset(currentYOffset, true);
return true;
} else {
//#debug
System.out.println("scroll: no change");
return false;
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setAppearanceMode(int)
*/
public void setAppearanceMode(int appearanceMode)
{
super.setAppearanceMode(appearanceMode);
// this is used in initContent() to circumvent the
// reversal of the previously set appearance mode
synchronized(this.itemsList) {
this.appearanceModeSet = true;
}
}
protected void initLayout(Style style, int availWidth) {
//#ifdef polish.css.view-type
if (this.containerView != null) {
this.containerView.initPadding(style, availWidth);
} else
//#endif
{
initPadding(style, availWidth);
}
//#ifdef polish.css.view-type
if (this.containerView != null) {
this.containerView.initMargin(style, availWidth);
} else
//#endif
{
initMargin(style, availWidth);
}
}
/**
* Retrieves the synchronization lock for this container.
* As a lock either the internal ArrayList for items is used or the paint lock of the screen when this container is associated with a screen.
* The lock can be used manipulate a Container that is currently displayed
* @return the synchronization lock
* @see Screen#getPaintLock()
* @see #add(Item)
*/
public Object getSynchronizationLock() {
Object lock = this.itemsList;
Screen scr = getScreen();
if (scr != null) {
lock = scr.getPaintLock();
}
return lock;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#initItem( int, int )
*/
protected void initContent(int firstLineWidth, int availWidth, int availHeight) {
//#debug
System.out.println("Container: intialising content for " + this + ": autofocus=" + this.autoFocusEnabled + ", autoFocusIndex=" + this.autoFocusIndex + ", isFocused=" + this.isFocused + ", firstLineWidth=" + firstLineWidth + ", availWidth=" + availWidth + ", availHeight=" + availHeight + ", size=" + this.itemsList.size() );
//this.availableContentWidth = firstLineWidth;
//#if polish.css.focused-style
if (this.focusedStyle != null) {
this.focusedTopMargin = this.focusedStyle.getMarginTop(availWidth) + this.focusedStyle.getPaddingTop(availWidth);
if (this.focusedStyle.border != null) {
this.focusedTopMargin += this.focusedStyle.border.borderWidthTop;
}
if (this.focusedStyle.background != null) {
this.focusedTopMargin += this.focusedStyle.background.borderWidth;
}
}
//#endif
synchronized (this.itemsList) {
int myContentWidth = 0;
int myContentHeight = 0;
Item[] myItems;
if (this.containerItems == null || this.containerItems.length != this.itemsList.size()) {
myItems = (Item[]) this.itemsList.toArray( new Item[ this.itemsList.size() ]);
this.containerItems = myItems;
} else {
myItems = (Item[]) this.itemsList.toArray(this.containerItems);
}
//#if (polish.css.child-style-first || polish.css.child-style-last) && polish.css.child-style
if (this.style != null && this.childStyle != null) {
Style firstStyle = null;
//#if polish.css.child-style-first
firstStyle = (Style) this.style.getObjectProperty("child-style-first");
//#endif
Style lastStyle = null;
//#if polish.css.child-style-last
lastStyle = (Style) this.style.getObjectProperty("child-style-last");
//#endif
if (firstStyle != null || lastStyle != null) {
int lastIndex = myItems.length - 1;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.style == null) {
item.setStyle( this.childStyle );
}
if (i != 0 && item.style == firstStyle) {
item.setStyle( this.childStyle );
}
if (i != lastIndex && item.style == lastStyle) {
item.setStyle( this.childStyle );
}
if (i == 0 && firstStyle != null && item.style != firstStyle) {
item.setStyle( firstStyle );
}
if (i == lastIndex && lastStyle != null && item.style != lastStyle) {
item.setStyle( lastStyle );
}
}
}
}
//#endif
if (this.autoFocusEnabled && this.autoFocusIndex >= myItems.length ) {
this.autoFocusIndex = 0;
}
//#if polish.Container.allowCycling != false
if (this.focusedItem instanceof Container && ((Container)this.focusedItem).allowCycling && getNumberOfInteractiveItems() > 1) {
((Container)this.focusedItem).allowCycling = false;
}
Item ancestor = this.parent;
while (this.allowCycling && ancestor != null) {
if ( (ancestor instanceof Container) && ((Container)ancestor).getNumberOfInteractiveItems()>1 ) {
this.allowCycling = false;
break;
}
ancestor = ancestor.parent;
}
//#endif
//#if tmp.supportViewType
if (this.containerView != null) {
// additional initialization is necessary when a view is used for this container:
boolean requireScrolling = this.isScrollRequired && this.isFocused;
// System.out.println("ABOUT TO CALL INIT CONTENT - focusedIndex of Container=" + this.focusedIndex);
this.containerView.parentItem = this;
this.containerView.parentContainer = this;
this.containerView.init( this, firstLineWidth, availWidth, availHeight);
if (this.defaultCommand != null || (this.commands != null && this.commands.size() > 0)) {
this.appearanceMode = INTERACTIVE;
} else if(!this.appearanceModeSet){
this.appearanceMode = this.containerView.appearanceMode;
}
if (this.isFocused && this.autoFocusEnabled) {
//#debug
System.out.println("Container/View: autofocusing element starting at " + this.autoFocusIndex);
if (this.autoFocusIndex >= 0 && this.appearanceMode != Item.PLAIN) {
for (int i = this.autoFocusIndex; i < myItems.length; i++) {
Item item = myItems[i];
if (item.appearanceMode != Item.PLAIN) {
// make sure that the item has applied it's own style first (not needed since it has been initialized by the container view already):
//item.getItemHeight( firstLineWidth, lineWidth );
// now focus the item:
setAutoFocusEnabled( false );
requireScrolling = (this.autoFocusIndex != 0);
// int heightBeforeFocus = item.itemHeight;
focusChild( i, item, 0, true);
// outcommented on 2008-07-09 because this results in a wrong
// available width for items with subsequent wrong getAbsoluteX() coordinates
// int availableWidth = item.itemWidth;
// if (availableWidth < this.minimumWidth) {
// availableWidth = this.minimumWidth;
// }
// if (item.getItemHeight( availableWidth, availableWidth ) > heightBeforeFocus) {
// item.isInitialized = false;
// this.containerView.initContent( this, firstLineWidth, lineWidth);
// }
this.isScrollRequired = this.isScrollRequired && requireScrolling; // override setting in focus()
//this.containerView.focusedIndex = i; is done within focus(i, item, 0) already
//this.containerView.focusedItem = item;
//System.out.println("autofocus: found item " + i );
break;
}
}
// when deactivating the auto focus the container won't initialize correctly after it has
// been cleared and items are added subsequently one after another (e.g. like within the Browser).
// } else {
// this.autoFocusEnabled = false;
}
}
this.contentWidth = this.containerView.contentWidth;
this.contentHeight = this.containerView.contentHeight;
if (requireScrolling && this.focusedItem != null) {
//#debug
System.out.println("initContent(): scrolling autofocused or scroll-required item for view, focused=" + this.focusedItem);
Item item = this.focusedItem;
scroll( 0, item.relativeX, item.relativeY, item.itemWidth, item.itemHeight, true );
}
else if (this.scrollItem != null) {
//System.out.println("initContent(): scrolling scrollItem=" + this.scrollItem);
boolean scrolled = scroll( 0, this.scrollItem, true );
if (scrolled) {
this.scrollItem = null;
}
}
if (this.focusedItem != null) {
updateInternalPosition(this.focusedItem);
}
return;
}
//#endif
boolean isLayoutShrink = (this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK;
boolean hasFocusableItem = false;
int numberOfVerticalExpandItems = 0;
Item lastVerticalExpandItem = null;
int lastVerticalExpandItemIndex = 0;
boolean hasCenterOrRightItems = false;
boolean hasVerticalExpandItems = false;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.isLayoutVerticalExpand()) {
hasVerticalExpandItems = true;
break;
}
}
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (hasVerticalExpandItems && item.isLayoutVerticalExpand()) {
// re-initialize items when we have vertical-expand items, so that relativeY and itemHeight is correctly calculated
// with each run:
item.setInitialized(false);
}
//System.out.println("initalising " + item.getClass().getName() + ":" + i);
int width = item.getItemWidth( availWidth, availWidth, availHeight );
int height = item.itemHeight; // no need to call getItemHeight() since the item is now initialised...
// now the item should have a style, so it can be safely focused
// without loosing the style information:
//String toString = item.toString();
//System.out.println("init of item " + i + ": height=" + height + " of item " + toString.substring( 19, Math.min(120, toString.length() ) ));
//if (item.isInvisible && height != 0) {
// System.out.println("*** item.height != 0 even though it is INVISIBLE - isInitialized=" + item.isInitialized );
//}
if (item.appearanceMode != PLAIN) {
hasFocusableItem = true;
}
if (this.isFocused && this.autoFocusEnabled && (i >= this.autoFocusIndex ) && (item.appearanceMode != Item.PLAIN)) {
setAutoFocusEnabled( false );
//System.out.println("Container.initContent: auto-focusing " + i + ": " + item );
focusChild( i, item, 0, true );
this.isScrollRequired = (this.isScrollRequired || hasFocusableItem) && (this.autoFocusIndex != 0); // override setting in focus()
height = item.getItemHeight(availWidth, availWidth, availHeight);
if (!isLayoutShrink) {
width = item.itemWidth; // no need to call getItemWidth() since the item is now initialised...
} else {
width = 0;
}
if (this.enableScrolling && this.autoFocusIndex != 0) {
//#debug
System.out.println("initContent(): scrolling autofocused item, autofocus-index=" + this.autoFocusIndex + ", i=" + i );
scroll( 0, 0, myContentHeight, width, height, true );
}
} else if (i == this.focusedIndex) {
if (isLayoutShrink) {
width = 0;
}
if (this.isScrollRequired) {
//#debug
System.out.println("initContent(): scroll is required - scrolling to y=" + myContentHeight + ", height=" + height);
scroll( 0, 0, myContentHeight, width, height, true );
this.isScrollRequired = false;
// } else if (item.internalX != NO_POSITION_SET ) {
// // ensure that lines of textfields etc are within the visible area:
// scroll(0, item );
}
}
if (item.isLayoutVerticalExpand()) {
numberOfVerticalExpandItems++;
lastVerticalExpandItem = item;
lastVerticalExpandItemIndex = i;
}
if (width > myContentWidth) {
myContentWidth = width;
}
item.relativeY = myContentHeight;
if (item.isLayoutCenter || item.isLayoutRight) {
hasCenterOrRightItems = true;
if (this.parent == null) {
myContentWidth = availWidth;
}
} else {
item.relativeX = 0;
}
myContentHeight += height != 0 ? height + this.paddingVertical : 0;
//System.out.println( i + ": height=" + height + ", myContentHeight=" + myContentHeight + ", item=" + item + ", style=" + (this.style == null ? "<none>" : this.style.name));
//System.out.println("item.yTopPos=" + item.yTopPos);
} // cycling through all items
if (numberOfVerticalExpandItems > 0 && myContentHeight < availHeight) {
int diff = availHeight - myContentHeight;
if (numberOfVerticalExpandItems == 1) {
// this is a simple case:
lastVerticalExpandItem.setItemHeight( lastVerticalExpandItem.itemHeight + diff );
for (int i = lastVerticalExpandItemIndex+1; i < myItems.length; i++)
{
Item item = myItems[i];
item.relativeY += diff;
}
} else {
// okay, there are several items that would like to be expanded vertically:
// System.out.println("having " + numberOfVerticalExpandItems + ", diff: " + diff + "=>" + (diff / numberOfVerticalExpandItems) + "=>" + ((diff / numberOfVerticalExpandItems) * numberOfVerticalExpandItems));
diff = diff / numberOfVerticalExpandItems;
int relYAdjust = 0;
for (int i = 0; i < myItems.length; i++)
{
Item item = myItems[i];
// System.out.println("changing relativeY from " + item.relativeY + " to " + (item.relativeY + relYAdjust) + ", relYAdjust=" + relYAdjust + " for " + item );
item.relativeY += relYAdjust;
if (item.isLayoutVerticalExpand()) {
// System.out.println("changing itemHeight from " + item.itemHeight + " to " + (item.itemHeight + diff) + " for " + item);
item.setItemHeight(item.itemHeight + diff );
relYAdjust += diff;
}
}
}
myContentHeight = availHeight;
}
if (this.minimumWidth != null && this.minimumWidth.getValue(firstLineWidth) > myContentWidth) {
myContentWidth = this.minimumWidth.getValue(firstLineWidth) - (getBorderWidthLeft() + getBorderWidthRight() + this.marginLeft + this.paddingLeft + this.marginRight + this.paddingRight);
}
//#if polish.css.expand-items
if (this.isExpandItems) {
for (int i = 0; i < myItems.length; i++)
{
Item item = myItems[i];
if (!item.isLayoutExpand && item.itemWidth < myContentWidth) {
item.setItemWidth( myContentWidth );
}
}
}
//#endif
if (!hasFocusableItem) {
if (this.defaultCommand != null || (this.commands != null && this.commands.size() > 0)) {
this.appearanceMode = INTERACTIVE;
} else if(!this.appearanceModeSet){
this.appearanceMode = PLAIN;
}
} else {
this.appearanceMode = INTERACTIVE;
Item item = this.focusedItem;
if (item == null) {
this.internalX = NO_POSITION_SET;
} else {
updateInternalPosition(item);
if (isLayoutShrink) {
//System.out.println("container has shrinking layout and contains focused item " + item);
boolean doExpand = item.isLayoutExpand;
int width;
if (doExpand) {
item.setInitialized(false);
item.isLayoutExpand = false;
width = item.getItemWidth( availWidth, availWidth, availHeight );
item.setInitialized(false);
item.isLayoutExpand = true;
if (width > myContentWidth) {
myContentWidth = width;
}
}
if ( this.minimumWidth != null && myContentWidth < this.minimumWidth.getValue(availWidth) ) {
myContentWidth = this.minimumWidth.getValue(availWidth);
}
if (doExpand) {
item.init(myContentWidth, myContentWidth, availHeight);
}
//myContentHeight += item.getItemHeight( lineWidth, lineWidth );
}
}
}
if (hasCenterOrRightItems) {
int width;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
width = item.itemWidth;
if (item.isLayoutCenter) {
item.relativeX = (myContentWidth - width) / 2;
} else if (item.isLayoutRight) {
item.relativeX = (myContentWidth - width);
}
}
}
if (this.scrollItem != null) {
boolean scrolled = scroll( 0, this.scrollItem, true );
//System.out.println( this + ": scrolled scrollItem " + this.scrollItem + ": " + scrolled);
if (scrolled) {
this.scrollItem = null;
}
}
this.contentHeight = myContentHeight;
this.contentWidth = myContentWidth;
//#debug
System.out.println("initContent(): Container " + this + " has a content-width of " + this.contentWidth + ", parent=" + this.parent);
}
}
/**
* Enables or disables the auto focus of this container
* @param enable true when autofocus should be enabled
*/
protected void setAutoFocusEnabled( boolean enable) {
// if (enable) {
// try { throw new RuntimeException("for autofocus, previous=" + this.autoFocusEnabled + ", index=" + this.autoFocusIndex ); } catch (Exception e) { e.printStackTrace(); }
// }
this.autoFocusEnabled = enable;
}
/**
* Updates the internal position of this container according to the specified item's one
* @param item the (assumed focused) item
*/
protected void updateInternalPosition(Item item) {
//#debug
System.out.println("updating internal position of " + this + " for child " + item);
if (item == null) {
return;
}
int prevX = this.internalX;
int prevY = this.internalY;
int prevWidth = this.internalWidth;
int prevHeight = this.internalHeight;
if (item.internalX != NO_POSITION_SET) { // && (item.itemHeight > getScrollHeight() || (item.contentY + item.internalY + item.internalHeight > item.itemHeight) ) ) {
// adjust internal settings for root container:
this.internalX = item.relativeX + item.contentX + item.internalX;
if (this.enableScrolling) {
this.internalY = getScrollYOffset() + item.relativeY + item.contentY + item.internalY;
} else {
this.internalY = item.relativeY + item.contentY + item.internalY;
}
this.internalWidth = item.internalWidth;
this.internalHeight = item.internalHeight;
//#debug
System.out.println(this + ": Adjusted internal area by internal area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
} else {
this.internalX = item.relativeX;
if (this.enableScrolling) {
this.internalY = getScrollYOffset() + item.relativeY;
} else {
this.internalY = item.relativeY;
}
this.internalWidth = item.itemWidth;
this.internalHeight = item.itemHeight;
//#debug
System.out.println(this + ": Adjusted internal area by full area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
}
if (this.isFocused
&& this.parent instanceof Container
&& (prevY != this.internalY || prevX != this.internalX || prevWidth != this.itemWidth || prevHeight != this.internalHeight)
) {
((Container)this.parent).updateInternalPosition( this );
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setContentWidth(int)
*/
protected void setContentWidth(int width)
{
if (width < this.contentWidth) {
initContent( width, width, this.availContentHeight);
} else {
super.setContentWidth(width);
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.setContentWidth( width );
}
//#endif
if (this.focusedItem != null && (this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK) {
this.focusedItem.init(width, width, this.contentHeight);
}
}
}
//#ifdef tmp.supportViewType
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#setContentHeight(int)
*/
protected void setContentHeight(int height) {
super.setContentHeight(height);
if(this.containerView != null) {
this.containerView.setContentHeight( height );
}
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setItemWidth(int)
*/
public void setItemWidth(int width) {
int prevContentX = this.contentX;
int myContentWidth = this.contentWidth + width - this.itemWidth;
super.setItemWidth(width);
//#ifdef tmp.supportViewType
if (this.containerView == null) {
//#endif
boolean hasCenterOrRightAlignedItems = false;
Item[] myItems = this.containerItems;
if (myItems != null) {
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
width = item.itemWidth;
if (item.isLayoutCenter) {
item.relativeX = (myContentWidth - width) / 2;
hasCenterOrRightAlignedItems = true;
} else if (item.isLayoutRight) {
item.relativeX = (myContentWidth - width);
hasCenterOrRightAlignedItems = true;
}
}
}
if (hasCenterOrRightAlignedItems) {
this.contentWidth = myContentWidth;
this.contentX = prevContentX;
}
//#ifdef tmp.supportViewType
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#paintContent(int, int, int, int, javax.microedition.lcdui.Graphics)
*/
protected void paintContent(int x, int y, int leftBorder, int rightBorder, Graphics g) {
//System.out.println("paintContent, size=" + this.itemsList.size() + ", isInitialized=" + this.isInitialized);
// System.out.println("paintContent with implicit width " + (rightBorder - leftBorder) + ", itemWidth=" + this.itemWidth + " of " + this ) ;
// paints all items,
// the layout will be done according to this containers'
// layout or according to the items layout, when specified.
// adjust vertical start for scrolling:
//#if polish.debug.debug
if (this.enableScrolling) {
// g.setColor( 0xFFFF00 );
// g.drawLine( leftBorder, y, rightBorder, y + getContentScrollHeight() );
// g.drawLine( rightBorder, y, leftBorder, y + + getContentScrollHeight() );
// g.drawString( "" + this.availableHeight, x, y, Graphics.TOP | Graphics.LEFT );
//#debug
System.out.println("Container: drawing " + this + " with yOffset=" + this.yOffset );
}
//#endif
boolean setClipping = ( this.enableScrolling && (this.yOffset != 0 || this.itemHeight > this.scrollHeight) ); //( this.yOffset != 0 && (this.marginTop != 0 || this.paddingTop != 0) );
int clipX = 0;
int clipY = 0;
int clipWidth = 0;
int clipHeight = 0;
if (setClipping) {
clipX = g.getClipX();
clipY = g.getClipY();
clipWidth = g.getClipWidth();
clipHeight = g.getClipHeight();
Screen scr = this.screen;
if (scr != null && scr.container == this && this.relativeY > scr.contentY ) {
int diff = this.relativeY - scr.contentY;
g.clipRect(clipX, y - diff, clipWidth, clipHeight - (y - clipY) + diff );
} else {
//g.clipRect(clipX, y, clipWidth, clipHeight - (y - clipY) );
// in this way we also clip the padding area at the bottom of the container (padding-bottom):
g.clipRect(clipX, y, clipWidth, this.scrollHeight - this.paddingTop - this.paddingBottom );
}
}
//x = leftBorder;
y += this.yOffset;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
//#debug
System.out.println("forwarding paint call to " + this.containerView );
this.containerView.paintContent( this, x, y, leftBorder, rightBorder, g);
if (setClipping) {
g.setClip(clipX, clipY, clipWidth, clipHeight);
}
} else {
//#endif
Item[] myItems = this.containerItems;
int startY = g.getClipY();
int endY = startY + g.getClipHeight();
Item focItem = this.focusedItem;
int focIndex = this.focusedIndex;
int itemX;
//int originalY = y;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
// currently the NEWLINE_AFTER and NEWLINE_BEFORE layouts will be ignored,
// since after every item a line break will be done. Use view-type: midp2; to place several items into a single row.
int itemY = y + item.relativeY;
if (i != focIndex && itemY + item.itemHeight >= startY && itemY < endY ){
//item.paint(x, y, leftBorder, rightBorder, g);
itemX = x + item.relativeX;
item.paint(itemX, itemY, itemX, itemX + item.itemWidth, g);
}
// if (item.itemHeight != 0) {
// y += item.itemHeight + this.paddingVertical;
// }
}
boolean paintFocusedItemOutside = false;
if (focItem != null) {
paintFocusedItemOutside = setClipping && (focItem.internalX != NO_POSITION_SET);
if (!paintFocusedItemOutside) {
itemX = x + focItem.relativeX;
focItem.paint(itemX, y + focItem.relativeY, itemX, itemX + focItem.itemWidth, g);
}
}
if (setClipping) {
g.setClip(clipX, clipY, clipWidth, clipHeight);
}
// paint the currently focused item outside of the clipping area when it has an internal area. This is
// for example useful for popup items that extend the actual container area.
if (paintFocusedItemOutside) {
//System.out.println("Painting focusedItem " + this.focusedItem + " with width=" + this.focusedItem.itemWidth + " and with increased colwidth of " + (focusedRightBorder - focusedX) );
itemX = x + focItem.relativeX;
focItem.paint(itemX, y + focItem.relativeY, itemX, itemX + focItem.itemWidth, g);
}
//#ifdef tmp.supportViewType
}
//#endif
// if (this.internalX != NO_POSITION_SET) {
// g.setColor(0xff00);
// g.drawRect( x + this.internalX, y + this.internalY, this.internalWidth, this.internalHeight );
// }
}
//#if tmp.supportViewType
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#paintBackgroundAndBorder(int, int, int, int, javax.microedition.lcdui.Graphics)
*/
protected void paintBackgroundAndBorder(int x, int y, int width, int height, Graphics g) {
if (this.containerView == null) {
super.paintBackgroundAndBorder(x, y, width, height, g);
} else {
// this is only necessary since ContainerViews are integrated differently from
// normal ItemViews - we should consider abonding this approach!
//#if polish.css.bgborder
if (this.bgBorder != null) {
int bgX = x - this.bgBorder.borderWidthLeft;
int bgW = width + this.bgBorder.borderWidthLeft + this.bgBorder.borderWidthRight;
int bgY = y - this.bgBorder.borderWidthTop;
int bgH = height + this.bgBorder.borderWidthTop + this.bgBorder.borderWidthBottom;
this.containerView.paintBorder( this.bgBorder, bgX, bgY, bgW, bgH, g );
}
//#endif
if ( this.background != null ) {
int bWidthL = getBorderWidthLeft();
int bWidthR = getBorderWidthRight();
int bWidthT = getBorderWidthTop();
int bWidthB = getBorderWidthBottom();
if ( this.border != null ) {
x += bWidthL;
y += bWidthT;
width -= bWidthL + bWidthR;
height -= bWidthT + bWidthB;
}
this.containerView.paintBackground( this.background, x, y, width, height, g );
if (this.border != null) {
x -= bWidthL;
y -= bWidthT;
width += bWidthL + bWidthR;
height += bWidthT + bWidthB;
}
}
if ( this.border != null ) {
this.containerView.paintBorder( this.border, x, y, width, height, g );
}
}
}
//#endif
//#ifdef polish.useDynamicStyles
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getCssSelector()
*/
protected String createCssSelector() {
return "container";
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyPressed(int, int)
*/
protected boolean handleKeyPressed(int keyCode, int gameAction) {
//#debug
System.out.println("handleKeyPressed( " + keyCode + ", " + gameAction + " ) for " + this + ", focusedItem=" + this.focusedItem);
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return super.handleKeyPressed(keyCode, gameAction);
}
Item item = this.focusedItem;
//looking for the next focusable Item if the focusedItem is not in
//the visible content area
//#ifdef tmp.supportFocusItemsInVisibleContentArea
//#if polish.hasPointerEvents
if(this.needsCheckItemInVisibleContent && item != null && !isItemInVisibleContentArea(item)
&& (gameAction == Canvas.DOWN || gameAction == Canvas.UP || gameAction == Canvas.LEFT || gameAction == Canvas.RIGHT)){
int next = -1;
int offset = 0;
//System.out.println("tmp.supportFocusItemsInVisibleContentArea is set");
if(gameAction == Canvas.DOWN ){
next = getFirstItemInVisibleContentArea(true);
offset = getScrollYOffset()-(this.getAvailableContentHeight());
}else if(gameAction == Canvas.UP ){
next = getLastItemInVisibleContentArea(true);
offset = getScrollYOffset()+(this.getAvailableContentHeight());
}
if(next != -1){
focusChild( next, this.get(next), gameAction, false );
item = get(next);
}
else{
if(gameAction == Canvas.DOWN || gameAction == Canvas.UP ){
boolean smooth = true;
//#ifdef polish.css.scroll-mode
smooth = this.scrollSmooth;
//#endif
setScrollYOffset(offset, smooth);
}
return true;
}
}else{
this.needsCheckItemInVisibleContent = false;
}
//#endif
//#endif
if (item != null) {
if (!item.isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
} else if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
int startY = getScrollYOffset() + item.relativeY + item.contentY + item.internalY;
if ( (
(startY < 0 && gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2)
|| (startY + item.internalHeight > this.scrollHeight && gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8)
)
&& (scroll(gameAction, item, false))
){
//System.out.println("scrolling instead of forwwarding key to child " + item + ", item.internalY=" + item.internalY + ", item.internalHeight=" + item.internalHeight + ", item.focused=" + (item instanceof Container ? item.relativeY + ((Container)item).focusedItem.relativeY : -1) );
return true;
}
}
int scrollOffset = getScrollYOffset();
if ( item.handleKeyPressed(keyCode, gameAction) ) {
//if (item.internalX != NO_POSITION_SET) {
if (this.enableScrolling) {
if (getScrollYOffset() == scrollOffset) {
//#debug
System.out.println("scrolling focused item that has handled key pressed, item=" + item + ", item.internalY=" + item.internalY);
scroll(gameAction, item, false);
}
} else {
updateInternalPosition(item);
}
//}
//#debug
System.out.println("Container(" + this + "): handleKeyPressed consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
return handleNavigate(keyCode, gameAction) || super.handleKeyPressed(keyCode, gameAction);
}
/**
* Handles a keyPressed or keyRepeated event for navigating in the container.
*
* @param keyCode the code of the keypress/keyrepeat event
* @param gameAction the associated game action
* @return true when the key was handled
*/
protected boolean handleNavigate(int keyCode, int gameAction) {
// now allow a navigation within the container:
boolean processed = false;
int offset = getRelativeScrollYOffset();
int availableScrollHeight = getScrollHeight();
Item focItem = this.focusedItem;
int y = 0;
int h = 0;
if (focItem != null && availableScrollHeight != -1) {
if (focItem.internalX == NO_POSITION_SET || (focItem.relativeY + focItem.contentY + focItem.internalY + focItem.internalHeight < availableScrollHeight)) {
y = focItem.relativeY;
h = focItem.itemHeight;
//System.out.println("normal item has focus: y=" + y + ", h=" + h + ", item=" + focItem);
} else {
y = focItem.relativeY + focItem.contentY + focItem.internalY;
h = focItem.internalHeight;
//System.out.println("internal item has focus: y=" + y + ", h=" + h + ", item=" + focItem);
}
//System.out.println("offset=" + offset + ", scrollHeight=" + availableScrollHeight + ", offset + y + h=" + (offset + y + h) + ", focusedItem=" + focItem);
}
if (
//#if polish.blackberry && !polish.hasTrackballEvents
(gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) ||
//#endif
(gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8))
{
if (focItem != null
&& (availableScrollHeight != -1 && offset + y + h > availableScrollHeight)
) {
//System.out.println("offset=" + offset + ", foc.relativeY=" + this.focusedItem.relativeY + ", foc.height=" + this.focusedItem.itemHeight + ", available=" + this.availableHeight);
// keep the focus do scroll downwards:
//#debug
System.out.println("Container(" + this + "): scrolling down: keeping focus, focusedIndex=" + this.focusedIndex + ", y=" + y + ", h=" + h + ", offset=" + offset );
} else {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
} else {
//#endif
processed = shiftFocus( true, 0 );
//#ifdef tmp.supportViewType
}
//#endif
}
//#debug
System.out.println("Container(" + this + "): forward shift by one item succeded: " + processed + ", focusedIndex=" + this.focusedIndex + ", enableScrolling=" + this.enableScrolling);
if ((!processed)
&& (
(availableScrollHeight != -1 && offset + y + h > availableScrollHeight)
|| (this.enableScrolling && offset + this.itemHeight > availableScrollHeight)
)
) {
int containerHeight = Math.max( this.contentHeight, this.backgroundHeight );
int availScrollHeight = getContentScrollHeight();
int scrollOffset = getScrollYOffset();
// scroll downwards:
int difference =
//#if polish.Container.ScrollDelta:defined
//#= ${polish.Container.ScrollDelta};
//#else
((containerHeight + scrollOffset) - availScrollHeight);
if(difference > (availScrollHeight / 2))
{
difference = availScrollHeight / 2;
}
//#endif
if(difference == 0)
{
return false;
}
offset = scrollOffset - difference;
if (offset > 0) {
offset = 0;
}
setScrollYOffset( offset, true );
processed = true;
//#debug
System.out.println("Down/Right: Decreasing (target)YOffset to " + offset);
}
} else if (
//#if polish.blackberry && !polish.hasTrackballEvents
(gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) ||
//#endif
(gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) )
{
if (focItem != null
&& availableScrollHeight != -1
&& offset + focItem.relativeY < 0 ) // this.focusedItem.yTopPos < this.yTop )
{
// keep the focus do scroll upwards:
//#debug
System.out.println("Container(" + this + "): scrolling up: keeping focus, relativeScrollOffset=" + offset + ", scrollHeight=" + availableScrollHeight + ", focusedIndex=" + this.focusedIndex + ", focusedItem.relativeY=" + this.focusedItem.relativeY + ", this.availableHeight=" + this.scrollHeight + ", targetYOffset=" + this.targetYOffset);
} else {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
} else {
//#endif
processed = shiftFocus( false, 0 );
//#ifdef tmp.supportViewType
}
//#endif
}
//#debug
System.out.println("Container(" + this + "): upward shift by one item succeded: " + processed + ", focusedIndex=" + this.focusedIndex );
if ((!processed)
&& ( (this.enableScrolling && offset < 0)
|| (availableScrollHeight != -1 && focItem != null && offset + focItem.relativeY < 0) )
) {
// scroll upwards:
int difference =
//#if polish.Container.ScrollDelta:defined
//#= ${polish.Container.ScrollDelta};
//#else
getScreen() != null ? getScreen().contentHeight / 2 : 30;
//#endif
offset = getScrollYOffset() + difference;
if (offset > 0) {
offset = 0;
}
setScrollYOffset(offset, true);
//#debug
System.out.println("Up/Left: Increasing (target)YOffset to " + offset);
processed = true;
}
}
//#ifdef tmp.supportViewType
else if (this.containerView != null)
{
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
}
//#endif
return processed;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyReleased(int, int)
*/
protected boolean handleKeyReleased(int keyCode, int gameAction) {
//#debug
System.out.println("handleKeyReleased( " + keyCode + ", " + gameAction + " ) for " + this);
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return super.handleKeyReleased(keyCode, gameAction);
}
Item item = this.focusedItem;
if (item != null) {
int scrollOffset = getScrollYOffset();
if ( item.handleKeyReleased( keyCode, gameAction ) ) {
if (item.isShown) { // could be that the item or its screen has been removed in the meantime...
if (this.enableScrolling) {
if (getScrollYOffset() == scrollOffset) {
//#debug
System.out.println("scrolling focused item that has handled key released, item=" + item + ", item.internalY=" + item.internalY);
scroll(gameAction, item, false);
}
} else {
updateInternalPosition(item);
}
}
// 2009-06-10:
// if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
// scroll(gameAction, item);
// }
// if (this.enableScrolling) {
// if (getScrollYOffset() == scrollOffset) {
// // #debug
// System.out.println("scrolling focused item that has handled key pressed, item=" + item + ", item.internalY=" + item.internalY);
// scroll(gameAction, item);
// }
// } else {
// if (item.itemHeight > getScrollHeight() && item.internalX != NO_POSITION_SET) {
// // adjust internal settings for root container:
// this.internalX = item.relativeX + item.contentX + item.internalX;
// this.internalY = item.relativeY + item.contentY + item.internalY;
// this.internalWidth = item.internalWidth;
// this.internalHeight = item.internalHeight;
// // #debug
// System.out.println(this + ": Adjusted internal area by internal area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
// } else {
// this.internalX = item.relativeX;
// this.internalY = item.relativeY;
// this.internalWidth = item.itemWidth;
// this.internalHeight = item.itemHeight;
// // #debug
// System.out.println(this + ": Adjusted internal area by full area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
// }
// }
//#debug
System.out.println("Container(" + this + "): handleKeyReleased consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handleKeyReleased(keyCode, gameAction) ) {
return true;
}
}
//#endif
return super.handleKeyReleased(keyCode, gameAction);
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyRepeated(int, int)
*/
protected boolean handleKeyRepeated(int keyCode, int gameAction) {
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return false;
}
if (this.focusedItem != null) {
Item item = this.focusedItem;
if ( item.handleKeyRepeated( keyCode, gameAction ) ) {
if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
scroll(gameAction, item, false);
}
//#debug
System.out.println("Container(" + this + "): handleKeyRepeated consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
return handleNavigate(keyCode, gameAction);
// note: in previous versions a keyRepeat event was just re-asigned to a keyPressed event. However, this resulted
// in non-logical behavior when an item wants to ignore keyRepeat events and only press "real" keyPressed events.
// So now events are ignored by containers when they are ignored by their currently focused item...
//return super.handleKeyRepeated(keyCode, gameAction);
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
/**
* Focuses the first visible item in the given vertical minimum and maximum offsets.
*
* @param container
* the container
* @param verticalMin
* the vertical minimum offset
* @param verticalMax
* the vertical maximum offset
* @return
* the newly focused item
*/
Item focusVisible(Container container, int verticalMin, int verticalMax) {
Item[] items = container.getItems();
Item focusedItem = null;
for (int index = 0; index < items.length; index++) {
Item item = items[index];
int itemTop= item.getAbsoluteY();
int itemBottom = itemTop + item.itemHeight;
int itemAppearanceMode = item.getAppearanceMode();
// if item is interactive ...
if(itemAppearanceMode == Item.INTERACTIVE || itemAppearanceMode == Item.HYPERLINK || itemAppearanceMode == Item.BUTTON) {
// ... and is a container and not fully visible ...
if(item instanceof Container && !isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, true)) {
// ... but partially visible ...
if(isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, false)) {
focusedItem = focusVisible((Container)item, verticalMin, verticalMax);
// if a child item was focused ...
if(focusedItem != null) {
focusIndex(index);
return item;
}
}
} else if(isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, true)) {
return focusIndex(index);
}
}
}
return null;
}
/**
* Returns true if the given item top and bottom offset is inside the given vertical minimum and maximum offset.
*
* @param verticalMin
* the vertical minimum offset
* @param verticalMax
* the vertical maximum offset
* @param itemTop
* the item top offset
* @param itemBottom
* the item bottom offset
* @param full
* true if the item must fit completly into the given vertical offsets otherwise false
* @return true
* if the item fits into the given vertical offsets otherwise false
*/
protected boolean isItemVisible(int verticalMin, int verticalMax, int itemTop, int itemBottom, boolean full) {
if(full) {
return itemTop >= verticalMin && itemBottom <= verticalMax;
} else {
return !(itemBottom <= verticalMin || itemTop >= verticalMax);
}
}
/**
* Focuses the child at the given index while preserving the scroll offset.
*
* @param index
* the index
* @return the focused item
*/
Item focusIndex(int index) {
int scrollOffset = getScrollYOffset();
setInitialized(false);
focusChild(index);
setInitialized(true);
setScrollYOffset(scrollOffset);
return getFocusedChild();
}
//#endif
/**
* Shifts the focus to the next or the previous item.
*
* @param forwardFocus true when the next item should be focused, false when
* the previous item should be focused.
* @param steps how many steps forward or backward the search for the next focusable item should be started,
* 0 for the current item, negative values go backwards.
* @return true when the focus could be moved to either the next or the previous item.
*/
private boolean shiftFocus(boolean forwardFocus, int steps ) {
Item[] items = getItems();
if ( items == null || items.length <= 1) {
//#debug
System.out.println("shiftFocus fails: this.items==null or items.length <= 0");
return false;
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
if(this.focusedIndex == -1) {
int verticalMin = getAbsoluteY();
int verticalMax = verticalMin + getScrollHeight();
Item newFocusedItem = focusVisible(this, verticalMin, verticalMax);
if(newFocusedItem != null) {
return true;
}
}
//#endif
//System.out.println("|");
Item focItem = this.focusedItem;
//#if polish.css.colspan
int i = this.focusedIndex;
if (steps != 0) {
//System.out.println("ShiftFocus: steps=" + steps + ", forward=" + forwardFocus);
int doneSteps = 0;
steps = Math.abs( steps ) + 1;
Item item = items[i];
while( doneSteps <= steps) {
doneSteps += item.colSpan;
if (doneSteps >= steps) {
//System.out.println("bailing out at too many steps: focusedIndex=" + this.focusedIndex + ", startIndex=" + i + ", steps=" + steps + ", doneSteps=" + doneSteps);
break;
}
if (forwardFocus) {
i++;
if (i == items.length - 1 ) {
i = items.length - 2;
break;
} else if (i == items.length) {
i = items.length - 1;
break;
}
} else {
i--;
if (i < 0) {
i = 1;
break;
}
}
item = items[i];
//System.out.println("focusedIndex=" + this.focusedIndex + ", startIndex=" + i + ", steps=" + steps + ", doneSteps=" + doneSteps);
}
if (doneSteps >= steps && item.colSpan != 1) {
if (forwardFocus) {
i--;
if (i < 0) {
i = items.length - 1;
}
//System.out.println("forward: Adjusting startIndex to " + i );
} else {
i = (i + 1) % items.length;
//System.out.println("backward: Adjusting startIndex to " + i );
}
}
}
//#else
//# int i = this.focusedIndex + steps;
if (i > items.length) {
i = items.length - 2;
}
if (i < 0) {
i = 1;
}
//#endif
Item item = null;
boolean allowCycle = this.allowCycling;
if (allowCycle) {
if (forwardFocus) {
// when you scroll to the bottom and
// there is still space, do
// scroll first before cycling to the
// first item:
allowCycle = (getScrollYOffset() + this.itemHeight <= getScrollHeight() + 1);
//System.out.println("allowCycle-calculation ( forward non-smoothScroll): yOffset=" + this.yOffset + ", itemHeight=" + this.itemHeight + " (together="+ (this.yOffset + this.itemHeight));
} else {
// when you scroll to the top and
// there is still space, do
// scroll first before cycling to the
// last item:
allowCycle = (getScrollYOffset() == 0);
}
}
//#debug
System.out.println("shiftFocus of " + this + ": allowCycle(local)=" + allowCycle + ", allowCycle(global)=" + this.allowCycling + ", isFoward=" + forwardFocus + ", enableScrolling=" + this.enableScrolling + ", targetYOffset=" + this.targetYOffset + ", yOffset=" + this.yOffset + ", focusedIndex=" + this.focusedIndex + ", start=" + i );
while (true) {
if (forwardFocus) {
i++;
if (i >= items.length) {
if (allowCycle) {
if (!fireContinueCycle(CycleListener.DIRECTION_BOTTOM_TO_TOP)) {
return false;
}
allowCycle = false;
i = 0;
//#debug
System.out.println("allowCycle: Restarting at the beginning");
} else {
break;
}
}
} else {
i--;
if (i < 0) {
if (allowCycle) {
if (!fireContinueCycle(CycleListener.DIRECTION_TOP_TO_BOTTOM)) {
return false;
}
allowCycle = false;
i = items.length - 1;
//#debug
System.out.println("allowCycle: Restarting at the end");
} else {
break;
}
}
}
item = items[i];
if (item.appearanceMode != Item.PLAIN) {
break;
}
}
if (item == null || item.appearanceMode == Item.PLAIN || item == focItem) {
//#debug
System.out.println("got original focused item: " + (item == focItem) + ", item==null:" + (item == null) + ", mode==PLAIN:" + (item == null ? false:(item.appearanceMode == PLAIN)) );
return false;
}
int direction = Canvas.UP;
if (forwardFocus) {
direction = Canvas.DOWN;
}
focusChild(i, item, direction, false );
return true;
}
/**
* Retrieves the index of the item which is currently focused.
*
* @return the index of the focused item, -1 when none is focused.
*/
public int getFocusedIndex() {
return this.focusedIndex;
}
/**
* Retrieves the currently focused item.
*
* @return the currently focused item, null when there is no focusable item in this container.
*/
public Item getFocusedItem() {
return this.focusedItem;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setStyle(de.enough.polish.ui.Style)
*/
public void setStyle(Style style) {
//#if polish.debug.debug
if (this.parent == null) {
//#debug
System.out.println("Container.setStyle without boolean parameter for container " + toString() );
}
//#endif
setStyleWithBackground(style, false);
}
/**
* Sets the style of this container.
*
* @param style the style
* @param ignoreBackground when true is given, the background and border-settings
* will be ignored.
*/
public void setStyleWithBackground( Style style, boolean ignoreBackground) {
super.setStyle(style);
if (ignoreBackground) {
this.background = null;
this.border = null;
this.marginTop = 0;
this.marginBottom = 0;
this.marginLeft = 0;
this.marginRight = 0;
}
this.isIgnoreMargins = ignoreBackground;
//#if polish.css.focused-style-first
Style firstFocusStyleObj = (Style) style.getObjectProperty("focused-style-first");
if (firstFocusStyleObj != null) {
this.focusedStyleFirst = firstFocusStyleObj;
}
//#endif
//#if polish.css.focused-style-last
Style lastFocusStyleObj = (Style) style.getObjectProperty("focused-style-last");
if (lastFocusStyleObj != null) {
this.focusedStyleLast = lastFocusStyleObj;
}
//#endif
//#if polish.css.focus-all-style
Style focusAllStyleObj = (Style) style.getObjectProperty("focus-all-style");
if (focusAllStyleObj != null) {
this.focusAllStyle = focusAllStyleObj;
}
//#endif
//#ifdef polish.css.view-type
// ContainerView viewType = (ContainerView) style.getObjectProperty("view-type");
// if (this instanceof ChoiceGroup) {
// System.out.println("SET.STYLE / CHOICEGROUP: found view-type (1): " + (viewType != null) + " for " + this);
// }
if (this.view != null && this.view instanceof ContainerView) {
ContainerView viewType = (ContainerView) this.view; // (ContainerView) style.getObjectProperty("view-type");
this.containerView = viewType;
this.view = null; // set to null so that this container can control the view completely. This is necessary for scrolling, for example.
viewType.parentContainer = this;
viewType.focusFirstElement = this.autoFocusEnabled;
viewType.allowCycling = this.allowCycling;
if (this.focusedItem != null) {
viewType.focusItem(this.focusedIndex, this.focusedItem, 0 );
}
} else if (!this.preserveViewType && style.getObjectProperty("view-type") == null && !this.setView) {
this.containerView = null;
}
//#endif
//#ifdef polish.css.columns
if (this.containerView == null) {
Integer columns = style.getIntProperty("columns");
if (columns != null) {
if (columns.intValue() > 1) {
//System.out.println("Container: Using default container view for displaying table");
this.containerView = new ContainerView();
this.containerView.parentContainer = this;
this.containerView.focusFirstElement = this.autoFocusEnabled;
this.containerView.allowCycling = this.allowCycling;
}
}
}
//#endif
//#if polish.css.scroll-mode
Integer scrollModeInt = style.getIntProperty("scroll-mode");
if ( scrollModeInt != null ) {
this.scrollSmooth = (scrollModeInt.intValue() == SCROLL_SMOOTH);
}
//#endif
//#ifdef polish.css.scroll-duration
Integer scrollDurationInt = style.getIntProperty("scroll-duration");
if (scrollDurationInt != null) {
this.scrollDuration = scrollDurationInt.intValue();
}
//#endif
//#if tmp.checkBouncing
Boolean allowBounceBool = style.getBooleanProperty("bounce");
if (allowBounceBool != null) {
this.allowBouncing = allowBounceBool.booleanValue();
}
//#endif
//#if polish.css.expand-items
synchronized(this.itemsList) {
Boolean expandItemsBool = style.getBooleanProperty("expand-items");
if (expandItemsBool != null) {
this.isExpandItems = expandItemsBool.booleanValue();
}
}
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.setStyle(style);
}
//#endif
//#if polish.css.focus-all
Boolean focusAllBool = style.getBooleanProperty("focus-all");
if (focusAllBool != null) {
this.isFocusAllChildren = focusAllBool.booleanValue();
}
//#endif
//#if polish.css.press-all
Boolean pressAllBool = style.getBooleanProperty("press-all");
if (pressAllBool != null) {
this.isPressAllChildren = pressAllBool.booleanValue();
}
//#endif
//#if polish.css.change-styles
String changeStyles = style.getProperty("change-styles");
if (changeStyles != null) {
int splitPos = changeStyles.indexOf('>');
if (splitPos != -1) {
String oldStyle = changeStyles.substring(0, splitPos ).trim();
String newStyle = changeStyles.substring(splitPos+1).trim();
try {
changeChildStyles(oldStyle, newStyle);
} catch (Exception e) {
//#debug error
System.out.println("Unable to apply change-styles \"" + changeStyles + "\"" + e );
}
}
}
//#endif
//#ifdef polish.css.show-delay
Integer showDelayInt = style.getIntProperty("show-delay");
if (showDelayInt != null) {
this.showDelay = showDelayInt.intValue();
}
//#endif
//#if polish.css.child-style
Style childStyleObj = (Style) style.getObjectProperty("child-style");
if (childStyleObj != null) {
this.childStyle = childStyleObj;
}
//#endif
}
//#ifdef tmp.supportViewType
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setStyle(de.enough.polish.ui.Style, boolean)
*/
public void setStyle(Style style, boolean resetStyle)
{
super.setStyle(style, resetStyle);
if (this.containerView != null) {
this.containerView.setStyle(style, resetStyle);
}
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#resetStyle(boolean)
*/
public void resetStyle(boolean recursive) {
super.resetStyle(recursive);
if (recursive) {
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++) {
Item item = (Item) items[i];
if (item == null) {
break;
}
item.resetStyle(recursive);
}
}
}
/**
* Changes the style of all children that are currently using the specified oldChildStyle with the given newChildStyle.
*
* @param oldChildStyleName the name of the style of child items that should be exchanged
* @param newChildStyleName the name of the new style for child items that were using the specified oldChildStyle before
* @throws IllegalArgumentException if no corresponding newChildStyle could be found
* @see StyleSheet#getStyle(String)
*/
public void changeChildStyles( String oldChildStyleName, String newChildStyleName) {
Style newChildStyle = StyleSheet.getStyle(newChildStyleName);
if (newChildStyle == null) {
throw new IllegalArgumentException("for " + newChildStyleName );
}
Style oldChildStyle = StyleSheet.getStyle(oldChildStyleName);
changeChildStyles(oldChildStyle, newChildStyle);
}
/**
* Changes the style of all children that are currently using the specified oldChildStyle with the given newChildStyle.
*
* @param oldChildStyle the style of child items that should be exchanged
* @param newChildStyle the new style for child items that were using the specified oldChildStyle before
* @throws IllegalArgumentException if newChildStyle is null
*/
public void changeChildStyles( Style oldChildStyle, Style newChildStyle) {
if (newChildStyle == null) {
throw new IllegalArgumentException();
}
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++)
{
Item child = (Item) children[i];
if (child == null) {
break;
}
if (child.style == oldChildStyle) {
child.setStyle( newChildStyle );
}
}
}
/**
* Parses the given URL and includes the index of the item, when there is an "%INDEX%" within the given url.
* @param url the resource URL which might include the substring "%INDEX%"
* @param item the item to which the URL belongs to. The item must be
* included in this container.
* @return the URL in which the %INDEX% is substituted by the index of the
* item in this container. The url "icon%INDEX%.png" is resolved
* to "icon1.png" when the item is the second item in this container.
* @throws NullPointerException when the given url or item is null
*/
public String parseIndexUrl(String url, Item item) {
int pos = url.indexOf("%INDEX%");
if (pos != -1) {
int index = this.itemsList.indexOf( item );
//TODO rob check if valid, when url ends with %INDEX%
url = url.substring(0, pos) + index + url.substring( pos + 7 );
}
return url;
}
/**
* Retrieves the position of the specified item.
*
* @param item the item
* @return the position of the item, or -1 when it is not defined
*/
public int getPosition( Item item ) {
return this.itemsList.indexOf( item );
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#focus(de.enough.polish.ui.Style, int)
*/
protected Style focus(Style focusStyle, int direction ) {
//#debug
System.out.println("focusing container " + this + " from " + (this.style != null ? this.style.name : "<no style>") + " to " + getFocusedStyle().name);
if (this.isFocused) {
return this.style;
}
this.plainStyle = null;
if ( this.itemsList.size() == 0) {
return super.focus(focusStyle, direction );
} else {
focusStyle = getFocusedStyle();
//#if polish.css.focus-all
if (this.isFocusAllChildren) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemFocusedStyle = item.getFocusedStyle();
if (itemFocusedStyle != focusStyle && itemFocusedStyle != StyleSheet.focusedStyle) {
if (!item.isFocused) {
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.focus(itemFocusedStyle, direction);
}
}
}
}
//#endif
//#if polish.css.focus-all-style
if (this.focusAllStyle != null) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.setStyle(this.focusAllStyle);
}
}
//#endif
Style result = this.style;
if ((focusStyle != null && focusStyle != StyleSheet.focusedStyle && (this.parent == null || (this.parent.getFocusedStyle() != focusStyle)))
//#if polish.css.include-label
|| (this.includeLabel && focusStyle != null)
//#endif
) {
result = super.focus( focusStyle, direction );
this.plainStyle = result;
}
if (!this.isStyleInitialized && result != null) {
//#debug
System.out.println("setting original style for container " + this + " with style " + result.name);
setStyle( result );
}
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.focus(focusStyle, direction);
//this.isInitialised = false; not required
}
//#endif
this.isFocused = true;
int newFocusIndex = this.focusedIndex;
//#if tmp.supportViewType
if ( this.containerView == null || this.containerView.allowsAutoTraversal ) {
//#endif
Item[] myItems = getItems();
if (this.autoFocusEnabled && this.autoFocusIndex < myItems.length && (myItems[this.autoFocusIndex].appearanceMode != PLAIN)) {
//#debug
System.out.println("focus(Style, direction): autofocusing " + this + ", focusedIndex=" + this.focusedIndex + ", autofocus=" + this.autoFocusIndex);
newFocusIndex = this.autoFocusIndex;
setAutoFocusEnabled( false );
} else {
// focus the first interactive item...
if (direction == Canvas.UP || direction == Canvas.LEFT ) {
//System.out.println("Container: direction UP with " + myItems.length + " items");
for (int i = myItems.length; --i >= 0; ) {
Item item = myItems[i];
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
} else {
//System.out.println("Container: direction DOWN");
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
}
}
this.focusedIndex = newFocusIndex;
if (newFocusIndex == -1) {
//System.out.println("DID NOT FIND SUITEABLE ITEM - current style=" + this.style.name);
// this container has only non-focusable items!
if (this.plainStyle != null) {
// this will result in plainStyle being returned in the super.focus() call:
this.style = this.plainStyle;
}
return super.focus( focusStyle, direction );
}
//#if tmp.supportViewType
} else if (this.focusedIndex == -1) {
Object[] myItems = this.itemsList.getInternalArray();
//System.out.println("Container: direction DOWN through view type " + this.view);
for (int i = 0; i < myItems.length; i++) {
Item item = (Item) myItems[i];
if (item == null) {
break;
}
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
this.focusedIndex = newFocusIndex;
if (newFocusIndex == -1) {
//System.out.println("DID NOT FIND SUITEABLE ITEM (2)");
// this container has only non-focusable items!
if (this.plainStyle != null) {
this.style = this.plainStyle;
}
return super.focus( focusStyle, direction );
}
}
//#endif
Item item = get( this.focusedIndex );
// Style previousStyle = item.style;
// if (previousStyle == null) {
// previousStyle = StyleSheet.defaultStyle;
// }
this.showCommandsHasBeenCalled = false;
//#if polish.css.focus-all
if (item.isFocused) {
Style orStyle = (Style) item.getAttribute(KEY_ORIGINAL_STYLE);
if (orStyle != null) {
//#debug
System.out.println("re-setting to plain style " + orStyle.name + " for item " + item);
item.style = orStyle;
}
}
//#endif
focusChild( this.focusedIndex, item, direction, true );
// item command handling is now done within showCommands and handleCommand
if (!this.showCommandsHasBeenCalled && this.commands != null) {
showCommands();
}
// if (item.commands == null && this.commands != null) {
// Screen scr = getScreen();
// if (scr != null) {
// scr.setItemCommands(this);
// }
// }
// change the label-style of this container:
//#ifdef polish.css.label-style
if (this.label != null && focusStyle != null) {
Style labStyle = (Style) focusStyle.getObjectProperty("label-style");
if (labStyle != null) {
this.labelStyle = this.label.style;
this.label.setStyle( labStyle );
}
}
//#endif
return result;
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#defocus(de.enough.polish.ui.Style)
*/
public void defocus(Style originalStyle) {
//#debug
System.out.println("defocus container " + this + " with style " + (originalStyle != null ? originalStyle.name : "<no style>"));
//#if polish.css.focus-all
if (this.isFocusAllChildren) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemPlainStyle = (Style) item.removeAttribute( KEY_ORIGINAL_STYLE );
if (itemPlainStyle != null) {
item.defocus(itemPlainStyle);
}
}
}
//#endif
Style originalItemStyle = this.itemStyle;
//#if polish.css.focus-all-style
if (this.focusAllStyle != null) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemPlainStyle = (Style) item.removeAttribute( KEY_ORIGINAL_STYLE );
if (itemPlainStyle != null) {
if (item == this.focusedItem) {
originalItemStyle = itemPlainStyle;
} else {
item.setStyle(itemPlainStyle);
}
}
}
}
//#endif
if ( this.itemsList.size() == 0 || this.focusedIndex == -1 ) {
super.defocus( originalStyle );
} else {
if (this.plainStyle != null) {
super.defocus( this.plainStyle );
if (originalStyle == null) {
originalStyle = this.plainStyle;
}
this.plainStyle = null;
} else if (this.isPressed) {
notifyItemPressedEnd();
}
this.isFocused = false;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.defocus( originalStyle );
setInitialized(false);
}
//#endif
Item item = this.focusedItem;
if (item != null) {
//#if polish.css.focus-all
if (item.isFocused) {
//#endif
item.defocus( originalItemStyle );
//#if polish.css.focus-all
}
//#endif
this.isFocused = false;
// now remove any commands which are associated with this item:
if (item.commands == null && this.commands != null) {
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
}
}
// change the label-style of this container:
//#ifdef polish.css.label-style
Style tmpLabelStyle = null;
if ( originalStyle != null) {
tmpLabelStyle = (Style) originalStyle.getObjectProperty("label-style");
}
if (tmpLabelStyle == null) {
tmpLabelStyle = StyleSheet.labelStyle;
}
if (this.label != null && tmpLabelStyle != null && this.label.style != tmpLabelStyle) {
this.label.setStyle( tmpLabelStyle );
}
//#endif
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#showCommands()
*/
public void showCommands() {
this.showCommandsHasBeenCalled = true;
super.showCommands();
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleCommand(javax.microedition.lcdui.Command)
*/
protected boolean handleCommand(Command cmd) {
boolean handled = super.handleCommand(cmd);
if (!handled && this.focusedItem != null) {
return this.focusedItem.handleCommand(cmd);
}
return handled;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#animate(long, de.enough.polish.ui.ClippingRegion)
*/
public void animate(long currentTime, ClippingRegion repaintRegion) {
super.animate(currentTime, repaintRegion);
boolean addFullRepaintRegion = false;
// scroll the container:
int target = this.targetYOffset;
int current = this.yOffset;
int diff = 0;
if (target != current) {
long passedTime = (currentTime - this.scrollStartTime);
int nextOffset = CssAnimation.calculatePointInRange(this.scrollStartYOffset, target, passedTime, this.scrollDuration , CssAnimation.FUNCTION_EXPONENTIAL_OUT );
this.yOffset = nextOffset;
addFullRepaintRegion = true;
}
int speed = this.scrollSpeed;
if (speed != 0) {
speed = (speed * (100 - this.scrollDamping)) / 100;
if (speed <= 0) {
speed = 0;
}
this.scrollSpeed = speed;
long timeDelta = currentTime - this.lastAnimationTime;
if (timeDelta > 1000) {
timeDelta = AnimationThread.ANIMATION_INTERVAL;
}
speed = (int) ((speed * timeDelta) / 1000);
if (speed == 0) {
this.scrollSpeed = 0;
}
int offset = this.yOffset;
if (this.scrollDirection == Canvas.UP) {
offset += speed;
target = offset;
if (offset > 0) {
this.scrollSpeed = 0;
target = 0;
//#if tmp.checkBouncing
if (!this.allowBouncing) {
offset = 0;
}
//#elif polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false
offset = 0;
//#endif
}
} else {
offset -= speed;
target = offset;
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
// Style myStyle = this.style;
// if (myStyle != null) {
// maxItemHeight -= myStyle.getPaddingTop(this.availableHeight) + myStyle.getPaddingBottom(this.availableHeight) + myStyle.getMarginTop(this.availableHeight) + myStyle.getMarginBottom(this.availableHeight);
// }
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (offset + maxItemHeight < this.scrollHeight) {
this.scrollSpeed = 0;
target = this.scrollHeight - maxItemHeight;
//#if tmp.checkBouncing
if (!this.allowBouncing) {
offset = target;
}
//#elif polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false
offset = target;
//#endif
}
}
this.yOffset = offset;
this.targetYOffset = target;
addFullRepaintRegion = true;
}
// add repaint region:
if (addFullRepaintRegion) {
int x, y, width, height;
Screen scr = getScreen();
height = getItemAreaHeight();
if (this.parent == null && (this.scrollHeight > height || this.enableScrolling)) { // parent==null is required for example when a commands container is scrolled.
x = scr.contentX;
y = scr.contentY;
height = scr.contentHeight;
width = scr.contentWidth + scr.getScrollBarWidth();
} else {
x = getAbsoluteX();
y = getAbsoluteY();
width = this.itemWidth;
//#if polish.useScrollBar || polish.classes.ScrollBar:defined
width += scr.getScrollBarWidth();
//#endif
}
repaintRegion.addRegion( x, y, width, height + diff + 1 );
}
this.lastAnimationTime = currentTime;
Item focItem = this.focusedItem;
if (focItem != null) {
focItem.animate(currentTime, repaintRegion);
}
//#ifdef tmp.supportViewType
ContainerView contView = this.containerView;
if ( contView != null ) {
contView.animate(currentTime, repaintRegion);
}
//#endif
//#if polish.css.show-delay
if (this.showDelay != 0 && this.showDelayIndex != 0) {
int index = Math.min( (int)((currentTime - this.showNotifyTime) / this.showDelay), this.itemsList.size());
if (index > this.showDelayIndex) {
for (int i=this.showDelayIndex; i<index; i++) {
try {
//System.out.println("calling show notify on item " + i + " at " + (currentTime - this.showNotifyTime) + ", show-delay=" + this.showDelay);
Item item = get(i);
item.showNotify();
} catch (Exception e) {
//#debug error
System.out.println("Unable to notify");
}
}
if (index == this.itemsList.size()) {
this.showDelayIndex = 0;
} else {
this.showDelayIndex = index;
}
}
}
//#endif
//#if polish.css.focus-all
if (this.isFocusAllChildren && this.isFocused) {
Item[] items = this.getItems();
for (int i = 0; i < items.length; i++) {
Item item = items[i];
item.animate(currentTime, repaintRegion);
}
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#addRepaintArea(de.enough.polish.ui.ClippingRegion)
*/
public void addRepaintArea(ClippingRegion repaintRegion) {
if (this.enableScrolling) {
Screen scr = getScreen();
int x = scr.contentX;
int y = scr.contentY;
int height = scr.contentHeight;
int width = scr.contentWidth + scr.getScrollBarWidth();
repaintRegion.addRegion(x, y, width, height);
} else {
super.addRepaintArea(repaintRegion);
}
}
/**
* Called by the system to notify the item that it is now at least
* partially visible, when it previously had been completely invisible.
* The item may receive <code>paint()</code> calls after
* <code>showNotify()</code> has been called.
*
* <p>The container implementation calls showNotify() on the embedded items.</p>
*/
protected void showNotify()
{
super.showNotify();
if (this.style != null && !this.isStyleInitialized) {
setStyle( this.style );
}
//#ifdef polish.useDynamicStyles
else if (this.style == null) {
initStyle();
}
//#else
else if (this.style == null && !this.isStyleInitialized) {
//#debug
System.out.println("Setting default style for container " + this );
setStyle( StyleSheet.defaultStyle );
}
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.showNotify();
}
//#endif
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.style != null && !item.isStyleInitialized) {
item.setStyle( item.style );
}
//#ifdef polish.useDynamicStyles
else if (item.style == null) {
initStyle();
}
//#else
else if (item.style == null && !item.isStyleInitialized) {
//#debug
System.out.println("Setting default style for item " + item );
item.setStyle( StyleSheet.defaultStyle );
}
//#endif
//#if polish.css.show-delay
if (this.showDelay == 0 || i == 0) {
//#endif
item.showNotify();
//#if polish.css.show-delay
}
//#endif
}
//#if polish.css.show-delay
this.showDelayIndex = (myItems.length > 1 ? 1 : 0);
this.showNotifyTime = System.currentTimeMillis();
//#endif
//#if !polish.Container.selectEntriesWhileTouchScrolling
if (minimumDragDistance == 0) {
minimumDragDistance = Math.min(Display.getScreenWidth(),Display.getScreenHeight())/10;
}
//#endif
}
/**
* Called by the system to notify the item that it is now completely
* invisible, when it previously had been at least partially visible. No
* further <code>paint()</code> calls will be made on this item
* until after a <code>showNotify()</code> has been called again.
*
* <p>The container implementation calls hideNotify() on the embedded items.</p>
*/
protected void hideNotify()
{
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.hideNotify();
}
//#endif
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
item.hideNotify();
}
}
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerPressed(int, int)
*/
protected boolean handlePointerPressed(int relX, int relY) {
//#debug
System.out.println("Container.handlePointerPressed(" + relX + ", " + relY + ") for " + this );
//System.out.println("Container.handlePointerPressed( x=" + x + ", y=" + y + "): adjustedY=" + (y - (this.yOffset + this.marginTop + this.paddingTop )) );
// an item within this container was selected:
this.lastPointerPressY = relY;
this.lastPointerPressYOffset = getScrollYOffset();
this.lastPointerPressTime = System.currentTimeMillis();
int origRelX = relX;
int origRelY = relY;
relY -= this.yOffset;
relY -= this.contentY;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
//System.out.println("Container.handlePointerPressed: adjusted to (" + relX + ", " + relY + ") for " + this );
boolean eventHandled = false;
Item item = this.focusedItem;
if (item != null) {
// the focused item can extend the parent container, e.g. subcommands,
// so give it a change to process the event itself:
int itemLayout = item.layout;
boolean processed = item.handlePointerPressed(relX - item.relativeX, relY - item.relativeY );
if (processed) {
//#debug
System.out.println("pointerPressed at " + relX + "," + relY + " consumed by focusedItem " + item);
// layout could have been changed:
if (item.layout != itemLayout && isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
if (item.isLayoutLeft()) {
item.relativeX = 0;
} else if (item.isLayoutCenter()) {
item.relativeX = (this.contentWidth - item.itemWidth)/2;
} else {
item.relativeX = this.contentWidth - item.itemWidth;
}
}
notifyItemPressedStart();
return true;
} else if (item.isPressed) {
eventHandled = notifyItemPressedStart();
}
}
//#ifdef tmp.supportViewType
if (contView != null) {
relX += viewXOffset;
if ( contView.handlePointerPressed(relX + this.contentX, relY + this.contentY) ) {
//System.out.println("ContainerView " + contView + " consumed pointer press event");
notifyItemPressedStart();
return true;
}
relX -= viewXOffset;
}
if (!isInItemArea(origRelX, origRelY - this.yOffset) || (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) ) {
//System.out.println("Container.handlePointerPressed(): out of range, relativeX=" + this.relativeX + ", relativeY=" + this.relativeY + ", contentHeight=" + this.contentHeight );
return ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
}
//#else
if (!isInItemArea(origRelX, origRelY) || (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) ) {
//System.out.println("Container.handlePointerPressed(): out of range, relativeX=" + this.relativeX + ", relativeY=" + this.relativeY + ", contentHeight=" + this.contentHeight );
return super.handlePointerPressed(origRelX, origRelY) || eventHandled;
}
//#endif
Screen scr = this.screen;
if ( ((origRelY < 0) && (scr == null || origRelY + this.relativeY - scr.contentY < 0))
|| (this.enableScrolling && origRelY > this.scrollHeight)
){
return ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
}
Item nextItem = getChildAt( origRelX, origRelY );
if (nextItem != null && nextItem != item) {
int index = this.itemsList.indexOf(nextItem);
//#debug
System.out.println("Container.handlePointerPressed(" + relX + "," + relY + "): found item " + index + "=" + item + " at relative " + relX + "," + relY + ", itemHeight=" + item.itemHeight);
// only focus the item when it has not been focused already:
int offset = getScrollYOffset();
focusChild(index, nextItem, 0, true);
setScrollYOffset( offset, false ); // don't move the UI while handling the press event:
// let the item also handle the pointer-pressing event:
nextItem.handlePointerPressed( relX - nextItem.relativeX , relY - nextItem.relativeY );
if (!this.isFocused) {
setAutoFocusEnabled( true );
this.autoFocusIndex = index;
}
notifyItemPressedStart();
return true;
}
// Item[] myItems = getItems();
// int itemRelX, itemRelY;
// for (int i = 0; i < myItems.length; i++) {
// item = myItems[i];
// itemRelX = relX - item.relativeX;
// itemRelY = relY - item.relativeY;
// //System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
// if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// // this item is not in the range or not suitable:
// continue;
// }
// // the pressed item has been found:
// //#debug
// System.out.println("Container.handlePointerPressed(" + relX + "," + relY + "): found item " + i + "=" + item + " at relative " + itemRelX + "," + itemRelY + ", itemHeight=" + item.itemHeight);
// // only focus the item when it has not been focused already:
// int offset = getScrollYOffset();
// focusChild(i, item, 0, true);
// setScrollYOffset( offset, false ); // don't move the UI while handling the press event:
// // let the item also handle the pointer-pressing event:
// item.handlePointerPressed( itemRelX , itemRelY );
// if (!this.isFocused) {
// this.autoFocusEnabled = true;
// this.autoFocusIndex = i;
// }
// return true;
// }
boolean handledBySuperImplementation = ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
//#if polish.android
if (!handledBySuperImplementation && (item != null) && (item._androidView != null) && (!item._androidView.isFocused())) {
item.defocus(this.itemStyle);
handledBySuperImplementation = true;
}
//#endif
return handledBySuperImplementation;
}
//#endif
//#ifdef polish.hasPointerEvents
/**
* Allows subclasses to check if a pointer release event is used for scrolling the container.
* This method can only be called when polish.hasPointerEvents is true.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
*/
protected boolean handlePointerScrollReleased(int relX, int relY) {
if (Display.getInstance().hasPointerMotionEvents()) {
return false;
}
int yDiff = relY - this.lastPointerPressY;
int bottomY = Math.max( this.itemHeight, this.internalY + this.internalHeight );
if (this.focusedItem != null && this.focusedItem.relativeY + this.focusedItem.backgroundHeight > bottomY) {
bottomY = this.focusedItem.relativeY + this.focusedItem.backgroundHeight;
}
if ( this.enableScrolling
&& (this.itemHeight > this.scrollHeight || this.yOffset != 0)
&& ((yDiff < -5 && this.yOffset + bottomY > this.scrollHeight) // scrolling downwards
|| (yDiff > 5 && this.yOffset != 0) ) // scrolling upwards
)
{
int offset = this.yOffset + yDiff;
if (offset > 0) {
offset = 0;
}
//System.out.println("adjusting scrolloffset to " + offset);
setScrollYOffset(offset, true);
return true;
}
return false;
}
//#endif
//#if polish.hasPointerEvents
/**
* Handles the behavior of the virtual keyboard when the item is focused.
* By defaukt, the virtual keyboard is hidden. Components which need to have the virtual keyboard
* shown when they are focused can override this method.
*/
public void handleOnFocusSoftKeyboardDisplayBehavior() {
Item focItem = this.focusedItem;
if (focItem != null) {
focItem.handleOnFocusSoftKeyboardDisplayBehavior();
} else {
super.handleOnFocusSoftKeyboardDisplayBehavior();
}
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerReleased(int, int)
*/
protected boolean handlePointerReleased(int relX, int relY) {
//#debug
System.out.println("Container.handlePointerReleased(" + relX + ", " + relY + ") for " + this );
// handle keyboard behaviour
if(this.isJustFocused) {
this.isJustFocused = false;
handleOnFocusSoftKeyboardDisplayBehavior();
}
//#ifdef tmp.supportFocusItemsInVisibleContentArea
//#if polish.hasPointerEvents
this.needsCheckItemInVisibleContent=true;
//#endif
//#endif
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
Item item = this.focusedItem;
if (this.enableScrolling) {
this.isScrolling = false;
int scrollDiff = Math.abs(getScrollYOffset() - this.lastPointerPressYOffset);
if ( scrollDiff > Display.getScreenHeight()/10 || handlePointerScrollReleased(relX, relY) ) {
// we have scrolling in the meantime
boolean processed = false;
if (item != null && item.isPressed) {
processed = item.handlePointerReleased(relX - item.relativeX, relY - item.relativeY );
setInitialized(false);
}
if (!processed) {
while (item instanceof Container) {
if (item.isPressed) {
item.notifyItemPressedEnd();
}
item = ((Container)item).focusedItem;
}
// we have scrolling in the meantime
if (item != null && item.isPressed) {
item.notifyItemPressedEnd();
setInitialized(false);
}
}
// check if we should continue the scrolling:
long dragTime = System.currentTimeMillis() - this.lastPointerPressTime;
if (dragTime < 1000 && dragTime > 1) {
int direction = Canvas.DOWN;
if (this.yOffset > this.lastPointerPressYOffset) {
direction = Canvas.UP;
}
startScroll( direction, (int) ((scrollDiff * 1000 ) / dragTime), 20 );
} else if (this.yOffset > 0) {
setScrollYOffset(0, true);
} else if (this.yOffset + this.contentHeight < this.availContentHeight) {
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (this.yOffset + maxItemHeight < this.scrollHeight) {
int target = this.scrollHeight - maxItemHeight;
setScrollYOffset( target, true );
}
}
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
}
// foward event to currently focused item:
int origRelX = relX;
// //#ifdef polish.css.before
// + getBeforeWidthWithPadding()
// //#endif
// ;
int origRelY = relY;
relY -= this.yOffset;
relY -= this.contentY;
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
if (contView.handlePointerReleased(relX + this.contentX, relY + this.contentY)) {
//System.out.println("ContainerView consumed pointer release event " + contView);
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
//System.out.println("Container.handlePointerReleased: adjusted to (" + relX + ", " + relY + ") for " + this );
if (item != null) {
// the focused item can extend the parent container, e.g. subcommands,
// so give it a change to process the event itself:
int itemLayout = item.layout;
boolean processed = item.handlePointerReleased(relX - item.relativeX, relY - item.relativeY );
if (processed) {
//#debug
System.out.println("pointerReleased at " + relX + "," + relY + " consumed by focusedItem " + item);
if (this.isPressed) {
notifyItemPressedEnd();
}
// layout could have been changed:
if (item.layout != itemLayout && isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
if (item.isLayoutLeft()) {
item.relativeX = 0;
} else if (item.isLayoutCenter()) {
item.relativeX = (this.contentWidth - item.itemWidth)/2;
} else {
item.relativeX = this.contentWidth - item.itemWidth;
}
}
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
} else if ( item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) {
//#debug
System.out.println("pointerReleased not handled by focused item but within that item's area. Item=" + item + ", container=" + this);
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
}
if (!isInItemArea(origRelX, origRelY)) {
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
Item nextItem = getChildAt(origRelX, origRelY);
if (nextItem != null && nextItem != item) {
item = nextItem;
int itemRelX = relX - item.relativeX;
int itemRelY = relY - item.relativeY;
item.handlePointerReleased( itemRelX , itemRelY );
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
// Item[] myItems = getItems();
// int itemRelX, itemRelY;
// for (int i = 0; i < myItems.length; i++) {
// item = myItems[i];
// itemRelX = relX - item.relativeX;
// itemRelY = relY - item.relativeY;
// //System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
// if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// // this item is not in the range or not suitable:
// continue;
// }
// // the pressed item has been found:
// //#debug
// System.out.println("Container.handlePointerReleased(" + relX + "," + relY + "): found item " + i + "=" + item + " at relative " + itemRelX + "," + itemRelY + ", itemHeight=" + item.itemHeight);
// // only focus the item when it has not been focused already:
// //focus(i, item, 0);
// // let the item also handle the pointer-pressing event:
// item.handlePointerReleased( itemRelX , itemRelY );
// return true;
// }
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerDragged(int, int)
*/
protected boolean handlePointerDragged(int relX, int relY) {
return false;
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerDragged(int, int)
*/
protected boolean handlePointerDragged(int relX, int relY, ClippingRegion repaintRegion) {
//#debug
System.out.println("handlePointerDraggged " + relX + ", " + relY + " for " + this + ", enableScrolling=" + this.enableScrolling + ", focusedItem=" + this.focusedItem);
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
Item item = this.focusedItem;
if (item != null && item.handlePointerDragged( relX - this.contentX - item.relativeX, relY - this.yOffset - this.contentY - item.relativeY, repaintRegion)) {
return true;
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
if(item != null) {
int dragDistance = Math.abs(relY - this.lastPointerPressY);
if(dragDistance > minimumDragDistance) {
focusChild(-1);
//#if polish.blackberry
//# ((BaseScreen)(Object)Display.getInstance()).notifyFocusSet(null);
//#endif
UiAccess.init(item, item.getAvailableWidth(), item.getAvailableWidth(), item.getAvailableHeight());
}
}
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerDragged(relX, relY, repaintRegion) ) {
return true;
}
}
//#endif
if (this.enableScrolling ) {
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (maxItemHeight > this.scrollHeight || this.yOffset != 0) {
int lastOffset = getScrollYOffset();
int nextOffset = this.lastPointerPressYOffset + (relY - this.lastPointerPressY);
//#if tmp.checkBouncing
if (!this.allowBouncing) {
//#endif
//#if tmp.checkBouncing || (polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false)
if (nextOffset > 0) {
nextOffset = 0;
} else {
if (nextOffset + maxItemHeight < this.scrollHeight) {
nextOffset = this.scrollHeight - maxItemHeight;
}
}
//#endif
//#if tmp.checkBouncing
} else {
//#endif
//#if tmp.checkBouncing || !(polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false)
if (nextOffset > this.scrollHeight/3) {
nextOffset = this.scrollHeight/3;
} else {
maxItemHeight += this.scrollHeight/3;
if (nextOffset + maxItemHeight < this.scrollHeight) {
nextOffset = this.scrollHeight - maxItemHeight;
}
}
//#endif
//#if tmp.checkBouncing
}
//#endif
this.isScrolling = (nextOffset != lastOffset);
if (this.isScrolling) {
setScrollYOffset( nextOffset, false );
addRepaintArea(repaintRegion);
return true;
}
}
}
return super.handlePointerDragged(relX, relY, repaintRegion);
}
//#endif
//#if polish.hasTouchEvents
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerTouchDown(int, int)
*/
public boolean handlePointerTouchDown(int x, int y) {
if (this.enableScrolling) {
this.lastPointerPressY = y;
this.lastPointerPressYOffset = getScrollYOffset();
this.lastPointerPressTime = System.currentTimeMillis();
}
Item item = this.focusedItem;
if (item != null) {
if (item.handlePointerTouchDown(x - item.relativeX, y - item.relativeY)) {
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerTouchDown(x,y) ) {
return true;
}
}
//#endif
return super.handlePointerTouchDown(x, y);
}
//#endif
//#if polish.hasTouchEvents
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerTouchUp(int, int)
*/
public boolean handlePointerTouchUp(int x, int y) {
Item item = this.focusedItem;
if (item != null) {
if (item.handlePointerTouchUp(x - item.relativeX, y - item.relativeY)) {
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerTouchUp(x,y) ) {
return true;
}
}
//#endif
if (this.enableScrolling) {
int scrollDiff = Math.abs(getScrollYOffset() - this.lastPointerPressYOffset);
if (scrollDiff > Display.getScreenHeight()/10) {
long dragTime = System.currentTimeMillis() - this.lastPointerPressTime;
if (dragTime < 1000 && dragTime > 1) {
int direction = Canvas.DOWN;
if (this.yOffset > this.lastPointerPressYOffset) {
direction = Canvas.UP;
}
startScroll( direction, (int) ((scrollDiff * 1000 ) / dragTime), 20 );
} else if (this.yOffset > 0) {
setScrollYOffset( 0, true );
}
}
}
return super.handlePointerTouchUp(x, y);
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getItemAreaHeight()
*/
public int getItemAreaHeight()
{
int max = super.getItemAreaHeight();
Item item = this.focusedItem;
if (item != null) {
max = Math.max( max, this.contentY + item.relativeY + item.getItemAreaHeight() );
}
return max;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getItemAt(int, int)
*/
public Item getItemAt(int relX, int relY) {
relY -= this.yOffset;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relX -= this.contentX;
relY -= this.contentY;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
relX -= this.containerView.getScrollXOffset();
}
//#endif
Item item = this.focusedItem;
if (item != null) {
int itemRelX = relX - item.relativeX;
int itemRelY = relY - item.relativeY;
// if (this.label != null) {
// System.out.println("itemRelY=" + itemRelY + " of item " + item + ", parent=" + this );
// }
if (item.isInItemArea(itemRelX, itemRelY)) {
return item.getItemAt(itemRelX, itemRelY);
}
}
Item[] myItems = getItems();
int itemRelX, itemRelY;
for (int i = 0; i < myItems.length; i++) {
item = myItems[i];
itemRelX = relX - item.relativeX;
itemRelY = relY - item.relativeY;
if ( i == this.focusedIndex || !item.isInItemArea(itemRelX, itemRelY)) {
// this item is not in the range or not suitable:
continue;
}
// the pressed item has been found:
return item.getItemAt(itemRelX, itemRelY);
}
relY += this.yOffset;
relX += this.contentX;
relY += this.contentY;
return super.getItemAt(relX, relY);
}
/**
* Retrieves the child of this container at the corresponding position.
*
* @param relX the relative horizontal position
* @param relY the relatiev vertical position
* @return the item at that position, if any
*/
public Item getChildAt(int relX, int relY) {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
return this.containerView.getChildAt( relX, relY );
}
//#endif
return getChildAtImpl( relX, relY );
}
/**
* Actual implementation for finding a child, can be used by ContainerViews.
* @param relX the relative horizontal position
* @param relY the relative vertical position
* @return the child item at the specified position
*/
protected Item getChildAtImpl(int relX, int relY) {
relY -= this.yOffset;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relY -= this.contentY;
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
Item item = this.focusedItem;
if (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY)) {
return item;
}
Item[] myItems = getItems();
int itemRelX, itemRelY;
for (int i = 0; i < myItems.length; i++) {
item = myItems[i];
itemRelX = relX - item.relativeX;
itemRelY = relY - item.relativeY;
//System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// this item is not in the range or not suitable:
continue;
}
return item;
}
return null;
}
/**
* Moves the focus away from the specified item.
*
* @param item the item that currently has the focus
*/
public void requestDefocus( Item item ) {
if (item == this.focusedItem) {
boolean success = shiftFocus(true, 1);
if (!success) {
defocus(this.itemStyle);
}
}
}
/**
* Requests the initialization of this container and all of its children items.
* This was previously used for dimension changes which is now picked up automatically and not required anymore.
*/
public void requestFullInit() {
for (int i = 0; i < this.itemsList.size(); i++) {
Item item = (Item) this.itemsList.get(i);
item.setInitialized(false);
if (item instanceof Container) {
((Container)item).requestFullInit();
}
}
requestInit();
}
/**
* Retrieves the vertical scrolling offset of this item.
*
* @return either the currently used offset or the targeted offset in case the targeted one is different. This is either a negative integer or 0.
* @see #getCurrentScrollYOffset()
*/
public int getScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getScrollYOffset();
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
/**
* Retrieves the current vertical scrolling offset of this item, depending on the scroll mode this can change with every paint iteration.
*
* @return the currently used offset in pixels, either a negative integer or 0.
* @see #getScrollYOffset()
*/
public int getCurrentScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getCurrentScrollYOffset();
}
return this.yOffset;
}
/**
* Retrieves the vertical scrolling offset of this item relative to the top most container.
*
* @return either the currently used offset or the targeted offset in case the targeted one is different.
*/
public int getRelativeScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getRelativeScrollYOffset() + this.relativeY;
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
/**
* Sets the vertical scrolling offset of this item.
*
* @param offset either the new offset
*/
public void setScrollYOffset( int offset) {
setScrollYOffset( offset, false );
}
/**
* Sets the vertical scrolling offset of this item.
*
* @param offset either the new offset
* @param smooth scroll to this new offset smooth if allowed
* @see #getScrollYOffset()
*/
public void setScrollYOffset( int offset, boolean smooth) {
//#debug
System.out.println("Setting scrollYOffset to " + offset + " for " + this);
//try { throw new RuntimeException("for yOffset " + offset + " in " + this); } catch (Exception e) { e.printStackTrace(); }
if (!this.enableScrolling && this.parent instanceof Container) {
((Container)this.parent).setScrollYOffset(offset, smooth);
return;
}
this.scrollStartTime = System.currentTimeMillis();
this.scrollStartYOffset = this.yOffset;
if (!smooth
//#ifdef polish.css.scroll-mode
|| !this.scrollSmooth
//#endif
) {
this.yOffset = offset;
}
this.targetYOffset = offset;
this.scrollSpeed = 0;
}
/**
* Determines whether this container or one of its parent containers is currently being scrolled
* @return true when this container or one of its parent containers is currently being scrolled
*/
public boolean isScrolling() {
if (this.enableScrolling) {
return (this.isScrolling) || (this.targetYOffset != this.yOffset) || (this.scrollSpeed != 0);
} else if (this.parent instanceof Container) {
return ((Container)this.parent).isScrolling();
} else {
return false;
}
}
/**
* Starts to scroll in the specified direction
* @param direction either Canvas.UP or Canvas.DOWN
* @param speed the speed in pixels per second
* @param damping the damping in percent; 0 means no damping at all; 100 means the scrolling will be stopped immediately
*/
public void startScroll( int direction,int speed, int damping) {
//#debug
System.out.println("startScrolling " + (direction == Canvas.UP ? "up" : "down") + " with speed=" + speed + ", damping=" + damping + " for " + this);
if (!this.enableScrolling && this.parent instanceof Container) {
((Container)this.parent).startScroll(direction, speed, damping);
return;
}
this.scrollDirection = direction;
this.scrollDamping = damping;
this.scrollSpeed = speed;
}
/**
* Retrieves the index of the specified item.
*
* @param item the item
* @return the index of the item; -1 when the item is not part of this container
*/
public int indexOf(Item item) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++) {
Object object = myItems[i];
if (object == null) {
break;
}
if (object == item) {
return i;
}
}
return -1;
}
/**
* Checks if this container includes the specified item
* @param item the item
* @return true when this container contains the item
*/
public boolean contains( Item item ) {
return this.itemsList.contains(item);
}
//#if (polish.debug.error || polish.keepToString) && polish.debug.container.includeChildren
/**
* Generates a String representation of this item.
* This method is only implemented when the logging framework is active or the preprocessing variable
* "polish.keepToString" is set to true.
* @return a String representation of this item.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append( super.toString() ).append( ": { ");
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
//#if polish.supportInvisibleItems || polish.css.visible
if (item.isInvisible) {
buffer.append( i ).append(":invis./plain:" + ( item.appearanceMode == PLAIN ) + "=[").append( item.toString() ).append("]");
} else {
buffer.append( i ).append("=").append( item.toString() );
}
//#else
buffer.append( i ).append("=").append( item.toString() );
//#endif
if (i != myItems.length - 1 ) {
buffer.append(", ");
}
}
buffer.append( " }");
return buffer.toString();
}
//#endif
/**
* Sets a list of items for this container.
* Use this direct access only when you know what you are doing.
*
* @param itemsList the list of items to set
*/
public void setItemsList(ArrayList itemsList) {
//System.out.println("Container.setItemsList");
clear();
if (this.isFocused) {
//System.out.println("enabling auto focus for index=" + this.focusedIndex);
setAutoFocusEnabled( true );
this.autoFocusIndex = this.focusedIndex;
}
this.focusedIndex = -1;
this.focusedItem = null;
if (this.enableScrolling) {
setScrollYOffset(0, false);
}
this.itemsList = itemsList;
this.containerItems = null;
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++) {
Item item = (Item) myItems[i];
if (item == null) {
break;
}
item.parent = this;
if (this.isShown) {
item.showNotify();
}
}
requestInit();
}
/**
* Calculates the number of interactive items included in this container.
* @return the number between 0 and size()
*/
public int getNumberOfInteractiveItems()
{
int number = 0;
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++)
{
Item item = (Item) items[i];
if (item == null) {
break;
}
if (item.appearanceMode != PLAIN) {
number++;
}
}
return number;
}
/**
* Releases all (memory intensive) resources such as images or RGB arrays of this background.
*/
public void releaseResources() {
super.releaseResources();
Item[] items = getItems();
for (int i = 0; i < items.length; i++)
{
Item item = items[i];
item.releaseResources();
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.releaseResources();
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#destroy()
*/
public void destroy() {
Item[] items = getItems();
clear();
super.destroy();
for (int i = 0; i < items.length; i++)
{
Item item = items[i];
item.destroy();
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.destroy();
this.containerView = null;
}
//#endif
}
/**
* Retrieves the internal array with all managed items embedded in this container, some entries might be null.
* Use this method only if you know what you are doing and only for reading.
* @return the internal array of the managed items
*/
public Object[] getInternalArray()
{
return this.itemsList.getInternalArray();
}
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteY()
// */
// public int getAbsoluteY()
// {
// return super.getAbsoluteY() + this.yOffset;
// }
//
// //#ifdef tmp.supportViewType
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteX()
// */
// public int getAbsoluteX() {
// int xAdjust = 0;
// if (this.containerView != null) {
// xAdjust = this.containerView.getScrollXOffset();
// }
// return super.getAbsoluteX() + xAdjust;
// }
// //#endif
//
//
//
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteX()
// */
// public boolean isInItemArea(int relX, int relY, Item child) {
// relY -= this.yOffset;
// //#ifdef tmp.supportViewType
// if (this.containerView != null) {
// relX -= this.containerView.getScrollXOffset();
// }
// //#endif
// return super.isInItemArea(relX, relY, child);
// }
//
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#isInItemArea(int, int)
*/
public boolean isInItemArea(int relX, int relY) {
Item focItem = this.focusedItem;
if (focItem != null && focItem.isInItemArea(relX - focItem.relativeX, relY - focItem.relativeY)) {
return true;
}
return super.isInItemArea(relX, relY);
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#fireEvent(java.lang.String, java.lang.Object)
*/
public void fireEvent(String eventName, Object eventData)
{
super.fireEvent(eventName, eventData);
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++)
{
Item item = (Item) items[i];
if (item == null) {
break;
}
item.fireEvent(eventName, eventData);
}
}
//#ifdef polish.css.view-type
/**
* Sets the view type for this item.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
* @param view the new view, use null to remove the current view
*/
public void setView( ItemView view ) {
if (!(view instanceof ContainerView)) {
super.setView( view );
return;
}
if (!this.isStyleInitialized && this.style != null) {
setStyle( this.style );
}
if (view == null) {
this.containerView = null;
this.view = null;
} else {
ContainerView viewType = (ContainerView) view;
viewType.parentContainer = this;
viewType.focusFirstElement = this.autoFocusEnabled;
viewType.allowCycling = this.allowCycling;
this.containerView = viewType;
if (this.style != null) {
view.setStyle( this.style );
}
}
this.setView = true;
}
//#endif
//#ifdef polish.css.view-type
/**
* Retrieves the view type for this item.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
*
* @return the current view, may be null
*/
public ItemView getView() {
if (this.containerView != null) {
return this.containerView;
}
return this.view;
}
//#endif
//#ifdef polish.css.view-type
/**
* Retrieves the view type for this item or instantiates a new one.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
*
* @param viewType the view registered in the style
* @param viewStyle the style
* @return the view, may be null
*/
protected ItemView getView( ItemView viewType, Style viewStyle) {
if (viewType instanceof ContainerView) {
if (this.containerView == null || this.containerView.getClass() != viewType.getClass()) {
try {
// formerly we have used the style's instance when that instance was still free.
// However, that approach lead to GC problems, as the style is not garbage collected.
viewType = (ItemView) viewType.getClass().newInstance();
viewType.parentItem = this;
if (this.isShown) {
if (this.containerView != null) {
this.containerView.hideNotify();
}
viewType.showNotify();
}
return viewType;
} catch (Exception e) {
//#debug error
System.out.println("Container: Unable to init view-type " + e );
}
}
return this.containerView;
}
return super.getView( viewType, viewStyle );
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#initMargin(de.enough.polish.ui.Style, int)
*/
protected void initMargin(Style style, int availWidth) {
if (this.isIgnoreMargins) {
this.marginLeft = 0;
this.marginRight = 0;
this.marginTop = 0;
this.marginBottom = 0;
} else {
this.marginLeft = style.getMarginLeft( availWidth );
this.marginRight = style.getMarginRight( availWidth );
this.marginTop = style.getMarginTop( availWidth );
this.marginBottom = style.getMarginBottom(availWidth);
}
}
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#onScreenSizeChanged(int, int)
*/
public void onScreenSizeChanged(int screenWidth, int screenHeight) {
Style lastStyle = this.style;
super.onScreenSizeChanged(screenWidth, screenHeight);
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.onScreenSizeChanged(screenWidth, screenHeight);
}
//#endif
//#if polish.css.landscape-style || polish.css.portrait-style
if (this.plainStyle != null && this.style != lastStyle) {
Style newStyle = null;
if (screenWidth > screenHeight) {
if (this.landscapeStyle != null && this.style != this.landscapeStyle) {
newStyle = this.landscapeStyle;
}
} else if (this.portraitStyle != null && this.style != this.portraitStyle){
newStyle = this.portraitStyle;
}
this.plainStyle = newStyle;
}
//#endif
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++) {
Item item = (Item) items[i];
if (item == null) {
break;
}
item.onScreenSizeChanged(screenWidth, screenHeight);
}
}
/**
* Recursively returns the focused child item of this Container or of the currently focused child Container.
* @return the focused child item or this Container when there is no focused child.
*/
public Item getFocusedChild() {
Item item = getFocusedItem();
if (item == null) {
return this;
}
if (item instanceof Container) {
return ((Container)item).getFocusedChild();
}
return item;
}
//#if polish.css.press-all
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#notifyItemPressedStart()
*/
public boolean notifyItemPressedStart() {
boolean handled = super.notifyItemPressedStart();
if (this.isPressAllChildren) {
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++) {
Item child = (Item) children[i];
if (child == null) {
break;
}
handled |= child.notifyItemPressedStart();
}
}
return handled;
}
//#endif
//#if polish.css.press-all
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#notifyItemPressedEnd()
*/
public void notifyItemPressedEnd() {
super.notifyItemPressedEnd();
if (this.isPressAllChildren) {
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++) {
Item child = (Item) children[i];
if (child == null) {
break;
}
child.notifyItemPressedEnd();
}
}
}
//#endif
/**
* Resets the pointer press y offset which is used for starting scrolling processes.
* This is only applicable for touch enabled handsets.
*/
public void resetLastPointerPressYOffset() {
//#if polish.hasPointerEvents
this.lastPointerPressYOffset = this.targetYOffset;
//#endif
}
//#ifdef polish.Container.additionalMethods:defined
//#include ${polish.Container.additionalMethods}
//#endif
}
| public void focusChild( int index, Item item, int direction, boolean force ) {
//#debug
System.out.println("Container (" + this + "): Focusing child item " + index + " (" + item + "), isInitialized=" + this.isInitialized + ", autoFocusEnabled=" + this.autoFocusEnabled );
//System.out.println("focus: yOffset=" + this.yOffset + ", targetYOffset=" + this.targetYOffset + ", enableScrolling=" + this.enableScrolling + ", isInitialized=" + this.isInitialized );
if (!isInitialized() && this.autoFocusEnabled) {
// setting the index for automatically focusing the appropriate item
// during the initialization:
//#debug
System.out.println("Container: Setting autofocus-index to " + index );
this.autoFocusIndex = index;
}
if (this.isFocused) {
setAutoFocusEnabled( false );
}
if (index == this.focusedIndex && item.isFocused && item == this.focusedItem) {
//#debug
System.out.println("Container: ignoring focusing of item " + index );
//#ifdef polish.css.view-type
if (this.containerView != null && this.containerView.focusedIndex != index) {
this.containerView.focusedItem = item;
this.containerView.focusedIndex = index;
}
//#endif
// ignore the focusing of the same element:
return;
}
//#if polish.blackberry
if (this.isShown) {
Display.getInstance().notifyFocusSet(item);
}
//#endif
// indicating if either the former focusedItem or the new focusedItem has changed it's size or it's layout by losing/gaining the focus,
// of course this can only work if this container is already initialized:
boolean isReinitializationRequired = false;
// first defocus the last focused item:
Item previouslyFocusedItem = this.focusedItem;
if (previouslyFocusedItem != null) {
int wBefore = previouslyFocusedItem.itemWidth;
int hBefore = previouslyFocusedItem.itemHeight;
int layoutBefore = previouslyFocusedItem.layout;
if (this.itemStyle != null) {
previouslyFocusedItem.defocus(this.itemStyle);
} else {
//#debug error
System.out.println("Container: Unable to defocus item - no previous style found.");
previouslyFocusedItem.defocus( StyleSheet.defaultStyle );
}
if (isInitialized()) {
//fix 2008-11-11: width given to an item can be different from availableContentWidth on ContainerViews:
//int wAfter = previouslyFocusedItem.getItemWidth( this.availableContentWidth, this.availableContentWidth, this.availableHeight );
//fix 2008-12-10: on some ContainerViews it can happen, that not all items have been initialized before:
//int wAfter = item.getItemWidth( item.availableWidth, item.availableWidth, item.availableHeight );
int wAfter = getChildWidth(item);
int hAfter = previouslyFocusedItem.itemHeight;
int layoutAfter = previouslyFocusedItem.layout;
if (wAfter != wBefore || hAfter != hBefore || layoutAfter != layoutBefore ) {
//#debug
System.out.println("dimension changed from " + wBefore + "x" + hBefore + " to " + wAfter + "x" + hAfter + " for previous " + previouslyFocusedItem);
isReinitializationRequired = true;
//#if tmp.supportViewType
if (this.containerView != null) {
previouslyFocusedItem.setInitialized(false); // could be that a container view poses restrictions on the possible size, i.e. within a table
}
//#endif
}
}
}
int wBefore = item.itemWidth;
int hBefore = item.itemHeight;
int layoutBefore = item.layout;
Style newStyle = getFocusedStyle( index, item);
boolean isDownwards = (direction == Canvas.DOWN) || (direction == Canvas.RIGHT) || (direction == 0 && index > this.focusedIndex);
int previousIndex = this.focusedIndex; // need to determine whether the user has scrolled from the bottom to the top
this.focusedIndex = index;
this.focusedItem = item;
int scrollOffsetBeforeScroll = getScrollYOffset();
//#if tmp.supportViewType
if ( this.containerView != null ) {
this.itemStyle = this.containerView.focusItem( index, item, direction, newStyle );
} else {
//#endif
this.itemStyle = item.focus( newStyle, direction );
//#if tmp.supportViewType
}
//#endif
//#ifdef polish.debug.error
if (this.itemStyle == null) {
//#debug error
System.out.println("Container: Unable to retrieve style of item " + item.getClass().getName() );
}
//#endif
//System.out.println("focus - still initialized=" + this.isInitialized + " for " + this);
if (isInitialized()) {
// this container has been initialized already,
// so the dimensions are known.
//System.out.println("focus: contentWidth=" + this.contentWidth + ", of container " + this);
//int wAfter = item.getItemWidth( this.availableContentWidth, this.availableContentWidth, this.availableHeight );
// fix 2008-11-11: availableContentWidth can be different from the width granted to items in a ContainerView:
int wAfter = getChildWidth( item );
int hAfter = item.itemHeight;
int layoutAfter = item.layout;
if (wAfter != wBefore || hAfter != hBefore || layoutAfter != layoutBefore ) {
//#debug
System.out.println("dimension changed from " + wBefore + "x" + hBefore + " to " + wAfter + "x" + hAfter + " for next " + item);
isReinitializationRequired = true;
//#if tmp.supportViewType
if (this.containerView != null) {
item.setInitialized(false); // could be that a container view poses restrictions on the possible size, i.e. within a table
}
//#endif
}
updateInternalPosition(item);
if (getScrollHeight() != -1) {
// Now adjust the scrolling:
Item nextItem;
if ( isDownwards && index < this.itemsList.size() - 1 ) {
nextItem = get( index + 1 );
//#debug
System.out.println("Focusing downwards, nextItem.relativY = [" + nextItem.relativeY + "], focusedItem.relativeY=[" + item.relativeY + "], this.yOffset=" + this.yOffset + ", this.targetYOffset=" + this.targetYOffset);
} else if ( !isDownwards && index > 0 ) {
nextItem = get( index - 1 );
//#debug
System.out.println("Focusing upwards, nextItem.yTopPos = " + nextItem.relativeY + ", focusedItem.relativeY=" + item.relativeY );
} else {
//#debug
System.out.println("Focusing last or first item.");
nextItem = item;
}
if (getScrollYOffset() == scrollOffsetBeforeScroll) {
if ( this.enableScrolling
&& (isDownwards && (index < previousIndex)
//#if polish.Container.selectEntriesWhileTouchScrolling
|| (previousIndex == -1)
//#endif
) ) {
// either the first item or the first selectable item has been focused, so scroll to the very top:
//#if tmp.supportViewType
if (this.containerView == null || !this.containerView.isVirtualContainer())
//#endif
{
setScrollYOffset(0, true);
}
} else {
int itemYTop = isDownwards ? item.relativeY : nextItem.relativeY;
int itemYBottom = isDownwards ? nextItem.relativeY + nextItem.itemHeight : item.relativeY + item.itemHeight;
int height = itemYBottom - itemYTop;
//System.out.println("scrolling for item " + item + ", nextItem=" + nextItem + " in " + this + " with relativeY=" + this.relativeY + ", itemYTop=" + itemYTop);
scroll( direction, this.relativeX, itemYTop, item.internalWidth, height, force );
}
}
}
} else if (getScrollHeight() != -1) { // if (this.enableScrolling) {
//#debug
System.out.println("focus: postpone scrolling to initContent() for " + this + ", item " + item);
this.isScrollRequired = true;
}
if (isInitialized()) {
setInitialized(!isReinitializationRequired);
} else if (this.contentWidth != 0) {
updateInternalPosition(item);
}
//#if polish.Container.notifyFocusChange
notifyStateChanged();
//#endif
if (this.focusListener != null) {
this.focusListener.onFocusChanged(this, this.focusedItem, this.focusedIndex);
}
}
/**
* Queries the width of an child item of this container.
* This allows subclasses to control the possible re-initialization that is happening here.
* Also ContainerViews can override the re-initialization in their respective getChildWidth() method.
* @param item the child item
* @return the width of the child item
* @see #getChildHeight(Item)
* @see ContainerView#getChildWidth(Item)
*/
protected int getChildWidth(Item item) {
//#if tmp.supportViewType
ContainerView contView = this.containerView;
if (contView != null) {
return contView.getChildWidth(item);
}
//#endif
int w;
if (item.availableWidth > 0) {
w = item.getItemWidth( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
w = item.getItemWidth( this.availContentWidth, this.availContentWidth, this.availContentHeight );
}
return w;
}
/**
* Queries the height of an child item of this container.
* This allows subclasses to control the possible re-initialization that is happening here.
* Also ContainerViews can override the re-initialization in their respective getChildHeight() method.
* @param item the child item
* @return the height of the child item
* @see #getChildHeight(Item)
* @see ContainerView#getChildHeight(Item)
*/
protected int getChildHeight(Item item) {
//#if tmp.supportViewType
ContainerView contView = this.containerView;
if (contView != null) {
return contView.getChildHeight(item);
}
//#endif
int h;
if (item.availableWidth > 0) {
h = item.getItemHeight( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
h = item.getItemHeight( this.availContentWidth, this.availContentWidth, this.availContentHeight );
}
return h;
}
/**
* Retrieves the best matching focus style for the given item
* @param index the index of the item
* @param item the item
* @return the matching focus style
*/
protected Style getFocusedStyle(int index, Item item)
{
Style newStyle = item.getFocusedStyle();
//#if polish.css.focused-style-first
if (index == 0 && this.focusedStyleFirst != null) {
newStyle = this.focusedStyleFirst;
}
//#endif
//#if polish.css.focused-style-last
if (this.focusedStyleLast != null && index == this.itemsList.size() - 1) {
newStyle = this.focusedStyleLast;
}
//#endif
return newStyle;
}
/**
* Scrolls this container so that the (internal) area of the given item is best seen.
* This is used when a GUI even has been consumed by the currently focused item.
* The call is fowarded to scroll( direction, x, y, w, h ).
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param item the item for which the scrolling should be adjusted
* @return true when the container was scrolled
*/
public boolean scroll(int direction, Item item, boolean force) {
//#debug
System.out.println("scroll: scrolling for item " + item + ", item.internalX=" + item.internalX +", relativeInternalY=" + ( item.relativeY + item.contentY + item.internalY ) + ", relativeY=" + item.relativeY + ", contentY=" + item.contentY + ", internalY=" + item.internalY);
if ( (item.internalX != NO_POSITION_SET)
&& ( (item.itemHeight > getScrollHeight()) || ( (item.internalY + item.internalHeight) > item.contentHeight ) )
) {
// use internal position of item for scrolling:
//System.out.println("using internal area for scrolling");
int relativeInternalX = item.relativeX + item.contentX + item.internalX;
int relativeInternalY = item.relativeY + item.contentY + item.internalY;
return scroll( direction, relativeInternalX, relativeInternalY, item.internalWidth, item.internalHeight, force );
} else {
if (!isInitialized() && item.relativeY == 0) {
// defer scrolling to init at a later stage:
//System.out.println( this + ": setting scrollItem to " + item);
synchronized(this.itemsList) {
this.scrollItem = item;
}
return true;
} else {
// use item dimensions for scrolling:
//System.out.println("use item area for scrolling");
return scroll( direction, item.relativeX, item.relativeY, item.itemWidth, item.itemHeight, force );
}
}
}
/**
* Adjusts the yOffset or the targetYOffset so that the given relative values are inside of the visible area.
* The call is forwarded to a parent container when scrolling is not enabled for this item.
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param x the horizontal position of the area relative to this content's left edge, is ignored in the current version
* @param y the vertical position of the area relative to this content's top edge
* @param width the width of the area
* @param height the height of the area
* @return true when the scroll request changed the internal scroll offsets
*/
protected boolean scroll( int direction, int x, int y, int width, int height ) {
return scroll( direction, x, y, width, height, false );
}
/**
* Adjusts the yOffset or the targetYOffset so that the given relative values are inside of the visible area.
* The call is forwarded to a parent container when scrolling is not enabled for this item.
*
* @param direction the direction, is used for adjusting the scrolling when the internal area is to large. Either 0 or Canvas.UP, Canvas.DOWN, Canvas.LEFT or Canvas.RIGHT
* @param x the horizontal position of the area relative to this content's left edge, is ignored in the current version
* @param y the vertical position of the area relative to this content's top edge
* @param width the width of the area
* @param height the height of the area
* @param force true when the area should be shown regardless where the the current scrolloffset is located
* @return true when the scroll request changed the internal scroll offsets
*/
protected boolean scroll( int direction, int x, int y, int width, int height, boolean force ) {
//#debug
System.out.println("scroll: direction=" + direction + ", y=" + y + ", availableHeight=" + this.scrollHeight + ", height=" + height + ", focusedIndex=" + this.focusedIndex + ", yOffset=" + this.yOffset + ", targetYOffset=" + this.targetYOffset +", numberOfItems=" + this.itemsList.size() + ", in " + this + ", downwards=" + (direction == Canvas.DOWN || direction == Canvas.RIGHT || direction == 0));
if (!this.enableScrolling) {
if (this.parent instanceof Container) {
x += this.contentX + this.relativeX;
y += this.contentY + this.relativeY;
//#debug
System.out.println("Forwarding scroll request to parent now with y=" + y);
return ((Container)this.parent).scroll(direction, x, y, width, height, force );
}
return false;
}
if ( height == 0) {
return false;
}
// assume scrolling down when the direction is not known:
boolean isDownwards = (direction == Canvas.DOWN || direction == Canvas.RIGHT || direction == 0);
boolean isUpwards = (direction == Canvas.UP );
int currentYOffset = this.targetYOffset; // yOffset starts at 0 and grows to -contentHeight + lastItem.itemHeight
//#if polish.css.scroll-mode
if (!this.scrollSmooth) {
currentYOffset = this.yOffset;
}
//#endif
int originalYOffset = currentYOffset;
int verticalSpace = this.scrollHeight - (this.contentY + this.marginBottom + this.paddingBottom + getBorderWidthBottom()); // the available height for this container
int yTopAdjust = 0;
Screen scr = this.screen;
boolean isCenterOrBottomLayout = (this.layout & LAYOUT_VCENTER) == LAYOUT_VCENTER || (this.layout & LAYOUT_BOTTOM) == LAYOUT_BOTTOM;
if (isCenterOrBottomLayout && (scr != null && this == scr.container && this.relativeY > scr.contentY)) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
yTopAdjust = this.relativeY - scr.contentY;
}
if ( y + height + currentYOffset + yTopAdjust > verticalSpace ) {
// the area is too low, so scroll down (= increase the negative yOffset):
//#debug
System.out.println("scroll: item too low: verticalSpace=" + verticalSpace + " y=" + y + ", height=" + height + ", yOffset=" + currentYOffset + ", yTopAdjust=" + yTopAdjust + ", relativeY=" + this.relativeY + ", screen.contentY=" + scr.contentY + ", scr=" + scr);
//currentYOffset += verticalSpace - (y + height + currentYOffset + yTopAdjust);
int newYOffset = verticalSpace - (y + height + yTopAdjust);
// check if the top of the area is still visible when scrolling downwards:
if ( !isUpwards && y + newYOffset < 0) {
newYOffset = -y;
}
if (isDownwards) {
// check if we scroll down more than one page:
int difference = Math.max(Math.abs(currentYOffset), Math.abs(newYOffset)) -
Math.min(Math.abs(currentYOffset), Math.abs(newYOffset));
if (difference > verticalSpace && !force ) {
newYOffset = currentYOffset - verticalSpace;
}
}
currentYOffset = newYOffset;
} else if ( y + currentYOffset < 0 ) {
//#debug
System.out.println("scroll: item too high: , y=" + y + ", current=" + currentYOffset + ", target=" + (-y) );
int newYOffset = -y;
// check if the bottom of the area is still visible when scrolling upwards:
if (isUpwards && newYOffset + y + height > verticalSpace) { // && height < verticalSpace) {
//2008-12-10: scrolling upwards resulted in too large jumps when we have big items, so
// adjust the offset in any case, not only when height is smaller than the vertical space (height < verticalSpace):
newYOffset = -(y + height) + verticalSpace;
}
int difference = Math.max(Math.abs(currentYOffset), Math.abs(newYOffset)) -
Math.min(Math.abs(currentYOffset), Math.abs(newYOffset));
if (difference > verticalSpace && !force ) {
newYOffset = currentYOffset + verticalSpace;
}
currentYOffset = newYOffset;
} else {
//#debug
System.out.println("scroll: do nothing");
return false;
}
if (currentYOffset != originalYOffset) {
setScrollYOffset(currentYOffset, true);
return true;
} else {
//#debug
System.out.println("scroll: no change");
return false;
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setAppearanceMode(int)
*/
public void setAppearanceMode(int appearanceMode)
{
super.setAppearanceMode(appearanceMode);
// this is used in initContent() to circumvent the
// reversal of the previously set appearance mode
synchronized(this.itemsList) {
this.appearanceModeSet = true;
}
}
protected void initLayout(Style style, int availWidth) {
//#ifdef polish.css.view-type
if (this.containerView != null) {
this.containerView.initPadding(style, availWidth);
} else
//#endif
{
initPadding(style, availWidth);
}
//#ifdef polish.css.view-type
if (this.containerView != null) {
this.containerView.initMargin(style, availWidth);
} else
//#endif
{
initMargin(style, availWidth);
}
}
/**
* Retrieves the synchronization lock for this container.
* As a lock either the internal ArrayList for items is used or the paint lock of the screen when this container is associated with a screen.
* The lock can be used manipulate a Container that is currently displayed
* @return the synchronization lock
* @see Screen#getPaintLock()
* @see #add(Item)
*/
public Object getSynchronizationLock() {
Object lock = this.itemsList;
Screen scr = getScreen();
if (scr != null) {
lock = scr.getPaintLock();
}
return lock;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#initItem( int, int )
*/
protected void initContent(int firstLineWidth, int availWidth, int availHeight) {
//#debug
System.out.println("Container: intialising content for " + this + ": autofocus=" + this.autoFocusEnabled + ", autoFocusIndex=" + this.autoFocusIndex + ", isFocused=" + this.isFocused + ", firstLineWidth=" + firstLineWidth + ", availWidth=" + availWidth + ", availHeight=" + availHeight + ", size=" + this.itemsList.size() );
//this.availableContentWidth = firstLineWidth;
//#if polish.css.focused-style
if (this.focusedStyle != null) {
this.focusedTopMargin = this.focusedStyle.getMarginTop(availWidth) + this.focusedStyle.getPaddingTop(availWidth);
if (this.focusedStyle.border != null) {
this.focusedTopMargin += this.focusedStyle.border.borderWidthTop;
}
if (this.focusedStyle.background != null) {
this.focusedTopMargin += this.focusedStyle.background.borderWidth;
}
}
//#endif
synchronized (this.itemsList) {
int myContentWidth = 0;
int myContentHeight = 0;
Item[] myItems;
if (this.containerItems == null || this.containerItems.length != this.itemsList.size()) {
myItems = (Item[]) this.itemsList.toArray( new Item[ this.itemsList.size() ]);
this.containerItems = myItems;
} else {
myItems = (Item[]) this.itemsList.toArray(this.containerItems);
}
//#if (polish.css.child-style-first || polish.css.child-style-last) && polish.css.child-style
if (this.style != null && this.childStyle != null) {
Style firstStyle = null;
//#if polish.css.child-style-first
firstStyle = (Style) this.style.getObjectProperty("child-style-first");
//#endif
Style lastStyle = null;
//#if polish.css.child-style-last
lastStyle = (Style) this.style.getObjectProperty("child-style-last");
//#endif
if (firstStyle != null || lastStyle != null) {
int lastIndex = myItems.length - 1;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.style == null) {
item.setStyle( this.childStyle );
}
if (i != 0 && item.style == firstStyle) {
item.setStyle( this.childStyle );
}
if (i != lastIndex && item.style == lastStyle) {
item.setStyle( this.childStyle );
}
if (i == 0 && firstStyle != null && item.style != firstStyle) {
item.setStyle( firstStyle );
}
if (i == lastIndex && lastStyle != null && item.style != lastStyle) {
item.setStyle( lastStyle );
}
}
}
}
//#endif
if (this.autoFocusEnabled && this.autoFocusIndex >= myItems.length ) {
this.autoFocusIndex = 0;
}
//#if polish.Container.allowCycling != false
if (this.focusedItem instanceof Container && ((Container)this.focusedItem).allowCycling && getNumberOfInteractiveItems() > 1) {
((Container)this.focusedItem).allowCycling = false;
}
Item ancestor = this.parent;
while (this.allowCycling && ancestor != null) {
if ( (ancestor instanceof Container) && ((Container)ancestor).getNumberOfInteractiveItems()>1 ) {
this.allowCycling = false;
break;
}
ancestor = ancestor.parent;
}
//#endif
//#if tmp.supportViewType
if (this.containerView != null) {
// additional initialization is necessary when a view is used for this container:
boolean requireScrolling = this.isScrollRequired && this.isFocused;
// System.out.println("ABOUT TO CALL INIT CONTENT - focusedIndex of Container=" + this.focusedIndex);
this.containerView.parentItem = this;
this.containerView.parentContainer = this;
this.containerView.init( this, firstLineWidth, availWidth, availHeight);
if (this.defaultCommand != null || (this.commands != null && this.commands.size() > 0)) {
this.appearanceMode = INTERACTIVE;
} else if(!this.appearanceModeSet){
this.appearanceMode = this.containerView.appearanceMode;
}
if (this.isFocused && this.autoFocusEnabled) {
//#debug
System.out.println("Container/View: autofocusing element starting at " + this.autoFocusIndex);
if (this.autoFocusIndex >= 0 && this.appearanceMode != Item.PLAIN) {
for (int i = this.autoFocusIndex; i < myItems.length; i++) {
Item item = myItems[i];
if (item.appearanceMode != Item.PLAIN) {
// make sure that the item has applied it's own style first (not needed since it has been initialized by the container view already):
//item.getItemHeight( firstLineWidth, lineWidth );
// now focus the item:
setAutoFocusEnabled( false );
requireScrolling = (this.autoFocusIndex != 0);
// int heightBeforeFocus = item.itemHeight;
focusChild( i, item, 0, true);
// outcommented on 2008-07-09 because this results in a wrong
// available width for items with subsequent wrong getAbsoluteX() coordinates
// int availableWidth = item.itemWidth;
// if (availableWidth < this.minimumWidth) {
// availableWidth = this.minimumWidth;
// }
// if (item.getItemHeight( availableWidth, availableWidth ) > heightBeforeFocus) {
// item.isInitialized = false;
// this.containerView.initContent( this, firstLineWidth, lineWidth);
// }
this.isScrollRequired = this.isScrollRequired && requireScrolling; // override setting in focus()
//this.containerView.focusedIndex = i; is done within focus(i, item, 0) already
//this.containerView.focusedItem = item;
//System.out.println("autofocus: found item " + i );
break;
}
}
// when deactivating the auto focus the container won't initialize correctly after it has
// been cleared and items are added subsequently one after another (e.g. like within the Browser).
// } else {
// this.autoFocusEnabled = false;
}
}
this.contentWidth = this.containerView.contentWidth;
this.contentHeight = this.containerView.contentHeight;
if (requireScrolling && this.focusedItem != null) {
//#debug
System.out.println("initContent(): scrolling autofocused or scroll-required item for view, focused=" + this.focusedItem);
Item item = this.focusedItem;
scroll( 0, item.relativeX, item.relativeY, item.itemWidth, item.itemHeight, true );
}
else if (this.scrollItem != null) {
//System.out.println("initContent(): scrolling scrollItem=" + this.scrollItem);
boolean scrolled = scroll( 0, this.scrollItem, true );
if (scrolled) {
this.scrollItem = null;
}
}
if (this.focusedItem != null) {
updateInternalPosition(this.focusedItem);
}
return;
}
//#endif
boolean isLayoutShrink = (this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK;
boolean hasFocusableItem = false;
int numberOfVerticalExpandItems = 0;
Item lastVerticalExpandItem = null;
int lastVerticalExpandItemIndex = 0;
boolean hasCenterOrRightItems = false;
boolean hasVerticalExpandItems = false;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.isLayoutVerticalExpand()) {
hasVerticalExpandItems = true;
break;
}
}
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (hasVerticalExpandItems && item.isLayoutVerticalExpand()) {
// re-initialize items when we have vertical-expand items, so that relativeY and itemHeight is correctly calculated
// with each run:
item.setInitialized(false);
}
//System.out.println("initalising " + item.getClass().getName() + ":" + i);
int width = item.getItemWidth( availWidth, availWidth, availHeight );
int height = item.itemHeight; // no need to call getItemHeight() since the item is now initialised...
// now the item should have a style, so it can be safely focused
// without loosing the style information:
//String toString = item.toString();
//System.out.println("init of item " + i + ": height=" + height + " of item " + toString.substring( 19, Math.min(120, toString.length() ) ));
//if (item.isInvisible && height != 0) {
// System.out.println("*** item.height != 0 even though it is INVISIBLE - isInitialized=" + item.isInitialized );
//}
if (item.appearanceMode != PLAIN) {
hasFocusableItem = true;
}
if (this.isFocused && this.autoFocusEnabled && (i >= this.autoFocusIndex ) && (item.appearanceMode != Item.PLAIN)) {
setAutoFocusEnabled( false );
//System.out.println("Container.initContent: auto-focusing " + i + ": " + item );
focusChild( i, item, 0, true );
this.isScrollRequired = (this.isScrollRequired || hasFocusableItem) && (this.autoFocusIndex != 0); // override setting in focus()
height = item.getItemHeight(availWidth, availWidth, availHeight);
if (!isLayoutShrink) {
width = item.itemWidth; // no need to call getItemWidth() since the item is now initialised...
} else {
width = 0;
}
if (this.enableScrolling && this.autoFocusIndex != 0) {
//#debug
System.out.println("initContent(): scrolling autofocused item, autofocus-index=" + this.autoFocusIndex + ", i=" + i );
scroll( 0, 0, myContentHeight, width, height, true );
}
} else if (i == this.focusedIndex) {
if (isLayoutShrink) {
width = 0;
}
if (this.isScrollRequired) {
//#debug
System.out.println("initContent(): scroll is required - scrolling to y=" + myContentHeight + ", height=" + height);
scroll( 0, 0, myContentHeight, width, height, true );
this.isScrollRequired = false;
// } else if (item.internalX != NO_POSITION_SET ) {
// // ensure that lines of textfields etc are within the visible area:
// scroll(0, item );
}
}
if (item.isLayoutVerticalExpand()) {
numberOfVerticalExpandItems++;
lastVerticalExpandItem = item;
lastVerticalExpandItemIndex = i;
}
if (width > myContentWidth) {
myContentWidth = width;
}
item.relativeY = myContentHeight;
if (item.isLayoutCenter || item.isLayoutRight) {
hasCenterOrRightItems = true;
if (this.parent == null) {
myContentWidth = availWidth;
}
} else {
item.relativeX = 0;
}
myContentHeight += height != 0 ? height + this.paddingVertical : 0;
//System.out.println( i + ": height=" + height + ", myContentHeight=" + myContentHeight + ", item=" + item + ", style=" + (this.style == null ? "<none>" : this.style.name));
//System.out.println("item.yTopPos=" + item.yTopPos);
} // cycling through all items
if (numberOfVerticalExpandItems > 0 && myContentHeight < availHeight) {
int diff = availHeight - myContentHeight;
if (numberOfVerticalExpandItems == 1) {
// this is a simple case:
lastVerticalExpandItem.setItemHeight( lastVerticalExpandItem.itemHeight + diff );
for (int i = lastVerticalExpandItemIndex+1; i < myItems.length; i++)
{
Item item = myItems[i];
item.relativeY += diff;
}
} else {
// okay, there are several items that would like to be expanded vertically:
// System.out.println("having " + numberOfVerticalExpandItems + ", diff: " + diff + "=>" + (diff / numberOfVerticalExpandItems) + "=>" + ((diff / numberOfVerticalExpandItems) * numberOfVerticalExpandItems));
diff = diff / numberOfVerticalExpandItems;
int relYAdjust = 0;
for (int i = 0; i < myItems.length; i++)
{
Item item = myItems[i];
// System.out.println("changing relativeY from " + item.relativeY + " to " + (item.relativeY + relYAdjust) + ", relYAdjust=" + relYAdjust + " for " + item );
item.relativeY += relYAdjust;
if (item.isLayoutVerticalExpand()) {
// System.out.println("changing itemHeight from " + item.itemHeight + " to " + (item.itemHeight + diff) + " for " + item);
item.setItemHeight(item.itemHeight + diff );
relYAdjust += diff;
}
}
}
myContentHeight = availHeight;
}
if (this.minimumWidth != null && this.minimumWidth.getValue(firstLineWidth) > myContentWidth) {
myContentWidth = this.minimumWidth.getValue(firstLineWidth) - (getBorderWidthLeft() + getBorderWidthRight() + this.marginLeft + this.paddingLeft + this.marginRight + this.paddingRight);
}
//#if polish.css.expand-items
if (this.isExpandItems) {
for (int i = 0; i < myItems.length; i++)
{
Item item = myItems[i];
if (!item.isLayoutExpand && item.itemWidth < myContentWidth) {
item.setItemWidth( myContentWidth );
}
}
}
//#endif
if (!hasFocusableItem) {
if (this.defaultCommand != null || (this.commands != null && this.commands.size() > 0)) {
this.appearanceMode = INTERACTIVE;
} else if(!this.appearanceModeSet){
this.appearanceMode = PLAIN;
}
} else {
this.appearanceMode = INTERACTIVE;
Item item = this.focusedItem;
if (item == null) {
this.internalX = NO_POSITION_SET;
} else {
updateInternalPosition(item);
if (isLayoutShrink) {
//System.out.println("container has shrinking layout and contains focused item " + item);
boolean doExpand = item.isLayoutExpand;
int width;
if (doExpand) {
item.setInitialized(false);
item.isLayoutExpand = false;
width = item.getItemWidth( availWidth, availWidth, availHeight );
item.setInitialized(false);
item.isLayoutExpand = true;
if (width > myContentWidth) {
myContentWidth = width;
}
}
if ( this.minimumWidth != null && myContentWidth < this.minimumWidth.getValue(availWidth) ) {
myContentWidth = this.minimumWidth.getValue(availWidth);
}
if (doExpand) {
item.init(myContentWidth, myContentWidth, availHeight);
}
//myContentHeight += item.getItemHeight( lineWidth, lineWidth );
}
}
}
if (hasCenterOrRightItems) {
int width;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
width = item.itemWidth;
if (item.isLayoutCenter) {
item.relativeX = (myContentWidth - width) / 2;
} else if (item.isLayoutRight) {
item.relativeX = (myContentWidth - width);
}
}
}
if (this.scrollItem != null) {
boolean scrolled = scroll( 0, this.scrollItem, true );
//System.out.println( this + ": scrolled scrollItem " + this.scrollItem + ": " + scrolled);
if (scrolled) {
this.scrollItem = null;
}
}
this.contentHeight = myContentHeight;
this.contentWidth = myContentWidth;
//#debug
System.out.println("initContent(): Container " + this + " has a content-width of " + this.contentWidth + ", parent=" + this.parent);
}
}
/**
* Enables or disables the auto focus of this container
* @param enable true when autofocus should be enabled
*/
protected void setAutoFocusEnabled( boolean enable) {
// if (enable) {
// try { throw new RuntimeException("for autofocus, previous=" + this.autoFocusEnabled + ", index=" + this.autoFocusIndex ); } catch (Exception e) { e.printStackTrace(); }
// }
this.autoFocusEnabled = enable;
}
/**
* Updates the internal position of this container according to the specified item's one
* @param item the (assumed focused) item
*/
protected void updateInternalPosition(Item item) {
//#debug
System.out.println("updating internal position of " + this + " for child " + item);
if (item == null) {
return;
}
int prevX = this.internalX;
int prevY = this.internalY;
int prevWidth = this.internalWidth;
int prevHeight = this.internalHeight;
if (item.internalX != NO_POSITION_SET) { // && (item.itemHeight > getScrollHeight() || (item.contentY + item.internalY + item.internalHeight > item.itemHeight) ) ) {
// adjust internal settings for root container:
this.internalX = item.relativeX + item.contentX + item.internalX;
if (this.enableScrolling) {
this.internalY = getScrollYOffset() + item.relativeY + item.contentY + item.internalY;
} else {
this.internalY = item.relativeY + item.contentY + item.internalY;
}
this.internalWidth = item.internalWidth;
this.internalHeight = item.internalHeight;
//#debug
System.out.println(this + ": Adjusted internal area by internal area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
} else {
this.internalX = item.relativeX;
if (this.enableScrolling) {
this.internalY = getScrollYOffset() + item.relativeY;
} else {
this.internalY = item.relativeY;
}
this.internalWidth = item.itemWidth;
this.internalHeight = item.itemHeight;
//#debug
System.out.println(this + ": Adjusted internal area by full area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
}
if (this.isFocused
&& this.parent instanceof Container
&& (prevY != this.internalY || prevX != this.internalX || prevWidth != this.itemWidth || prevHeight != this.internalHeight)
) {
((Container)this.parent).updateInternalPosition( this );
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setContentWidth(int)
*/
protected void setContentWidth(int width)
{
if (width < this.contentWidth) {
initContent( width, width, this.availContentHeight);
} else {
super.setContentWidth(width);
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.setContentWidth( width );
}
//#endif
if (this.focusedItem != null && (this.layout & LAYOUT_SHRINK) == LAYOUT_SHRINK) {
this.focusedItem.init(width, width, this.contentHeight);
}
}
}
//#ifdef tmp.supportViewType
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#setContentHeight(int)
*/
protected void setContentHeight(int height) {
super.setContentHeight(height);
if(this.containerView != null) {
this.containerView.setContentHeight( height );
}
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setItemWidth(int)
*/
public void setItemWidth(int width) {
int prevContentX = this.contentX;
int myContentWidth = this.contentWidth + width - this.itemWidth;
super.setItemWidth(width);
//#ifdef tmp.supportViewType
if (this.containerView == null) {
//#endif
boolean hasCenterOrRightAlignedItems = false;
Item[] myItems = this.containerItems;
if (myItems != null) {
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
width = item.itemWidth;
if (item.isLayoutCenter) {
item.relativeX = (myContentWidth - width) / 2;
hasCenterOrRightAlignedItems = true;
} else if (item.isLayoutRight) {
item.relativeX = (myContentWidth - width);
hasCenterOrRightAlignedItems = true;
}
}
}
if (hasCenterOrRightAlignedItems) {
this.contentWidth = myContentWidth;
this.contentX = prevContentX;
}
//#ifdef tmp.supportViewType
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#paintContent(int, int, int, int, javax.microedition.lcdui.Graphics)
*/
protected void paintContent(int x, int y, int leftBorder, int rightBorder, Graphics g) {
//System.out.println("paintContent, size=" + this.itemsList.size() + ", isInitialized=" + this.isInitialized);
// System.out.println("paintContent with implicit width " + (rightBorder - leftBorder) + ", itemWidth=" + this.itemWidth + " of " + this ) ;
// paints all items,
// the layout will be done according to this containers'
// layout or according to the items layout, when specified.
// adjust vertical start for scrolling:
//#if polish.debug.debug
if (this.enableScrolling) {
// g.setColor( 0xFFFF00 );
// g.drawLine( leftBorder, y, rightBorder, y + getContentScrollHeight() );
// g.drawLine( rightBorder, y, leftBorder, y + + getContentScrollHeight() );
// g.drawString( "" + this.availableHeight, x, y, Graphics.TOP | Graphics.LEFT );
//#debug
System.out.println("Container: drawing " + this + " with yOffset=" + this.yOffset );
}
//#endif
boolean setClipping = ( this.enableScrolling && (this.yOffset != 0 || this.itemHeight > this.scrollHeight) ); //( this.yOffset != 0 && (this.marginTop != 0 || this.paddingTop != 0) );
int clipX = 0;
int clipY = 0;
int clipWidth = 0;
int clipHeight = 0;
if (setClipping) {
clipX = g.getClipX();
clipY = g.getClipY();
clipWidth = g.getClipWidth();
clipHeight = g.getClipHeight();
Screen scr = this.screen;
if (scr != null && scr.container == this && this.relativeY > scr.contentY ) {
int diff = this.relativeY - scr.contentY;
g.clipRect(clipX, y - diff, clipWidth, clipHeight - (y - clipY) + diff );
} else {
//g.clipRect(clipX, y, clipWidth, clipHeight - (y - clipY) );
// in this way we also clip the padding area at the bottom of the container (padding-bottom):
g.clipRect(clipX, y, clipWidth, this.scrollHeight - this.paddingTop - this.paddingBottom );
}
}
//x = leftBorder;
y += this.yOffset;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
//#debug
System.out.println("forwarding paint call to " + this.containerView );
this.containerView.paintContent( this, x, y, leftBorder, rightBorder, g);
if (setClipping) {
g.setClip(clipX, clipY, clipWidth, clipHeight);
}
} else {
//#endif
Item[] myItems = this.containerItems;
int startY = g.getClipY();
int endY = startY + g.getClipHeight();
Item focItem = this.focusedItem;
int focIndex = this.focusedIndex;
int itemX;
//int originalY = y;
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
// currently the NEWLINE_AFTER and NEWLINE_BEFORE layouts will be ignored,
// since after every item a line break will be done. Use view-type: midp2; to place several items into a single row.
int itemY = y + item.relativeY;
if (i != focIndex && itemY + item.itemHeight >= startY && itemY < endY ){
//item.paint(x, y, leftBorder, rightBorder, g);
itemX = x + item.relativeX;
item.paint(itemX, itemY, itemX, itemX + item.itemWidth, g);
}
// if (item.itemHeight != 0) {
// y += item.itemHeight + this.paddingVertical;
// }
}
boolean paintFocusedItemOutside = false;
if (focItem != null) {
paintFocusedItemOutside = setClipping && (focItem.internalX != NO_POSITION_SET);
if (!paintFocusedItemOutside) {
itemX = x + focItem.relativeX;
focItem.paint(itemX, y + focItem.relativeY, itemX, itemX + focItem.itemWidth, g);
}
}
if (setClipping) {
g.setClip(clipX, clipY, clipWidth, clipHeight);
}
// paint the currently focused item outside of the clipping area when it has an internal area. This is
// for example useful for popup items that extend the actual container area.
if (paintFocusedItemOutside) {
//System.out.println("Painting focusedItem " + this.focusedItem + " with width=" + this.focusedItem.itemWidth + " and with increased colwidth of " + (focusedRightBorder - focusedX) );
itemX = x + focItem.relativeX;
focItem.paint(itemX, y + focItem.relativeY, itemX, itemX + focItem.itemWidth, g);
}
//#ifdef tmp.supportViewType
}
//#endif
// if (this.internalX != NO_POSITION_SET) {
// g.setColor(0xff00);
// g.drawRect( x + this.internalX, y + this.internalY, this.internalWidth, this.internalHeight );
// }
}
//#if tmp.supportViewType
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#paintBackgroundAndBorder(int, int, int, int, javax.microedition.lcdui.Graphics)
*/
protected void paintBackgroundAndBorder(int x, int y, int width, int height, Graphics g) {
if (this.containerView == null) {
super.paintBackgroundAndBorder(x, y, width, height, g);
} else {
// this is only necessary since ContainerViews are integrated differently from
// normal ItemViews - we should consider abonding this approach!
//#if polish.css.bgborder
if (this.bgBorder != null) {
int bgX = x - this.bgBorder.borderWidthLeft;
int bgW = width + this.bgBorder.borderWidthLeft + this.bgBorder.borderWidthRight;
int bgY = y - this.bgBorder.borderWidthTop;
int bgH = height + this.bgBorder.borderWidthTop + this.bgBorder.borderWidthBottom;
this.containerView.paintBorder( this.bgBorder, bgX, bgY, bgW, bgH, g );
}
//#endif
if ( this.background != null ) {
int bWidthL = getBorderWidthLeft();
int bWidthR = getBorderWidthRight();
int bWidthT = getBorderWidthTop();
int bWidthB = getBorderWidthBottom();
if ( this.border != null ) {
x += bWidthL;
y += bWidthT;
width -= bWidthL + bWidthR;
height -= bWidthT + bWidthB;
}
this.containerView.paintBackground( this.background, x, y, width, height, g );
if (this.border != null) {
x -= bWidthL;
y -= bWidthT;
width += bWidthL + bWidthR;
height += bWidthT + bWidthB;
}
}
if ( this.border != null ) {
this.containerView.paintBorder( this.border, x, y, width, height, g );
}
}
}
//#endif
//#ifdef polish.useDynamicStyles
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getCssSelector()
*/
protected String createCssSelector() {
return "container";
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyPressed(int, int)
*/
protected boolean handleKeyPressed(int keyCode, int gameAction) {
//#debug
System.out.println("handleKeyPressed( " + keyCode + ", " + gameAction + " ) for " + this + ", focusedItem=" + this.focusedItem);
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return super.handleKeyPressed(keyCode, gameAction);
}
Item item = this.focusedItem;
//looking for the next focusable Item if the focusedItem is not in
//the visible content area
//#ifdef tmp.supportFocusItemsInVisibleContentArea
//#if polish.hasPointerEvents
if(this.needsCheckItemInVisibleContent && item != null && !isItemInVisibleContentArea(item)
&& (gameAction == Canvas.DOWN || gameAction == Canvas.UP || gameAction == Canvas.LEFT || gameAction == Canvas.RIGHT)){
int next = -1;
int offset = 0;
//System.out.println("tmp.supportFocusItemsInVisibleContentArea is set");
if(gameAction == Canvas.DOWN ){
next = getFirstItemInVisibleContentArea(true);
offset = getScrollYOffset()-(this.getAvailableContentHeight());
}else if(gameAction == Canvas.UP ){
next = getLastItemInVisibleContentArea(true);
offset = getScrollYOffset()+(this.getAvailableContentHeight());
}
if(next != -1){
focusChild( next, this.get(next), gameAction, false );
item = get(next);
}
else{
if(gameAction == Canvas.DOWN || gameAction == Canvas.UP ){
boolean smooth = true;
//#ifdef polish.css.scroll-mode
smooth = this.scrollSmooth;
//#endif
setScrollYOffset(offset, smooth);
}
return true;
}
}else{
this.needsCheckItemInVisibleContent = false;
}
//#endif
//#endif
if (item != null) {
if (!item.isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
} else if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
int startY = getScrollYOffset() + item.relativeY + item.contentY + item.internalY;
if ( (
(startY < 0 && gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2)
|| (startY + item.internalHeight > this.scrollHeight && gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8)
)
&& (scroll(gameAction, item, false))
){
//System.out.println("scrolling instead of forwwarding key to child " + item + ", item.internalY=" + item.internalY + ", item.internalHeight=" + item.internalHeight + ", item.focused=" + (item instanceof Container ? item.relativeY + ((Container)item).focusedItem.relativeY : -1) );
return true;
}
}
int scrollOffset = getScrollYOffset();
if ( item.handleKeyPressed(keyCode, gameAction) ) {
//if (item.internalX != NO_POSITION_SET) {
if (this.enableScrolling) {
if (getScrollYOffset() == scrollOffset) {
//#debug
System.out.println("scrolling focused item that has handled key pressed, item=" + item + ", item.internalY=" + item.internalY);
scroll(gameAction, item, false);
}
} else {
updateInternalPosition(item);
}
//}
//#debug
System.out.println("Container(" + this + "): handleKeyPressed consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
return handleNavigate(keyCode, gameAction) || super.handleKeyPressed(keyCode, gameAction);
}
/**
* Handles a keyPressed or keyRepeated event for navigating in the container.
*
* @param keyCode the code of the keypress/keyrepeat event
* @param gameAction the associated game action
* @return true when the key was handled
*/
protected boolean handleNavigate(int keyCode, int gameAction) {
// now allow a navigation within the container:
boolean processed = false;
int offset = getRelativeScrollYOffset();
int availableScrollHeight = getScrollHeight();
Item focItem = this.focusedItem;
int y = 0;
int h = 0;
if (focItem != null && availableScrollHeight != -1) {
if (focItem.internalX == NO_POSITION_SET || (focItem.relativeY + focItem.contentY + focItem.internalY + focItem.internalHeight < availableScrollHeight)) {
y = focItem.relativeY;
h = focItem.itemHeight;
//System.out.println("normal item has focus: y=" + y + ", h=" + h + ", item=" + focItem);
} else {
y = focItem.relativeY + focItem.contentY + focItem.internalY;
h = focItem.internalHeight;
//System.out.println("internal item has focus: y=" + y + ", h=" + h + ", item=" + focItem);
}
//System.out.println("offset=" + offset + ", scrollHeight=" + availableScrollHeight + ", offset + y + h=" + (offset + y + h) + ", focusedItem=" + focItem);
}
if (
//#if polish.blackberry && !polish.hasTrackballEvents
(gameAction == Canvas.RIGHT && keyCode != Canvas.KEY_NUM6) ||
//#endif
(gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8))
{
if (focItem != null
&& (availableScrollHeight != -1 && offset + y + h > availableScrollHeight)
) {
//System.out.println("offset=" + offset + ", foc.relativeY=" + this.focusedItem.relativeY + ", foc.height=" + this.focusedItem.itemHeight + ", available=" + this.availableHeight);
// keep the focus do scroll downwards:
//#debug
System.out.println("Container(" + this + "): scrolling down: keeping focus, focusedIndex=" + this.focusedIndex + ", y=" + y + ", h=" + h + ", offset=" + offset );
} else {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
} else {
//#endif
processed = shiftFocus( true, 0 );
//#ifdef tmp.supportViewType
}
//#endif
}
//#debug
System.out.println("Container(" + this + "): forward shift by one item succeded: " + processed + ", focusedIndex=" + this.focusedIndex + ", enableScrolling=" + this.enableScrolling);
if ((!processed)
&& (
(availableScrollHeight != -1 && offset + y + h > availableScrollHeight)
|| (this.enableScrolling && offset + this.itemHeight > availableScrollHeight)
)
) {
int containerHeight = Math.max( this.contentHeight, this.backgroundHeight );
int availScrollHeight = getContentScrollHeight();
int scrollOffset = getScrollYOffset();
// scroll downwards:
int difference =
//#if polish.Container.ScrollDelta:defined
//#= ${polish.Container.ScrollDelta};
//#else
((containerHeight + scrollOffset) - availScrollHeight);
if(difference > (availScrollHeight / 2))
{
difference = availScrollHeight / 2;
}
//#endif
if(difference == 0)
{
return false;
}
offset = scrollOffset - difference;
if (offset > 0) {
offset = 0;
}
setScrollYOffset( offset, true );
processed = true;
//#debug
System.out.println("Down/Right: Decreasing (target)YOffset to " + offset);
}
} else if (
//#if polish.blackberry && !polish.hasTrackballEvents
(gameAction == Canvas.LEFT && keyCode != Canvas.KEY_NUM4) ||
//#endif
(gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) )
{
if (focItem != null
&& availableScrollHeight != -1
&& offset + focItem.relativeY < 0 ) // this.focusedItem.yTopPos < this.yTop )
{
// keep the focus do scroll upwards:
//#debug
System.out.println("Container(" + this + "): scrolling up: keeping focus, relativeScrollOffset=" + offset + ", scrollHeight=" + availableScrollHeight + ", focusedIndex=" + this.focusedIndex + ", focusedItem.relativeY=" + this.focusedItem.relativeY + ", this.availableHeight=" + this.scrollHeight + ", targetYOffset=" + this.targetYOffset);
} else {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
} else {
//#endif
processed = shiftFocus( false, 0 );
//#ifdef tmp.supportViewType
}
//#endif
}
//#debug
System.out.println("Container(" + this + "): upward shift by one item succeded: " + processed + ", focusedIndex=" + this.focusedIndex );
if ((!processed)
&& ( (this.enableScrolling && offset < 0)
|| (availableScrollHeight != -1 && focItem != null && offset + focItem.relativeY < 0) )
) {
// scroll upwards:
int difference =
//#if polish.Container.ScrollDelta:defined
//#= ${polish.Container.ScrollDelta};
//#else
getScreen() != null ? getScreen().contentHeight / 2 : 30;
//#endif
offset = getScrollYOffset() + difference;
if (offset > 0) {
offset = 0;
}
setScrollYOffset(offset, true);
//#debug
System.out.println("Up/Left: Increasing (target)YOffset to " + offset);
processed = true;
}
}
//#ifdef tmp.supportViewType
else if (this.containerView != null)
{
processed = this.containerView.handleKeyPressed(keyCode, gameAction);
}
//#endif
return processed;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyReleased(int, int)
*/
protected boolean handleKeyReleased(int keyCode, int gameAction) {
//#debug
System.out.println("handleKeyReleased( " + keyCode + ", " + gameAction + " ) for " + this);
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return super.handleKeyReleased(keyCode, gameAction);
}
Item item = this.focusedItem;
if (item != null) {
int scrollOffset = getScrollYOffset();
if ( item.handleKeyReleased( keyCode, gameAction ) ) {
if (item.isShown) { // could be that the item or its screen has been removed in the meantime...
if (this.enableScrolling) {
if (getScrollYOffset() == scrollOffset) {
//#debug
System.out.println("scrolling focused item that has handled key released, item=" + item + ", item.internalY=" + item.internalY);
scroll(gameAction, item, false);
}
} else {
updateInternalPosition(item);
}
}
// 2009-06-10:
// if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
// scroll(gameAction, item);
// }
// if (this.enableScrolling) {
// if (getScrollYOffset() == scrollOffset) {
// // #debug
// System.out.println("scrolling focused item that has handled key pressed, item=" + item + ", item.internalY=" + item.internalY);
// scroll(gameAction, item);
// }
// } else {
// if (item.itemHeight > getScrollHeight() && item.internalX != NO_POSITION_SET) {
// // adjust internal settings for root container:
// this.internalX = item.relativeX + item.contentX + item.internalX;
// this.internalY = item.relativeY + item.contentY + item.internalY;
// this.internalWidth = item.internalWidth;
// this.internalHeight = item.internalHeight;
// // #debug
// System.out.println(this + ": Adjusted internal area by internal area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
// } else {
// this.internalX = item.relativeX;
// this.internalY = item.relativeY;
// this.internalWidth = item.itemWidth;
// this.internalHeight = item.itemHeight;
// // #debug
// System.out.println(this + ": Adjusted internal area by full area of " + item + " to x=" + this.internalX + ", y=" + this.internalY + ", w=" + this.internalWidth + ", h=" + this.internalHeight );
// }
// }
//#debug
System.out.println("Container(" + this + "): handleKeyReleased consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handleKeyReleased(keyCode, gameAction) ) {
return true;
}
}
//#endif
return super.handleKeyReleased(keyCode, gameAction);
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyRepeated(int, int)
*/
protected boolean handleKeyRepeated(int keyCode, int gameAction) {
if (this.itemsList.size() == 0 && this.focusedItem == null) {
return false;
}
if (this.focusedItem != null) {
Item item = this.focusedItem;
if ( item.handleKeyRepeated( keyCode, gameAction ) ) {
if (this.enableScrolling && item.internalX != NO_POSITION_SET) {
scroll(gameAction, item, false);
}
//#debug
System.out.println("Container(" + this + "): handleKeyRepeated consumed by item " + item.getClass().getName() + "/" + item );
return true;
}
}
return handleNavigate(keyCode, gameAction);
// note: in previous versions a keyRepeat event was just re-asigned to a keyPressed event. However, this resulted
// in non-logical behavior when an item wants to ignore keyRepeat events and only press "real" keyPressed events.
// So now events are ignored by containers when they are ignored by their currently focused item...
//return super.handleKeyRepeated(keyCode, gameAction);
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
/**
* Focuses the first visible item in the given vertical minimum and maximum offsets.
*
* @param container
* the container
* @param verticalMin
* the vertical minimum offset
* @param verticalMax
* the vertical maximum offset
* @return
* the newly focused item
*/
Item focusVisible(Container container, int verticalMin, int verticalMax) {
Item[] items = container.getItems();
Item focusedItem = null;
for (int index = 0; index < items.length; index++) {
Item item = items[index];
int itemTop= item.getAbsoluteY();
int itemBottom = itemTop + item.itemHeight;
int itemAppearanceMode = item.getAppearanceMode();
// if item is interactive ...
if(itemAppearanceMode == Item.INTERACTIVE || itemAppearanceMode == Item.HYPERLINK || itemAppearanceMode == Item.BUTTON) {
// ... and is a container and not fully visible ...
if(item instanceof Container && !isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, true)) {
// ... but partially visible ...
if(isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, false)) {
focusedItem = focusVisible((Container)item, verticalMin, verticalMax);
// if a child item was focused ...
if(focusedItem != null) {
focusIndex(index);
return item;
}
}
} else if(isItemVisible(verticalMin, verticalMax, itemTop, itemBottom, true)) {
return focusIndex(index);
}
}
}
return null;
}
/**
* Returns true if the given item top and bottom offset is inside the given vertical minimum and maximum offset.
*
* @param verticalMin
* the vertical minimum offset
* @param verticalMax
* the vertical maximum offset
* @param itemTop
* the item top offset
* @param itemBottom
* the item bottom offset
* @param full
* true if the item must fit completly into the given vertical offsets otherwise false
* @return true
* if the item fits into the given vertical offsets otherwise false
*/
protected boolean isItemVisible(int verticalMin, int verticalMax, int itemTop, int itemBottom, boolean full) {
if(full) {
return itemTop >= verticalMin && itemBottom <= verticalMax;
} else {
return !(itemBottom <= verticalMin || itemTop >= verticalMax);
}
}
/**
* Focuses the child at the given index while preserving the scroll offset.
*
* @param index
* the index
* @return the focused item
*/
Item focusIndex(int index) {
int scrollOffset = getScrollYOffset();
setInitialized(false);
focusChild(index);
setInitialized(true);
setScrollYOffset(scrollOffset);
return getFocusedChild();
}
//#endif
/**
* Shifts the focus to the next or the previous item.
*
* @param forwardFocus true when the next item should be focused, false when
* the previous item should be focused.
* @param steps how many steps forward or backward the search for the next focusable item should be started,
* 0 for the current item, negative values go backwards.
* @return true when the focus could be moved to either the next or the previous item.
*/
private boolean shiftFocus(boolean forwardFocus, int steps ) {
Item[] items = getItems();
if ( items == null || items.length <= 1) {
//#debug
System.out.println("shiftFocus fails: this.items==null or items.length <= 0");
return false;
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
if(this.focusedIndex == -1) {
int verticalMin = getAbsoluteY();
int verticalMax = verticalMin + getScrollHeight();
Item newFocusedItem = focusVisible(this, verticalMin, verticalMax);
if(newFocusedItem != null) {
return true;
}
}
//#endif
//System.out.println("|");
Item focItem = this.focusedItem;
//#if polish.css.colspan
int i = this.focusedIndex;
if (steps != 0) {
//System.out.println("ShiftFocus: steps=" + steps + ", forward=" + forwardFocus);
int doneSteps = 0;
steps = Math.abs( steps ) + 1;
Item item = items[i];
while( doneSteps <= steps) {
doneSteps += item.colSpan;
if (doneSteps >= steps) {
//System.out.println("bailing out at too many steps: focusedIndex=" + this.focusedIndex + ", startIndex=" + i + ", steps=" + steps + ", doneSteps=" + doneSteps);
break;
}
if (forwardFocus) {
i++;
if (i == items.length - 1 ) {
i = items.length - 2;
break;
} else if (i == items.length) {
i = items.length - 1;
break;
}
} else {
i--;
if (i < 0) {
i = 1;
break;
}
}
item = items[i];
//System.out.println("focusedIndex=" + this.focusedIndex + ", startIndex=" + i + ", steps=" + steps + ", doneSteps=" + doneSteps);
}
if (doneSteps >= steps && item.colSpan != 1) {
if (forwardFocus) {
i--;
if (i < 0) {
i = items.length - 1;
}
//System.out.println("forward: Adjusting startIndex to " + i );
} else {
i = (i + 1) % items.length;
//System.out.println("backward: Adjusting startIndex to " + i );
}
}
}
//#else
//# int i = this.focusedIndex + steps;
if (i > items.length) {
i = items.length - 2;
}
if (i < 0) {
i = 1;
}
//#endif
Item item = null;
boolean allowCycle = this.allowCycling;
if (allowCycle) {
if (forwardFocus) {
// when you scroll to the bottom and
// there is still space, do
// scroll first before cycling to the
// first item:
allowCycle = (getScrollYOffset() + this.itemHeight <= getScrollHeight() + 1);
//System.out.println("allowCycle-calculation ( forward non-smoothScroll): yOffset=" + this.yOffset + ", itemHeight=" + this.itemHeight + " (together="+ (this.yOffset + this.itemHeight));
} else {
// when you scroll to the top and
// there is still space, do
// scroll first before cycling to the
// last item:
allowCycle = (getScrollYOffset() == 0);
}
}
//#debug
System.out.println("shiftFocus of " + this + ": allowCycle(local)=" + allowCycle + ", allowCycle(global)=" + this.allowCycling + ", isFoward=" + forwardFocus + ", enableScrolling=" + this.enableScrolling + ", targetYOffset=" + this.targetYOffset + ", yOffset=" + this.yOffset + ", focusedIndex=" + this.focusedIndex + ", start=" + i );
while (true) {
if (forwardFocus) {
i++;
if (i >= items.length) {
if (allowCycle) {
if (!fireContinueCycle(CycleListener.DIRECTION_BOTTOM_TO_TOP)) {
return false;
}
allowCycle = false;
i = 0;
//#debug
System.out.println("allowCycle: Restarting at the beginning");
} else {
break;
}
}
} else {
i--;
if (i < 0) {
if (allowCycle) {
if (!fireContinueCycle(CycleListener.DIRECTION_TOP_TO_BOTTOM)) {
return false;
}
allowCycle = false;
i = items.length - 1;
//#debug
System.out.println("allowCycle: Restarting at the end");
} else {
break;
}
}
}
item = items[i];
if (item.appearanceMode != Item.PLAIN) {
break;
}
}
if (item == null || item.appearanceMode == Item.PLAIN || item == focItem) {
//#debug
System.out.println("got original focused item: " + (item == focItem) + ", item==null:" + (item == null) + ", mode==PLAIN:" + (item == null ? false:(item.appearanceMode == PLAIN)) );
return false;
}
int direction = Canvas.UP;
if (forwardFocus) {
direction = Canvas.DOWN;
}
focusChild(i, item, direction, false );
return true;
}
/**
* Retrieves the index of the item which is currently focused.
*
* @return the index of the focused item, -1 when none is focused.
*/
public int getFocusedIndex() {
return this.focusedIndex;
}
/**
* Retrieves the currently focused item.
*
* @return the currently focused item, null when there is no focusable item in this container.
*/
public Item getFocusedItem() {
return this.focusedItem;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setStyle(de.enough.polish.ui.Style)
*/
public void setStyle(Style style) {
//#if polish.debug.debug
if (this.parent == null) {
//#debug
System.out.println("Container.setStyle without boolean parameter for container " + toString() );
}
//#endif
setStyleWithBackground(style, false);
}
/**
* Sets the style of this container.
*
* @param style the style
* @param ignoreBackground when true is given, the background and border-settings
* will be ignored.
*/
public void setStyleWithBackground( Style style, boolean ignoreBackground) {
super.setStyle(style);
if (ignoreBackground) {
this.background = null;
this.border = null;
this.marginTop = 0;
this.marginBottom = 0;
this.marginLeft = 0;
this.marginRight = 0;
}
this.isIgnoreMargins = ignoreBackground;
//#if polish.css.focused-style-first
Style firstFocusStyleObj = (Style) style.getObjectProperty("focused-style-first");
if (firstFocusStyleObj != null) {
this.focusedStyleFirst = firstFocusStyleObj;
}
//#endif
//#if polish.css.focused-style-last
Style lastFocusStyleObj = (Style) style.getObjectProperty("focused-style-last");
if (lastFocusStyleObj != null) {
this.focusedStyleLast = lastFocusStyleObj;
}
//#endif
//#if polish.css.focus-all-style
Style focusAllStyleObj = (Style) style.getObjectProperty("focus-all-style");
if (focusAllStyleObj != null) {
this.focusAllStyle = focusAllStyleObj;
}
//#endif
//#ifdef polish.css.view-type
// ContainerView viewType = (ContainerView) style.getObjectProperty("view-type");
// if (this instanceof ChoiceGroup) {
// System.out.println("SET.STYLE / CHOICEGROUP: found view-type (1): " + (viewType != null) + " for " + this);
// }
if (this.view != null && this.view instanceof ContainerView) {
ContainerView viewType = (ContainerView) this.view; // (ContainerView) style.getObjectProperty("view-type");
this.containerView = viewType;
this.view = null; // set to null so that this container can control the view completely. This is necessary for scrolling, for example.
viewType.parentContainer = this;
viewType.focusFirstElement = this.autoFocusEnabled;
viewType.allowCycling = this.allowCycling;
if (this.focusedItem != null) {
viewType.focusItem(this.focusedIndex, this.focusedItem, 0 );
}
} else if (!this.preserveViewType && style.getObjectProperty("view-type") == null && !this.setView) {
this.containerView = null;
}
//#endif
//#ifdef polish.css.columns
if (this.containerView == null) {
Integer columns = style.getIntProperty("columns");
if (columns != null) {
if (columns.intValue() > 1) {
//System.out.println("Container: Using default container view for displaying table");
this.containerView = new ContainerView();
this.containerView.parentContainer = this;
this.containerView.focusFirstElement = this.autoFocusEnabled;
this.containerView.allowCycling = this.allowCycling;
}
}
}
//#endif
//#if polish.css.scroll-mode
Integer scrollModeInt = style.getIntProperty("scroll-mode");
if ( scrollModeInt != null ) {
this.scrollSmooth = (scrollModeInt.intValue() == SCROLL_SMOOTH);
}
//#endif
//#ifdef polish.css.scroll-duration
Integer scrollDurationInt = style.getIntProperty("scroll-duration");
if (scrollDurationInt != null) {
this.scrollDuration = scrollDurationInt.intValue();
}
//#endif
//#if tmp.checkBouncing
Boolean allowBounceBool = style.getBooleanProperty("bounce");
if (allowBounceBool != null) {
this.allowBouncing = allowBounceBool.booleanValue();
}
//#endif
//#if polish.css.expand-items
synchronized(this.itemsList) {
Boolean expandItemsBool = style.getBooleanProperty("expand-items");
if (expandItemsBool != null) {
this.isExpandItems = expandItemsBool.booleanValue();
}
}
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.setStyle(style);
}
//#endif
//#if polish.css.focus-all
Boolean focusAllBool = style.getBooleanProperty("focus-all");
if (focusAllBool != null) {
this.isFocusAllChildren = focusAllBool.booleanValue();
}
//#endif
//#if polish.css.press-all
Boolean pressAllBool = style.getBooleanProperty("press-all");
if (pressAllBool != null) {
this.isPressAllChildren = pressAllBool.booleanValue();
}
//#endif
//#if polish.css.change-styles
String changeStyles = style.getProperty("change-styles");
if (changeStyles != null) {
int splitPos = changeStyles.indexOf('>');
if (splitPos != -1) {
String oldStyle = changeStyles.substring(0, splitPos ).trim();
String newStyle = changeStyles.substring(splitPos+1).trim();
try {
changeChildStyles(oldStyle, newStyle);
} catch (Exception e) {
//#debug error
System.out.println("Unable to apply change-styles \"" + changeStyles + "\"" + e );
}
}
}
//#endif
//#ifdef polish.css.show-delay
Integer showDelayInt = style.getIntProperty("show-delay");
if (showDelayInt != null) {
this.showDelay = showDelayInt.intValue();
}
//#endif
//#if polish.css.child-style
Style childStyleObj = (Style) style.getObjectProperty("child-style");
if (childStyleObj != null) {
this.childStyle = childStyleObj;
}
//#endif
}
//#ifdef tmp.supportViewType
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#setStyle(de.enough.polish.ui.Style, boolean)
*/
public void setStyle(Style style, boolean resetStyle)
{
super.setStyle(style, resetStyle);
if (this.containerView != null) {
this.containerView.setStyle(style, resetStyle);
}
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#resetStyle(boolean)
*/
public void resetStyle(boolean recursive) {
super.resetStyle(recursive);
if (recursive) {
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++) {
Item item = (Item) items[i];
if (item == null) {
break;
}
item.resetStyle(recursive);
}
}
}
/**
* Changes the style of all children that are currently using the specified oldChildStyle with the given newChildStyle.
*
* @param oldChildStyleName the name of the style of child items that should be exchanged
* @param newChildStyleName the name of the new style for child items that were using the specified oldChildStyle before
* @throws IllegalArgumentException if no corresponding newChildStyle could be found
* @see StyleSheet#getStyle(String)
*/
public void changeChildStyles( String oldChildStyleName, String newChildStyleName) {
Style newChildStyle = StyleSheet.getStyle(newChildStyleName);
if (newChildStyle == null) {
throw new IllegalArgumentException("for " + newChildStyleName );
}
Style oldChildStyle = StyleSheet.getStyle(oldChildStyleName);
changeChildStyles(oldChildStyle, newChildStyle);
}
/**
* Changes the style of all children that are currently using the specified oldChildStyle with the given newChildStyle.
*
* @param oldChildStyle the style of child items that should be exchanged
* @param newChildStyle the new style for child items that were using the specified oldChildStyle before
* @throws IllegalArgumentException if newChildStyle is null
*/
public void changeChildStyles( Style oldChildStyle, Style newChildStyle) {
if (newChildStyle == null) {
throw new IllegalArgumentException();
}
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++)
{
Item child = (Item) children[i];
if (child == null) {
break;
}
if (child.style == oldChildStyle) {
child.setStyle( newChildStyle );
}
}
}
/**
* Parses the given URL and includes the index of the item, when there is an "%INDEX%" within the given url.
* @param url the resource URL which might include the substring "%INDEX%"
* @param item the item to which the URL belongs to. The item must be
* included in this container.
* @return the URL in which the %INDEX% is substituted by the index of the
* item in this container. The url "icon%INDEX%.png" is resolved
* to "icon1.png" when the item is the second item in this container.
* @throws NullPointerException when the given url or item is null
*/
public String parseIndexUrl(String url, Item item) {
int pos = url.indexOf("%INDEX%");
if (pos != -1) {
int index = this.itemsList.indexOf( item );
//TODO rob check if valid, when url ends with %INDEX%
url = url.substring(0, pos) + index + url.substring( pos + 7 );
}
return url;
}
/**
* Retrieves the position of the specified item.
*
* @param item the item
* @return the position of the item, or -1 when it is not defined
*/
public int getPosition( Item item ) {
return this.itemsList.indexOf( item );
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#focus(de.enough.polish.ui.Style, int)
*/
protected Style focus(Style focusStyle, int direction ) {
//#debug
System.out.println("focusing container " + this + " from " + (this.style != null ? this.style.name : "<no style>") + " to " + getFocusedStyle().name);
if (this.isFocused) {
return this.style;
}
this.plainStyle = null;
if ( this.itemsList.size() == 0) {
return super.focus(focusStyle, direction );
} else {
focusStyle = getFocusedStyle();
//#if polish.css.focus-all
if (this.isFocusAllChildren) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemFocusedStyle = item.getFocusedStyle();
if (itemFocusedStyle != focusStyle && itemFocusedStyle != StyleSheet.focusedStyle) {
if (!item.isFocused) {
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.focus(itemFocusedStyle, direction);
}
}
}
}
//#endif
//#if polish.css.focus-all-style
if (this.focusAllStyle != null) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
if (item.style != null) {
item.setAttribute(KEY_ORIGINAL_STYLE, item.style);
}
item.setStyle(this.focusAllStyle);
}
}
//#endif
Style result = this.style;
if ((focusStyle != null && focusStyle != StyleSheet.focusedStyle && (this.parent == null || (this.parent.getFocusedStyle() != focusStyle)))
//#if polish.css.include-label
|| (this.includeLabel && focusStyle != null)
//#endif
) {
result = super.focus( focusStyle, direction );
this.plainStyle = result;
}
if (!this.isStyleInitialized && result != null) {
//#debug
System.out.println("setting original style for container " + this + " with style " + result.name);
setStyle( result );
}
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.focus(focusStyle, direction);
//this.isInitialised = false; not required
}
//#endif
this.isFocused = true;
int newFocusIndex = this.focusedIndex;
//#if tmp.supportViewType
if ( this.containerView == null || this.containerView.allowsAutoTraversal ) {
//#endif
Item[] myItems = getItems();
if (this.autoFocusEnabled && this.autoFocusIndex < myItems.length && (myItems[this.autoFocusIndex].appearanceMode != PLAIN)) {
//#debug
System.out.println("focus(Style, direction): autofocusing " + this + ", focusedIndex=" + this.focusedIndex + ", autofocus=" + this.autoFocusIndex);
newFocusIndex = this.autoFocusIndex;
setAutoFocusEnabled( false );
} else {
// focus the first interactive item...
if (direction == Canvas.UP || direction == Canvas.LEFT ) {
//System.out.println("Container: direction UP with " + myItems.length + " items");
for (int i = myItems.length; --i >= 0; ) {
Item item = myItems[i];
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
} else {
//System.out.println("Container: direction DOWN");
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
}
}
this.focusedIndex = newFocusIndex;
if (newFocusIndex == -1) {
//System.out.println("DID NOT FIND SUITEABLE ITEM - current style=" + this.style.name);
// this container has only non-focusable items!
if (this.plainStyle != null) {
// this will result in plainStyle being returned in the super.focus() call:
this.style = this.plainStyle;
}
return super.focus( focusStyle, direction );
}
//#if tmp.supportViewType
} else if (this.focusedIndex == -1) {
Object[] myItems = this.itemsList.getInternalArray();
//System.out.println("Container: direction DOWN through view type " + this.view);
for (int i = 0; i < myItems.length; i++) {
Item item = (Item) myItems[i];
if (item == null) {
break;
}
if (item.appearanceMode != PLAIN) {
newFocusIndex = i;
break;
}
}
this.focusedIndex = newFocusIndex;
if (newFocusIndex == -1) {
//System.out.println("DID NOT FIND SUITEABLE ITEM (2)");
// this container has only non-focusable items!
if (this.plainStyle != null) {
this.style = this.plainStyle;
}
return super.focus( focusStyle, direction );
}
}
//#endif
Item item = get( this.focusedIndex );
// Style previousStyle = item.style;
// if (previousStyle == null) {
// previousStyle = StyleSheet.defaultStyle;
// }
this.showCommandsHasBeenCalled = false;
//#if polish.css.focus-all
if (item.isFocused) {
Style orStyle = (Style) item.getAttribute(KEY_ORIGINAL_STYLE);
if (orStyle != null) {
//#debug
System.out.println("re-setting to plain style " + orStyle.name + " for item " + item);
item.style = orStyle;
}
}
//#endif
focusChild( this.focusedIndex, item, direction, true );
// item command handling is now done within showCommands and handleCommand
if (!this.showCommandsHasBeenCalled && this.commands != null) {
showCommands();
}
// if (item.commands == null && this.commands != null) {
// Screen scr = getScreen();
// if (scr != null) {
// scr.setItemCommands(this);
// }
// }
// change the label-style of this container:
//#ifdef polish.css.label-style
if (this.label != null && focusStyle != null) {
Style labStyle = (Style) focusStyle.getObjectProperty("label-style");
if (labStyle != null) {
this.labelStyle = this.label.style;
this.label.setStyle( labStyle );
}
}
//#endif
return result;
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#defocus(de.enough.polish.ui.Style)
*/
public void defocus(Style originalStyle) {
//#debug
System.out.println("defocus container " + this + " with style " + (originalStyle != null ? originalStyle.name : "<no style>"));
//#if polish.css.focus-all
if (this.isFocusAllChildren) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemPlainStyle = (Style) item.removeAttribute( KEY_ORIGINAL_STYLE );
if (itemPlainStyle != null) {
item.defocus(itemPlainStyle);
}
}
}
//#endif
Style originalItemStyle = this.itemStyle;
//#if polish.css.focus-all-style
if (this.focusAllStyle != null) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++)
{
Item item = (Item) myItems[i];
if (item == null) {
break;
}
Style itemPlainStyle = (Style) item.removeAttribute( KEY_ORIGINAL_STYLE );
if (itemPlainStyle != null) {
if (item == this.focusedItem) {
originalItemStyle = itemPlainStyle;
} else {
item.setStyle(itemPlainStyle);
}
}
}
}
//#endif
if ( this.itemsList.size() == 0 || this.focusedIndex == -1 ) {
super.defocus( originalStyle );
} else {
if (this.plainStyle != null) {
super.defocus( this.plainStyle );
if (originalStyle == null) {
originalStyle = this.plainStyle;
}
this.plainStyle = null;
} else if (this.isPressed) {
notifyItemPressedEnd();
}
this.isFocused = false;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.defocus( originalStyle );
setInitialized(false);
}
//#endif
Item item = this.focusedItem;
if (item != null) {
//#if polish.css.focus-all
if (item.isFocused) {
//#endif
item.defocus( originalItemStyle );
//#if polish.css.focus-all
}
//#endif
this.isFocused = false;
// now remove any commands which are associated with this item:
if (item.commands == null && this.commands != null) {
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
}
}
// change the label-style of this container:
//#ifdef polish.css.label-style
Style tmpLabelStyle = null;
if ( originalStyle != null) {
tmpLabelStyle = (Style) originalStyle.getObjectProperty("label-style");
}
if (tmpLabelStyle == null) {
tmpLabelStyle = StyleSheet.labelStyle;
}
if (this.label != null && tmpLabelStyle != null && this.label.style != tmpLabelStyle) {
this.label.setStyle( tmpLabelStyle );
}
//#endif
}
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#showCommands()
*/
public void showCommands() {
this.showCommandsHasBeenCalled = true;
super.showCommands();
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleCommand(javax.microedition.lcdui.Command)
*/
protected boolean handleCommand(Command cmd) {
boolean handled = super.handleCommand(cmd);
if (!handled && this.focusedItem != null) {
return this.focusedItem.handleCommand(cmd);
}
return handled;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#animate(long, de.enough.polish.ui.ClippingRegion)
*/
public void animate(long currentTime, ClippingRegion repaintRegion) {
super.animate(currentTime, repaintRegion);
boolean addFullRepaintRegion = false;
// scroll the container:
int target = this.targetYOffset;
int current = this.yOffset;
int diff = 0;
if (target != current) {
long passedTime = (currentTime - this.scrollStartTime);
int nextOffset = CssAnimation.calculatePointInRange(this.scrollStartYOffset, target, passedTime, this.scrollDuration , CssAnimation.FUNCTION_EXPONENTIAL_OUT );
this.yOffset = nextOffset;
addFullRepaintRegion = true;
}
int speed = this.scrollSpeed;
if (speed != 0) {
speed = (speed * (100 - this.scrollDamping)) / 100;
if (speed <= 0) {
speed = 0;
}
this.scrollSpeed = speed;
long timeDelta = currentTime - this.lastAnimationTime;
if (timeDelta > 1000) {
timeDelta = AnimationThread.ANIMATION_INTERVAL;
}
speed = (int) ((speed * timeDelta) / 1000);
if (speed == 0) {
this.scrollSpeed = 0;
}
int offset = this.yOffset;
if (this.scrollDirection == Canvas.UP) {
offset += speed;
target = offset;
if (offset > 0) {
this.scrollSpeed = 0;
target = 0;
//#if tmp.checkBouncing
if (!this.allowBouncing) {
offset = 0;
}
//#elif polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false
offset = 0;
//#endif
}
} else {
offset -= speed;
target = offset;
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
// Style myStyle = this.style;
// if (myStyle != null) {
// maxItemHeight -= myStyle.getPaddingTop(this.availableHeight) + myStyle.getPaddingBottom(this.availableHeight) + myStyle.getMarginTop(this.availableHeight) + myStyle.getMarginBottom(this.availableHeight);
// }
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (offset + maxItemHeight < this.scrollHeight) {
this.scrollSpeed = 0;
target = this.scrollHeight - maxItemHeight;
//#if tmp.checkBouncing
if (!this.allowBouncing) {
offset = target;
}
//#elif polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false
offset = target;
//#endif
}
}
this.yOffset = offset;
this.targetYOffset = target;
addFullRepaintRegion = true;
}
// add repaint region:
if (addFullRepaintRegion) {
int x, y, width, height;
Screen scr = getScreen();
height = getItemAreaHeight();
if (this.parent == null && (this.scrollHeight > height || this.enableScrolling)) { // parent==null is required for example when a commands container is scrolled.
x = scr.contentX;
y = scr.contentY;
height = scr.contentHeight;
width = scr.contentWidth + scr.getScrollBarWidth();
} else {
x = getAbsoluteX();
y = getAbsoluteY();
width = this.itemWidth;
//#if polish.useScrollBar || polish.classes.ScrollBar:defined
width += scr.getScrollBarWidth();
//#endif
}
repaintRegion.addRegion( x, y, width, height + diff + 1 );
}
this.lastAnimationTime = currentTime;
Item focItem = this.focusedItem;
if (focItem != null) {
focItem.animate(currentTime, repaintRegion);
}
//#ifdef tmp.supportViewType
ContainerView contView = this.containerView;
if ( contView != null ) {
contView.animate(currentTime, repaintRegion);
}
//#endif
//#if polish.css.show-delay
if (this.showDelay != 0 && this.showDelayIndex != 0) {
int index = Math.min( (int)((currentTime - this.showNotifyTime) / this.showDelay), this.itemsList.size());
if (index > this.showDelayIndex) {
for (int i=this.showDelayIndex; i<index; i++) {
try {
//System.out.println("calling show notify on item " + i + " at " + (currentTime - this.showNotifyTime) + ", show-delay=" + this.showDelay);
Item item = get(i);
item.showNotify();
} catch (Exception e) {
//#debug error
System.out.println("Unable to notify");
}
}
if (index == this.itemsList.size()) {
this.showDelayIndex = 0;
} else {
this.showDelayIndex = index;
}
}
}
//#endif
//#if polish.css.focus-all
if (this.isFocusAllChildren && this.isFocused) {
Item[] items = this.getItems();
for (int i = 0; i < items.length; i++) {
Item item = items[i];
item.animate(currentTime, repaintRegion);
}
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#addRepaintArea(de.enough.polish.ui.ClippingRegion)
*/
public void addRepaintArea(ClippingRegion repaintRegion) {
if (this.enableScrolling) {
Screen scr = getScreen();
int x = scr.contentX;
int y = scr.contentY;
int height = scr.contentHeight;
int width = scr.contentWidth + scr.getScrollBarWidth();
repaintRegion.addRegion(x, y, width, height);
} else {
super.addRepaintArea(repaintRegion);
}
}
/**
* Called by the system to notify the item that it is now at least
* partially visible, when it previously had been completely invisible.
* The item may receive <code>paint()</code> calls after
* <code>showNotify()</code> has been called.
*
* <p>The container implementation calls showNotify() on the embedded items.</p>
*/
protected void showNotify()
{
super.showNotify();
if (this.style != null && !this.isStyleInitialized) {
setStyle( this.style );
}
//#ifdef polish.useDynamicStyles
else if (this.style == null) {
initStyle();
}
//#else
else if (this.style == null && !this.isStyleInitialized) {
//#debug
System.out.println("Setting default style for container " + this );
setStyle( StyleSheet.defaultStyle );
}
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.showNotify();
}
//#endif
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
if (item.style != null && !item.isStyleInitialized) {
item.setStyle( item.style );
}
//#ifdef polish.useDynamicStyles
else if (item.style == null) {
initStyle();
}
//#else
else if (item.style == null && !item.isStyleInitialized) {
//#debug
System.out.println("Setting default style for item " + item );
item.setStyle( StyleSheet.defaultStyle );
}
//#endif
//#if polish.css.show-delay
if (this.showDelay == 0 || i == 0) {
//#endif
item.showNotify();
//#if polish.css.show-delay
}
//#endif
}
//#if polish.css.show-delay
this.showDelayIndex = (myItems.length > 1 ? 1 : 0);
this.showNotifyTime = System.currentTimeMillis();
//#endif
//#if !polish.Container.selectEntriesWhileTouchScrolling
if (minimumDragDistance == 0) {
minimumDragDistance = Math.min(Display.getScreenWidth(),Display.getScreenHeight())/10;
}
//#endif
}
/**
* Called by the system to notify the item that it is now completely
* invisible, when it previously had been at least partially visible. No
* further <code>paint()</code> calls will be made on this item
* until after a <code>showNotify()</code> has been called again.
*
* <p>The container implementation calls hideNotify() on the embedded items.</p>
*/
protected void hideNotify()
{
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.hideNotify();
}
//#endif
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
item.hideNotify();
}
}
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerPressed(int, int)
*/
protected boolean handlePointerPressed(int relX, int relY) {
//#debug
System.out.println("Container.handlePointerPressed(" + relX + ", " + relY + ") for " + this );
//System.out.println("Container.handlePointerPressed( x=" + x + ", y=" + y + "): adjustedY=" + (y - (this.yOffset + this.marginTop + this.paddingTop )) );
// an item within this container was selected:
this.lastPointerPressY = relY;
this.lastPointerPressYOffset = getScrollYOffset();
this.lastPointerPressTime = System.currentTimeMillis();
int origRelX = relX;
int origRelY = relY;
relY -= this.yOffset;
relY -= this.contentY;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
//System.out.println("Container.handlePointerPressed: adjusted to (" + relX + ", " + relY + ") for " + this );
boolean eventHandled = false;
Item item = this.focusedItem;
if (item != null) {
// the focused item can extend the parent container, e.g. subcommands,
// so give it a change to process the event itself:
int itemLayout = item.layout;
boolean processed = item.handlePointerPressed(relX - item.relativeX, relY - item.relativeY );
if (processed) {
//#debug
System.out.println("pointerPressed at " + relX + "," + relY + " consumed by focusedItem " + item);
// layout could have been changed:
if (item.layout != itemLayout && isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
if (item.isLayoutLeft()) {
item.relativeX = 0;
} else if (item.isLayoutCenter()) {
item.relativeX = (this.contentWidth - item.itemWidth)/2;
} else {
item.relativeX = this.contentWidth - item.itemWidth;
}
}
notifyItemPressedStart();
return true;
} else if (item.isPressed) {
eventHandled = notifyItemPressedStart();
}
}
//#ifdef tmp.supportViewType
if (contView != null) {
relX += viewXOffset;
if ( contView.handlePointerPressed(relX + this.contentX, relY + this.contentY) ) {
//System.out.println("ContainerView " + contView + " consumed pointer press event");
notifyItemPressedStart();
return true;
}
relX -= viewXOffset;
}
if (!isInItemArea(origRelX, origRelY - this.yOffset) || (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) ) {
//System.out.println("Container.handlePointerPressed(): out of range, relativeX=" + this.relativeX + ", relativeY=" + this.relativeY + ", contentHeight=" + this.contentHeight );
return ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
}
//#else
if (!isInItemArea(origRelX, origRelY) || (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) ) {
//System.out.println("Container.handlePointerPressed(): out of range, relativeX=" + this.relativeX + ", relativeY=" + this.relativeY + ", contentHeight=" + this.contentHeight );
return super.handlePointerPressed(origRelX, origRelY) || eventHandled;
}
//#endif
Screen scr = this.screen;
if ( ((origRelY < 0) && (scr == null || origRelY + this.relativeY - scr.contentY < 0))
|| (this.enableScrolling && origRelY > this.scrollHeight)
){
return ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
}
Item nextItem = getChildAt( origRelX, origRelY );
if (nextItem != null && nextItem != item) {
int index = this.itemsList.indexOf(nextItem);
//#debug
System.out.println("Container.handlePointerPressed(" + relX + "," + relY + "): found item " + index + "=" + item + " at relative " + relX + "," + relY + ", itemHeight=" + item.itemHeight);
// only focus the item when it has not been focused already:
int offset = getScrollYOffset();
focusChild(index, nextItem, 0, true);
setScrollYOffset( offset, false ); // don't move the UI while handling the press event:
// let the item also handle the pointer-pressing event:
nextItem.handlePointerPressed( relX - nextItem.relativeX , relY - nextItem.relativeY );
if (!this.isFocused) {
setAutoFocusEnabled( true );
this.autoFocusIndex = index;
}
notifyItemPressedStart();
return true;
}
// Item[] myItems = getItems();
// int itemRelX, itemRelY;
// for (int i = 0; i < myItems.length; i++) {
// item = myItems[i];
// itemRelX = relX - item.relativeX;
// itemRelY = relY - item.relativeY;
// //System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
// if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// // this item is not in the range or not suitable:
// continue;
// }
// // the pressed item has been found:
// //#debug
// System.out.println("Container.handlePointerPressed(" + relX + "," + relY + "): found item " + i + "=" + item + " at relative " + itemRelX + "," + itemRelY + ", itemHeight=" + item.itemHeight);
// // only focus the item when it has not been focused already:
// int offset = getScrollYOffset();
// focusChild(i, item, 0, true);
// setScrollYOffset( offset, false ); // don't move the UI while handling the press event:
// // let the item also handle the pointer-pressing event:
// item.handlePointerPressed( itemRelX , itemRelY );
// if (!this.isFocused) {
// this.autoFocusEnabled = true;
// this.autoFocusIndex = i;
// }
// return true;
// }
boolean handledBySuperImplementation = ((this.defaultCommand != null) && super.handlePointerPressed(origRelX, origRelY)) || eventHandled;
//#if polish.android
if (!handledBySuperImplementation && (item != null) && (item._androidView != null) && (!item._androidView.isFocused())) {
item.defocus(this.itemStyle);
handledBySuperImplementation = true;
}
//#endif
return handledBySuperImplementation;
}
//#endif
//#ifdef polish.hasPointerEvents
/**
* Allows subclasses to check if a pointer release event is used for scrolling the container.
* This method can only be called when polish.hasPointerEvents is true.
*
* @param relX the x position of the pointer pressing relative to this item's left position
* @param relY the y position of the pointer pressing relative to this item's top position
*/
protected boolean handlePointerScrollReleased(int relX, int relY) {
if (Display.getInstance().hasPointerMotionEvents()) {
return false;
}
int yDiff = relY - this.lastPointerPressY;
int bottomY = Math.max( this.itemHeight, this.internalY + this.internalHeight );
if (this.focusedItem != null && this.focusedItem.relativeY + this.focusedItem.backgroundHeight > bottomY) {
bottomY = this.focusedItem.relativeY + this.focusedItem.backgroundHeight;
}
if ( this.enableScrolling
&& (this.itemHeight > this.scrollHeight || this.yOffset != 0)
&& ((yDiff < -5 && this.yOffset + bottomY > this.scrollHeight) // scrolling downwards
|| (yDiff > 5 && this.yOffset != 0) ) // scrolling upwards
)
{
int offset = this.yOffset + yDiff;
if (offset > 0) {
offset = 0;
}
//System.out.println("adjusting scrolloffset to " + offset);
setScrollYOffset(offset, true);
return true;
}
return false;
}
//#endif
//#if polish.hasPointerEvents
/**
* Handles the behavior of the virtual keyboard when the item is focused.
* By defaukt, the virtual keyboard is hidden. Components which need to have the virtual keyboard
* shown when they are focused can override this method.
*/
public void handleOnFocusSoftKeyboardDisplayBehavior() {
Item focItem = this.focusedItem;
if (focItem != null) {
focItem.handleOnFocusSoftKeyboardDisplayBehavior();
} else {
super.handleOnFocusSoftKeyboardDisplayBehavior();
}
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerReleased(int, int)
*/
protected boolean handlePointerReleased(int relX, int relY) {
//#debug
System.out.println("Container.handlePointerReleased(" + relX + ", " + relY + ") for " + this );
// handle keyboard behaviour
if(this.isJustFocused) {
this.isJustFocused = false;
handleOnFocusSoftKeyboardDisplayBehavior();
}
//#ifdef tmp.supportFocusItemsInVisibleContentArea
//#if polish.hasPointerEvents
this.needsCheckItemInVisibleContent=true;
//#endif
//#endif
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
Item item = this.focusedItem;
if (this.enableScrolling) {
this.isScrolling = false;
int scrollDiff = Math.abs(getScrollYOffset() - this.lastPointerPressYOffset);
if ( scrollDiff > Display.getScreenHeight()/10 || handlePointerScrollReleased(relX, relY) ) {
// we have scrolling in the meantime
boolean processed = false;
if (item != null && item.isPressed) {
processed = item.handlePointerReleased(relX - item.relativeX, relY - item.relativeY );
setInitialized(false);
}
if (!processed) {
while (item instanceof Container) {
if (item.isPressed) {
item.notifyItemPressedEnd();
}
item = ((Container)item).focusedItem;
}
// we have scrolling in the meantime
if (item != null && item.isPressed) {
item.notifyItemPressedEnd();
setInitialized(false);
}
}
// check if we should continue the scrolling:
long dragTime = System.currentTimeMillis() - this.lastPointerPressTime;
if (dragTime < 1000 && dragTime > 1) {
int direction = Canvas.DOWN;
if (this.yOffset > this.lastPointerPressYOffset) {
direction = Canvas.UP;
}
startScroll( direction, (int) ((scrollDiff * 1000 ) / dragTime), 20 );
} else if (this.yOffset > 0) {
setScrollYOffset(0, true);
} else if (this.yOffset + this.contentHeight < this.availContentHeight) {
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (this.yOffset + maxItemHeight < this.scrollHeight) {
int target = this.scrollHeight - maxItemHeight;
setScrollYOffset( target, true );
}
}
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
}
// foward event to currently focused item:
int origRelX = relX;
// //#ifdef polish.css.before
// + getBeforeWidthWithPadding()
// //#endif
// ;
int origRelY = relY;
relY -= this.yOffset;
relY -= this.contentY;
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
if (contView.handlePointerReleased(relX + this.contentX, relY + this.contentY)) {
//System.out.println("ContainerView consumed pointer release event " + contView);
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
//System.out.println("Container.handlePointerReleased: adjusted to (" + relX + ", " + relY + ") for " + this );
if (item != null) {
// the focused item can extend the parent container, e.g. subcommands,
// so give it a change to process the event itself:
int itemLayout = item.layout;
boolean processed = item.handlePointerReleased(relX - item.relativeX, relY - item.relativeY );
if (processed) {
//#debug
System.out.println("pointerReleased at " + relX + "," + relY + " consumed by focusedItem " + item);
if (this.isPressed) {
notifyItemPressedEnd();
}
// layout could have been changed:
if (item.layout != itemLayout && isInitialized()) {
if (item.availableWidth != 0) {
item.init( item.availableWidth, item.availableWidth, item.availableHeight );
} else {
item.init( this.contentWidth, this.contentWidth, this.contentHeight );
}
if (item.isLayoutLeft()) {
item.relativeX = 0;
} else if (item.isLayoutCenter()) {
item.relativeX = (this.contentWidth - item.itemWidth)/2;
} else {
item.relativeX = this.contentWidth - item.itemWidth;
}
}
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
} else if ( item.isInItemArea(relX - item.relativeX, relY - item.relativeY )) {
//#debug
System.out.println("pointerReleased not handled by focused item but within that item's area. Item=" + item + ", container=" + this);
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
}
if (!isInItemArea(origRelX, origRelY)) {
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
Item nextItem = getChildAt(origRelX, origRelY);
if (nextItem != null && nextItem != item) {
item = nextItem;
int itemRelX = relX - item.relativeX;
int itemRelY = relY - item.relativeY;
item.handlePointerReleased( itemRelX , itemRelY );
if (this.isPressed) {
notifyItemPressedEnd();
}
return true;
}
// Item[] myItems = getItems();
// int itemRelX, itemRelY;
// for (int i = 0; i < myItems.length; i++) {
// item = myItems[i];
// itemRelX = relX - item.relativeX;
// itemRelY = relY - item.relativeY;
// //System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
// if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// // this item is not in the range or not suitable:
// continue;
// }
// // the pressed item has been found:
// //#debug
// System.out.println("Container.handlePointerReleased(" + relX + "," + relY + "): found item " + i + "=" + item + " at relative " + itemRelX + "," + itemRelY + ", itemHeight=" + item.itemHeight);
// // only focus the item when it has not been focused already:
// //focus(i, item, 0);
// // let the item also handle the pointer-pressing event:
// item.handlePointerReleased( itemRelX , itemRelY );
// return true;
// }
return (this.defaultCommand != null) && super.handlePointerReleased(origRelX, origRelY);
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerDragged(int, int)
*/
protected boolean handlePointerDragged(int relX, int relY) {
return false;
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerDragged(int, int)
*/
protected boolean handlePointerDragged(int relX, int relY, ClippingRegion repaintRegion) {
//#debug
System.out.println("handlePointerDraggged " + relX + ", " + relY + " for " + this + ", enableScrolling=" + this.enableScrolling + ", focusedItem=" + this.focusedItem);
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
Item item = this.focusedItem;
if (item != null && item.handlePointerDragged( relX - this.contentX - item.relativeX, relY - this.yOffset - this.contentY - item.relativeY, repaintRegion)) {
return true;
}
//#if !polish.Container.selectEntriesWhileTouchScrolling
if (item != null) {
int dragDistance = Math.abs(relY - this.lastPointerPressY);
if(dragDistance > minimumDragDistance) {
focusChild(-1);
//#if polish.blackberry
//# ((BaseScreen)(Object)Display.getInstance()).notifyFocusSet(null);
//#endif
UiAccess.init(item, item.getAvailableWidth(), item.getAvailableWidth(), item.getAvailableHeight());
}
}
//#endif
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerDragged(relX, relY, repaintRegion) ) {
return true;
}
}
//#endif
if (this.enableScrolling ) {
int maxItemHeight = getItemAreaHeight();
Screen scr = this.screen;
if (scr != null
&& this == scr.container
&& this.relativeY > scr.contentY
) {
// this is an adjustment for calculating the correct scroll offset for containers with a vertical-center or bottom layout:
maxItemHeight += this.relativeY - scr.contentY;
}
if (maxItemHeight > this.scrollHeight || this.yOffset != 0) {
int lastOffset = getScrollYOffset();
int nextOffset = this.lastPointerPressYOffset + (relY - this.lastPointerPressY);
//#if tmp.checkBouncing
if (!this.allowBouncing) {
//#endif
//#if tmp.checkBouncing || (polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false)
if (nextOffset > 0) {
nextOffset = 0;
} else {
if (nextOffset + maxItemHeight < this.scrollHeight) {
nextOffset = this.scrollHeight - maxItemHeight;
}
}
//#endif
//#if tmp.checkBouncing
} else {
//#endif
//#if tmp.checkBouncing || !(polish.Container.ScrollBounce:defined && polish.Container.ScrollBounce == false)
if (nextOffset > this.scrollHeight/3) {
nextOffset = this.scrollHeight/3;
} else {
maxItemHeight += this.scrollHeight/3;
if (nextOffset + maxItemHeight < this.scrollHeight) {
nextOffset = this.scrollHeight - maxItemHeight;
}
}
//#endif
//#if tmp.checkBouncing
}
//#endif
this.isScrolling = (nextOffset != lastOffset);
if (this.isScrolling) {
setScrollYOffset( nextOffset, false );
addRepaintArea(repaintRegion);
return true;
}
}
}
return super.handlePointerDragged(relX, relY, repaintRegion);
}
//#endif
//#if polish.hasTouchEvents
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerTouchDown(int, int)
*/
public boolean handlePointerTouchDown(int x, int y) {
if (this.enableScrolling) {
this.lastPointerPressY = y;
this.lastPointerPressYOffset = getScrollYOffset();
this.lastPointerPressTime = System.currentTimeMillis();
}
Item item = this.focusedItem;
if (item != null) {
if (item.handlePointerTouchDown(x - item.relativeX, y - item.relativeY)) {
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerTouchDown(x,y) ) {
return true;
}
}
//#endif
return super.handlePointerTouchDown(x, y);
}
//#endif
//#if polish.hasTouchEvents
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerTouchUp(int, int)
*/
public boolean handlePointerTouchUp(int x, int y) {
Item item = this.focusedItem;
if (item != null) {
if (item.handlePointerTouchUp(x - item.relativeX, y - item.relativeY)) {
return true;
}
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
if ( this.containerView.handlePointerTouchUp(x,y) ) {
return true;
}
}
//#endif
if (this.enableScrolling) {
int scrollDiff = Math.abs(getScrollYOffset() - this.lastPointerPressYOffset);
if (scrollDiff > Display.getScreenHeight()/10) {
long dragTime = System.currentTimeMillis() - this.lastPointerPressTime;
if (dragTime < 1000 && dragTime > 1) {
int direction = Canvas.DOWN;
if (this.yOffset > this.lastPointerPressYOffset) {
direction = Canvas.UP;
}
startScroll( direction, (int) ((scrollDiff * 1000 ) / dragTime), 20 );
} else if (this.yOffset > 0) {
setScrollYOffset( 0, true );
}
}
}
return super.handlePointerTouchUp(x, y);
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getItemAreaHeight()
*/
public int getItemAreaHeight()
{
int max = super.getItemAreaHeight();
Item item = this.focusedItem;
if (item != null) {
max = Math.max( max, this.contentY + item.relativeY + item.getItemAreaHeight() );
}
return max;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getItemAt(int, int)
*/
public Item getItemAt(int relX, int relY) {
relY -= this.yOffset;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relX -= this.contentX;
relY -= this.contentY;
//#ifdef tmp.supportViewType
if (this.containerView != null) {
relX -= this.containerView.getScrollXOffset();
}
//#endif
Item item = this.focusedItem;
if (item != null) {
int itemRelX = relX - item.relativeX;
int itemRelY = relY - item.relativeY;
// if (this.label != null) {
// System.out.println("itemRelY=" + itemRelY + " of item " + item + ", parent=" + this );
// }
if (item.isInItemArea(itemRelX, itemRelY)) {
return item.getItemAt(itemRelX, itemRelY);
}
}
Item[] myItems = getItems();
int itemRelX, itemRelY;
for (int i = 0; i < myItems.length; i++) {
item = myItems[i];
itemRelX = relX - item.relativeX;
itemRelY = relY - item.relativeY;
if ( i == this.focusedIndex || !item.isInItemArea(itemRelX, itemRelY)) {
// this item is not in the range or not suitable:
continue;
}
// the pressed item has been found:
return item.getItemAt(itemRelX, itemRelY);
}
relY += this.yOffset;
relX += this.contentX;
relY += this.contentY;
return super.getItemAt(relX, relY);
}
/**
* Retrieves the child of this container at the corresponding position.
*
* @param relX the relative horizontal position
* @param relY the relatiev vertical position
* @return the item at that position, if any
*/
public Item getChildAt(int relX, int relY) {
//#ifdef tmp.supportViewType
if (this.containerView != null) {
return this.containerView.getChildAt( relX, relY );
}
//#endif
return getChildAtImpl( relX, relY );
}
/**
* Actual implementation for finding a child, can be used by ContainerViews.
* @param relX the relative horizontal position
* @param relY the relative vertical position
* @return the child item at the specified position
*/
protected Item getChildAtImpl(int relX, int relY) {
relY -= this.yOffset;
// //#ifdef polish.css.before
// relX -= getBeforeWidthWithPadding();
// //#endif
relY -= this.contentY;
relX -= this.contentX;
//#ifdef tmp.supportViewType
int viewXOffset = 0;
ContainerView contView = this.containerView;
if (contView != null) {
viewXOffset = contView.getScrollXOffset();
relX -= viewXOffset;
}
//#endif
Item item = this.focusedItem;
if (item != null && item.isInItemArea(relX - item.relativeX, relY - item.relativeY)) {
return item;
}
Item[] myItems = getItems();
int itemRelX, itemRelY;
for (int i = 0; i < myItems.length; i++) {
item = myItems[i];
itemRelX = relX - item.relativeX;
itemRelY = relY - item.relativeY;
//System.out.println( item + ".relativeX=" + item.relativeX + ", .relativeY=" + item.relativeY + ", pointer event relatively at " + itemRelX + ", " + itemRelY);
if ( i == this.focusedIndex || (item.appearanceMode == Item.PLAIN) || !item.isInItemArea(itemRelX, itemRelY)) {
// this item is not in the range or not suitable:
continue;
}
return item;
}
return null;
}
/**
* Moves the focus away from the specified item.
*
* @param item the item that currently has the focus
*/
public void requestDefocus( Item item ) {
if (item == this.focusedItem) {
boolean success = shiftFocus(true, 1);
if (!success) {
defocus(this.itemStyle);
}
}
}
/**
* Requests the initialization of this container and all of its children items.
* This was previously used for dimension changes which is now picked up automatically and not required anymore.
*/
public void requestFullInit() {
for (int i = 0; i < this.itemsList.size(); i++) {
Item item = (Item) this.itemsList.get(i);
item.setInitialized(false);
if (item instanceof Container) {
((Container)item).requestFullInit();
}
}
requestInit();
}
/**
* Retrieves the vertical scrolling offset of this item.
*
* @return either the currently used offset or the targeted offset in case the targeted one is different. This is either a negative integer or 0.
* @see #getCurrentScrollYOffset()
*/
public int getScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getScrollYOffset();
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
/**
* Retrieves the current vertical scrolling offset of this item, depending on the scroll mode this can change with every paint iteration.
*
* @return the currently used offset in pixels, either a negative integer or 0.
* @see #getScrollYOffset()
*/
public int getCurrentScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getCurrentScrollYOffset();
}
return this.yOffset;
}
/**
* Retrieves the vertical scrolling offset of this item relative to the top most container.
*
* @return either the currently used offset or the targeted offset in case the targeted one is different.
*/
public int getRelativeScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
return ((Container)this.parent).getRelativeScrollYOffset() + this.relativeY;
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
/**
* Sets the vertical scrolling offset of this item.
*
* @param offset either the new offset
*/
public void setScrollYOffset( int offset) {
setScrollYOffset( offset, false );
}
/**
* Sets the vertical scrolling offset of this item.
*
* @param offset either the new offset
* @param smooth scroll to this new offset smooth if allowed
* @see #getScrollYOffset()
*/
public void setScrollYOffset( int offset, boolean smooth) {
//#debug
System.out.println("Setting scrollYOffset to " + offset + " for " + this);
//try { throw new RuntimeException("for yOffset " + offset + " in " + this); } catch (Exception e) { e.printStackTrace(); }
if (!this.enableScrolling && this.parent instanceof Container) {
((Container)this.parent).setScrollYOffset(offset, smooth);
return;
}
this.scrollStartTime = System.currentTimeMillis();
this.scrollStartYOffset = this.yOffset;
if (!smooth
//#ifdef polish.css.scroll-mode
|| !this.scrollSmooth
//#endif
) {
this.yOffset = offset;
}
this.targetYOffset = offset;
this.scrollSpeed = 0;
}
/**
* Determines whether this container or one of its parent containers is currently being scrolled
* @return true when this container or one of its parent containers is currently being scrolled
*/
public boolean isScrolling() {
if (this.enableScrolling) {
return (this.isScrolling) || (this.targetYOffset != this.yOffset) || (this.scrollSpeed != 0);
} else if (this.parent instanceof Container) {
return ((Container)this.parent).isScrolling();
} else {
return false;
}
}
/**
* Starts to scroll in the specified direction
* @param direction either Canvas.UP or Canvas.DOWN
* @param speed the speed in pixels per second
* @param damping the damping in percent; 0 means no damping at all; 100 means the scrolling will be stopped immediately
*/
public void startScroll( int direction,int speed, int damping) {
//#debug
System.out.println("startScrolling " + (direction == Canvas.UP ? "up" : "down") + " with speed=" + speed + ", damping=" + damping + " for " + this);
if (!this.enableScrolling && this.parent instanceof Container) {
((Container)this.parent).startScroll(direction, speed, damping);
return;
}
this.scrollDirection = direction;
this.scrollDamping = damping;
this.scrollSpeed = speed;
}
/**
* Retrieves the index of the specified item.
*
* @param item the item
* @return the index of the item; -1 when the item is not part of this container
*/
public int indexOf(Item item) {
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++) {
Object object = myItems[i];
if (object == null) {
break;
}
if (object == item) {
return i;
}
}
return -1;
}
/**
* Checks if this container includes the specified item
* @param item the item
* @return true when this container contains the item
*/
public boolean contains( Item item ) {
return this.itemsList.contains(item);
}
//#if (polish.debug.error || polish.keepToString) && polish.debug.container.includeChildren
/**
* Generates a String representation of this item.
* This method is only implemented when the logging framework is active or the preprocessing variable
* "polish.keepToString" is set to true.
* @return a String representation of this item.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append( super.toString() ).append( ": { ");
Item[] myItems = getItems();
for (int i = 0; i < myItems.length; i++) {
Item item = myItems[i];
//#if polish.supportInvisibleItems || polish.css.visible
if (item.isInvisible) {
buffer.append( i ).append(":invis./plain:" + ( item.appearanceMode == PLAIN ) + "=[").append( item.toString() ).append("]");
} else {
buffer.append( i ).append("=").append( item.toString() );
}
//#else
buffer.append( i ).append("=").append( item.toString() );
//#endif
if (i != myItems.length - 1 ) {
buffer.append(", ");
}
}
buffer.append( " }");
return buffer.toString();
}
//#endif
/**
* Sets a list of items for this container.
* Use this direct access only when you know what you are doing.
*
* @param itemsList the list of items to set
*/
public void setItemsList(ArrayList itemsList) {
//System.out.println("Container.setItemsList");
clear();
if (this.isFocused) {
//System.out.println("enabling auto focus for index=" + this.focusedIndex);
setAutoFocusEnabled( true );
this.autoFocusIndex = this.focusedIndex;
}
this.focusedIndex = -1;
this.focusedItem = null;
if (this.enableScrolling) {
setScrollYOffset(0, false);
}
this.itemsList = itemsList;
this.containerItems = null;
Object[] myItems = this.itemsList.getInternalArray();
for (int i = 0; i < myItems.length; i++) {
Item item = (Item) myItems[i];
if (item == null) {
break;
}
item.parent = this;
if (this.isShown) {
item.showNotify();
}
}
requestInit();
}
/**
* Calculates the number of interactive items included in this container.
* @return the number between 0 and size()
*/
public int getNumberOfInteractiveItems()
{
int number = 0;
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++)
{
Item item = (Item) items[i];
if (item == null) {
break;
}
if (item.appearanceMode != PLAIN) {
number++;
}
}
return number;
}
/**
* Releases all (memory intensive) resources such as images or RGB arrays of this background.
*/
public void releaseResources() {
super.releaseResources();
Item[] items = getItems();
for (int i = 0; i < items.length; i++)
{
Item item = items[i];
item.releaseResources();
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.releaseResources();
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#destroy()
*/
public void destroy() {
Item[] items = getItems();
clear();
super.destroy();
for (int i = 0; i < items.length; i++)
{
Item item = items[i];
item.destroy();
}
//#ifdef tmp.supportViewType
if (this.containerView != null) {
this.containerView.destroy();
this.containerView = null;
}
//#endif
}
/**
* Retrieves the internal array with all managed items embedded in this container, some entries might be null.
* Use this method only if you know what you are doing and only for reading.
* @return the internal array of the managed items
*/
public Object[] getInternalArray()
{
return this.itemsList.getInternalArray();
}
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteY()
// */
// public int getAbsoluteY()
// {
// return super.getAbsoluteY() + this.yOffset;
// }
//
// //#ifdef tmp.supportViewType
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteX()
// */
// public int getAbsoluteX() {
// int xAdjust = 0;
// if (this.containerView != null) {
// xAdjust = this.containerView.getScrollXOffset();
// }
// return super.getAbsoluteX() + xAdjust;
// }
// //#endif
//
//
//
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getAbsoluteX()
// */
// public boolean isInItemArea(int relX, int relY, Item child) {
// relY -= this.yOffset;
// //#ifdef tmp.supportViewType
// if (this.containerView != null) {
// relX -= this.containerView.getScrollXOffset();
// }
// //#endif
// return super.isInItemArea(relX, relY, child);
// }
//
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#isInItemArea(int, int)
*/
public boolean isInItemArea(int relX, int relY) {
Item focItem = this.focusedItem;
if (focItem != null && focItem.isInItemArea(relX - focItem.relativeX, relY - focItem.relativeY)) {
return true;
}
return super.isInItemArea(relX, relY);
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#fireEvent(java.lang.String, java.lang.Object)
*/
public void fireEvent(String eventName, Object eventData)
{
super.fireEvent(eventName, eventData);
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++)
{
Item item = (Item) items[i];
if (item == null) {
break;
}
item.fireEvent(eventName, eventData);
}
}
//#ifdef polish.css.view-type
/**
* Sets the view type for this item.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
* @param view the new view, use null to remove the current view
*/
public void setView( ItemView view ) {
if (!(view instanceof ContainerView)) {
super.setView( view );
return;
}
if (!this.isStyleInitialized && this.style != null) {
setStyle( this.style );
}
if (view == null) {
this.containerView = null;
this.view = null;
} else {
ContainerView viewType = (ContainerView) view;
viewType.parentContainer = this;
viewType.focusFirstElement = this.autoFocusEnabled;
viewType.allowCycling = this.allowCycling;
this.containerView = viewType;
if (this.style != null) {
view.setStyle( this.style );
}
}
this.setView = true;
}
//#endif
//#ifdef polish.css.view-type
/**
* Retrieves the view type for this item.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
*
* @return the current view, may be null
*/
public ItemView getView() {
if (this.containerView != null) {
return this.containerView;
}
return this.view;
}
//#endif
//#ifdef polish.css.view-type
/**
* Retrieves the view type for this item or instantiates a new one.
* Please note that this is only supported when view-type CSS attributes are used within
* your application.
*
* @param viewType the view registered in the style
* @param viewStyle the style
* @return the view, may be null
*/
protected ItemView getView( ItemView viewType, Style viewStyle) {
if (viewType instanceof ContainerView) {
if (this.containerView == null || this.containerView.getClass() != viewType.getClass()) {
try {
// formerly we have used the style's instance when that instance was still free.
// However, that approach lead to GC problems, as the style is not garbage collected.
viewType = (ItemView) viewType.getClass().newInstance();
viewType.parentItem = this;
if (this.isShown) {
if (this.containerView != null) {
this.containerView.hideNotify();
}
viewType.showNotify();
}
return viewType;
} catch (Exception e) {
//#debug error
System.out.println("Container: Unable to init view-type " + e );
}
}
return this.containerView;
}
return super.getView( viewType, viewStyle );
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#initMargin(de.enough.polish.ui.Style, int)
*/
protected void initMargin(Style style, int availWidth) {
if (this.isIgnoreMargins) {
this.marginLeft = 0;
this.marginRight = 0;
this.marginTop = 0;
this.marginBottom = 0;
} else {
this.marginLeft = style.getMarginLeft( availWidth );
this.marginRight = style.getMarginRight( availWidth );
this.marginTop = style.getMarginTop( availWidth );
this.marginBottom = style.getMarginBottom(availWidth);
}
}
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Item#onScreenSizeChanged(int, int)
*/
public void onScreenSizeChanged(int screenWidth, int screenHeight) {
Style lastStyle = this.style;
super.onScreenSizeChanged(screenWidth, screenHeight);
//#if tmp.supportViewType
if (this.containerView != null) {
this.containerView.onScreenSizeChanged(screenWidth, screenHeight);
}
//#endif
//#if polish.css.landscape-style || polish.css.portrait-style
if (this.plainStyle != null && this.style != lastStyle) {
Style newStyle = null;
if (screenWidth > screenHeight) {
if (this.landscapeStyle != null && this.style != this.landscapeStyle) {
newStyle = this.landscapeStyle;
}
} else if (this.portraitStyle != null && this.style != this.portraitStyle){
newStyle = this.portraitStyle;
}
this.plainStyle = newStyle;
}
//#endif
Object[] items = this.itemsList.getInternalArray();
for (int i = 0; i < items.length; i++) {
Item item = (Item) items[i];
if (item == null) {
break;
}
item.onScreenSizeChanged(screenWidth, screenHeight);
}
}
/**
* Recursively returns the focused child item of this Container or of the currently focused child Container.
* @return the focused child item or this Container when there is no focused child.
*/
public Item getFocusedChild() {
Item item = getFocusedItem();
if (item == null) {
return this;
}
if (item instanceof Container) {
return ((Container)item).getFocusedChild();
}
return item;
}
//#if polish.css.press-all
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#notifyItemPressedStart()
*/
public boolean notifyItemPressedStart() {
boolean handled = super.notifyItemPressedStart();
if (this.isPressAllChildren) {
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++) {
Item child = (Item) children[i];
if (child == null) {
break;
}
handled |= child.notifyItemPressedStart();
}
}
return handled;
}
//#endif
//#if polish.css.press-all
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#notifyItemPressedEnd()
*/
public void notifyItemPressedEnd() {
super.notifyItemPressedEnd();
if (this.isPressAllChildren) {
Object[] children = this.itemsList.getInternalArray();
for (int i = 0; i < children.length; i++) {
Item child = (Item) children[i];
if (child == null) {
break;
}
child.notifyItemPressedEnd();
}
}
}
//#endif
/**
* Resets the pointer press y offset which is used for starting scrolling processes.
* This is only applicable for touch enabled handsets.
*/
public void resetLastPointerPressYOffset() {
//#if polish.hasPointerEvents
this.lastPointerPressYOffset = this.targetYOffset;
//#endif
}
//#ifdef polish.Container.additionalMethods:defined
//#include ${polish.Container.additionalMethods}
//#endif
}
|
diff --git a/ghana-national-tools/src/main/java/org/motechproject/ghana/national/tools/seed/data/source/BaseSeedSource.java b/ghana-national-tools/src/main/java/org/motechproject/ghana/national/tools/seed/data/source/BaseSeedSource.java
index a518b608..9d87cfcf 100644
--- a/ghana-national-tools/src/main/java/org/motechproject/ghana/national/tools/seed/data/source/BaseSeedSource.java
+++ b/ghana-national-tools/src/main/java/org/motechproject/ghana/national/tools/seed/data/source/BaseSeedSource.java
@@ -1,17 +1,17 @@
package org.motechproject.ghana.national.tools.seed.data.source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
public class BaseSeedSource {
protected JdbcTemplate jdbcTemplate;
@Autowired
- public void init(@Qualifier("dataSource") DataSource dataSource) {
+ public void init(@Qualifier("migrationDataSource") DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
}
| true | true | public void init(@Qualifier("dataSource") DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
| public void init(@Qualifier("migrationDataSource") DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
|
diff --git a/src/com/android/email/MessagingController.java b/src/com/android/email/MessagingController.java
index 97c0fb02..e5300c75 100644
--- a/src/com/android/email/MessagingController.java
+++ b/src/com/android/email/MessagingController.java
@@ -1,2951 +1,2953 @@
package com.android.email;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.Process;
import android.os.PowerManager.WakeLock;
import android.util.Config;
import android.util.Log;
import com.android.email.activity.FolderMessageList;
import com.android.email.mail.Address;
import com.android.email.mail.Body;
import com.android.email.mail.FetchProfile;
import com.android.email.mail.Flag;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessageRetrievalListener;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Part;
import com.android.email.mail.Store;
import com.android.email.mail.Transport;
import com.android.email.mail.Folder.FolderType;
import com.android.email.mail.Folder.OpenMode;
import com.android.email.mail.internet.MimeMessage;
import com.android.email.mail.internet.MimeUtility;
import com.android.email.mail.internet.TextBody;
import com.android.email.mail.store.LocalStore;
import com.android.email.mail.store.LocalStore.LocalFolder;
import com.android.email.mail.store.LocalStore.LocalMessage;
import com.android.email.mail.store.LocalStore.PendingCommand;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable {
/**
* The maximum message size that we'll consider to be "small". A small message is downloaded
* in full immediately instead of in pieces. Anything over this size will be downloaded in
* pieces with attachments being left off completely and downloaded on demand.
*
*
* 25k for a "small" message was picked by educated trial and error.
* http://answers.google.com/answers/threadview?id=312463 claims that the
* average size of an email is 59k, which I feel is too large for our
* blind download. The following tests were performed on a download of
* 25 random messages.
* <pre>
* 5k - 61 seconds,
* 25k - 51 seconds,
* 55k - 53 seconds,
* </pre>
* So 25k gives good performance and a reasonable data footprint. Sounds good to me.
*/
// Daniel I. Applebaum Changing to 5k for faster syncing
private static final int MAX_SMALL_MESSAGE_SIZE = (5 * 1024);
private static final String PENDING_COMMAND_MOVE_OR_COPY =
"com.android.email.MessagingController.moveOrCopy";
private static final String PENDING_COMMAND_EMPTY_TRASH =
"com.android.email.MessagingController.emptyTrash";
private static final String PENDING_COMMAND_SET_FLAG =
"com.android.email.MessagingController.setFlag";
private static final String PENDING_COMMAND_APPEND =
"com.android.email.MessagingController.append";
private static final String PENDING_COMMAND_MARK_ALL_AS_READ =
"com.android.email.MessagingController.markAllAsRead";
private static final String PENDING_COMMAND_CLEAR_ALL_PENDING =
"com.android.email.MessagingController.clearAllPending";
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new LinkedBlockingQueue<Command>();
private BlockingQueue<Command> backCommands = new LinkedBlockingQueue<Command>();
private Thread mThread;
//private Set<MessagingListener> mListeners = Collections.synchronizedSet(new HashSet<MessagingListener>());
private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>();
private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>();
private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>();
public enum SORT_TYPE {
SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false),
SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true),
SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true),
SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true),
SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true),
SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true);
private int ascendingToast;
private int descendingToast;
private boolean defaultAscending;
SORT_TYPE(int ascending, int descending, boolean ndefaultAscending)
{
ascendingToast = ascending;
descendingToast = descending;
defaultAscending = ndefaultAscending;
}
public int getToast(boolean ascending)
{
if (ascending)
{
return ascendingToast;
}
else
{
return descendingToast;
}
}
public boolean isDefaultAscending()
{
return defaultAscending;
}
};
private SORT_TYPE sortType = SORT_TYPE.SORT_DATE;
private MessagingListener checkMailListener = null;
private boolean mBusy;
private Application mApplication;
// Key is accountUuid:folderName:messageUid , value is unimportant
private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>();
// Key is accountUuid:folderName , value is a long of the highest message UID ever emptied from Trash
private ConcurrentHashMap<String, Long> expungedUid = new ConcurrentHashMap<String, Long>();
private String createMessageKey(Account account, String folder, Message message)
{
return createMessageKey(account, folder, message.getUid());
}
private String createMessageKey(Account account, String folder, String uid)
{
return account.getUuid() + ":" + folder + ":" + uid;
}
private String createFolderKey(Account account, String folder)
{
return account.getUuid() + ":" + folder;
}
private void suppressMessage(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return;
}
String messKey = createMessageKey(account, folder, message);
// Log.d(Email.LOG_TAG, "Suppressing message with key " + messKey);
deletedUids.put(messKey, "true");
}
private void unsuppressMessage(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return;
}
unsuppressMessage(account, folder, message.getUid());
}
private void unsuppressMessage(Account account, String folder, String uid)
{
if (account == null || folder == null || uid == null)
{
return;
}
String messKey = createMessageKey(account, folder, uid);
//Log.d(Email.LOG_TAG, "Unsuppressing message with key " + messKey);
deletedUids.remove(messKey);
}
private boolean isMessageSuppressed(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return false;
}
String messKey = createMessageKey(account, folder, message);
//Log.d(Email.LOG_TAG, "Checking suppression of message with key " + messKey);
if (deletedUids.containsKey(messKey))
{
//Log.d(Email.LOG_TAG, "Message with key " + messKey + " is suppressed");
return true;
}
Long expungedUidL = expungedUid.get(createFolderKey(account, folder));
if (expungedUidL != null)
{
long expungedUid = expungedUidL;
String messageUidS = message.getUid();
try
{
long messageUid = Long.parseLong(messageUidS);
if (messageUid <= expungedUid)
{
return false;
}
}
catch (NumberFormatException nfe)
{
// Nothing to do
}
}
return false;
}
private MessagingController(Application application) {
mApplication = application;
mThread = new Thread(this);
mThread.start();
}
public void log(String logmess)
{
Log.d(Email.LOG_TAG, logmess);
if (Email.logFile != null)
{
FileOutputStream fos = null;
try
{
File logFile = new File(Email.logFile);
fos = new FileOutputStream(logFile, true);
PrintStream ps = new PrintStream(fos);
ps.println(new Date() + ":" + Email.LOG_TAG + ":" + logmess);
ps.flush();
ps.close();
fos.flush();
fos.close();
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to log message '" + logmess + "'", e);
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (Exception e)
{
}
}
}
}
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
* @param application
* @return
*/
public synchronized static MessagingController getInstance(Application application) {
if (inst == null) {
inst = new MessagingController(application);
}
return inst;
}
public boolean isBusy() {
return mBusy;
}
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true) {
String commandDescription = null;
try {
Command command = mCommands.poll();
if (command == null)
{
command = backCommands.poll();
}
if (command == null)
{
command = mCommands.poll(1, TimeUnit.SECONDS);
}
if (command != null)
{
commandDescription = command.description;
Log.d(Email.LOG_TAG, "Running background command '" + command.description + "'");
mBusy = true;
command.runnable.run();
Log.d(Email.LOG_TAG, "Background command '" + command.description + "' completed");
for (MessagingListener l : getListeners()) {
l.controllerCommandCompleted(mCommands.size() > 0);
}
if (command.listener != null && !mListeners.contains(command.listener)) {
command.listener.controllerCommandCompleted(mCommands.size() > 0);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "Error running command '" + commandDescription + "'", e);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable) {
try {
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
mCommands.put(command);
}
catch (InterruptedException ie) {
throw new Error(ie);
}
}
private void putBackground(String description, MessagingListener listener, Runnable runnable) {
try {
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
backCommands.put(command);
}
catch (InterruptedException ie) {
throw new Error(ie);
}
}
public void addListener(MessagingListener listener) {
mListeners.add(listener);
}
public void removeListener(MessagingListener listener) {
mListeners.remove(listener);
}
public Set<MessagingListener> getListeners()
{
return mListeners;
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
* TODO this needs to cache the remote folder list
*
* @param account
* @param includeRemote
* @param listener
* @throws MessagingException
*/
public void listFolders(
final Account account,
boolean refreshRemote,
MessagingListener listener) {
for (MessagingListener l : getListeners()) {
l.listFoldersStarted(account);
}
if (listener != null) {
listener.listFoldersStarted(account);
}
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder[] localFolders = localStore.getPersonalNamespaces();
if ( refreshRemote || localFolders == null || localFolders.length == 0) {
doRefreshRemote(account, listener);
return;
}
for (MessagingListener l : getListeners()) {
l.listFolders(account, localFolders);
}
if (listener != null)
{
listener.listFolders(account, localFolders);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.listFoldersFailed(account, e.getMessage());
}
if (listener != null) {
listener.listFoldersFailed(account, e.getMessage());
}
addErrorMessage(account, e);
return;
}
for (MessagingListener l : getListeners()) {
l.listFoldersFinished(account);
}
if (listener != null) {
listener.listFoldersFinished(account);
}
}
private void doRefreshRemote (final Account account, MessagingListener listener) {
put("doRefreshRemote", listener, new Runnable() {
public void run() {
try {
Store store = Store.getInstance(account.getStoreUri(), mApplication);
Folder[] remoteFolders = store.getPersonalNamespaces();
LocalStore localStore = (LocalStore)Store.getInstance(
account.getLocalStoreUri(),
mApplication);
HashSet<String> remoteFolderNames = new HashSet<String>();
for (int i = 0, count = remoteFolders.length; i < count; i++) {
LocalFolder localFolder = localStore.getFolder(remoteFolders[i].getName());
if (!localFolder.exists()) {
localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount());
}
remoteFolderNames.add(remoteFolders[i].getName());
}
Folder[] localFolders = localStore.getPersonalNamespaces();
/*
* Clear out any folders that are no longer on the remote store.
*/
for (Folder localFolder : localFolders) {
String localFolderName = localFolder.getName();
if (localFolderName.equalsIgnoreCase(Email.INBOX) ||
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName())) {
continue;
}
if (!remoteFolderNames.contains(localFolder.getName())) {
localFolder.delete(false);
}
}
localFolders = localStore.getPersonalNamespaces();
for (MessagingListener l : getListeners()) {
l.listFolders(account, localFolders);
}
for (MessagingListener l : getListeners()) {
l.listFoldersFinished(account);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.listFoldersFailed(account, "");
}
addErrorMessage(account, e);
}
}
});
}
/**
* List the local message store for the given folder. This work is done
* synchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessages(final Account account, final String folder,
MessagingListener listener) {
for (MessagingListener l : getListeners()) {
l.listLocalMessagesStarted(account, folder);
}
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
ArrayList<Message> messages = new ArrayList<Message>();
for (Message message : localMessages) {
if (!message.isSet(Flag.DELETED) &&
isMessageSuppressed(account, localFolder.getName(), message) == false) {
messages.add(message);
}
}
for (MessagingListener l : getListeners()) {
l.listLocalMessages(account, folder, messages.toArray(new Message[0]));
}
for (MessagingListener l : getListeners()) {
l.listLocalMessagesFinished(account, folder);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.listLocalMessagesFailed(account, folder, e.getMessage());
}
addErrorMessage(account, e);
}
}
public void loadMoreMessages(Account account, String folder, MessagingListener listener) {
try {
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.setVisibleLimit(localFolder.getVisibleLimit()
+ account.getDisplayCount());
synchronizeMailbox(account, folder, listener);
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException("Unable to set visible limit on folder", me);
}
}
public void resetVisibleLimits(Account[] accounts) {
for (Account account : accounts) {
try {
LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
localStore.resetVisibleLimits(account.getDisplayCount());
}
catch (MessagingException e) {
addErrorMessage(account, e);
Log.e(Email.LOG_TAG, "Unable to reset visible limits", e);
}
}
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
*/
public void synchronizeMailbox(final Account account, final String folder,
MessagingListener listener) {
put("synchronizeMailbox", listener, new Runnable() {
public void run() {
synchronizeMailboxSynchronous(account, folder);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is generally only called
* by synchronizeMailbox.
* @param account
* @param folder
*
* TODO Break this method up into smaller chunks.
*/
public void synchronizeMailboxSynchronous(final Account account, final String folder) {
/*
* We don't ever sync the Outbox.
*/
if (folder.equals(account.getOutboxFolderName())) {
return;
}
if (account.getErrorFolderName().equals(folder)){
return;
}
String debugLine = "Synchronizing folder " + account.getDescription() + ":" + folder;
if (Config.LOGV) {
Log.v(Email.LOG_TAG, debugLine);
}
log(debugLine);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxStarted(account, folder);
}
LocalFolder tLocalFolder = null;
Exception commandException = null;
try {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to process pending commands for folder " +
account.getDescription() + ":" + folder);
}
try
{
processPendingCommandsSynchronous(account);
}
catch (Exception e)
{
addErrorMessage(account, e);
Log.e(Email.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get local folder " + folder);
}
final LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
tLocalFolder = (LocalFolder) localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages) {
localUidMap.put(message.getUid(), message);
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get remote store for " + folder);
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get remote folder " + folder);
}
Folder remoteFolder = remoteStore.getFolder(folder);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName())) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
Log.i(Email.LOG_TAG, "Done synchronizing folder " + folder);
return;
}
}
}
/*
* Synchronization process:
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest Email.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - Email.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date
newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep
cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to open remote folder " + folder);
}
remoteFolder.open(OpenMode.READ_WRITE);
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
Message[] remoteMessageArray = new Message[0];
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " +
remoteMessageCount);
}
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through "
+ remoteEnd + " for folder " + folder);
}
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message thisMess : remoteMessageArray)
{
remoteMessages.add(thisMess);
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Got messages for folder " + folder);
}
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
*/
Iterator<Message> iter = remoteMessages.iterator();
while (iter.hasNext()) {
Message message = iter.next();
Message localMessage = localUidMap.get(message.getUid());
if (localMessage == null ||
(!localMessage.isSet(Flag.DELETED) &&
!localMessage.isSet(Flag.X_DOWNLOADED_FULL) &&
!localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))) {
unsyncedMessages.add(message);
iter.remove();
}
}
}
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
s * critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags()) {
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to sync unsynced messages for folder " + folder);
}
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageFinished(Message message, int number, int ofTotal) {
try {
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
// Store the new message locally
localFolder.appendMessages(new Message[] {
message
});
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null) {
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(account, folder,
localFolder.getMessage(message.getUid()));
}
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message.",
e);
addErrorMessage(account, e);
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags()) {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to sync remote messages for folder " + folder);
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : remoteMessages) {
boolean messageChanged = false;
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
- if (localMessage == null) {
+ if (localMessage == null || localMessage.isSet(Flag.DELETED)) {
continue;
}
for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED } )
{
if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) {
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
if (messageChanged && isMessageSuppressed(account, folder, localMessage) == false)
{
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Synced remote messages for folder " + folder);
}
/*
* Get and store the unread message count.
*/
int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
if (remoteUnreadMessageCount == -1) {
localFolder.setUnreadMessageCount(localFolder.getUnreadMessageCount()
+ newMessages.size());
}
else {
localFolder.setUnreadMessageCount(remoteUnreadMessageCount);
}
/*
* Remove any messages that are in the local store but no longer on the remote store.
*/
for (Message localMessage : localMessages) {
- if (remoteUidMap.get(localMessage.getUid()) == null) {
+ if (remoteUidMap.get(localMessage.getUid()) == null &&
+ !localMessage.isSet(Flag.DELETED))
+ {
localMessage.setFlag(Flag.X_DESTROYED, true);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
/*
* Now we download the actual content of messages.
*/
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
/*
* Sort the messages into two buckets, small and large. Small messages will be
* downloaded fully and large messages will be downloaded in parts. By sorting
* into two buckets we can pipeline the commands for each set of messages
* into a single command to the server saving lots of round trips.
*/
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Have " + largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages to fetch for folder " + folder);
}
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
}
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener() {
public void messageFinished(Message message, int number, int ofTotal) {
try {
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (isMessageSuppressed(account, folder, localMessage) == false)
{
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(
account,
folder,
localMessage);
}
}
}
catch (MessagingException me) {
addErrorMessage(account, me);
Log.e(Email.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
}
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
}
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE) {
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
} else {
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
if (isMessageSuppressed(account, folder, message) == false)
{
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(
account,
folder,
localFolder.getMessage(message.getUid()));
}
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
}
/*
* Notify listeners that we're finally done.
*/
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
remoteFolder.close(false);
localFolder.close(false);
if (Config.LOGD) {
log( "Done synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date() +
" with " + newMessages.size() + " new messages");
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFinished(
account,
folder,
remoteMessageCount, newMessages.size());
}
if (commandException != null)
{
String rootMessage = getRootCauseMessage(commandException);
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null)
{
try
{
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
tLocalFolder.close(false);
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
addErrorMessage(account, e);
log("Failed synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date());
}
}
private String getRootCauseMessage(Throwable t)
{
Throwable rootCause = t;
Throwable nextCause = rootCause;
do
{
nextCause = rootCause.getCause();
if (nextCause != null)
{
rootCause = nextCause;
}
} while (nextCause != null);
return rootCause.getMessage();
}
private void queuePendingCommand(Account account, PendingCommand command) {
try {
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
localStore.addPendingCommand(command);
}
catch (Exception e) {
addErrorMessage(account, e);
throw new RuntimeException("Unable to enqueue pending command", e);
}
}
private void processPendingCommands(final Account account) {
put("processPendingCommands", null, new Runnable() {
public void run() {
try {
processPendingCommandsSynchronous(account);
}
catch (MessagingException me) {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "processPendingCommands", me);
}
addErrorMessage(account, me);
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
private void processPendingCommandsSynchronous(Account account) throws MessagingException {
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
ArrayList<PendingCommand> commands = localStore.getPendingCommands();
PendingCommand processingCommand = null;
try
{
for (PendingCommand command : commands) {
processingCommand = command;
Log.d(Email.LOG_TAG, "Processing pending command '" + command + "'");
/*
* We specifically do not catch any exceptions here. If a command fails it is
* most likely due to a server or IO error and it must be retried before any
* other command processes. This maintains the order of the commands.
*/
try
{
if (PENDING_COMMAND_APPEND.equals(command.command)) {
processPendingAppend(command, account);
}
else if (PENDING_COMMAND_SET_FLAG.equals(command.command)) {
processPendingSetFlag(command, account);
}
else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command)) {
processPendingMarkAllAsRead(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command)) {
processPendingMoveOrCopy(command, account);
}
else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command)) {
processPendingEmptyTrash(command, account);
}
localStore.removePendingCommand(command);
Log.d(Email.LOG_TAG, "Done processing pending command '" + command + "'");
}
catch (MessagingException me)
{
if (me.isPermanentFailure())
{
Log.e(Email.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue");
localStore.removePendingCommand(processingCommand);
}
else
{
throw me;
}
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, me);
Log.e(Email.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me;
}
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message. Once the local message is successfully processed it is deleted so
* that the server message will be synchronized down without an additional copy being
* created.
* TODO update the local message UID instead of deleteing it
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingAppend(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
LocalStore localStore = (LocalStore) Store.getInstance(
account.getLocalStoreUri(),
mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid);
if (localMessage == null) {
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return;
}
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return;
}
Message remoteMessage = null;
if (!localMessage.getUid().startsWith("Local")
&& !localMessage.getUid().contains("-")) {
remoteMessage = remoteFolder.getMessage(localMessage.getUid());
}
if (remoteMessage == null) {
if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED))
{
Log.w(Email.LOG_TAG, "Local message with uid " + localMessage.getUid() +
" has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " +
" same message id");
String rUid = remoteFolder.getUidFromMessageId(localMessage);
if (rUid != null)
{
Log.w(Email.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " +
" uid " + rUid + ", assuming message was already copied and aborting this copy");
String oldUid = localMessage.getUid();
localMessage.setUid(rUid);
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
return;
}
else
{
Log.w(Email.LOG_TAG, "No remote message with message-id found, proceeding with append");
}
}
/*
* If the message does not exist remotely we just upload it and then
* update our local copy with the new uid.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
}
else {
/*
* If the remote message exists we need to determine which copy to keep.
*/
/*
* See if the remote message is newer than ours.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = localMessage.getInternalDate();
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate.compareTo(localDate) > 0) {
/*
* If the remote message is newer than ours we'll just
* delete ours and move on. A sync will get the server message
* if we need to be able to see it.
*/
localMessage.setFlag(Flag.DELETED, true);
}
else {
/*
* Otherwise we'll upload our message and then delete the remote message.
*/
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
remoteMessage.setFlag(Flag.DELETED, true);
remoteFolder.expunge();
}
}
}
/**
* Process a pending trash message command.
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingMoveOrCopy(PendingCommand command, Account account)
throws MessagingException {
String srcFolder = command.arguments[0];
String uid = command.arguments[1];
String destFolder = command.arguments[2];
String isCopyS = command.arguments[3];
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteSrcFolder = remoteStore.getFolder(srcFolder);
Folder remoteDestFolder = remoteStore.getFolder(destFolder);
if (!remoteSrcFolder.exists()) {
Log.w(Email.LOG_TAG, "processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist");
return;
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE) {
Log.w(Email.LOG_TAG, "processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write");
return;
}
Message remoteMessage = null;
if (!uid.startsWith("Local")
&& !uid.contains("-")) {
// Why bother with this, perhaps just pass the UID to the store to save a roundtrip? And check for error returns, of course
// Same applies for deletion
remoteMessage = remoteSrcFolder.getMessage(uid);
}
if (remoteMessage == null) {
Log.w(Email.LOG_TAG, "processingPendingMoveOrCopy: remoteMessage " + uid + " does not exist");
return;
}
if (Config.LOGD)
{
Log.d(Email.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder
+ ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
}
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
Log.d(Email.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message");
remoteMessage.delete(account.getTrashFolderName());
return;
}
remoteDestFolder.open(OpenMode.READ_WRITE);
if (remoteDestFolder.getMode() != OpenMode.READ_WRITE) {
Log.w(Email.LOG_TAG, "processingPendingMoveOrCopy: could not open remoteDestFolder " + srcFolder + " read/write");
return;
}
if (isCopy) {
remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
else {
remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
remoteSrcFolder.close(true);
remoteDestFolder.close(true);
}
/**
* Processes a pending mark read or unread command.
*
* @param command arguments = (String folder, String uid, boolean read)
* @param account
*/
private void processPendingSetFlag(PendingCommand command, Account account)
throws MessagingException {
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
boolean newState = Boolean.parseBoolean(command.arguments[2]);
Flag flag = Flag.valueOf(command.arguments[3]);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return;
}
Message remoteMessage = null;
if (!uid.startsWith("Local")
&& !uid.contains("-")) {
remoteMessage = remoteFolder.getMessage(uid);
}
if (remoteMessage == null) {
return;
}
remoteMessage.setFlag(flag, newState);
}
private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException {
String folder = command.arguments[0];
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder)localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message[] messages = localFolder.getMessages(null);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false)
{
message.setFlag(Flag.SEEN, true);
}
}
localFolder.setUnreadMessageCount(0);
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder);
}
try
{
if (account.getErrorFolderName().equals(folder))
{
return;
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return;
}
remoteFolder.setFlags(new Flag[] { Flag.SEEN }, true);
remoteFolder.close(false);
}
catch (UnsupportedOperationException uoe)
{
Log.w(Email.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe);
}
finally
{
localFolder.close(false);
}
}
static long uidfill = 0;
static AtomicBoolean loopCatch = new AtomicBoolean();
public void addErrorMessage(Account account, Throwable t)
{
if (Email.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (t == null)
{
return;
}
String rootCauseMessage = getRootCauseMessage(t);
log("Error" + "'" + rootCauseMessage + "'");
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
Message message = new MimeMessage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
t.printStackTrace(ps);
ps.close();
message.setBody(new TextBody(baos.toString()));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(rootCauseMessage);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.setSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
}
catch (Throwable it)
{
Log.e(Email.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void addErrorMessage(Account account, String subject, String body)
{
if (Email.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (body == null || body.length() < 1)
{
return;
}
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
Message message = new MimeMessage();
message.setBody(new TextBody(body));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(subject);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.setSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
}
catch (Throwable it)
{
Log.e(Email.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void markAllMessagesRead(final Account account, final String folder)
{
Log.v(Email.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read");
List<String> args = new ArrayList<String>();
args.add(folder);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MARK_ALL_AS_READ;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
/**
* Mark the message with the given account, folder and uid either Seen or not Seen.
* @param account
* @param folder
* @param uid
* @param seen
*/
public void markMessageRead(
final Account account,
final String folder,
final String uid,
final boolean seen) {
setMessageFlag(account, folder, uid, Flag.SEEN, seen);
}
public void setMessageFlag(
final Account account,
final String folder,
final String uid,
final Flag flag,
final boolean newState) {
// TODO: put this into the background, but right now that causes odd behavior
// because the FolderMessageList doesn't have its own cache of the flag states
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
message.setFlag(flag, newState);
// Allows for re-allowing sending of messages that could not be sent
if (flag == Flag.FLAGGED && newState == false
&& uid != null
&& account.getOutboxFolderName().equals(folder))
{
sendCount.remove(uid);
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, folder);
}
if (account.getErrorFolderName().equals(folder))
{
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG;
command.arguments = new String[] { folder, uid, Boolean.toString(newState), flag.toString() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException(me);
}
}
public void clearAllPending(final Account account)
{
try
{
Log.w(Email.LOG_TAG, "Clearing pending commands!");
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
localStore.removePendingCommands();
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Unable to clear pending command", me);
addErrorMessage(account, me);
}
}
private void loadMessageForViewRemote(final Account account, final String folder,
final String uid, MessagingListener listener) {
put("loadMessageForViewRemote", listener, new Runnable() {
public void run() {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
// This is a view message request, so mark it read
if (!message.isSet(Flag.SEEN)) {
markMessageRead(account, folder, uid, true);
}
if (message.isSet(Flag.X_DOWNLOADED_FULL)) {
/*
* If the message has been synchronized since we were called we'll
* just hand it back cause it's ready to go.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { message }, fp, null);
for (MessagingListener l : getListeners()) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
localFolder.close(false);
return;
}
/*
* At this point the message is not available, so we need to download it
* fully if possible.
*/
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(folder);
remoteFolder.open(OpenMode.READ_WRITE);
// Get the remote message and fully download it
Message remoteMessage = remoteFolder.getMessage(uid);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// Store the message locally and load the stored message into memory
localFolder.appendMessages(new Message[] { remoteMessage });
message = localFolder.getMessage(uid);
localFolder.fetch(new Message[] { message }, fp, null);
// Mark that this message is now fully synched
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
for (MessagingListener l : getListeners()) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
remoteFolder.close(false);
localFolder.close(false);
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFailed(account, folder, uid, e.getMessage());
}
addErrorMessage(account, e);
}
}
});
}
public void loadMessageForView(final Account account, final String folder, final String uid,
MessagingListener listener) {
for (MessagingListener l : getListeners()) {
l.loadMessageForViewStarted(account, folder, uid);
}
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (!message.isSet(Flag.SEEN)) {
markMessageRead(account, folder, uid, true);
}
for (MessagingListener l : getListeners()) {
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (!message.isSet(Flag.X_DOWNLOADED_FULL)) {
loadMessageForViewRemote(account, folder, uid, listener);
localFolder.close(false);
return;
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] {
message
}, fp, null);
for (MessagingListener l : getListeners()) {
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null)
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFinished(account, folder, uid, message);
}
if (listener != null)
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
localFolder.close(false);
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.loadMessageForViewFailed(account, folder, uid, e.getMessage());
}
addErrorMessage(account, e);
}
}
/**
* Attempts to load the attachment specified by part from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(
final Account account,
final Message message,
final Part part,
final Object tag,
MessagingListener listener) {
/*
* Check if the attachment has already been downloaded. If it has there's no reason to
* download it, so we just tell the listener that it's ready to go.
*/
try {
if (part.getBody() != null) {
for (MessagingListener l : getListeners()) {
l.loadAttachmentStarted(account, message, part, tag, false);
}
for (MessagingListener l : getListeners()) {
l.loadAttachmentFinished(account, message, part, tag);
}
return;
}
}
catch (MessagingException me) {
/*
* If the header isn't there the attachment isn't downloaded yet, so just continue
* on.
*/
}
for (MessagingListener l : getListeners()) {
l.loadAttachmentStarted(account, message, part, tag, true);
}
put("loadAttachment", listener, new Runnable() {
public void run() {
try {
LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
/*
* We clear out any attachments already cached in the entire store and then
* we update the passed in message to reflect that there are no cached
* attachments. This is in support of limiting the account to having one
* attachment downloaded at a time.
*/
localStore.pruneCachedAttachments();
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
for (Part attachment : attachments) {
attachment.setBody(null);
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(message.getFolder().getName());
Folder remoteFolder = remoteStore.getFolder(message.getFolder().getName());
remoteFolder.open(OpenMode.READ_WRITE);
FetchProfile fp = new FetchProfile();
fp.add(part);
remoteFolder.fetch(new Message[] { message }, fp, null);
localFolder.updateMessage((LocalMessage)message);
localFolder.close(false);
for (MessagingListener l : getListeners()) {
l.loadAttachmentFinished(account, message, part, tag);
}
}
catch (MessagingException me) {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "", me);
}
for (MessagingListener l : getListeners()) {
l.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
addErrorMessage(account, me);
}
}
});
}
/**
* Stores the given message in the Outbox and starts a sendPendingMessages command to
* attempt to send the message.
* @param account
* @param message
* @param listener
*/
public void sendMessage(final Account account,
final Message message,
MessagingListener listener) {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(account.getOutboxFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
localFolder.close(false);
sendPendingMessages(account, null);
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
// TODO general failed
}
addErrorMessage(account, e);
}
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final Account account,
MessagingListener listener) {
put("sendPendingMessages", listener, new Runnable() {
public void run() {
sendPendingMessagesSynchronous(account);
}
});
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessagesSynchronous(final Account account) {
try {
Store localStore = Store.getInstance(
account.getLocalStoreUri(),
mApplication);
Folder localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists()) {
return;
}
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesStarted(account);
}
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
boolean anyFlagged = false;
/*
* The profile we will use to pull all of the content
* for a given local message into memory for sending.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
LocalFolder localSentFolder =
(LocalFolder) localStore.getFolder(
account.getSentFolderName());
Log.i(Email.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send");
Transport transport = Transport.getInstance(account.getTransportUri());
for (Message message : localMessages) {
if (message.isSet(Flag.DELETED)) {
message.setFlag(Flag.X_DESTROYED, true);
continue;
}
if (message.isSet(Flag.FLAGGED)) {
Log.i(Email.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid());
continue;
}
try {
AtomicInteger count = new AtomicInteger(0);
AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count);
if (oldCount != null)
{
count = oldCount;
}
Log.i(Email.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get());
if (count.incrementAndGet() > Email.MAX_SEND_ATTEMPTS)
{
Log.e(Email.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging");
message.setFlag(Flag.FLAGGED, true);
anyFlagged = true;
continue;
}
localFolder.fetch(new Message[] { message }, fp, null);
try {
message.setFlag(Flag.X_SEND_IN_PROGRESS, true);
Log.i(Email.LOG_TAG, "Sending message with UID " + message.getUid());
transport.sendMessage(message);
message.setFlag(Flag.X_SEND_IN_PROGRESS, false);
message.setFlag(Flag.SEEN, true);
Log.i(Email.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
localFolder.moveMessages(
new Message[] { message },
localSentFolder);
Log.i(Email.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[] {
localSentFolder.getName(),
message.getUid() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e) {
if (e instanceof MessagingException)
{
MessagingException me = (MessagingException)e;
if (me.isPermanentFailure() == false)
{
// Decrement the counter if the message could not possibly have been sent
int newVal = count.decrementAndGet();
Log.i(Email.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal
+ "; no possible send");
}
}
message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(Email.LOG_TAG, "Failed to send message", e);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, e);
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "Failed to fetch message for sending", e);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, e);
/*
* We ignore this exception because a future refresh will retry this
* message.
*/
}
}
localFolder.expunge();
if (localFolder.getMessageCount() == 0) {
localFolder.delete(false);
}
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesCompleted(account);
}
if (anyFlagged)
{
addErrorMessage(account, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_fmt, Email.ERROR_FOLDER_NAME));
NotificationManager notifMgr =
(NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic,
mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis());
Intent i = FolderMessageList.actionHandleAccountIntent(mApplication, account, account.getErrorFolderName());
PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0);
notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_abbrev, Email.ERROR_FOLDER_NAME), pi);
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = Email.NOTIFICATION_LED_SENDING_FAILURE_COLOR;
notif.ledOnMS = Email.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = Email.NOTIFICATION_LED_FAST_OFF_TIME;
notifMgr.notify(-1000 - account.getAccountNumber(), notif);
}
}
catch (Exception e) {
for (MessagingListener l : getListeners()) {
l.sendPendingMessagesFailed(account);
}
addErrorMessage(account, e);
}
}
public void getAccountUnreadCount(final Context context, final Account account,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable() {
public void run() {
int unreadMessageCount = 0;
try {
unreadMessageCount = account.getUnreadMessageCount(context, mApplication);
}
catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Count not get unread count for account " + account.getDescription(),
me);
}
l.accountStatusChanged(account, unreadMessageCount);
}
};
putBackground("getAccountUnread:" + account.getDescription(), l, unreadRunnable);
}
public boolean moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
if (!message.getUid().startsWith("Local")
&& !message.getUid().contains("-")) {
put("moveMessage", null, new Runnable() {
public void run() {
moveOrCopyMessageSynchronous(account, srcFolder, message, destFolder, false, listener);
}
});
return true;
}
else
{
return false;
}
}
public boolean isMoveCapable(Message message) {
if (!message.getUid().startsWith("Local")
&& !message.getUid().contains("-")) {
return true;
}
else {
return false;
}
}
public boolean isCopyCapable(Message message) {
return isMoveCapable(message);
}
public boolean isMoveCapable(final Account account)
{
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
return localStore.isMoveCapable() && remoteStore.isMoveCapable();
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Exception while ascertaining move capability", me);
return false;
}
}
public boolean isCopyCapable(final Account account)
{
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
return localStore.isCopyCapable() && remoteStore.isCopyCapable();
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Exception while ascertaining copy capability", me);
return false;
}
}
public boolean copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
if (!message.getUid().startsWith("Local")
&& !message.getUid().contains("-")) {
put("copyMessage", null, new Runnable() {
public void run() {
moveOrCopyMessageSynchronous(account, srcFolder, message, destFolder, true, listener);
}
});
return true;
}
else
{
return false;
}
}
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message message,
final String destFolder, final boolean isCopy, MessagingListener listener)
{
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false)) {
return;
}
if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false)) {
return;
}
Folder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
Message lMessage = localSrcFolder.getMessage(message.getUid());
String origUid = message.getUid();
if (lMessage != null)
{
if (Config.LOGD)
{
Log.d(Email.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder
+ ", uid = " + origUid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
}
if (isCopy) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localSrcFolder.fetch(new Message[] { message }, fp, null);
localSrcFolder.copyMessages(new Message[] { message }, localDestFolder);
}
else {
localSrcFolder.moveMessages(new Message[] { message }, localDestFolder);
for (MessagingListener l : getListeners()) {
l.messageUidChanged(account, srcFolder, origUid, message.getUid());
}
unsuppressMessage(account, srcFolder, origUid);
}
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY;
command.arguments = new String[] { srcFolder, origUid, destFolder, Boolean.toString(isCopy) };
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException("Error moving message", me);
}
}
public void deleteMessage(final Account account, final String folder, final Message message,
final MessagingListener listener) {
suppressMessage(account, folder, message);
put("deleteMessage", null, new Runnable() {
public void run() {
deleteMessageSynchronous(account, folder, message, listener);
}
});
}
private void deleteMessageSynchronous(final Account account, final String folder, final Message message,
MessagingListener listener) {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder localFolder = localStore.getFolder(folder);
Message lMessage = localFolder.getMessage(message.getUid());
String origUid = message.getUid();
if (lMessage != null)
{
if (folder.equals(account.getTrashFolderName()))
{
if (Config.LOGD)
{
Log.d(Email.LOG_TAG, "Deleting message in trash folder, not copying");
}
lMessage.setFlag(Flag.DELETED, true);
}
else
{
Folder localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (localTrashFolder.exists() == false)
{
localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES);
}
if (localTrashFolder.exists() == true)
{
if (Config.LOGD)
{
Log.d(Email.LOG_TAG, "Deleting message in normal folder, moving");
}
localFolder.moveMessages(new Message[] { message }, localTrashFolder);
}
}
}
localFolder.close(false);
unsuppressMessage(account, folder, message);
if (listener != null) {
listener.messageDeleted(account, folder, message);
}
for (MessagingListener l : getListeners()) {
l.folderStatusChanged(account, account.getTrashFolderName());
}
if (Config.LOGD)
{
Log.d(Email.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy());
}
if (folder.equals(account.getOutboxFolderName()))
{
// If the message was in the Outbox, then it has been copied to local Trash, and has
// to be copied to remote trash
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[] {
account.getTrashFolderName(),
message.getUid() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG;
command.arguments = new String[] { folder, origUid, Boolean.toString(true), Flag.DELETED.toString() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE) {
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY;
command.arguments = new String[] { folder, origUid, account.getTrashFolderName(), "false" };
queuePendingCommand(account, command);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ)
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG;
command.arguments = new String[] { folder, origUid, Boolean.toString(true), Flag.SEEN.toString() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
else
{
if (Config.LOGD)
{
Log.d(Email.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server");
}
}
}
catch (MessagingException me) {
addErrorMessage(account, me);
throw new RuntimeException("Error deleting message from local store.", me);
}
}
private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException {
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName());
if (remoteFolder.exists())
{
remoteFolder.open(OpenMode.READ_WRITE);
remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true);
remoteFolder.close(true);
}
}
public void emptyTrash(final Account account, MessagingListener listener) {
put("emptyTrash", listener, new Runnable() {
public void run() {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
Folder localFolder = localStore.getFolder(account.getTrashFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.setFlags(new Flag[] { Flag.DELETED }, true);
localFolder.close(true);
for (MessagingListener l : getListeners()) {
l.emptyTrashCompleted(account);
}
List<String> args = new ArrayList<String>();
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EMPTY_TRASH;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "emptyTrash failed", e);
addErrorMessage(account, e);
}
}
});
}
public void sendAlternate(final Context context, Account account, Message message)
{
if (Config.LOGD)
{
Log.d(Email.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName()
+ ":" + message.getUid() + " for sendAlternate");
}
loadMessageForView(account, message.getFolder().getName(),
message.getUid(), new MessagingListener()
{
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
Message message)
{
if (Config.LOGD)
{
Log.d(Email.LOG_TAG, "Got message " + account.getDescription() + ":" + folder
+ ":" + message.getUid() + " for sendAlternate");
}
try
{
Intent msg=new Intent(Intent.ACTION_SEND);
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(message,
"text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
quotedText = MimeUtility.getTextFromPart(part);
}
if (quotedText != null)
{
msg.putExtra(Intent.EXTRA_TEXT, quotedText);
}
msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject());
msg.setType("text/plain");
context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title)));
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Unable to send email through alternate program", me);
}
}
});
}
/**
* Checks mail for one or multiple accounts. If account is null all accounts
* are checked.
*
* @param context
* @param account
* @param listener
*/
public void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener) {
if (useManualWakeLock) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Email");
wakeLock.setReferenceCounted(false);
wakeLock.acquire(Email.MANUAL_WAKE_LOCK_TIMEOUT);
}
for (MessagingListener l : getListeners()) {
l.checkMailStarted(context, account);
}
put("checkMail", listener, new Runnable() {
public void run() {
final NotificationManager notifMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
try
{
Log.i(Email.LOG_TAG, "Starting mail check");
Preferences prefs = Preferences.getPreferences(context);
Account[] accounts;
if (account != null) {
accounts = new Account[] {
account
};
} else {
accounts = prefs.getAccounts();
}
for (final Account account : accounts) {
final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000;
if (ignoreLastCheckedTime == false && accountInterval <= 0)
{
if (Config.LOGV || true)
{
Log.v(Email.LOG_TAG, "Skipping synchronizing account " + account.getDescription());
}
continue;
}
if (Config.LOGV || true)
{
Log.v(Email.LOG_TAG, "Synchronizing account " + account.getDescription());
}
putBackground("sendPending " + account.getDescription(), null, new Runnable() {
public void run() {
if (account.isShowOngoing()) {
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis());
Intent intent = FolderMessageList.actionHandleAccountIntent(context, account, Email.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title),
account.getDescription() , pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (Email.NOTIFICATION_LED_WHILE_SYNCING) {
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = Email.NOTIFICATION_LED_DIM_COLOR;
notif.ledOnMS = Email.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = Email.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(Email.FETCHING_EMAIL_NOTIFICATION_ID, notif);
}
try
{
sendPendingMessagesSynchronous(account);
}
finally {
if (account.isShowOngoing()) {
notifMgr.cancel(Email.FETCHING_EMAIL_NOTIFICATION_ID);
}
}
}
}
);
try
{
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode();
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
for (final Folder folder : localStore.getPersonalNamespaces())
{
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayMode = folder.getDisplayClass();
Folder.FolderClass fSyncMode = folder.getSyncClass();
if ((aDisplayMode == Account.FolderMode.FIRST_CLASS &&
fDisplayMode != Folder.FolderClass.FIRST_CLASS)
|| (aDisplayMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fDisplayMode != Folder.FolderClass.FIRST_CLASS &&
fDisplayMode != Folder.FolderClass.SECOND_CLASS)
|| (aDisplayMode == Account.FolderMode.NOT_SECOND_CLASS &&
fDisplayMode == Folder.FolderClass.SECOND_CLASS))
{
// Never sync a folder that isn't displayed
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in display mode " + fDisplayMode + " while account is in display mode " + aDisplayMode);
}
continue;
}
if ((aSyncMode == Account.FolderMode.FIRST_CLASS &&
fSyncMode != Folder.FolderClass.FIRST_CLASS)
|| (aSyncMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fSyncMode != Folder.FolderClass.FIRST_CLASS &&
fSyncMode != Folder.FolderClass.SECOND_CLASS)
|| (aSyncMode == Account.FolderMode.NOT_SECOND_CLASS &&
fSyncMode == Folder.FolderClass.SECOND_CLASS))
{
// Do not sync folders in the wrong class
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in sync mode " + fSyncMode + " while account is in sync mode " + aSyncMode);
}
continue;
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " +
new Date(folder.getLastChecked()));
}
if (ignoreLastCheckedTime == false && folder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "Not syncing folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
}
continue;
}
putBackground("sync" + folder.getName(), null, new Runnable() {
public void run() {
try {
// In case multiple Commands get enqueued, don't run more than
// once
final LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder tLocalFolder = (LocalFolder) localStore.getFolder(folder.getName());
tLocalFolder.open(Folder.OpenMode.READ_WRITE);
if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "Not running Command for folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
}
return;
}
if (account.isShowOngoing()) {
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()),
System.currentTimeMillis());
Intent intent = FolderMessageList.actionHandleAccountIntent(context, account, Email.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription()
+ context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (Email.NOTIFICATION_LED_WHILE_SYNCING) {
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = Email.NOTIFICATION_LED_DIM_COLOR;
notif.ledOnMS = Email.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = Email.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(Email.FETCHING_EMAIL_NOTIFICATION_ID, notif);
}
try
{
synchronizeMailboxSynchronous(account, folder.getName());
}
finally {
if (account.isShowOngoing()) {
notifMgr.cancel(Email.FETCHING_EMAIL_NOTIFICATION_ID);
}
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Exception while processing folder " +
account.getDescription() + ":" + folder.getName(), e);
addErrorMessage(account, e);
}
}
}
);
}
}
catch (MessagingException e) {
Log.e(Email.LOG_TAG, "Unable to synchronize account " + account.getName(), e);
addErrorMessage(account, e);
}
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Unable to synchronize mail", e);
addErrorMessage(account, e);
}
putBackground("finalize sync", null, new Runnable() {
public void run() {
Log.i(Email.LOG_TAG, "Finished mail sync");
for (MessagingListener l : getListeners()) {
l.checkMailFinished(context, account);
}
}
}
);
}
});
}
public void compact(final Account account, final MessagingListener ml)
{
putBackground("compact:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
long oldSize = localStore.getSize();
localStore.compact();
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners()) {
l.accountSizeChanged(account, oldSize, newSize);
l.accountReset(account);
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void clear(final Account account, final MessagingListener ml)
{
putBackground("clear:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), mApplication);
long oldSize = localStore.getSize();
localStore.clear();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners()) {
l.accountSizeChanged(account, oldSize, newSize);
l.accountReset(account);
}
}
catch (Exception e)
{
Log.e(Email.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void saveDraft(final Account account, final Message message) {
try {
Store localStore = Store.getInstance(account.getLocalStoreUri(), mApplication);
LocalFolder localFolder =
(LocalFolder) localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[] {
localFolder.getName(),
localMessage.getUid() };
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException e) {
Log.e(Email.LOG_TAG, "Unable to save message as draft.", e);
addErrorMessage(account, e);
}
}
class Command {
public Runnable runnable;
public MessagingListener listener;
public String description;
}
public MessagingListener getCheckMailListener()
{
return checkMailListener;
}
public void setCheckMailListener(MessagingListener checkMailListener)
{
if (this.checkMailListener != null)
{
removeListener(this.checkMailListener);
}
this.checkMailListener = checkMailListener;
if (this.checkMailListener != null)
{
addListener(this.checkMailListener);
}
}
public SORT_TYPE getSortType()
{
return sortType;
}
public void setSortType(SORT_TYPE sortType)
{
this.sortType = sortType;
}
public boolean isSortAscending(SORT_TYPE sortType)
{
Boolean sortAsc = sortAscending.get(sortType);
if (sortAsc == null)
{
return sortType.isDefaultAscending();
}
else return sortAsc;
}
public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending)
{
sortAscending.put(sortType, nsortAscending);
}
}
| false | true | public void synchronizeMailboxSynchronous(final Account account, final String folder) {
/*
* We don't ever sync the Outbox.
*/
if (folder.equals(account.getOutboxFolderName())) {
return;
}
if (account.getErrorFolderName().equals(folder)){
return;
}
String debugLine = "Synchronizing folder " + account.getDescription() + ":" + folder;
if (Config.LOGV) {
Log.v(Email.LOG_TAG, debugLine);
}
log(debugLine);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxStarted(account, folder);
}
LocalFolder tLocalFolder = null;
Exception commandException = null;
try {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to process pending commands for folder " +
account.getDescription() + ":" + folder);
}
try
{
processPendingCommandsSynchronous(account);
}
catch (Exception e)
{
addErrorMessage(account, e);
Log.e(Email.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get local folder " + folder);
}
final LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
tLocalFolder = (LocalFolder) localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages) {
localUidMap.put(message.getUid(), message);
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get remote store for " + folder);
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get remote folder " + folder);
}
Folder remoteFolder = remoteStore.getFolder(folder);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName())) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
Log.i(Email.LOG_TAG, "Done synchronizing folder " + folder);
return;
}
}
}
/*
* Synchronization process:
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest Email.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - Email.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date
newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep
cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to open remote folder " + folder);
}
remoteFolder.open(OpenMode.READ_WRITE);
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
Message[] remoteMessageArray = new Message[0];
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " +
remoteMessageCount);
}
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through "
+ remoteEnd + " for folder " + folder);
}
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message thisMess : remoteMessageArray)
{
remoteMessages.add(thisMess);
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Got messages for folder " + folder);
}
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
*/
Iterator<Message> iter = remoteMessages.iterator();
while (iter.hasNext()) {
Message message = iter.next();
Message localMessage = localUidMap.get(message.getUid());
if (localMessage == null ||
(!localMessage.isSet(Flag.DELETED) &&
!localMessage.isSet(Flag.X_DOWNLOADED_FULL) &&
!localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))) {
unsyncedMessages.add(message);
iter.remove();
}
}
}
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
s * critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags()) {
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to sync unsynced messages for folder " + folder);
}
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageFinished(Message message, int number, int ofTotal) {
try {
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
// Store the new message locally
localFolder.appendMessages(new Message[] {
message
});
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null) {
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(account, folder,
localFolder.getMessage(message.getUid()));
}
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message.",
e);
addErrorMessage(account, e);
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags()) {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to sync remote messages for folder " + folder);
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : remoteMessages) {
boolean messageChanged = false;
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
if (localMessage == null) {
continue;
}
for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED } )
{
if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) {
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
if (messageChanged && isMessageSuppressed(account, folder, localMessage) == false)
{
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Synced remote messages for folder " + folder);
}
/*
* Get and store the unread message count.
*/
int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
if (remoteUnreadMessageCount == -1) {
localFolder.setUnreadMessageCount(localFolder.getUnreadMessageCount()
+ newMessages.size());
}
else {
localFolder.setUnreadMessageCount(remoteUnreadMessageCount);
}
/*
* Remove any messages that are in the local store but no longer on the remote store.
*/
for (Message localMessage : localMessages) {
if (remoteUidMap.get(localMessage.getUid()) == null) {
localMessage.setFlag(Flag.X_DESTROYED, true);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
/*
* Now we download the actual content of messages.
*/
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
/*
* Sort the messages into two buckets, small and large. Small messages will be
* downloaded fully and large messages will be downloaded in parts. By sorting
* into two buckets we can pipeline the commands for each set of messages
* into a single command to the server saving lots of round trips.
*/
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Have " + largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages to fetch for folder " + folder);
}
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
}
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener() {
public void messageFinished(Message message, int number, int ofTotal) {
try {
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (isMessageSuppressed(account, folder, localMessage) == false)
{
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(
account,
folder,
localMessage);
}
}
}
catch (MessagingException me) {
addErrorMessage(account, me);
Log.e(Email.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
}
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
}
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE) {
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
} else {
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
if (isMessageSuppressed(account, folder, message) == false)
{
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(
account,
folder,
localFolder.getMessage(message.getUid()));
}
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
}
/*
* Notify listeners that we're finally done.
*/
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
remoteFolder.close(false);
localFolder.close(false);
if (Config.LOGD) {
log( "Done synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date() +
" with " + newMessages.size() + " new messages");
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFinished(
account,
folder,
remoteMessageCount, newMessages.size());
}
if (commandException != null)
{
String rootMessage = getRootCauseMessage(commandException);
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null)
{
try
{
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
tLocalFolder.close(false);
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
addErrorMessage(account, e);
log("Failed synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date());
}
}
| public void synchronizeMailboxSynchronous(final Account account, final String folder) {
/*
* We don't ever sync the Outbox.
*/
if (folder.equals(account.getOutboxFolderName())) {
return;
}
if (account.getErrorFolderName().equals(folder)){
return;
}
String debugLine = "Synchronizing folder " + account.getDescription() + ":" + folder;
if (Config.LOGV) {
Log.v(Email.LOG_TAG, debugLine);
}
log(debugLine);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxStarted(account, folder);
}
LocalFolder tLocalFolder = null;
Exception commandException = null;
try {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to process pending commands for folder " +
account.getDescription() + ":" + folder);
}
try
{
processPendingCommandsSynchronous(account);
}
catch (Exception e)
{
addErrorMessage(account, e);
Log.e(Email.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get local folder " + folder);
}
final LocalStore localStore =
(LocalStore) Store.getInstance(account.getLocalStoreUri(), mApplication);
tLocalFolder = (LocalFolder) localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages) {
localUidMap.put(message.getUid(), message);
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get remote store for " + folder);
}
Store remoteStore = Store.getInstance(account.getStoreUri(), mApplication);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get remote folder " + folder);
}
Folder remoteFolder = remoteStore.getFolder(folder);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName())) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
Log.i(Email.LOG_TAG, "Done synchronizing folder " + folder);
return;
}
}
}
/*
* Synchronization process:
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest Email.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - Email.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date
newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep
cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to open remote folder " + folder);
}
remoteFolder.open(OpenMode.READ_WRITE);
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
Message[] remoteMessageArray = new Message[0];
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " +
remoteMessageCount);
}
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through "
+ remoteEnd + " for folder " + folder);
}
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message thisMess : remoteMessageArray)
{
remoteMessages.add(thisMess);
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Got messages for folder " + folder);
}
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
*/
Iterator<Message> iter = remoteMessages.iterator();
while (iter.hasNext()) {
Message message = iter.next();
Message localMessage = localUidMap.get(message.getUid());
if (localMessage == null ||
(!localMessage.isSet(Flag.DELETED) &&
!localMessage.isSet(Flag.X_DOWNLOADED_FULL) &&
!localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))) {
unsyncedMessages.add(message);
iter.remove();
}
}
}
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
s * critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags()) {
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to sync unsynced messages for folder " + folder);
}
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageFinished(Message message, int number, int ofTotal) {
try {
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
// Store the new message locally
localFolder.appendMessages(new Message[] {
message
});
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null) {
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(account, folder,
localFolder.getMessage(message.getUid()));
}
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message.",
e);
addErrorMessage(account, e);
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags()) {
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: About to sync remote messages for folder " + folder);
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : remoteMessages) {
boolean messageChanged = false;
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
if (localMessage == null || localMessage.isSet(Flag.DELETED)) {
continue;
}
for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED } )
{
if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) {
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
if (messageChanged && isMessageSuppressed(account, folder, localMessage) == false)
{
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Synced remote messages for folder " + folder);
}
/*
* Get and store the unread message count.
*/
int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
if (remoteUnreadMessageCount == -1) {
localFolder.setUnreadMessageCount(localFolder.getUnreadMessageCount()
+ newMessages.size());
}
else {
localFolder.setUnreadMessageCount(remoteUnreadMessageCount);
}
/*
* Remove any messages that are in the local store but no longer on the remote store.
*/
for (Message localMessage : localMessages) {
if (remoteUidMap.get(localMessage.getUid()) == null &&
!localMessage.isSet(Flag.DELETED))
{
localMessage.setFlag(Flag.X_DESTROYED, true);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
/*
* Now we download the actual content of messages.
*/
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
/*
* Sort the messages into two buckets, small and large. Small messages will be
* downloaded fully and large messages will be downloaded in parts. By sorting
* into two buckets we can pipeline the commands for each set of messages
* into a single command to the server saving lots of round trips.
*/
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Have " + largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages to fetch for folder " + folder);
}
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
}
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener() {
public void messageFinished(Message message, int number, int ofTotal) {
try {
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (isMessageSuppressed(account, folder, localMessage) == false)
{
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(
account,
folder,
localMessage);
}
}
}
catch (MessagingException me) {
addErrorMessage(account, me);
Log.e(Email.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal) {
}
});
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
}
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
}
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE) {
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
} else {
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] {
message
});
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
if (isMessageSuppressed(account, folder, message) == false)
{
// Update the listener with what we've found
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxNewMessage(
account,
folder,
localFolder.getMessage(message.getUid()));
}
}
}
if (Config.LOGV) {
Log.v(Email.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
}
/*
* Notify listeners that we're finally done.
*/
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
remoteFolder.close(false);
localFolder.close(false);
if (Config.LOGD) {
log( "Done synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date() +
" with " + newMessages.size() + " new messages");
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFinished(
account,
folder,
remoteMessageCount, newMessages.size());
}
if (commandException != null)
{
String rootMessage = getRootCauseMessage(commandException);
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null)
{
try
{
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
tLocalFolder.close(false);
}
catch (MessagingException me)
{
Log.e(Email.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners()) {
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
addErrorMessage(account, e);
log("Failed synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date());
}
}
|
diff --git a/src/main/java/org/mybatis/spring/SqlSessionTemplate.java b/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
index 817a389..851fbd7 100644
--- a/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
+++ b/src/main/java/org/mybatis/spring/SqlSessionTemplate.java
@@ -1,254 +1,254 @@
/*
* Copyright 2010 The myBatis 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.
*/
package org.mybatis.spring;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.support.JdbcAccessor;
import org.springframework.util.Assert;
/**
* Helper class that simplifies data access via the MyBatis
* {@link org.apache.ibatis.session.SqlSession} API, converting checked SQLExceptions into unchecked
* DataAccessExceptions, following the <code>org.springframework.dao</code> exception hierarchy.
* Uses the same {@link org.springframework.jdbc.support.SQLExceptionTranslator} mechanism as
* {@link org.springframework.jdbc.core.JdbcTemplate}.
*
* The main method of this class executes a callback that implements a data access action.
* Furthermore, this class provides numerous convenience methods that mirror
* {@link org.apache.ibatis.session.SqlSession}'s execution methods.
*
* It is generally recommended to use the convenience methods on this template for plain
* query/insert/update/delete operations. However, for more complex operations like batch updates, a
* custom SqlSessionCallback must be implemented, usually as anonymous inner class. For example:
*
* <pre class="code">
* getSqlSessionTemplate().execute(new SqlSessionCallback<Object>() {
* public Object doInSqlSession(SqlSession sqlSession) throws SQLException {
* sqlSession.getMapper(MyMapper.class).update(parameterObject);
* sqlSession.update("MyMapper.update", otherParameterObject);
* return null;
* }
* }, ExecutorType.BATCH);
* </pre>
*
* The template needs a SqlSessionFactory to create SqlSessions, passed in via the
* "sqlSessionFactory" property. A Spring context typically uses a {@link SqlSessionFactoryBean} to
* build the SqlSessionFactory. The template can additionally be configured with a DataSource for
* fetching Connections, although this is not necessary since a DataSource is specified for the
* SqlSessionFactory itself (through configured Environment).
*
* @see #execute
* @see #setSqlSessionFactory(org.apache.ibatis.session.SqlSessionFactory)
* @see SqlSessionFactoryBean#setDataSource
* @see org.apache.ibatis.session.SqlSessionFactory#getConfiguration()
* @see org.apache.ibatis.session.SqlSession
* @see org.mybatis.spring.SqlSessionOperations
* @version $Id$
*/
@SuppressWarnings({ "unchecked" })
public class SqlSessionTemplate extends JdbcAccessor implements SqlSessionOperations {
private SqlSessionFactory sqlSessionFactory;
public SqlSessionTemplate() {}
public SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
setSqlSessionFactory(sqlSessionFactory);
}
/**
* Sets the SqlSessionFactory this template will use when creating SqlSessions.
*/
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
/**
* Returns either the DataSource explicitly set for this template of the one specified by the SqlSessionFactory's Environment.
*
* @see org.apache.ibatis.mapping.Environment
*/
@Override
public DataSource getDataSource() {
DataSource ds = super.getDataSource();
return (ds != null ? ds : this.sqlSessionFactory.getConfiguration().getEnvironment().getDataSource());
}
@Override
public void afterPropertiesSet() {
if (this.sqlSessionFactory == null) {
throw new IllegalArgumentException("Property 'sqlSessionFactory' is required");
}
super.afterPropertiesSet();
}
public <T> T execute(SqlSessionCallback<T> action) throws DataAccessException {
return execute(action, this.sqlSessionFactory.getConfiguration().getDefaultExecutorType());
}
/**
* Execute the given data access action on a Executor.
*
* @param action callback object that specifies the data access action
* @param executorType SIMPLE, REUSE, BATCH
* @return a result object returned by the action, or <code>null</code>
* @throws DataAccessException in case of errors
*/
public <T> T execute(SqlSessionCallback<T> action, ExecutorType executorType) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Assert.notNull(this.sqlSessionFactory, "No SqlSessionFactory specified");
SqlSession sqlSession = SqlSessionUtils.getSqlSession(this.sqlSessionFactory, getDataSource(), executorType);
try {
return action.doInSqlSession(sqlSession);
} catch (Throwable t) {
throw wrapException(t);
} finally {
SqlSessionUtils.closeSqlSession(sqlSession, this.sqlSessionFactory);
}
}
public Object selectOne(String statement) {
return selectOne(statement, null);
}
public Object selectOne(final String statement, final Object parameter) {
return execute(new SqlSessionCallback<Object>() {
public Object doInSqlSession(SqlSession sqlSession) {
return sqlSession.selectOne(statement, parameter);
}
});
}
public <T> List<T> selectList(String statement) {
return selectList(statement, null);
}
public <T> List<T> selectList(String statement, Object parameter) {
return selectList(statement, parameter, RowBounds.DEFAULT);
}
public <T> List<T> selectList(final String statement, final Object parameter, final RowBounds rowBounds) {
return execute(new SqlSessionCallback<List<T>>() {
public List<T> doInSqlSession(SqlSession sqlSession) {
return sqlSession.selectList(statement, parameter, rowBounds);
}
});
}
public void select(String statement, Object parameter, ResultHandler handler) {
select(statement, parameter, RowBounds.DEFAULT, handler);
}
public void select(final String statement, final Object parameter, final RowBounds rowBounds,
final ResultHandler handler) {
execute(new SqlSessionCallback<Object>() {
public Object doInSqlSession(SqlSession sqlSession) {
sqlSession.select(statement, parameter, rowBounds, handler);
return null;
}
});
}
public int insert(String statement) {
return insert(statement, null);
}
public int insert(final String statement, final Object parameter) {
return execute(new SqlSessionCallback<Integer>() {
public Integer doInSqlSession(SqlSession sqlSession) {
return sqlSession.insert(statement, parameter);
}
});
}
public int update(String statement) {
return update(statement, null);
}
public int update(final String statement, final Object parameter) {
return execute(new SqlSessionCallback<Integer>() {
public Integer doInSqlSession(SqlSession sqlSession) {
return sqlSession.update(statement, parameter);
}
});
}
public int delete(String statement) {
return delete(statement, null);
}
public int delete(final String statement, final Object parameter) {
return execute(new SqlSessionCallback<Integer>() {
public Integer doInSqlSession(SqlSession sqlSession) {
return sqlSession.delete(statement, parameter);
}
});
}
public <T> T getMapper(final Class<T> type) {
return (T) java.lang.reflect.Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type},
new InvocationHandler() {
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
return execute(new SqlSessionCallback<Object>() {
public Object doInSqlSession(SqlSession sqlSession) throws SQLException {
try {
return method.invoke(sqlSession.getMapper(type), args);
} catch (java.lang.reflect.InvocationTargetException e) {
- throw wrapException(e);
+ throw wrapException(e.getCause());
} catch (Exception e) {
throw new MyBatisSystemException("SqlSession operation", e);
}
}
});
}
});
}
public DataAccessException wrapException(Throwable t) {
if (t instanceof PersistenceException) {
if (t.getCause() instanceof SQLException) {
return getExceptionTranslator().translate("SqlSession operation", null, (SQLException) t.getCause());
} else {
return new MyBatisSystemException("SqlSession operation", t);
}
} else if (t instanceof DataAccessException) {
return (DataAccessException) t;
} else {
return new MyBatisSystemException("SqlSession operation", t);
}
}
}
| true | true | public <T> T getMapper(final Class<T> type) {
return (T) java.lang.reflect.Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type},
new InvocationHandler() {
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
return execute(new SqlSessionCallback<Object>() {
public Object doInSqlSession(SqlSession sqlSession) throws SQLException {
try {
return method.invoke(sqlSession.getMapper(type), args);
} catch (java.lang.reflect.InvocationTargetException e) {
throw wrapException(e);
} catch (Exception e) {
throw new MyBatisSystemException("SqlSession operation", e);
}
}
});
}
});
}
| public <T> T getMapper(final Class<T> type) {
return (T) java.lang.reflect.Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type},
new InvocationHandler() {
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
return execute(new SqlSessionCallback<Object>() {
public Object doInSqlSession(SqlSession sqlSession) throws SQLException {
try {
return method.invoke(sqlSession.getMapper(type), args);
} catch (java.lang.reflect.InvocationTargetException e) {
throw wrapException(e.getCause());
} catch (Exception e) {
throw new MyBatisSystemException("SqlSession operation", e);
}
}
});
}
});
}
|
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/preview/JavaFXPreviewTopComponent.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/preview/JavaFXPreviewTopComponent.java
index c9b1537b..1797af1e 100644
--- a/javafx.editor/src/org/netbeans/modules/javafx/editor/preview/JavaFXPreviewTopComponent.java
+++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/preview/JavaFXPreviewTopComponent.java
@@ -1,296 +1,296 @@
package org.netbeans.modules.javafx.editor.preview;
import java.awt.Graphics;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import org.netbeans.api.project.FileOwnerQuery;
import org.netbeans.api.project.Project;
import org.netbeans.modules.javafx.project.JavaFXProject;
import org.netbeans.spi.project.support.ant.PropertyEvaluator;
import org.netbeans.spi.project.support.ant.PropertyUtils;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.modules.InstalledFileLocator;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
/**
* Top component which displays JavaFX Preview.
*/
public final class JavaFXPreviewTopComponent extends TopComponent implements PropertyChangeListener {
private static JavaFXPreviewTopComponent instance;
/** path to the icon used by the component and its open action */
// static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
private static final String PREFERRED_ID = "JavaFXPreviewTopComponent"; //NOI18N
private static final Logger log = Logger.getLogger("org.netbeans.javafx.preview"); //NOI18N
private static final File fxHome = InstalledFileLocator.getDefault().locate("javafx-sdk", "org.netbeans.modules.javafx.platform", false); //NOI18N
private static final File previewLib = InstalledFileLocator.getDefault().locate("modules/ext/org-netbeans-javafx-preview.jar", "org.netbeans.modules.javafx.editor", false); //NOI18N
private BufferedImage bi;
private DataObject oldD;
private Process pr;
private int timer;
private final RequestProcessor.Task task = RequestProcessor.getDefault().create(new Runnable() {
public void run() {
synchronized (JavaFXPreviewTopComponent.this) {
if (pr != null) {
pr.destroy();
timer = 0;
task.schedule(150);
return;
}
}
if (oldD != null) {
oldD.removePropertyChangeListener(JavaFXPreviewTopComponent.this);
oldD = null;
}
Node[] sel = TopComponent.getRegistry().getActivatedNodes();
if (sel.length == 1) {
DataObject d = sel[0].getLookup().lookup(DataObject.class);
if (d != null) {
FileObject f = d.getPrimaryFile();
if (f.isData()) bi = null;
if ("fx".equals(f.getExt())) { //NOI18N
d.addPropertyChangeListener(JavaFXPreviewTopComponent.this);
oldD = d;
Project p = FileOwnerQuery.getOwner(f);
if (p instanceof JavaFXProject) {
PropertyEvaluator ev = ((JavaFXProject)p).evaluator();
FileObject srcRoots[] = ((JavaFXProject)p).getFOSourceRoots();
StringBuffer src = new StringBuffer();
String className = null;
for (FileObject srcRoot : srcRoots) {
if (src.length() > 0) src.append(';');
src.append(FileUtil.toFile(srcRoot).getAbsolutePath());
if (FileUtil.isParentOf(srcRoot, f)) {
className = FileUtil.getRelativePath(srcRoot, f);
className = className.substring(0, className.length() - 3).replace('/', '.');
}
}
String cp = ev.getProperty("javac.classpath"); //NOI18N
cp = cp == null ? "" : cp.trim();
String enc = ev.getProperty("source.encoding"); //NOI18N
if (enc == null || enc.trim().length() == 0) enc = "UTF-8"; //NOI18N
File basedir = FileUtil.toFile(p.getProjectDirectory());
File build = PropertyUtils.resolveFile(basedir, "build/compiled"); //NOI18N
ArrayList<String> args = new ArrayList<String>();
args.add(fxHome + "/bin/javafxc" + (Utilities.isWindows() ? ".exe" : "")); //NOI18N
args.add("-cp"); //NOI18N
args.add(build.getAbsolutePath() + File.pathSeparator + cp);
args.add("-sourcepath"); //NOI18N
args.add(src.toString());
args.add("-d"); //NOI18N
args.add(build.getAbsolutePath());
args.add("-encoding"); //NOI18N
args.add(enc.trim());
args.add(FileUtil.toFile(f).getAbsolutePath());
try {
build.mkdirs();
log.info(args.toString());
synchronized (JavaFXPreviewTopComponent.this) {
pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir);
}
if (log.isLoggable(Level.INFO)) {
ByteArrayOutputStream err = new ByteArrayOutputStream();
InputStream in = pr.getErrorStream();
try {
FileUtil.copy(in, err);
} catch (IOException e) {
log.severe(e.getLocalizedMessage());
} finally {
try {
in.close();
} catch (IOException e) {}
}
log.info(err.toString());
}
pr.waitFor();
String jvmargs = ev.getProperty("run.jvmargs"); //NOI18N
String appargs = ev.getProperty("application.args"); //NOI18N
if (pr.exitValue() == 0) {
args = new ArrayList<String>();
args.add(fxHome + "/bin/javafx" + (Utilities.isWindows() ? ".exe" : "")); //NOI18N
args.add("-javaagent:" + previewLib.getAbsolutePath());//NOI18N
args.add("-Xbootclasspath/p:" + previewLib.getAbsolutePath());//NOI18N
args.add("-Dcom.apple.backgroundOnly=true"); //NOI18N
- if (jvmargs != null) for (String ja : jvmargs.trim().split("\\s+")) args.add(ja); //NOI18N
+ if (jvmargs != null) for (String ja : jvmargs.trim().split("\\s+")) if (ja.length()>0) args.add(ja); //NOI18N
args.add("-cp"); //NOI18N
- args.add(build.getAbsolutePath() + File.pathSeparator + cp); //NOI18N
+ args.add(src.toString() + File.pathSeparator + build.getAbsolutePath() + File.pathSeparator + cp); //NOI18N
args.add(className);
if (appargs != null) for (String aa : appargs.trim().split("\\s+")) args.add(aa); //NOI18N
log.info(args.toString());
synchronized (JavaFXPreviewTopComponent.this) {
pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir);
}
if (log.isLoggable(Level.INFO)) {
RequestProcessor.getDefault().execute(new Runnable() {
public void run() {
ByteArrayOutputStream err = new ByteArrayOutputStream();
InputStream in = pr.getErrorStream();
try {
final byte[] BUFFER = new byte[4096];
int len;
while (pr != null && timer > 0) {
while ((len = in.available()) > 0) {
len = in.read(BUFFER, 0, BUFFER.length > len ? len : BUFFER.length);
err.write(BUFFER, 0, len);
}
Thread.sleep(50);
}
} catch (IOException e) {
log.severe(e.getLocalizedMessage());
} catch (InterruptedException ie) {
} finally {
try {
in.close();
} catch (IOException e) {}
}
log.info(err.toString());
}
});
}
InputStream in = pr.getInputStream();
timer = 200;
while (timer-- > 0 && in.available() == 0) Thread.sleep(50);
if (in.available() > 0) bi = ImageIO.read(in);
}
} catch (Exception ex) {
//ignore
} finally {
synchronized (JavaFXPreviewTopComponent.this) {
pr.destroy();
pr = null;
}
}
}
}
}
}
repaint();
}
});
@Override
public void paintComponent(Graphics g) {
BufferedImage b = bi;
if (b != null) g.drawImage(b, 0, 0, null);
else {
g.clearRect(0, 0, getWidth(), getHeight());
String noPreview = NbBundle.getMessage(JavaFXPreviewTopComponent.class, "MSG_NoPreview"); //NOI18N
Rectangle2D r = g.getFontMetrics().getStringBounds(noPreview, g);
g.drawString(noPreview, (getWidth()-(int)r.getWidth())/2, (getHeight()-(int)r.getHeight())/2);
}
}
private JavaFXPreviewTopComponent() {
initComponents();
setName(NbBundle.getMessage(JavaFXPreviewTopComponent.class, "CTL_JavaFXPreviewTopComponent")); //NOI18N
setToolTipText(NbBundle.getMessage(JavaFXPreviewTopComponent.class, "HINT_JavaFXPreviewTopComponent")); //NOI18N
// setIcon(Utilities.loadImage(ICON_PATH, true));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setLayout(new java.awt.BorderLayout());
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
/**
* Gets default instance. Do not use directly: reserved for *.settings files only,
* i.e. deserialization routines; otherwise you could get a non-deserialized instance.
* To obtain the singleton instance, use {@link #findInstance}.
*/
public static synchronized JavaFXPreviewTopComponent getDefault() {
if (instance == null) {
instance = new JavaFXPreviewTopComponent();
}
return instance;
}
/**
* Obtain the JavaFXPreviewTopComponent instance. Never call {@link #getDefault} directly!
*/
public static synchronized JavaFXPreviewTopComponent findInstance() {
TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
if (win == null) {
Logger.getLogger(JavaFXPreviewTopComponent.class.getName()).warning("Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system."); //NOI18N
return getDefault();
}
if (win instanceof JavaFXPreviewTopComponent) {
return (JavaFXPreviewTopComponent) win;
}
Logger.getLogger(JavaFXPreviewTopComponent.class.getName()).warning("There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior."); //NOI18N
return getDefault();
}
@Override
public int getPersistenceType() {
return TopComponent.PERSISTENCE_ALWAYS;
}
@Override
public void componentOpened() {
TopComponent.getRegistry().addPropertyChangeListener(this);
task.schedule(150);
}
@Override
public void componentClosed() {
TopComponent.getRegistry().removePropertyChangeListener(this);
}
public void propertyChange(PropertyChangeEvent ev) {
if (TopComponent.Registry.PROP_ACTIVATED_NODES.equals(ev.getPropertyName()) || DataObject.PROP_MODIFIED.equals(ev.getPropertyName())) {
task.schedule(150);
}
}
/** replaces this in object stream */
@Override
public Object writeReplace() {
return new ResolvableHelper();
}
@Override
protected String preferredID() {
return PREFERRED_ID;
}
final static class ResolvableHelper implements Serializable {
private static final long serialVersionUID = 1L;
public Object readResolve() {
return JavaFXPreviewTopComponent.getDefault();
}
}
}
| false | true | public void run() {
synchronized (JavaFXPreviewTopComponent.this) {
if (pr != null) {
pr.destroy();
timer = 0;
task.schedule(150);
return;
}
}
if (oldD != null) {
oldD.removePropertyChangeListener(JavaFXPreviewTopComponent.this);
oldD = null;
}
Node[] sel = TopComponent.getRegistry().getActivatedNodes();
if (sel.length == 1) {
DataObject d = sel[0].getLookup().lookup(DataObject.class);
if (d != null) {
FileObject f = d.getPrimaryFile();
if (f.isData()) bi = null;
if ("fx".equals(f.getExt())) { //NOI18N
d.addPropertyChangeListener(JavaFXPreviewTopComponent.this);
oldD = d;
Project p = FileOwnerQuery.getOwner(f);
if (p instanceof JavaFXProject) {
PropertyEvaluator ev = ((JavaFXProject)p).evaluator();
FileObject srcRoots[] = ((JavaFXProject)p).getFOSourceRoots();
StringBuffer src = new StringBuffer();
String className = null;
for (FileObject srcRoot : srcRoots) {
if (src.length() > 0) src.append(';');
src.append(FileUtil.toFile(srcRoot).getAbsolutePath());
if (FileUtil.isParentOf(srcRoot, f)) {
className = FileUtil.getRelativePath(srcRoot, f);
className = className.substring(0, className.length() - 3).replace('/', '.');
}
}
String cp = ev.getProperty("javac.classpath"); //NOI18N
cp = cp == null ? "" : cp.trim();
String enc = ev.getProperty("source.encoding"); //NOI18N
if (enc == null || enc.trim().length() == 0) enc = "UTF-8"; //NOI18N
File basedir = FileUtil.toFile(p.getProjectDirectory());
File build = PropertyUtils.resolveFile(basedir, "build/compiled"); //NOI18N
ArrayList<String> args = new ArrayList<String>();
args.add(fxHome + "/bin/javafxc" + (Utilities.isWindows() ? ".exe" : "")); //NOI18N
args.add("-cp"); //NOI18N
args.add(build.getAbsolutePath() + File.pathSeparator + cp);
args.add("-sourcepath"); //NOI18N
args.add(src.toString());
args.add("-d"); //NOI18N
args.add(build.getAbsolutePath());
args.add("-encoding"); //NOI18N
args.add(enc.trim());
args.add(FileUtil.toFile(f).getAbsolutePath());
try {
build.mkdirs();
log.info(args.toString());
synchronized (JavaFXPreviewTopComponent.this) {
pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir);
}
if (log.isLoggable(Level.INFO)) {
ByteArrayOutputStream err = new ByteArrayOutputStream();
InputStream in = pr.getErrorStream();
try {
FileUtil.copy(in, err);
} catch (IOException e) {
log.severe(e.getLocalizedMessage());
} finally {
try {
in.close();
} catch (IOException e) {}
}
log.info(err.toString());
}
pr.waitFor();
String jvmargs = ev.getProperty("run.jvmargs"); //NOI18N
String appargs = ev.getProperty("application.args"); //NOI18N
if (pr.exitValue() == 0) {
args = new ArrayList<String>();
args.add(fxHome + "/bin/javafx" + (Utilities.isWindows() ? ".exe" : "")); //NOI18N
args.add("-javaagent:" + previewLib.getAbsolutePath());//NOI18N
args.add("-Xbootclasspath/p:" + previewLib.getAbsolutePath());//NOI18N
args.add("-Dcom.apple.backgroundOnly=true"); //NOI18N
if (jvmargs != null) for (String ja : jvmargs.trim().split("\\s+")) args.add(ja); //NOI18N
args.add("-cp"); //NOI18N
args.add(build.getAbsolutePath() + File.pathSeparator + cp); //NOI18N
args.add(className);
if (appargs != null) for (String aa : appargs.trim().split("\\s+")) args.add(aa); //NOI18N
log.info(args.toString());
synchronized (JavaFXPreviewTopComponent.this) {
pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir);
}
if (log.isLoggable(Level.INFO)) {
RequestProcessor.getDefault().execute(new Runnable() {
public void run() {
ByteArrayOutputStream err = new ByteArrayOutputStream();
InputStream in = pr.getErrorStream();
try {
final byte[] BUFFER = new byte[4096];
int len;
while (pr != null && timer > 0) {
while ((len = in.available()) > 0) {
len = in.read(BUFFER, 0, BUFFER.length > len ? len : BUFFER.length);
err.write(BUFFER, 0, len);
}
Thread.sleep(50);
}
} catch (IOException e) {
log.severe(e.getLocalizedMessage());
} catch (InterruptedException ie) {
} finally {
try {
in.close();
} catch (IOException e) {}
}
log.info(err.toString());
}
});
}
InputStream in = pr.getInputStream();
timer = 200;
while (timer-- > 0 && in.available() == 0) Thread.sleep(50);
if (in.available() > 0) bi = ImageIO.read(in);
}
} catch (Exception ex) {
//ignore
} finally {
synchronized (JavaFXPreviewTopComponent.this) {
pr.destroy();
pr = null;
}
}
}
}
}
}
repaint();
}
| public void run() {
synchronized (JavaFXPreviewTopComponent.this) {
if (pr != null) {
pr.destroy();
timer = 0;
task.schedule(150);
return;
}
}
if (oldD != null) {
oldD.removePropertyChangeListener(JavaFXPreviewTopComponent.this);
oldD = null;
}
Node[] sel = TopComponent.getRegistry().getActivatedNodes();
if (sel.length == 1) {
DataObject d = sel[0].getLookup().lookup(DataObject.class);
if (d != null) {
FileObject f = d.getPrimaryFile();
if (f.isData()) bi = null;
if ("fx".equals(f.getExt())) { //NOI18N
d.addPropertyChangeListener(JavaFXPreviewTopComponent.this);
oldD = d;
Project p = FileOwnerQuery.getOwner(f);
if (p instanceof JavaFXProject) {
PropertyEvaluator ev = ((JavaFXProject)p).evaluator();
FileObject srcRoots[] = ((JavaFXProject)p).getFOSourceRoots();
StringBuffer src = new StringBuffer();
String className = null;
for (FileObject srcRoot : srcRoots) {
if (src.length() > 0) src.append(';');
src.append(FileUtil.toFile(srcRoot).getAbsolutePath());
if (FileUtil.isParentOf(srcRoot, f)) {
className = FileUtil.getRelativePath(srcRoot, f);
className = className.substring(0, className.length() - 3).replace('/', '.');
}
}
String cp = ev.getProperty("javac.classpath"); //NOI18N
cp = cp == null ? "" : cp.trim();
String enc = ev.getProperty("source.encoding"); //NOI18N
if (enc == null || enc.trim().length() == 0) enc = "UTF-8"; //NOI18N
File basedir = FileUtil.toFile(p.getProjectDirectory());
File build = PropertyUtils.resolveFile(basedir, "build/compiled"); //NOI18N
ArrayList<String> args = new ArrayList<String>();
args.add(fxHome + "/bin/javafxc" + (Utilities.isWindows() ? ".exe" : "")); //NOI18N
args.add("-cp"); //NOI18N
args.add(build.getAbsolutePath() + File.pathSeparator + cp);
args.add("-sourcepath"); //NOI18N
args.add(src.toString());
args.add("-d"); //NOI18N
args.add(build.getAbsolutePath());
args.add("-encoding"); //NOI18N
args.add(enc.trim());
args.add(FileUtil.toFile(f).getAbsolutePath());
try {
build.mkdirs();
log.info(args.toString());
synchronized (JavaFXPreviewTopComponent.this) {
pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir);
}
if (log.isLoggable(Level.INFO)) {
ByteArrayOutputStream err = new ByteArrayOutputStream();
InputStream in = pr.getErrorStream();
try {
FileUtil.copy(in, err);
} catch (IOException e) {
log.severe(e.getLocalizedMessage());
} finally {
try {
in.close();
} catch (IOException e) {}
}
log.info(err.toString());
}
pr.waitFor();
String jvmargs = ev.getProperty("run.jvmargs"); //NOI18N
String appargs = ev.getProperty("application.args"); //NOI18N
if (pr.exitValue() == 0) {
args = new ArrayList<String>();
args.add(fxHome + "/bin/javafx" + (Utilities.isWindows() ? ".exe" : "")); //NOI18N
args.add("-javaagent:" + previewLib.getAbsolutePath());//NOI18N
args.add("-Xbootclasspath/p:" + previewLib.getAbsolutePath());//NOI18N
args.add("-Dcom.apple.backgroundOnly=true"); //NOI18N
if (jvmargs != null) for (String ja : jvmargs.trim().split("\\s+")) if (ja.length()>0) args.add(ja); //NOI18N
args.add("-cp"); //NOI18N
args.add(src.toString() + File.pathSeparator + build.getAbsolutePath() + File.pathSeparator + cp); //NOI18N
args.add(className);
if (appargs != null) for (String aa : appargs.trim().split("\\s+")) args.add(aa); //NOI18N
log.info(args.toString());
synchronized (JavaFXPreviewTopComponent.this) {
pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir);
}
if (log.isLoggable(Level.INFO)) {
RequestProcessor.getDefault().execute(new Runnable() {
public void run() {
ByteArrayOutputStream err = new ByteArrayOutputStream();
InputStream in = pr.getErrorStream();
try {
final byte[] BUFFER = new byte[4096];
int len;
while (pr != null && timer > 0) {
while ((len = in.available()) > 0) {
len = in.read(BUFFER, 0, BUFFER.length > len ? len : BUFFER.length);
err.write(BUFFER, 0, len);
}
Thread.sleep(50);
}
} catch (IOException e) {
log.severe(e.getLocalizedMessage());
} catch (InterruptedException ie) {
} finally {
try {
in.close();
} catch (IOException e) {}
}
log.info(err.toString());
}
});
}
InputStream in = pr.getInputStream();
timer = 200;
while (timer-- > 0 && in.available() == 0) Thread.sleep(50);
if (in.available() > 0) bi = ImageIO.read(in);
}
} catch (Exception ex) {
//ignore
} finally {
synchronized (JavaFXPreviewTopComponent.this) {
pr.destroy();
pr = null;
}
}
}
}
}
}
repaint();
}
|
diff --git a/src/net/sf/gogui/tools/convert/Main.java b/src/net/sf/gogui/tools/convert/Main.java
index 24f3c345..b8cfc99a 100644
--- a/src/net/sf/gogui/tools/convert/Main.java
+++ b/src/net/sf/gogui/tools/convert/Main.java
@@ -1,130 +1,131 @@
//----------------------------------------------------------------------------
// Main.java
//----------------------------------------------------------------------------
package net.sf.gogui.tools.convert;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Locale;
import net.sf.gogui.game.ConstGameTree;
import net.sf.gogui.gamefile.GameReader;
import net.sf.gogui.sgf.SgfWriter;
import net.sf.gogui.tex.TexWriter;
import net.sf.gogui.util.FileUtil;
import net.sf.gogui.util.Options;
import net.sf.gogui.util.StringUtil;
import net.sf.gogui.version.Version;
import net.sf.gogui.xml.XmlWriter;
/** Convert SGF and Jago XML Go game files to other formats. */
public final class Main
{
/** Main function. */
public static void main(String[] args)
{
try
{
String options[] = {
"check",
"config:",
"force",
"format:",
"help",
"title:",
"version",
"werror"
};
Options opt = Options.parse(args, options);
if (opt.contains("help"))
{
printUsage(System.out);
System.exit(0);
}
if (opt.contains("version"))
{
System.out.println("GoGuiConvert " + Version.get());
System.exit(0);
}
boolean force = opt.contains("force");
String title = opt.get("title", "");
boolean werror = opt.contains("werror");
boolean checkOnly = opt.contains("check");
ArrayList<String> arguments = opt.getArguments();
if (! (arguments.size() == 2
|| (arguments.size() == 1 && checkOnly)))
{
printUsage(System.err);
System.exit(1);
}
File in = new File(arguments.get(0));
File out = null;
String format = null;
if (! checkOnly)
{
out = new File(arguments.get(1));
if (opt.contains("format"))
format = opt.get("format");
else
format =
FileUtil.getExtension(out).toLowerCase(Locale.ENGLISH);
if (! format.equals("sgf")
&& ! format.equals("tex")
&& ! format.equals("xml"))
throw new Exception("Unknown format");
if (out.exists() && ! force)
throw new Exception("File \"" + out + "\" already exists");
}
if (! in.exists())
throw new Exception("File \"" + in + "\" not found");
GameReader reader = new GameReader(in);
ConstGameTree tree = reader.getTree();
String warnings = reader.getWarnings();
if (warnings != null)
{
System.err.println(warnings);
- System.exit(1);
+ if (werror)
+ System.exit(1);
}
if (! checkOnly)
{
String version = Version.get();
if (format.equals("xml"))
new XmlWriter(new FileOutputStream(out), tree,
"GoGuiConvert:" + version);
else if (format.equals("sgf"))
new SgfWriter(new FileOutputStream(out), tree,
"GoGuiConvert", version);
else if (format.equals("tex"))
new TexWriter(title, new FileOutputStream(out), tree);
else
assert false; // checked above
}
}
catch (Throwable t)
{
StringUtil.printException(t);
System.exit(1);
}
}
/** Make constructor unavailable; class is for namespace only. */
private Main()
{
}
private static void printUsage(PrintStream out)
{
out.print("Usage: gogui-convert infile outfile\n" +
"\n" +
"-check only check reading a file\n" +
"-config config file\n" +
"-force overwrite existing files\n" +
"-format output format (sgf,tex,xml)\n" +
"-help display this help and exit\n" +
"-title use title\n" +
"-version print version and exit\n" +
"-werror handle read warnings as errors\n");
}
}
| true | true | public static void main(String[] args)
{
try
{
String options[] = {
"check",
"config:",
"force",
"format:",
"help",
"title:",
"version",
"werror"
};
Options opt = Options.parse(args, options);
if (opt.contains("help"))
{
printUsage(System.out);
System.exit(0);
}
if (opt.contains("version"))
{
System.out.println("GoGuiConvert " + Version.get());
System.exit(0);
}
boolean force = opt.contains("force");
String title = opt.get("title", "");
boolean werror = opt.contains("werror");
boolean checkOnly = opt.contains("check");
ArrayList<String> arguments = opt.getArguments();
if (! (arguments.size() == 2
|| (arguments.size() == 1 && checkOnly)))
{
printUsage(System.err);
System.exit(1);
}
File in = new File(arguments.get(0));
File out = null;
String format = null;
if (! checkOnly)
{
out = new File(arguments.get(1));
if (opt.contains("format"))
format = opt.get("format");
else
format =
FileUtil.getExtension(out).toLowerCase(Locale.ENGLISH);
if (! format.equals("sgf")
&& ! format.equals("tex")
&& ! format.equals("xml"))
throw new Exception("Unknown format");
if (out.exists() && ! force)
throw new Exception("File \"" + out + "\" already exists");
}
if (! in.exists())
throw new Exception("File \"" + in + "\" not found");
GameReader reader = new GameReader(in);
ConstGameTree tree = reader.getTree();
String warnings = reader.getWarnings();
if (warnings != null)
{
System.err.println(warnings);
System.exit(1);
}
if (! checkOnly)
{
String version = Version.get();
if (format.equals("xml"))
new XmlWriter(new FileOutputStream(out), tree,
"GoGuiConvert:" + version);
else if (format.equals("sgf"))
new SgfWriter(new FileOutputStream(out), tree,
"GoGuiConvert", version);
else if (format.equals("tex"))
new TexWriter(title, new FileOutputStream(out), tree);
else
assert false; // checked above
}
}
catch (Throwable t)
{
StringUtil.printException(t);
System.exit(1);
}
}
| public static void main(String[] args)
{
try
{
String options[] = {
"check",
"config:",
"force",
"format:",
"help",
"title:",
"version",
"werror"
};
Options opt = Options.parse(args, options);
if (opt.contains("help"))
{
printUsage(System.out);
System.exit(0);
}
if (opt.contains("version"))
{
System.out.println("GoGuiConvert " + Version.get());
System.exit(0);
}
boolean force = opt.contains("force");
String title = opt.get("title", "");
boolean werror = opt.contains("werror");
boolean checkOnly = opt.contains("check");
ArrayList<String> arguments = opt.getArguments();
if (! (arguments.size() == 2
|| (arguments.size() == 1 && checkOnly)))
{
printUsage(System.err);
System.exit(1);
}
File in = new File(arguments.get(0));
File out = null;
String format = null;
if (! checkOnly)
{
out = new File(arguments.get(1));
if (opt.contains("format"))
format = opt.get("format");
else
format =
FileUtil.getExtension(out).toLowerCase(Locale.ENGLISH);
if (! format.equals("sgf")
&& ! format.equals("tex")
&& ! format.equals("xml"))
throw new Exception("Unknown format");
if (out.exists() && ! force)
throw new Exception("File \"" + out + "\" already exists");
}
if (! in.exists())
throw new Exception("File \"" + in + "\" not found");
GameReader reader = new GameReader(in);
ConstGameTree tree = reader.getTree();
String warnings = reader.getWarnings();
if (warnings != null)
{
System.err.println(warnings);
if (werror)
System.exit(1);
}
if (! checkOnly)
{
String version = Version.get();
if (format.equals("xml"))
new XmlWriter(new FileOutputStream(out), tree,
"GoGuiConvert:" + version);
else if (format.equals("sgf"))
new SgfWriter(new FileOutputStream(out), tree,
"GoGuiConvert", version);
else if (format.equals("tex"))
new TexWriter(title, new FileOutputStream(out), tree);
else
assert false; // checked above
}
}
catch (Throwable t)
{
StringUtil.printException(t);
System.exit(1);
}
}
|
diff --git a/src/main/java/edu/msergey/jalg/sorting/QuickSortInPlace.java b/src/main/java/edu/msergey/jalg/sorting/QuickSortInPlace.java
index 4dda681..c0676fc 100644
--- a/src/main/java/edu/msergey/jalg/sorting/QuickSortInPlace.java
+++ b/src/main/java/edu/msergey/jalg/sorting/QuickSortInPlace.java
@@ -1,43 +1,39 @@
package edu.msergey.jalg.sorting;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* In place quick sort with efficent memory use.
* Pivot is 1st element.
*/
public class QuickSortInPlace<E extends Comparable> extends SortWithProfiling<E> {
public QuickSortInPlace(E[] data) {
super(data);
}
@Override
public E[] sort() {
sort(data, 0, data.length - 1);
return data;
}
private void sort(E[] a, int l, int r) {
- if (r - l <= 0) return;
+ if (r <= l) return;
E pivot = a[l];
int j = l + 1;
- for (int i = l + 1; i < r; i++) {
+ for (int i = l + 1; i <= r; i++) {
if (a[i].compareTo(pivot) < 0) {
+ exchange(i, j);
j++;
- E temp = a[i];
- a[i] = a[j];
- a[j] = temp;
}
}
- E temp = a[j-1];
- a[j-1] = a[l];
- a[l] = temp;
+ exchange(j-1, l);
sort(a, l, j-1);
sort(a, j, r);
}
}
| false | true | private void sort(E[] a, int l, int r) {
if (r - l <= 0) return;
E pivot = a[l];
int j = l + 1;
for (int i = l + 1; i < r; i++) {
if (a[i].compareTo(pivot) < 0) {
j++;
E temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
E temp = a[j-1];
a[j-1] = a[l];
a[l] = temp;
sort(a, l, j-1);
sort(a, j, r);
}
| private void sort(E[] a, int l, int r) {
if (r <= l) return;
E pivot = a[l];
int j = l + 1;
for (int i = l + 1; i <= r; i++) {
if (a[i].compareTo(pivot) < 0) {
exchange(i, j);
j++;
}
}
exchange(j-1, l);
sort(a, l, j-1);
sort(a, j, r);
}
|
diff --git a/mes-plugins/mes-plugins-production-scheduling/src/main/java/com/qcadoo/mes/productionScheduling/OrderRealizationTimeServiceImpl.java b/mes-plugins/mes-plugins-production-scheduling/src/main/java/com/qcadoo/mes/productionScheduling/OrderRealizationTimeServiceImpl.java
index b4676bcb46..63d58a5a5f 100644
--- a/mes-plugins/mes-plugins-production-scheduling/src/main/java/com/qcadoo/mes/productionScheduling/OrderRealizationTimeServiceImpl.java
+++ b/mes-plugins/mes-plugins-production-scheduling/src/main/java/com/qcadoo/mes/productionScheduling/OrderRealizationTimeServiceImpl.java
@@ -1,167 +1,167 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 0.4.10
*
* This file is part of Qcadoo.
*
* Qcadoo is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.productionScheduling;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.qcadoo.localization.api.utils.DateUtils;
import com.qcadoo.mes.basic.ShiftsServiceImpl;
import com.qcadoo.model.api.EntityTreeNode;
import com.qcadoo.view.api.ComponentState;
import com.qcadoo.view.api.ViewDefinitionState;
import com.qcadoo.view.api.components.FieldComponent;
@Service
public class OrderRealizationTimeServiceImpl implements OrderRealizationTimeService {
private static final String OPERATION_NODE_ENTITY_TYPE = "operation";
@Autowired
private ShiftsServiceImpl shiftsService;
@Override
public void changeDateFrom(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args) {
if (!(state instanceof FieldComponent)) {
return;
}
FieldComponent dateTo = (FieldComponent) state;
FieldComponent dateFrom = (FieldComponent) viewDefinitionState.getComponentByReference("dateFrom");
FieldComponent realizationTime = (FieldComponent) viewDefinitionState.getComponentByReference("realizationTime");
if (StringUtils.hasText((String) dateTo.getFieldValue()) && !StringUtils.hasText((String) dateFrom.getFieldValue())) {
Date date = shiftsService.findDateFromForOrder(getDateFromField(dateTo.getFieldValue()),
Integer.valueOf((String) realizationTime.getFieldValue()));
if (date != null) {
dateFrom.setFieldValue(setDateToField(date));
}
}
}
@Override
public void changeDateTo(final ViewDefinitionState viewDefinitionState, final ComponentState state, final String[] args) {
if (!(state instanceof FieldComponent)) {
return;
}
FieldComponent dateFrom = (FieldComponent) state;
FieldComponent dateTo = (FieldComponent) viewDefinitionState.getComponentByReference("dateTo");
FieldComponent realizationTime = (FieldComponent) viewDefinitionState.getComponentByReference("realizationTime");
if (!StringUtils.hasText((String) dateTo.getFieldValue()) && StringUtils.hasText((String) dateFrom.getFieldValue())) {
Date date = shiftsService.findDateToForOrder(getDateFromField(dateFrom.getFieldValue()),
Integer.valueOf((String) realizationTime.getFieldValue()));
if (date != null) {
dateTo.setFieldValue(setDateToField(date));
}
}
}
@Override
public Object setDateToField(final Date date) {
return new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT, Locale.getDefault()).format(date);
}
@Override
public Date getDateFromField(final Object value) {
try {
return new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT, Locale.getDefault()).parse((String) value);
} catch (ParseException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
@Transactional
public int estimateRealizationTimeForOperation(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity) {
return estimateRealizationTimeForOperation(operationComponent, plannedQuantity, true);
}
@Override
@Transactional
public int estimateRealizationTimeForOperation(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity,
Boolean includeTpz) {
- if (operationComponent.getField("entityType") == null
- && OPERATION_NODE_ENTITY_TYPE.equals(operationComponent.getField("entityType"))) {
+ if (operationComponent.getField("entityType") != null
+ && !OPERATION_NODE_ENTITY_TYPE.equals(operationComponent.getField("entityType"))) {
+ return estimateRealizationTimeForOperation(
+ operationComponent.getBelongsToField("referenceTechnology").getTreeField("operationComponents").getRoot(),
+ plannedQuantity);
+ } else {
int operationTime = 0;
int pathTime = 0;
for (EntityTreeNode child : operationComponent.getChildren()) {
int tmpPathTime = estimateRealizationTimeForOperation(child, plannedQuantity);
if (tmpPathTime > pathTime) {
pathTime = tmpPathTime;
}
}
BigDecimal productionInOneCycle = (BigDecimal) operationComponent.getField("productionInOneCycle");
BigDecimal roundUp = plannedQuantity.divide(productionInOneCycle, BigDecimal.ROUND_UP);
if ("01all".equals(operationComponent.getField("countRealized"))
|| operationComponent.getBelongsToField("parent") == null) {
operationTime = (roundUp.multiply(BigDecimal.valueOf(getIntegerValue(operationComponent.getField("tj")))))
.intValue();
} else {
operationTime = ((operationComponent.getField("countMachine") == null ? BigDecimal.ZERO
: (BigDecimal) operationComponent.getField("countMachine")).multiply(BigDecimal
.valueOf(getIntegerValue(operationComponent.getField("tj"))))).intValue();
}
if (includeTpz) {
operationTime += getIntegerValue(operationComponent.getField("tpz"));
}
if ("orderOperationComponent".equals(operationComponent.getDataDefinition().getName())) {
operationComponent.setField("effectiveOperationRealizationTime", operationTime);
operationComponent.setField("operationOffSet", pathTime);
operationComponent.getDataDefinition().save(operationComponent);
}
pathTime += operationTime + getIntegerValue(operationComponent.getField("timeNextOperation"));
return pathTime;
- } else {
- return estimateRealizationTimeForOperation(
- operationComponent.getBelongsToField("referenceTechnology").getTreeField("operationComponents").getRoot(),
- plannedQuantity);
}
}
private Integer getIntegerValue(final Object value) {
return value == null ? Integer.valueOf(0) : (Integer) value;
}
@Override
public BigDecimal getBigDecimalFromField(final Object value, final Locale locale) {
try {
DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(locale);
format.setParseBigDecimal(true);
return new BigDecimal(format.parse(value.toString()).doubleValue());
} catch (ParseException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
| false | true | public int estimateRealizationTimeForOperation(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity,
Boolean includeTpz) {
if (operationComponent.getField("entityType") == null
&& OPERATION_NODE_ENTITY_TYPE.equals(operationComponent.getField("entityType"))) {
int operationTime = 0;
int pathTime = 0;
for (EntityTreeNode child : operationComponent.getChildren()) {
int tmpPathTime = estimateRealizationTimeForOperation(child, plannedQuantity);
if (tmpPathTime > pathTime) {
pathTime = tmpPathTime;
}
}
BigDecimal productionInOneCycle = (BigDecimal) operationComponent.getField("productionInOneCycle");
BigDecimal roundUp = plannedQuantity.divide(productionInOneCycle, BigDecimal.ROUND_UP);
if ("01all".equals(operationComponent.getField("countRealized"))
|| operationComponent.getBelongsToField("parent") == null) {
operationTime = (roundUp.multiply(BigDecimal.valueOf(getIntegerValue(operationComponent.getField("tj")))))
.intValue();
} else {
operationTime = ((operationComponent.getField("countMachine") == null ? BigDecimal.ZERO
: (BigDecimal) operationComponent.getField("countMachine")).multiply(BigDecimal
.valueOf(getIntegerValue(operationComponent.getField("tj"))))).intValue();
}
if (includeTpz) {
operationTime += getIntegerValue(operationComponent.getField("tpz"));
}
if ("orderOperationComponent".equals(operationComponent.getDataDefinition().getName())) {
operationComponent.setField("effectiveOperationRealizationTime", operationTime);
operationComponent.setField("operationOffSet", pathTime);
operationComponent.getDataDefinition().save(operationComponent);
}
pathTime += operationTime + getIntegerValue(operationComponent.getField("timeNextOperation"));
return pathTime;
} else {
return estimateRealizationTimeForOperation(
operationComponent.getBelongsToField("referenceTechnology").getTreeField("operationComponents").getRoot(),
plannedQuantity);
}
}
| public int estimateRealizationTimeForOperation(final EntityTreeNode operationComponent, final BigDecimal plannedQuantity,
Boolean includeTpz) {
if (operationComponent.getField("entityType") != null
&& !OPERATION_NODE_ENTITY_TYPE.equals(operationComponent.getField("entityType"))) {
return estimateRealizationTimeForOperation(
operationComponent.getBelongsToField("referenceTechnology").getTreeField("operationComponents").getRoot(),
plannedQuantity);
} else {
int operationTime = 0;
int pathTime = 0;
for (EntityTreeNode child : operationComponent.getChildren()) {
int tmpPathTime = estimateRealizationTimeForOperation(child, plannedQuantity);
if (tmpPathTime > pathTime) {
pathTime = tmpPathTime;
}
}
BigDecimal productionInOneCycle = (BigDecimal) operationComponent.getField("productionInOneCycle");
BigDecimal roundUp = plannedQuantity.divide(productionInOneCycle, BigDecimal.ROUND_UP);
if ("01all".equals(operationComponent.getField("countRealized"))
|| operationComponent.getBelongsToField("parent") == null) {
operationTime = (roundUp.multiply(BigDecimal.valueOf(getIntegerValue(operationComponent.getField("tj")))))
.intValue();
} else {
operationTime = ((operationComponent.getField("countMachine") == null ? BigDecimal.ZERO
: (BigDecimal) operationComponent.getField("countMachine")).multiply(BigDecimal
.valueOf(getIntegerValue(operationComponent.getField("tj"))))).intValue();
}
if (includeTpz) {
operationTime += getIntegerValue(operationComponent.getField("tpz"));
}
if ("orderOperationComponent".equals(operationComponent.getDataDefinition().getName())) {
operationComponent.setField("effectiveOperationRealizationTime", operationTime);
operationComponent.setField("operationOffSet", pathTime);
operationComponent.getDataDefinition().save(operationComponent);
}
pathTime += operationTime + getIntegerValue(operationComponent.getField("timeNextOperation"));
return pathTime;
}
}
|
diff --git a/backend/src/main/java/com/gooddata/integration/rest/GdcRESTApiWrapper.java b/backend/src/main/java/com/gooddata/integration/rest/GdcRESTApiWrapper.java
index 984414ef..ba7245f6 100644
--- a/backend/src/main/java/com/gooddata/integration/rest/GdcRESTApiWrapper.java
+++ b/backend/src/main/java/com/gooddata/integration/rest/GdcRESTApiWrapper.java
@@ -1,2214 +1,2222 @@
/*
* Copyright (c) 2009, GoodData Corporation. 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 GoodData Corporation nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gooddata.integration.rest;
import com.gooddata.exception.*;
import com.gooddata.integration.model.Column;
import com.gooddata.integration.model.Project;
import com.gooddata.integration.model.SLI;
import com.gooddata.integration.rest.configuration.NamePasswordConfiguration;
import com.gooddata.util.FileUtil;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.cookie.MalformedCookieException;
import org.apache.commons.httpclient.cookie.RFC2109Spec;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The GoodData REST API Java wrapper.
*
* @author Zdenek Svoboda <[email protected]>
* @version 1.0
*/
public class GdcRESTApiWrapper {
private static Logger l = Logger.getLogger(GdcRESTApiWrapper.class);
/**
* GDC URIs
*/
private static final String MD_URI = "/gdc/md/";
private static final String QUERY_URI = "/query/";
private static final String LOGIN_URI = "/gdc/account/login";
private static final String TOKEN_URI = "/gdc/account/token";
private static final String DATA_INTERFACES_URI = "/ldm/singleloadinterface";
private static final String PROJECTS_URI = "/gdc/projects";
private static final String PULL_URI = "/etl/pull";
private static final String IDENTIFIER_URI = "/identifiers";
private static final String SLI_DESCRIPTOR_URI = "/descriptor";
public static final String MAQL_EXEC_URI = "/ldm/manage";
public static final String REPORT_QUERY = "/query/reports";
public static final String EXECUTOR = "/gdc/xtab2/executor3";
public static final String INVITATION_URI = "/invitations";
public static final String OBJ_URI = "/obj";
public static final String VARIABLES_SEARCH_URI = "/variables/search";
public static final String VARIABLES_CREATE_URI = "/variables/item";
public static final String OBJ_TYPE_FILTER = "filtres";
public static final String OBJ_TYPE_METRIC = "metrics";
public static final String OBJ_TYPE_REPORT = "reports";
public static final String OBJ_TYPE_REPORT_DEFINITION = "reportdefinition";
public static final String OBJ_TYPE_FACT = "facts";
public static final String OBJ_TYPE_FOLDER = "folders";
public static final String OBJ_TYPE_ATTRIBUTE = "attributes";
public static final String OBJ_TYPE_DIMENSION = "dimensions";
public static final String OBJ_TYPE_DATASET = "datasets";
public static final String OBJ_TYPE_VARIABLE = "prompts";
public static final String OBJ_TYPE_DASHBOARD = "projectdashboards";
public static final String OBJ_TYPE_DOMAIN = "domains";
public static final String DLI_MANIFEST_FILENAME = "upload_info.json";
protected HttpClient client;
protected NamePasswordConfiguration config;
private String ssToken;
private JSONObject profile;
private static HashMap<String,Integer> ROLES = new HashMap<String,Integer>();
private static final CookieSpec COOKIE_SPEC = new RFC2109Spec();
/* TODO This is fragile and may not work for all projects and/or future versions.
* Use /gdc/projects/{projectId}/roles to retrieve roles for a particular project.
*/
static {
ROLES.put("ADMIN",new Integer(1));
ROLES.put("EDITOR",new Integer(2));
ROLES.put("DASHBOARD ONLY",new Integer(3));
}
/**
* Constructs the GoodData REST API Java wrapper
*
* @param config NamePasswordConfiguration object with the GDC name and password configuration
*/
public GdcRESTApiWrapper(NamePasswordConfiguration config) {
this.config = config;
client = new HttpClient();
final String proxyHost = System.getProperty("http.proxyHost");
final int proxyPort = System.getProperty("http.proxyPort") == null
? 8080 : Integer.parseInt(System.getProperty("http.proxyPort"));
if (proxyHost != null) {
client.getHostConfiguration().setProxy(proxyHost,proxyPort);
}
}
/**
* GDC login - obtain GDC SSToken
*
* @return the new SS token
* @throws GdcLoginException
*/
public String login() throws GdcLoginException {
l.debug("Logging into GoodData.");
JSONObject loginStructure = getLoginStructure();
PostMethod loginPost = createPostMethod(getServerUrl() + LOGIN_URI);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(loginStructure.toString().getBytes()));
loginPost.setRequestEntity(request);
try {
String resp = executeMethodOk(loginPost, false); // do not re-login on SC_UNAUTHORIZED
// read SST from cookie
ssToken = extractCookie(loginPost, "GDCAuthSST");
setTokenCookie();
l.debug("Succesfully logged into GoodData.");
JSONObject rsp = JSONObject.fromObject(resp);
JSONObject userLogin = rsp.getJSONObject("userLogin");
String profileUri = userLogin.getString("profile");
if(profileUri != null && profileUri.length()>0) {
GetMethod gm = createGetMethod(getServerUrl() + profileUri);
resp = executeMethodOk(gm);
this.profile = JSONObject.fromObject(resp);
}
else {
l.debug("Empty account profile.");
throw new GdcRestApiException("Empty account profile.");
}
return ssToken;
} catch (HttpMethodException ex) {
l.debug("Error logging into GoodData.", ex);
throw new GdcLoginException("Login to GDC failed.", ex);
} finally {
loginPost.releaseConnection();
}
}
/**
* Creates a new login JSON structure
*
* @return the login JSON structure
*/
private JSONObject getLoginStructure() {
JSONObject credentialsStructure = new JSONObject();
credentialsStructure.put("login", config.getUsername());
credentialsStructure.put("password", config.getPassword());
credentialsStructure.put("remember", 1);
JSONObject loginStructure = new JSONObject();
loginStructure.put("postUserLogin", credentialsStructure);
return loginStructure;
}
private String extractCookie(HttpMethod method, String cookieName) {
for (final Header cookieHeader : method.getResponseHeaders("Set-Cookie")) {
try {
final Cookie[] cookies = COOKIE_SPEC.parse(
config.getGdcHost(),
"https".equals(config.getProtocol()) ? 443 : 80,
"/", // force all cookie paths to be accepted
"https".equals(config.getProtocol()),
cookieHeader);
for (final Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return cookie.getValue();
}
}
} catch (MalformedCookieException e) {
l.warn("Ignoring malformed cookie: " + e.getMessage());
l.debug("Ignoring malformed cookie", e);
}
}
throw new GdcRestApiException(cookieName + " cookie not found in the response to "
+ method.getName() + " to " + method.getPath());
}
/**
* Sets the SS token
*
* @throws GdcLoginException
*/
private void setTokenCookie() throws GdcLoginException {
HttpMethod secutityTokenGet = createGetMethod(getServerUrl() + TOKEN_URI);
// set SSToken from config
Cookie sstCookie = new Cookie(config.getGdcHost(), "GDCAuthSST", ssToken, TOKEN_URI, -1, false);
sstCookie.setPathAttributeSpecified(true);
client.getState().addCookie(sstCookie);
try {
executeMethodOk(secutityTokenGet, false);
} catch (HttpMethodException ex) {
l.debug("Cannot login to:" + getServerUrl() + TOKEN_URI + ".",ex);
throw new GdcLoginException("Cannot login to:" + getServerUrl() + TOKEN_URI + ".",ex);
} finally {
secutityTokenGet.releaseConnection();
}
}
/**
* Retrieves the project info by the project's name
*
* @param name the project name
* @return the GoodDataProjectInfo populated with the project's information
* @throws HttpMethodException
* @throws GdcProjectAccessException
*/
public Project getProjectByName(String name) throws HttpMethodException, GdcProjectAccessException {
l.debug("Getting project by name="+name);
for (Iterator<JSONObject> linksIter = getProjectsLinks(); linksIter.hasNext();) {
JSONObject link = (JSONObject) linksIter.next();
String cat = link.getString("category");
if (!"project".equalsIgnoreCase(cat)) {
continue;
}
String title = link.getString("title");
if (title.equals(name)) {
Project proj = new Project(link);
l.debug("Got project by name="+name);
return proj;
}
}
l.debug("The project name=" + name + " doesn't exists.");
throw new GdcProjectAccessException("The project name=" + name + " doesn't exists.");
}
/**
* Retrieves the project info by the project's ID
*
* @param id the project id
* @return the GoodDataProjectInfo populated with the project's information
* @throws HttpMethodException
* @throws GdcProjectAccessException
*/
public Project getProjectById(String id) throws HttpMethodException, GdcProjectAccessException {
l.debug("Getting project by id="+id);
for (Iterator<JSONObject> linksIter = getProjectsLinks(); linksIter.hasNext();) {
JSONObject link = (JSONObject) linksIter.next();
String cat = link.getString("category");
if (!"project".equalsIgnoreCase(cat)) {
continue;
}
String name = link.getString("identifier");
if (name.equals(id)) {
Project proj = new Project(link);
l.debug("Got project by id="+id);
return proj;
}
}
l.debug("The project id=" + id + " doesn't exists.");
throw new GdcProjectAccessException("The project id=" + id + " doesn't exists.");
}
/**
* Returns the existing projects links
*
* @return accessible projects links
* @throws com.gooddata.exception.HttpMethodException
*/
@SuppressWarnings("unchecked")
private Iterator<JSONObject> getProjectsLinks() throws HttpMethodException {
l.debug("Getting project links.");
HttpMethod req = createGetMethod(getServerUrl() + MD_URI);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
JSONObject about = parsedResp.getJSONObject("about");
JSONArray links = about.getJSONArray("links");
l.debug("Got project links "+links);
return links.iterator();
}
finally {
req.releaseConnection();
}
}
/**
* Returns the List of GoodDataProjectInfo structures for the accessible projects
*
* @return the List of GoodDataProjectInfo structures for the accessible projects
* @throws HttpMethodException
*/
public List<Project> listProjects() throws HttpMethodException {
l.debug("Listing projects.");
List<Project> list = new ArrayList<Project>();
for (Iterator<JSONObject> linksIter = getProjectsLinks(); linksIter.hasNext();) {
JSONObject link = linksIter.next();
String cat = link.getString("category");
if (!"project".equalsIgnoreCase(cat)) {
continue;
}
Project proj = new Project(link);
list.add(proj);
}
l.debug("Found projects "+list);
return list;
}
/**
* Returns a list of project's SLIs
*
* @param projectId project's ID
* @return a list of project's SLIs
* @throws HttpMethodException if there is a communication error
* @throws GdcProjectAccessException if the SLI doesn't exist
*/
public List<SLI> getSLIs(String projectId) throws HttpMethodException, GdcProjectAccessException {
l.debug("Getting SLIs from project id="+projectId);
List<SLI> list = new ArrayList<SLI>();
String ifcUri = getSLIsUri(projectId);
HttpMethod interfacesGet = createGetMethod(ifcUri);
try {
String response = executeMethodOk(interfacesGet);
JSONObject responseObject = JSONObject.fromObject(response);
if (responseObject.isNullObject()) {
l.debug("The project id=" + projectId + " doesn't exist!");
throw new GdcProjectAccessException("The project id=" + projectId + " doesn't exist!");
}
JSONObject interfaceQuery = responseObject.getJSONObject("about");
if (interfaceQuery.isNullObject()) {
l.debug("The project id=" + projectId + " doesn't exist!");
throw new GdcProjectAccessException("The project id=" + projectId + " doesn't exist!");
}
JSONArray links = interfaceQuery.getJSONArray("links");
if (links == null) {
l.debug("The project id=" + projectId + " doesn't exist!");
throw new GdcProjectAccessException("The project id=" + projectId + " doesn't exist!");
}
for (Object ol : links) {
JSONObject link = (JSONObject) ol;
SLI ii = new SLI(link);
list.add(ii);
}
l.debug("Got SLIs "+list+" from project id="+projectId);
}
finally {
interfacesGet.releaseConnection();
}
return list;
}
/**
* Retrieves the SLI columns
*
* @param uri the SLI uri
* @return list of SLI columns
* @throws GdcProjectAccessException if the SLI doesn't exist
* @throws HttpMethodException if there is a communication issue with the GDC platform
*/
public List<Column> getSLIColumns(String uri) throws GdcProjectAccessException, HttpMethodException {
l.debug("Retrieveing SLI columns for SLI uri="+uri);
List<Column> list = new ArrayList<Column>();
HttpMethod sliGet = createGetMethod(getServerUrl() + uri + "/manifest");
try {
String response = executeMethodOk(sliGet);
JSONObject responseObject = JSONObject.fromObject(response);
if (responseObject.isNullObject()) {
l.debug("The SLI uri=" + uri + " doesn't exist!");
throw new GdcProjectAccessException("The SLI uri=" + uri + " doesn't exist!");
}
JSONObject dataSetSLIManifest = responseObject.getJSONObject("dataSetSLIManifest");
if (dataSetSLIManifest.isNullObject()) {
l.debug("The SLI uri=" + uri + " doesn't exist!");
throw new GdcProjectAccessException("The SLI uri=" + uri + " doesn't exist!");
}
JSONArray parts = dataSetSLIManifest.getJSONArray("parts");
for(Object oPart : parts) {
list.add(new Column((JSONObject)oPart));
}
}
finally {
sliGet.releaseConnection();
}
return list;
}
/**
* Retrieves the SLI column data type
*
* @param projectId projectId
* @param sliColumnIdentifier SLI column identifier (name in the SLI manifest)
* @return the SLI column datatype
*/
public String getSLIColumnDataType(String projectId, String sliColumnIdentifier) {
l.debug("Retrieveing SLI column datatype projectId="+projectId+" SLI column name="+sliColumnIdentifier);
MetadataObject o = getMetadataObject(projectId, sliColumnIdentifier);
if(o!=null) {
JSONObject c = o.getContent();
if(c != null) {
String type = c.getString("columnType");
if(type != null && type.length() > 0) {
return type;
}
else {
l.debug("Error Retrieveing SLI column datatype projectId="+projectId+" SLI column name="+sliColumnIdentifier+" No columnType key in the content.");
throw new GdcRestApiException("Error Retrieveing SLI column datatype projectId="+projectId+" SLI column name="+sliColumnIdentifier+" No columnType key in the content.");
}
}
else {
l.debug("Error Retrieveing SLI column datatype projectId="+projectId+" SLI column name="+sliColumnIdentifier+" No content structure.");
throw new GdcRestApiException("Error Retrieveing SLI column datatype projectId="+projectId+" SLI column name="+sliColumnIdentifier+" No content structure.");
}
}
else {
l.debug("Error Retrieveing SLI column datatype projectId="+projectId+" SLI column name="+sliColumnIdentifier+" MD object doesn't exist.");
throw new GdcRestApiException("Error Retrieveing SLI column datatype projectId="+projectId+" SLI column name="+sliColumnIdentifier+" MD object doesn't exist.");
}
}
/**
* Retrieves the SLI columns
*
* @param uri the SLI uri
* @return JSON manifest
* @throws GdcProjectAccessException if the SLI doesn't exist
* @throws HttpMethodException if there is a communication issue with the GDC platform
*/
public JSONObject getSLIManifest(String uri) throws GdcProjectAccessException, HttpMethodException {
l.debug("Retrieveing SLI columns for SLI uri="+uri);
List<Column> list = new ArrayList<Column>();
HttpMethod sliGet = createGetMethod(getServerUrl() + uri + "/manifest");
try {
String response = executeMethodOk(sliGet);
JSONObject responseObject = JSONObject.fromObject(response);
if (responseObject.isNullObject()) {
l.debug("The SLI uri=" + uri + " doesn't exist!");
throw new GdcProjectAccessException("The SLI uri=" + uri + " doesn't exist!");
}
return responseObject;
}
finally {
sliGet.releaseConnection();
}
}
/**
* Finds a project SLI by it's name
*
* @param name the SLI name
* @param projectId the project id
* @return the SLI
* @throws GdcProjectAccessException if the SLI doesn't exist
* @throws HttpMethodException if there is a communication issue with the GDC platform
*/
public SLI getSLIByName(String name, String projectId) throws GdcProjectAccessException, HttpMethodException {
l.debug("Get SLI by name="+name+" project id="+projectId);
List<SLI> slis = getSLIs(projectId);
for (SLI sli : slis) {
if (name.equals(sli.getName())) {
l.debug("Got SLI by name="+name+" project id="+projectId);
return sli;
}
}
l.debug("The SLI name=" + name + " doesn't exist in the project id="+projectId);
throw new GdcProjectAccessException("The SLI name=" + name + " doesn't exist in the project id="+projectId);
}
/**
* Finds a project SLI by it's id
*
* @param id the SLI id
* @param projectId the project id
* @return the SLI
* @throws GdcProjectAccessException if the SLI doesn't exist
* @throws HttpMethodException if there is a communication issue with the GDC platform
*/
public SLI getSLIById(String id, String projectId) throws GdcProjectAccessException, HttpMethodException {
l.debug("Get SLI by id="+id+" project id="+projectId);
List<SLI> slis = getSLIs(projectId);
for (SLI sli : slis) {
if (id.equals(sli.getId())) {
l.debug("Got SLI by id="+id+" project id="+projectId);
return sli;
}
}
l.debug("The SLI id=" + id+ " doesn't exist in the project id="+projectId);
throw new GdcProjectAccessException("The SLI id=" + id+ " doesn't exist in the project id="+projectId);
}
public String getToken() {
return ssToken;
}
/**
* Enumerates all reports on in a project
* @param projectId project Id
* @return LIst of report uris
*/
public List<String> enumerateReports(String projectId) {
l.debug("Enumerating reports for project id="+projectId);
List<String> list = new ArrayList<String>();
String qUri = getProjectMdUrl(projectId) + REPORT_QUERY;
HttpMethod qGet = createGetMethod(qUri);
try {
String qr = executeMethodOk(qGet);
JSONObject q = JSONObject.fromObject(qr);
if (q.isNullObject()) {
l.debug("Enumerating reports for project id="+projectId+" failed.");
throw new GdcProjectAccessException("Enumerating reports for project id="+projectId+" failed.");
}
JSONObject qry = q.getJSONObject("query");
if (qry.isNullObject()) {
l.debug("Enumerating reports for project id="+projectId+" failed.");
throw new GdcProjectAccessException("Enumerating reports for project id="+projectId+" failed.");
}
JSONArray entries = qry.getJSONArray("entries");
if (entries == null) {
l.debug("Enumerating reports for project id="+projectId+" failed.");
throw new GdcProjectAccessException("Enumerating reports for project id="+projectId+" failed.");
}
for(Object oentry : entries) {
JSONObject entry = (JSONObject)oentry;
int deprecated = entry.getInt("deprecated");
if(deprecated == 0)
list.add(entry.getString("link"));
}
}
finally {
qGet.releaseConnection();
}
return list;
}
/**
* Gets a report definition from the report uri (/gdc/obj...)
* @param reportUri report uri (/gdc/obj...)
* @return report definition
*/
public String getReportDefinition(String reportUri) {
HttpMethod qGet = null;
try {
l.debug("Getting report definition for report uri="+reportUri);
String qUri = getServerUrl() + reportUri;
qGet = createGetMethod(qUri);
String qr = executeMethodOk(qGet);
JSONObject q = JSONObject.fromObject(qr);
if (q.isNullObject()) {
l.debug("Error getting report definition for report uri="+reportUri);
throw new GdcProjectAccessException("Error getting report definition for report uri="+reportUri);
}
JSONObject report = q.getJSONObject("report");
if (report.isNullObject()) {
l.debug("Error getting report definition for report uri="+reportUri);
throw new GdcProjectAccessException("Error getting report definition for report uri="+reportUri);
}
JSONObject content = report.getJSONObject("content");
if (content.isNullObject()) {
l.debug("Error getting report definition for report uri="+reportUri);
throw new GdcProjectAccessException("Error getting report definition for report uri="+reportUri);
}
JSONArray results = content.getJSONArray("results");
if (results == null) {
l.debug("Error getting report definition for report uri="+reportUri);
throw new GdcProjectAccessException("Error getting report definition for report uri="+reportUri);
}
if(results.size()>0) {
String lastResultUri = results.getString(results.size()-1);
qUri = getServerUrl() + lastResultUri;
qGet = createGetMethod(qUri);
qr = executeMethodOk(qGet);
q = JSONObject.fromObject(qr);
if (q.isNullObject()) {
l.debug("Error getting report definition for result uri="+lastResultUri);
throw new GdcProjectAccessException("Error getting report definition for result uri="+lastResultUri);
}
JSONObject result = q.getJSONObject("reportResult2");
if (result.isNullObject()) {
l.debug("Error getting report definition for result uri="+lastResultUri);
throw new GdcProjectAccessException("Error getting report definition for result uri="+lastResultUri);
}
content = result.getJSONObject("content");
if (result.isNullObject()) {
l.debug("Error getting report definition for result uri="+lastResultUri);
throw new GdcProjectAccessException("Error getting report definition for result uri="+lastResultUri);
}
return content.getString("reportDefinition");
}
// Here we haven't found any results. Let's try the defaultReportDefinition
if(content.containsKey("defaultReportDefinition")) {
String defaultRepDef = content.getString("defaultReportDefinition");
if(defaultRepDef != null && defaultRepDef.length() > 0)
return defaultRepDef;
}
l.debug("Error getting report definition for report uri="+reportUri+" . No report results!");
throw new GdcProjectAccessException("Error getting report definition for report uri="+reportUri+
" . No report results!");
}
finally {
if(qGet != null)
qGet.releaseConnection();
}
}
private String getProjectIdFromObjectUri(String uri) {
Pattern regexp = Pattern.compile("gdc/md/.*?/");
Matcher m = regexp.matcher(uri);
if(m.find()) {
return m.group().split("/")[2];
}
else {
l.debug("The passed string '"+uri+"' doesn't have the GoodData URI structure!");
throw new InvalidParameterException("The passed string '"+uri+"' doesn't have the GoodData URI structure!");
}
}
/**
* Computes the metric value
* @param metricUri metric URI
* @return the metric value
*/
public double computeMetric(String metricUri) {
l.debug("Computing metric uri="+metricUri);
double retVal = 0;
String projectId = getProjectIdFromObjectUri(metricUri);
JSONObject reportDefinition = new JSONObject();
JSONObject metric = new JSONObject();
metric.put("alias", "");
metric.put("uri", metricUri);
JSONArray metrics = new JSONArray();
metrics.add(metric);
JSONArray columns = new JSONArray();
columns.add("metricGroup");
JSONObject grid = new JSONObject();
grid.put("metrics", metrics);
grid.put("columns", columns);
grid.put("rows",new JSONArray());
grid.put("columnWidths",new JSONArray());
JSONObject sort = new JSONObject();
sort.put("columns",new JSONArray());
sort.put("rows",new JSONArray());
grid.put("sort", sort);
JSONObject content = new JSONObject();
content.put("grid", grid);
content.put("filters",new JSONArray());
reportDefinition.put("content", content);
JSONObject meta = new JSONObject();
meta.put("category","reportDefinition");
meta.put("title", "N/A");
reportDefinition.put("meta", meta);
MetadataObject obj = new MetadataObject();
obj.put("reportDefinition", reportDefinition);
MetadataObject resp = new MetadataObject(createMetadataObject(projectId, obj));
String dataResultUri = executeReportDefinition(resp.getUri());
JSONObject result = getObjectByUri(dataResultUri);
if(result != null && !result.isEmpty() && !result.isNullObject()) {
JSONObject xtabData = result.getJSONObject("xtab_data");
if(xtabData != null && !xtabData.isEmpty() && !xtabData.isNullObject()) {
JSONArray data = xtabData.getJSONArray("data");
if(data != null && !data.isEmpty()) {
retVal = data.getJSONArray(0).getDouble(0);
}
else {
l.debug("Can't compute the metric. No data structure in result.");
throw new InvalidParameterException("Can't compute the metric. No data structure in result.");
}
}
else {
l.debug("Can't compute the metric. No xtab_data structure in result.");
throw new InvalidParameterException("Can't compute the metric. No xtab_data structure in result.");
}
}
else {
l.debug("Can't compute the metric. No result from XTAB.");
throw new InvalidParameterException("Can't compute the metric. No result from XTAB.");
}
l.debug("Metric uri="+metricUri+ " computed. Result is "+retVal);
return retVal;
}
/**
* Report definition to execute
* @param reportDefUri report definition to execute
*/
public String executeReportDefinition(String reportDefUri) {
l.debug("Executing report definition uri="+reportDefUri);
PostMethod execPost = createPostMethod(getServerUrl() + EXECUTOR);
JSONObject execDef = new JSONObject();
execDef.put("reportDefinition",reportDefUri);
JSONObject exec = new JSONObject();
exec.put("report_req", execDef);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(exec.toString().getBytes()));
execPost.setRequestEntity(request);
String taskLink = null;
try {
String task = executeMethodOk(execPost);
if(task != null && task.length()>0) {
JSONObject tr = JSONObject.fromObject(task);
if(tr.isNullObject()) {
l.debug("Executing report definition uri="+reportDefUri + " failed. Returned invalid result result="+tr);
throw new GdcRestApiException("Executing report definition uri="+reportDefUri + " failed. " +
"Returned invalid result result="+tr);
}
JSONObject reportResult = tr.getJSONObject("reportResult2");
if(reportResult.isNullObject()) {
l.debug("Executing report definition uri="+reportDefUri + " failed. Returned invalid result result="+tr);
throw new GdcRestApiException("Executing report definition uri="+reportDefUri + " failed. " +
"Returned invalid result result="+tr);
}
JSONObject content = reportResult.getJSONObject("content");
if(content.isNullObject()) {
l.debug("Executing report definition uri="+reportDefUri + " failed. Returned invalid result result="+tr);
throw new GdcRestApiException("Executing report definition uri="+reportDefUri + " failed. " +
"Returned invalid result result="+tr);
}
return content.getString("dataResult");
}
else {
l.debug("Executing report definition uri="+reportDefUri + " failed. Returned invalid task link uri="+task);
throw new GdcRestApiException("Executing report definition uri="+reportDefUri +
" failed. Returned invalid task link uri="+task);
}
} catch (HttpMethodException ex) {
l.debug("Executing report definition uri="+reportDefUri + " failed.", ex);
throw new GdcRestApiException("Executing report definition uri="+reportDefUri + " failed.");
} finally {
execPost.releaseConnection();
}
}
/**
* Kicks the GDC platform to inform it that the FTP transfer is finished.
*
* @param projectId the project's ID
* @param remoteDir the remote (FTP) directory that contains the data
* @return the link that is used for polling the loading progress
* @throws GdcRestApiException
*/
public String startLoading(String projectId, String remoteDir) throws GdcRestApiException {
l.debug("Initiating data load project id="+projectId+" remoteDir="+remoteDir);
PostMethod pullPost = createPostMethod(getProjectMdUrl(projectId) + PULL_URI);
JSONObject pullStructure = getPullStructure(remoteDir);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(pullStructure.toString().getBytes()));
pullPost.setRequestEntity(request);
String taskLink = null;
try {
String response = executeMethodOk(pullPost);
JSONObject responseObject = JSONObject.fromObject(response);
taskLink = responseObject.getJSONObject("pullTask").getString("uri");
} catch (HttpMethodException ex) {
throw new GdcRestApiException("Loading fails: " + ex.getMessage());
} finally {
pullPost.releaseConnection();
}
l.debug("Data load project id="+projectId+" remoteDir="+remoteDir+" initiated. Status is on uri="+taskLink);
return taskLink;
}
/**
* Returns the pull API JSON structure
*
* @param directory the remote directory
* @return the pull API JSON structure
*/
private JSONObject getPullStructure(String directory) {
JSONObject pullStructure = new JSONObject();
pullStructure.put("pullIntegration", directory);
return pullStructure;
}
/**
* Checks if the loading is finished
*
* @param link the link returned from the start loading
* @return the loading status
*/
public String getLoadingStatus(String link) throws HttpMethodException {
l.debug("Getting data loading status uri="+link);
HttpMethod ptm = createGetMethod(getServerUrl() + link);
try {
String response = executeMethodOk(ptm);
JSONObject task = JSONObject.fromObject(response);
String status = task.getString("taskStatus");
l.debug("Loading status="+status);
return status;
}
finally {
ptm.releaseConnection();
}
}
/**
* Create a new GoodData project
*
* @param name project name
* @param desc project description
* @param templateUri project template uri
* @return the project Id
* @throws GdcRestApiException
*/
public String createProject(String name, String desc, String templateUri) throws GdcRestApiException {
l.debug("Creating project name="+name);
PostMethod createProjectPost = createPostMethod(getServerUrl() + PROJECTS_URI);
JSONObject createProjectStructure = getCreateProject(name, desc, templateUri);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
createProjectStructure.toString().getBytes()));
createProjectPost.setRequestEntity(request);
String uri = null;
try {
String response = executeMethodOk(createProjectPost);
JSONObject responseObject = JSONObject.fromObject(response);
uri = responseObject.getString("uri");
} catch (HttpMethodException ex) {
l.debug("Creating project fails: ",ex);
throw new GdcRestApiException("Creating project fails: ",ex);
} finally {
createProjectPost.releaseConnection();
}
if(uri != null && uri.length() > 0) {
String id = getProjectId(uri);
l.debug("Created project id="+id);
return id;
}
l.debug("Error creating project.");
throw new GdcRestApiException("Error creating project.");
}
/**
* Returns the create project JSON structure
*
* @param name project name
* @param desc project description
* @param templateUri project template uri
* @return the create project JSON structure
*/
private JSONObject getCreateProject(String name, String desc, String templateUri) {
JSONObject meta = new JSONObject();
meta.put("title", name);
meta.put("summary", desc);
if(templateUri != null && templateUri.length() > 0) {
meta.put("projectTemplate", templateUri);
}
JSONObject content = new JSONObject();
//content.put("state", "ENABLED");
content.put("guidedNavigation","1");
JSONObject project = new JSONObject();
project.put("meta", meta);
project.put("content", content);
JSONObject createStructure = new JSONObject();
createStructure.put("project", project);
return createStructure;
}
/**
* Returns the project status
* @param projectId project ID
* @return current project status
*/
public String getProjectStatus(String projectId) {
l.debug("Getting project status for project "+projectId);
String uri = getProjectDeleteUri(projectId);
HttpMethod ptm = createGetMethod(getServerUrl() + uri);
try {
String response = executeMethodOk(ptm);
JSONObject jresp = JSONObject.fromObject(response);
JSONObject project = jresp.getJSONObject("project");
JSONObject content = project.getJSONObject("content");
String status = content.getString("state");
l.debug("Project "+projectId+" status="+status);
return status;
}
finally {
ptm.releaseConnection();
}
}
/**
* Drops a GoodData project
*
* @param projectId project id
* @throws GdcRestApiException
*/
public void dropProject(String projectId) throws GdcRestApiException {
l.debug("Dropping project id="+projectId);
DeleteMethod dropProjectDelete = createDeleteMethod(getServerUrl() + getProjectDeleteUri(projectId));
try {
executeMethodOk(dropProjectDelete);
} catch (HttpMethodException ex) {
l.debug("Dropping project id="+projectId + " failed.",ex);
throw new GdcRestApiException("Dropping project id="+projectId + " failed.",ex);
} finally {
dropProjectDelete.releaseConnection();
}
l.debug("Dropped project id="+projectId);
}
/**
* Retrieves the project id from the URI returned by the create project
* @param uri the create project URI
* @return project id
* @throws GdcRestApiException in case the project doesn't exist
*/
protected String getProjectId(String uri) throws GdcRestApiException {
l.debug("Getting project id by uri="+uri);
HttpMethod req = createGetMethod(getServerUrl() + uri);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
if(parsedResp.isNullObject()) {
l.debug("Can't get project from "+uri);
throw new GdcRestApiException("Can't get project from "+uri);
}
JSONObject project = parsedResp.getJSONObject("project");
if(project.isNullObject()) {
l.debug("Can't get project from "+uri);
throw new GdcRestApiException("Can't get project from "+uri);
}
JSONObject links = project.getJSONObject("links");
if(links.isNullObject()) {
l.debug("Can't get project from "+uri);
throw new GdcRestApiException("Can't get project from "+uri);
}
String mdUrl = links.getString("metadata");
if(mdUrl != null && mdUrl.length()>0) {
String[] cs = mdUrl.split("/");
if(cs != null && cs.length > 0) {
l.debug("Got project id="+cs[cs.length -1]+" by uri="+uri);
return cs[cs.length -1];
}
}
l.debug("Can't get project from "+uri);
throw new GdcRestApiException("Can't get project from "+uri);
}
finally {
req.releaseConnection();
}
}
/**
* Executes the MAQL and creates/modifies the project's LDM
*
* @param projectId the project's ID
* @param maql String with the MAQL statements
* @return result String
* @throws GdcRestApiException
*/
public String[] executeMAQL(String projectId, String maql) throws GdcRestApiException {
l.debug("Executing MAQL projectId="+projectId+" MAQL:\n"+maql);
PostMethod maqlPost = createPostMethod(getProjectMdUrl(projectId) + MAQL_EXEC_URI);
JSONObject maqlStructure = getMAQLExecStructure(maql);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
maqlStructure.toString().getBytes()));
maqlPost.setRequestEntity(request);
String result = null;
try {
String response = executeMethodOk(maqlPost);
JSONObject responseObject = JSONObject.fromObject(response);
JSONArray uris = responseObject.getJSONArray("uris");
return (String[])uris.toArray(new String[]{""});
} catch (HttpMethodException ex) {
l.debug("MAQL execution: ",ex);
throw new GdcRestApiException("MAQL execution: ",ex);
} finally {
maqlPost.releaseConnection();
}
}
/**
* Returns the pull API JSON structure
*
* @param maql String with the MAQL statements
* @return the MAQL API JSON structure
*/
private JSONObject getMAQLExecStructure(String maql) {
JSONObject maqlStructure = new JSONObject();
JSONObject maqlObj = new JSONObject();
maqlObj.put("maql", maql);
maqlStructure.put("manage", maqlObj);
return maqlStructure;
}
/**
* Executes HttpMethod and test if the response if 200(OK)
*
* @param method the HTTP method
* @return response body as String
* @throws HttpMethodException
*/
protected String executeMethodOk(HttpMethod method) throws HttpMethodException {
return executeMethodOk(method, true);
}
/**
* Executes HttpMethod and test if the response if 200(OK)
*
* @param method the HTTP method
* @param reLoginOn401 flag saying whether we should call login() and retry on
* @return response body as String
* @throws HttpMethodException
*/
private String executeMethodOk(HttpMethod method, boolean reLoginOn401) throws HttpMethodException {
if (reLoginOn401) {
setTokenCookie();
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
return method.getResponseBodyAsString();
} else if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED && reLoginOn401) {
// refresh the temporary token
setTokenCookie();
return executeMethodOk(method, false);
} else if (method.getStatusCode() == HttpStatus.SC_CREATED) {
return method.getResponseBodyAsString();
} else if (method.getStatusCode() == HttpStatus.SC_ACCEPTED) {
throw new HttpMethodNotFinishedYetException(method.getResponseBodyAsString());
} else if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
throw new HttpMethodNoContentException(method.getResponseBodyAsString());
} else {
String msg = method.getStatusCode() + " " + method.getStatusText();
String body = method.getResponseBodyAsString();
if (body != null) {
msg += ": ";
try {
JSONObject parsedBody = JSONObject.fromObject(body);
msg += parsedBody.toString();
} catch (JSONException jsone) {
msg += body;
}
}
l.debug("Exception executing " + method.getName() + " on " + method.getPath() + ": " + msg);
throw new HttpMethodException("Exception executing " + method.getName() + " on " + method.getPath() + ": " + msg);
}
} catch (HttpException e) {
l.debug("Error invoking GoodData REST API.",e);
throw new HttpMethodException("Error invoking GoodData REST API.",e);
} catch (IOException e) {
l.debug("Error invoking GoodData REST API.",e);
throw new HttpMethodException("Error invoking GoodData REST API.",e);
}
}
/**
* Returns the data interfaces URI
*
* @param projectId project ID
* @return SLI collection URI
*/
public String getSLIsUri(String projectId) {
return getProjectMdUrl(projectId) + DATA_INTERFACES_URI;
}
/**
* Returns the SLI URI
*
* @param sliId SLI ID
* @param projectId project ID
* @return DLI URI
*/
public String getSLIUri(String sliId, String projectId) {
return getProjectMdUrl(projectId) + DATA_INTERFACES_URI + "/" + sliId + SLI_DESCRIPTOR_URI;
}
protected String getServerUrl() {
return config.getUrl();
}
/**
* Constructs project's metadata uri
*
* @param projectId project ID
*/
protected String getProjectMdUrl(String projectId) {
return getServerUrl() + MD_URI + projectId;
}
/**
* Gets the project ID from the project URI
* @param projectUri project URI
* @return the project id
*/
public String getProjectIdFromUri(String projectUri) {
String[] cmpnts = projectUri.split("/");
if(cmpnts != null && cmpnts.length > 0) {
String id = cmpnts[cmpnts.length-1];
return id;
}
else
throw new GdcRestApiException("Invalid project uri structure uri="+projectUri);
}
/**
* Gets the project delete URI from the project id
* @param projectId project ID
* @return the project delete URI
*/
protected String getProjectDeleteUri(String projectId) {
if(profile != null) {
JSONObject as = profile.getJSONObject("accountSetting");
if(as!=null) {
JSONObject lnks = as.getJSONObject("links");
if(lnks != null) {
String projectsUri = lnks.getString("projects");
if(projectsUri != null && projectsUri.length()>0) {
HttpMethod req = createGetMethod(getServerUrl()+projectsUri);
try {
String resp = executeMethodOk(req);
JSONObject rsp = JSONObject.fromObject(resp);
if(rsp != null) {
JSONArray projects = rsp.getJSONArray("projects");
for(Object po : projects) {
JSONObject p = (JSONObject)po;
JSONObject project = p.getJSONObject("project");
if(project != null) {
JSONObject links = project.getJSONObject("links");
if(links != null) {
String uri = links.getString("metadata");
if(uri != null && uri.length() > 0) {
String id = getProjectIdFromUri(uri);
if(projectId.equals(id)) {
String sf = links.getString("self");
if(sf != null && sf.length()>0)
return sf;
}
}
else {
l.debug("Project with no metadata uri.");
throw new GdcRestApiException("Project with no metadata uri.");
}
}
else {
l.debug("Project with no links.");
throw new GdcRestApiException("Project with no links.");
}
}
else {
l.debug("No project in the project list.");
throw new GdcRestApiException("No project in the project list.");
}
}
}
else {
l.debug("Can't get project from "+projectsUri);
throw new GdcRestApiException("Can't get projects from uri="+projectsUri);
}
}
finally {
req.releaseConnection();
}
}
else {
l.debug("No projects link in the account settings.");
throw new GdcRestApiException("No projects link in the account settings.");
}
}
else {
l.debug("No links in the account settings.");
throw new GdcRestApiException("No links in the account settings.");
}
}
else {
l.debug("No account settings.");
throw new GdcRestApiException("No account settings.");
}
}
else {
l.debug("No active account profile found. Perhaps you are not connected to the GoodData anymore.");
throw new GdcRestApiException("No active account profile found. Perhaps you are not connected to the GoodData anymore.");
}
l.debug("Project "+projectId+" not found in the current account profile.");
throw new GdcRestApiException("Project "+projectId+" not found in the current account profile.");
}
/**
* Profile getter
* @return the profile of the currently logged user
*/
protected JSONObject getProfile() {
return profile;
}
/**
* Invites a new user to a project
* @param projectId project ID
* @param eMail invited user e-mail
* @param message invitation message
*/
public void inviteUser(String projectId, String eMail, String message) {
this.inviteUser(projectId, eMail, message, null);
}
/**
* Invites a new user to a project
* @param projectId project ID
* @param eMail invited user e-mail
* @param message invitation message
*/
public void inviteUser(String projectId, String eMail, String message, String role) {
l.debug("Executing inviteUser projectId="+projectId+" e-mail="+eMail+" message="+message);
PostMethod invitePost = createPostMethod(getServerUrl() + getProjectDeleteUri(projectId) + INVITATION_URI);
JSONObject inviteStructure = getInviteStructure(projectId, eMail, message, role);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
inviteStructure.toString().getBytes()));
invitePost.setRequestEntity(request);
try {
executeMethodOk(invitePost);
} catch (HttpMethodException ex) {
l.debug("Failed executing inviteUser projectId="+projectId+" e-mail="+eMail+" message="+message);
throw new GdcRestApiException("Failed executing inviteUser projectId="+projectId+" e-mail="+eMail+" message="+message,ex);
} finally {
invitePost.releaseConnection();
}
}
/**
* Creates a new invitation structure
* @param pid project id
* @param eMail e-mail
* @param msg invitation message
* @return the new invitation structure
*/
private JSONObject getInviteStructure(String pid, String eMail, String msg, String role) {
JSONObject content = new JSONObject();
content.put("firstname","");
content.put("lastname","");
content.put("email",eMail);
String puri = getServerUrl() + getProjectDeleteUri(pid);
if(role != null && role.length() > 0) {
Integer roleId = ROLES.get(role.toUpperCase());
if(roleId == null)
throw new InvalidParameterException("The role '"+role+"' is not recognized by the GoodData platform.");
content.put("role",puri+"/"+roleId);
}
JSONObject action = new JSONObject();
action.put("setMessage",msg);
content.put("action", action);
JSONObject invitation = new JSONObject();
invitation.put("content", content);
JSONObject invitations = new JSONObject();
JSONArray ia = new JSONArray();
JSONObject inve = new JSONObject();
inve.put("invitation", invitation);
ia.add(inve);
invitations.put("invitations", ia);
return invitations;
}
/**
* Converst MD identifier to uri
* @param projectId project ID
* @param identifiers MD object identifiers
* @return map identifier:uri
*/
public Map<String,String> identifierToUri(String projectId, String[] identifiers) {
l.debug("Executing identifierToUri identifier="+identifiers);
Map<String, String> result = new HashMap<String,String>();
PostMethod p = createPostMethod(getProjectMdUrl(projectId) + IDENTIFIER_URI);
JSONObject is = getIdentifiersStructure(identifiers);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
is.toString().getBytes()));
p.setRequestEntity(request);
try {
String resp = executeMethodOk(p);
JSONObject parsedResp = JSONObject.fromObject(resp);
JSONArray idents = parsedResp.getJSONArray("identifiers");
if(idents != null && !idents.isEmpty()) {
for(int i=0; i<idents.size(); i++) {
JSONObject ident = idents.getJSONObject(i);
result.put(ident.getString("identifier"), ident.getString("uri"));
}
}
} catch (HttpMethodException ex) {
l.debug("Failed executing identifierToUri identifier="+identifiers);
throw new GdcRestApiException("Failed executing identifierToUri identifier="+identifiers,ex);
} finally {
p.releaseConnection();
}
return result;
}
/**
* Creates a new identifiers structure
* @param identifiers MD object identifier
* @return the new identifiers structure
*/
private JSONObject getIdentifiersStructure(String[] identifiers) {
JSONObject identifierToUri = new JSONObject();
JSONArray ids = new JSONArray();
for(int i=0; i< identifiers.length; i++) {
ids.add(identifiers[i]);
}
identifierToUri.put("identifierToUri",ids);
return identifierToUri;
}
/**
* Retrieves a metadata object definition by Uri
* @param objectUri object uri
* @return the object to get
*/
protected JSONObject getObjectByUri(String objectUri) {
l.debug("Executing getObjectByUri uri="+objectUri);
HttpMethod req = createGetMethod(getServerUrl() + objectUri);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
if(parsedResp.isNullObject()) {
l.debug("Can't getObjectByUri object uri="+objectUri);
throw new GdcRestApiException("Can't getObjectByUri object uri="+objectUri);
}
return parsedResp;
}
finally {
req.releaseConnection();
}
}
/**
* Retrieves a metadata object definition
* @param objectUri object uri
* @return the object to get
*/
public MetadataObject getMetadataObject(String objectUri) {
l.debug("Executing getMetadataObject uri="+objectUri);
MetadataObject o = new MetadataObject(getObjectByUri(objectUri));
String tp = o.getType();
if(tp.equalsIgnoreCase("report")) {
try {
String rdf = getReportDefinition(objectUri);
JSONObject c = o.getContent();
c.put("defaultReportDefinition",rdf);
}
catch (GdcProjectAccessException e) {
l.debug("Can't extract the default report definition.");
}
}
return o;
}
/**
* Retrieves a metadata object definition
* @param projectId project id (hash)
* @param objectId object id (integer)
* @return the object to get
*/
public MetadataObject getMetadataObject(String projectId, int objectId) {
l.debug("Executing getMetadataObject id="+objectId+" on project id="+projectId);
return getMetadataObject(MD_URI + projectId + OBJ_URI + "/" + objectId);
}
/**
* Retrieves a metadata object definition
* @param projectId project id (hash)
* @param identifier object identifier
* @return the object to get
*/
public MetadataObject getMetadataObject(String projectId, String identifier) {
l.debug("Executing getObjectByIdentifier identifier="+identifier);
Map<String,String> uris = identifierToUri(projectId, new String[] {identifier});
if(uris != null && uris.size()>0) {
String uri = uris.get(identifier);
if(uri != null && uri.length()>0)
return getMetadataObject(uri);
else {
l.debug("Can't getObjectByIdentifier identifier="+identifier+" The identifier doesn't exists.");
throw new GdcRestApiException("Can't getObjectByIdentifier identifier="+identifier+" The identifier doesn't exists.");
}
}
else {
l.debug("Can't getObjectByIdentifier identifier="+identifier+" The identifier doesn't exists.");
throw new GdcRestApiException("Can't getObjectByIdentifier identifier="+identifier+" The identifier doesn't exists.");
}
}
/**
* Returns the JSON list of all project's prompt responses
* @param projectId project ID
* @return the JSON object with all variables
*/
public JSONObject getProjectVariables(String projectId) {
l.debug("Executing getProjectVariables on project id="+projectId);
PostMethod p = createPostMethod(getProjectMdUrl(projectId) + VARIABLES_SEARCH_URI);
JSONObject is = getVariableSearchStructure();
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
is.toString().getBytes()));
p.setRequestEntity(request);
try {
String resp = executeMethodOk(p);
JSONObject parsedResp = JSONObject.fromObject(resp);
return parsedResp;
} catch (HttpMethodException ex) {
l.debug("Failed executing getProjectVariables on project id="+projectId);
throw new GdcRestApiException("Failed executing getProjectVariables on project id="+projectId, ex);
} finally {
p.releaseConnection();
}
}
/**
* Stores the variable ina project
* @param projectId - project ID
* @param variable - variable JSON structure
* @return the newly created variable
*/
public JSONObject createVariable(String projectId, JSONObject variable) {
l.debug("Executing createVariable on project id="+projectId+ "variable='"+variable.toString(2)+"'");
PostMethod req = createPostMethod(getProjectMdUrl(projectId) + VARIABLES_CREATE_URI);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
variable.toString().getBytes()));
req.setRequestEntity(request);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
return parsedResp;
} catch (HttpMethodException ex) {
l.debug("Failed executing createVariable on project id="+projectId+ "content='"+variable.toString()+"'");
throw new GdcRestApiException("Failed executing createVariable on project id="+projectId+ "content='"+variable.toString()+"'",ex);
} finally {
req.releaseConnection();
}
}
/**
* Stores the variable ina project
* @param uri - variable uri
* @param variable - variable JSON structure
* @return the newly created variable
*/
public JSONObject modifyVariable(String uri, JSONObject variable) {
l.debug("Executing modifyVariable uri="+uri+ "variable='"+variable.toString(2)+"'");
PostMethod req = createPostMethod(getServerUrl() + uri);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
variable.toString().getBytes()));
req.setRequestEntity(request);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
return parsedResp;
} catch (HttpMethodException ex) {
l.debug("Failed executing modifyVariable uri="+uri+ "content='"+variable.toString()+"'");
throw new GdcRestApiException("Failed executing modifyVariable uri="+uri+ "content='"+variable.toString()+"'",ex);
} finally {
req.releaseConnection();
}
}
/**
* Returns the default variable search structure
* @return the default variable search structure
*/
private JSONObject getVariableSearchStructure() {
JSONObject srch = new JSONObject();
JSONObject variableSearch = new JSONObject();
variableSearch.put("variables", new JSONArray());
variableSearch.put("context", new JSONArray());
srch.put("variablesSearch", variableSearch);
return srch;
}
/**
* List the metadata server objects by their type
* @param projectId project ID
* @param objectType object type
* @return the list of object URIs
*/
public List<String> listMetadataObjects(String projectId, String objectType) {
ArrayList<String> ret = new ArrayList<String>();
l.debug("Executing listMetadataObjects type="+objectType+" in project id="+projectId);
HttpMethod req = createGetMethod(getProjectMdUrl(projectId) + QUERY_URI+objectType);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
if(parsedResp == null || parsedResp.isNullObject() || parsedResp.isEmpty()) {
l.debug("Can't listMetadataObjects type="+objectType+" in project id="+projectId+". Invalid response.");
throw new GdcRestApiException("Can't listMetadataObjects type="+objectType+" in project id="+projectId+". Invalid response.");
}
JSONObject query = parsedResp.getJSONObject("query");
if(query == null || query.isNullObject() || query.isEmpty()) {
l.debug("Can't listMetadataObjects type="+objectType+" in project id="+projectId+". No query key in the response.");
throw new GdcRestApiException("Can't listMetadataObjects type="+objectType+" in project id="+projectId+". No query key in the response.");
}
JSONArray entries = query.getJSONArray("entries");
if(entries == null) {
l.debug("Can't listMetadataObjects type="+objectType+" in project id="+projectId+". No entries key in the response.");
throw new GdcRestApiException("Can't listMetadataObjects type="+objectType+" in project id="+projectId+". No entries key in the response.");
}
for(Object o : entries) {
JSONObject obj = (JSONObject)o;
ret.add(obj.getString("link"));
}
return ret;
}
finally {
req.releaseConnection();
}
}
/**
* Returns the dependent objects
* @param uri the uri of the top-level object
* @return list of dependent objects
*/
public List<JSONObject> using(String uri) {
l.debug("Executing using uri="+uri);
List<JSONObject> ret = new ArrayList<JSONObject>();
//HACK!
String usedUri = uri.replace("/obj/","/using/");
HttpMethod req = createGetMethod(getServerUrl() + usedUri);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
if(parsedResp == null || parsedResp.isNullObject() || parsedResp.isEmpty()) {
l.debug("Can't call using on uri="+uri+". Invalid response.");
throw new GdcRestApiException("Can't call using on uri="+uri+". Invalid response.");
}
JSONObject using = parsedResp.getJSONObject("using");
if(using == null || using.isNullObject() || using.isEmpty()) {
l.debug("Can't call using on uri="+uri+". No using data.");
throw new GdcRestApiException("Can't call using on uri="+uri+". No using data.");
}
JSONArray nodes = using.getJSONArray("nodes");
if(nodes == null) {
l.debug("Can't call using on uri="+uri+". No nodes key in the response.");
throw new GdcRestApiException("Can't call using on uri="+uri+". No nodes key in the response.");
}
for(Object o : nodes) {
JSONObject obj = (JSONObject)o;
ret.add(obj);
}
return ret;
}
finally {
req.releaseConnection();
}
}
/**
* Returns the dependent objects
* @param uri the uri of the top-level object
* @return list of dependent objects
*/
public List<JSONObject> usedBy(String uri) {
l.debug("Executing usedby uri="+uri);
List<JSONObject> ret = new ArrayList<JSONObject>();
//HACK!
String usedUri = uri.replace("/obj/","/usedby/");
HttpMethod req = createGetMethod(getServerUrl() + usedUri);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
if(parsedResp == null || parsedResp.isNullObject() || parsedResp.isEmpty()) {
l.debug("Can't call usedby on uri="+uri+". Invalid response.");
throw new GdcRestApiException("Can't call usedby on uri="+uri+". Invalid response.");
}
JSONObject usedby = parsedResp.getJSONObject("usedby");
if(usedby == null || usedby.isNullObject() || usedby.isEmpty()) {
l.debug("Can't call usedby on uri="+uri+". No usedby data.");
throw new GdcRestApiException("Can't call usedby on uri="+uri+". No usedby data.");
}
JSONArray nodes = usedby.getJSONArray("nodes");
if(nodes == null) {
l.debug("Can't call usedby on uri="+uri+". No nodes key in the response.");
throw new GdcRestApiException("Can't call usedby on uri="+uri+". No nodes key in the response.");
}
for(Object o : nodes) {
JSONObject obj = (JSONObject)o;
ret.add(obj);
}
return ret;
}
finally {
req.releaseConnection();
}
}
private HashSet ignoredTypes = new HashSet<String>(Arrays.asList(new String[] {"column","table","tableDataLoad","dimension","reportResult","reportResult2","dataLoadingColumn"}));
/**
* Exports a MD object to disk with all dependencies
* @param uris the object uris
* @param dir the target directory
*/
public void exportMetadataObjectWithDependencies(String[] uris, String dir) throws IOException {
l.debug("Executing exportMetadataObjectWithDependencies uris="+uris+" dir="+dir);
Map<String,MetadataObject> m = getMetadataObjectWithDependencies(uris);
for(String identifier : m.keySet()) {
MetadataObject o = m.get(identifier);
String t = o.getType();
String uri = o.getUri();
String id = uri.substring(uri.lastIndexOf("/")+1);
String name = t+"."+identifier+"."+id+".gmd";
name = name.replace("..",".");
FileUtil.writeJSONToFile(o, dir+"/"+name);
}
if(uris.length > 0) {
String pid = getProjectIdFromObjectUri(uris[0]);
JSONObject o = getProjectVariables(pid);
String name = "variables."+pid+".gvr";
FileUtil.writeJSONToFile(o, dir+"/"+name);
}
}
/**
* Gets a MD object to and all its dependencies
* @param uris the object uris
* @return map of <identifier, object>
*/
public Map<String,MetadataObject> getMetadataObjectWithDependencies(String[] uris) throws IOException {
l.debug("Executing getMetadataObjectWithDependencies uris="+uris);
Map<String,MetadataObject> m = new HashMap<String,MetadataObject>();
Set<String> exported = new HashSet();
for(String uri : uris) {
l.debug("Exporting dependencies of uri="+uri);
MetadataObject o = getMetadataObject(uri);
o.stripKeysForRead();
String identifier = o.getIdentifier();
m.put(identifier, o);
List<JSONObject> dependencies = using(uri);
l.debug("There are "+dependencies.size() +" using dependencies.");
for(JSONObject d : dependencies) {
String tp = d.getString("category");
if(!ignoredTypes.contains(tp)) {
String link = d.getString("link");
l.debug("Exporting uri="+link);
if(!exported.contains(link)) {
MetadataObject od = getMetadataObject(link);
String dif = od.getIdentifier();
od.stripKeysForRead();
m.put(dif, od);
exported.add(link);
l.debug("Exported uri="+link);
}
else {
l.debug("Cache hit for uri="+link);
}
}
}
dependencies = usedBy(uri);
l.debug("There are "+dependencies.size() +" usedBy dependencies.");
for(JSONObject d : dependencies) {
String tp = d.getString("category");
if(!ignoredTypes.contains(tp)) {
String link = d.getString("link");
l.debug("Exporting uri="+link);
if(!exported.contains(link)) {
MetadataObject od = getMetadataObject(link);
String dif = od.getIdentifier();
od.stripKeysForRead();
m.put(dif, od);
exported.add(link);
l.debug("Exported uri="+link);
}
else {
l.debug("Cache hit for uri="+link);
}
}
}
}
return m;
}
/**
* Stores all MD objects to dir
* @param pid project ID
* @param dir directory
* @throws IOException
*/
public void storeMetadataObjects(String pid, String dir) throws IOException {
List<String> uris = new ArrayList<String>();
List<String> links = listMetadataObjects(pid, OBJ_TYPE_DASHBOARD);
for(String link : links) {
uris.add(link);
}
links = listMetadataObjects(pid, OBJ_TYPE_DOMAIN);
for(String link : links) {
uris.add(link);
}
links = listMetadataObjects(pid, OBJ_TYPE_REPORT);
for(String link : links) {
uris.add(link);
}
links = listMetadataObjects(pid, OBJ_TYPE_METRIC);
for(String link : links) {
uris.add(link);
}
links = listMetadataObjects(pid, OBJ_TYPE_VARIABLE);
for(String link : links) {
uris.add(link);
}
links = listMetadataObjects(pid, OBJ_TYPE_DATASET);
for(String link : links) {
uris.add(link);
}
links = listMetadataObjects(pid, OBJ_TYPE_FOLDER);
for(String link : links) {
uris.add(link);
}
links = listMetadataObjects(pid, OBJ_TYPE_ATTRIBUTE);
for(String link : links) {
uris.add(link);
}
links = listMetadataObjects(pid, OBJ_TYPE_FACT);
for(String link : links) {
uris.add(link);
}
exportMetadataObjectWithDependencies(uris.toArray(new String[] {}), dir);
}
/**
* Loads indexes for the metadata object copy/refresh
* @param dir
* @param identifiers
* @param ids
* @throws IOException
*/
protected void loadMdIndexes(String dir, Map identifiers, Map ids) throws IOException {
File d = new File(dir);
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.getName().endsWith(".gmd");
}
};
File[] mdObjects = d.listFiles(fileFilter);
for(File of : mdObjects) {
MetadataObject o = new MetadataObject(FileUtil.readJSONFromFile(of.getAbsolutePath()));
String identifier = o.getIdentifier();
String id = o.getUri();
identifiers.put(identifier, o);
ids.put(id, o);
}
}
/**
* Loads indexes for the metadata object copy/refresh
* @param dir
* @return List of variables
* @throws IOException
*/
protected List<JSONObject> loadVariables(String dir) throws IOException {
List<JSONObject> vars = new ArrayList<JSONObject>();
File d = new File(dir);
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.getName().endsWith(".gvr");
}
};
File[] mdObjects = d.listFiles(fileFilter);
for(File of : mdObjects) {
JSONObject variables = JSONObject.fromObject(FileUtil.readJSONFromFile(of.getAbsolutePath()));
vars.addAll(parseVariables(variables));
}
return vars;
}
private List<JSONObject> parseVariables(JSONObject o) throws IOException {
List<JSONObject> vars = new ArrayList<JSONObject>();
JSONArray variables = o.getJSONArray("variables");
Iterator i = variables.iterator();
while(i.hasNext()) {
vars.add((JSONObject)i.next());
}
return vars;
}
/**
* Stores all metadata objects from a specified directory and adjusts the IDs by identifiers
* Always creates new objects
* @param srcDir source objects input directory
* @param dstDir destination objects input directory
* @throws IOException
*/
public void copyMetadataObjects(final String pid, String srcDir, String dstDir, final boolean overwriteExisting) throws IOException {
final Map<String,MetadataObject> storedObjectsByIdentifier = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> storedObjectsById = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> sourceObjectsByIdentifier = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> sourceObjectsById = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> processedObjectsByIdentifier = (overwriteExisting)?(new HashMap<String,MetadataObject>()):(storedObjectsByIdentifier);
loadMdIndexes(srcDir, sourceObjectsByIdentifier, sourceObjectsById);
loadMdIndexes(dstDir, storedObjectsByIdentifier, storedObjectsById);
class Store {
public String storeObjectWithDependencies(MetadataObject o) {
+ l.debug("Executing storeObjectWithDependencies "+o.toString());
MetadataObject r = null;
String identifier = o.getIdentifier();
String tp = o.getType();
if(!processedObjectsByIdentifier.containsKey(identifier)) {
l.debug("Storing object identifier="+identifier+" type="+tp);
if(!tp.equalsIgnoreCase("attributeDisplayForm") && !tp.equalsIgnoreCase("attribute") &&
!tp.equalsIgnoreCase("fact") && !tp.equalsIgnoreCase("dataSet")) {
List<String> ids = o.getDependentObjectUris();
String content = o.toString();
for(String id : ids) {
+ l.debug("storeObjectWithDependencies resolving dependent ID id="+id);
MetadataObject src = sourceObjectsById.get(id);
+ l.debug("storeObjectWithDependencies found id="+id+" in source objects src="+src.toString());
if(src != null) {
String srcUri = id;
String newUri = storeObjectWithDependencies(src);
- content = content.replace(srcUri, newUri);
+ l.debug("storeObjectWithDependencies replacing srcUri="+"\""+srcUri+"\""+" with newUri="+"\""+newUri+"\"");
+ content = content.replace("\""+srcUri+"\"", "\""+newUri+"\"");
+ l.debug("storeObjectWithDependencies replacing srcUri="+"["+srcUri+"]"+" with newUri="+"["+newUri+"]");
+ content = content.replace("["+srcUri+"]", "["+newUri+"]");
}
else {
l.info("Can't find object uri="+id+" in the source!");
}
}
MetadataObject newObject = new MetadataObject(JSONObject.fromObject(content));
newObject.stripKeysForCreate();
if(storedObjectsByIdentifier.containsKey(identifier)) {
JSONObject m = newObject.getMeta();
MetadataObject eob = storedObjectsByIdentifier.get(identifier);
String uri = eob.getUri();
m.put("uri", uri);
if(overwriteExisting) {
modifyMetadataObject(uri, newObject);
}
r = newObject;
}
else {
r = new MetadataObject(createMetadataObject(pid, newObject));
String uri = r.getUri();
JSONObject m = r.getMeta();
m.put("identifier", identifier);
modifyMetadataObject(uri, r);
}
storedObjectsByIdentifier.put(identifier,r);
processedObjectsByIdentifier.put(identifier,r);
String id = r.getUri();
storedObjectsById.put(id,r);
}
else {
r = storedObjectsByIdentifier.get(identifier);
if(r == null) {
l.info("Missing LDM object in the target model identifier="+identifier+" type="+tp);
l.debug("Missing LDM object in the target model identifier="+identifier+" type="+tp);
throw new GdcRestApiException("Missing LDM object in the target model identifier="+identifier+
" type="+tp);
}
if(overwriteExisting) {
JSONObject srcMeta = o.getMeta();
JSONObject newMeta = r.getMeta();
String[] copyTags = {"title","summary","tags"};
for(String tag : copyTags) {
newMeta.put(tag,srcMeta.getString(tag));
}
if(tp.equalsIgnoreCase("attribute")) {
JSONObject srcContent = o.getContent();
JSONObject newContent = r.getContent();
if(srcContent.containsKey("drillDownStepAttributeDF")) {
String duri = srcContent.getString("drillDownStepAttributeDF");
if(duri != null && duri.length() >0) {
MetadataObject drillDownDF = sourceObjectsById.get(duri);
if(drillDownDF != null) {
String drillDownDFIdentifier = drillDownDF.getIdentifier();
MetadataObject newDrillDownDF = storedObjectsByIdentifier.get(drillDownDFIdentifier);
if(newDrillDownDF != null) {
newContent.put("drillDownStepAttributeDF",newDrillDownDF.getUri());
}
else {
l.info("The destination project doesn't contain the label with identifier "+
drillDownDFIdentifier + " that is used in the drill down for attribute with identifier "+
identifier);
}
}
else {
l.info("The source project doesn't contain the drill down label with used in " +
"the attribute with identifier "+ identifier);
}
}
}
}
modifyMetadataObject(r.getUri(), r);
storedObjectsByIdentifier.put(identifier,r);
processedObjectsByIdentifier.put(identifier,r);
}
}
}
else {
r = storedObjectsByIdentifier.get(identifier);
}
+ String ruri = r.getUri();
+ l.debug("Executed storeObjectWithDependencies uri="+ruri);
return r.getUri();
}
private String oldUriToNewUri(String oldUri) {
MetadataObject oldObj = sourceObjectsById.get(oldUri);
if(oldObj != null) {
String identifier = oldObj.getIdentifier();
if(identifier != null && identifier.length()>0) {
MetadataObject newObj = storedObjectsByIdentifier.get(identifier);
if(newObj != null) {
String newUri = newObj.getUri();
if(newUri != null && newUri.length() >0) {
return newUri;
}
else {
l.debug("The object with identifier="+identifier+" doesn't have any uri.");
throw new GdcRestApiException("The object with identifier="+identifier+" doesn't have any uri.");
}
}
else {
l.debug("Can't find the object with identifier="+identifier+" in the project metadata.");
throw new GdcRestApiException("Can't find the object with identifier="+identifier+" in the project metadata.");
}
}
else {
l.debug("The object with uri="+oldUri+" doesn't have any identifier.");
throw new GdcRestApiException("The object with uri="+oldUri+" doesn't have any identifier.");
}
}
else {
l.debug("Can't find the object with uri="+oldUri+" in the source metadata.");
throw new GdcRestApiException("Can't find the object with uri="+oldUri+" in the source metadata.");
}
}
/**
* Extracts the dependent objects uris from the content
* @return list of depenedent object uris
*/
public List<String> getVariableDependentObjectUris(JSONObject variable) {
List<String> uris = new ArrayList<String>();
String uri = variable.getString("uri");
String content = variable.toString();
Pattern p = Pattern.compile("\\\"/gdc/md/[^/]*?/obj/[0-9]+?\\\"");
Matcher m = p.matcher(content);
while(m.find()) {
String u = m.group();
u = u.replace("\"","");
if(!u.equalsIgnoreCase(uri) && !uris.contains(u))
uris.add(u);
}
return uris;
}
public void storeVariables(List<JSONObject> vars, List<JSONObject> oldVars) {
HashMap<String, JSONObject> oldVariablesByPromptIdentifier = new HashMap<String, JSONObject>();
for(JSONObject v : oldVars) {
String oldPromptUri = v.getString("prompt");
if(oldPromptUri != null && oldPromptUri.length()>0) {
MetadataObject oldPrompt = storedObjectsById.get(oldPromptUri);
if(oldPrompt != null && !oldPrompt.isEmpty() && !oldPrompt.isNullObject()) {
String oldIdentifier = oldPrompt.getIdentifier();
if(oldIdentifier != null && oldIdentifier.length()>0) {
oldVariablesByPromptIdentifier.put(oldIdentifier, v);
}
else {
l.debug("Source prompt with no identifier:"+oldPrompt.toString(2));
throw new GdcRestApiException("Source prompt with no identifier:"+oldPrompt.toString(2));
}
}
else {
l.debug("No source prompt for source variable:"+v.toString(2));
throw new GdcRestApiException("No source prompt for source variable:"+v.toString(2));
}
}
else {
l.debug("Source project variable with no prompt specification:"+v.toString(2));
throw new GdcRestApiException("Source project variable with no prompt specification:"+v.toString(2));
}
}
for(JSONObject v : vars) {
String newPromptUri = v.getString("prompt");
if(newPromptUri != null && newPromptUri.length()>0) {
MetadataObject newPrompt = sourceObjectsById.get(newPromptUri);
if(newPrompt != null && !newPrompt.isEmpty() && !newPrompt.isNullObject()) {
String newIdentifier = newPrompt.getIdentifier();
if(newIdentifier != null && newIdentifier.length()>0) {
List<String> ids = getVariableDependentObjectUris(v);
v.discard("uri");
v.discard("related");
String content = v.toString();
for(String id : ids) {
MetadataObject src = sourceObjectsById.get(id);
if(src != null) {
String newUri = oldUriToNewUri(id);
content = content.replace(id, newUri);
}
else {
l.info("Can't find object uri="+id+" in the source!");
}
}
JSONObject variableContent = JSONObject.fromObject(content);
variableContent.put("related","/gdc/projects/"+pid);
JSONObject variable = new JSONObject();
variable.put("variable",variableContent);
if(oldVariablesByPromptIdentifier.containsKey(newIdentifier)) {
if(overwriteExisting) {
JSONObject oldVariable = oldVariablesByPromptIdentifier.get(newIdentifier);
String uri = oldVariable.getString("uri");
if(uri != null && uri.length()>0) {
modifyVariable(uri, variable);
}
else {
l.debug("Source project variable with no uri:"+v.toString(2));
throw new GdcRestApiException("Source project variable with no uri:"+v.toString(2));
}
}
}
else {
createVariable(pid, variable);
}
}
else {
l.debug("Destination prompt with no identifier:"+newPrompt.toString(2));
throw new GdcRestApiException("Destination prompt with no identifier:"+newPrompt.toString(2));
}
}
else {
l.debug("No destination prompt for source variable:"+v.toString(2));
throw new GdcRestApiException("No destination prompt for source variable:"+v.toString(2));
}
}
else {
l.debug("Destination project variable with no prompt specification:"+v.toString(2));
throw new GdcRestApiException("Destination project variable with no prompt specification:"+v.toString(2));
}
}
}
}
Store storage = new Store();
for(MetadataObject obj : sourceObjectsByIdentifier.values()) {
storage.storeObjectWithDependencies(obj);
}
List<JSONObject> newVariables = loadVariables(srcDir);
List<JSONObject> oldVariables = parseVariables(getProjectVariables(pid));
if(newVariables != null && newVariables.size()>0) {
storage.storeVariables(newVariables, oldVariables);
}
}
/**
* Creates a new object in the metadata server
* @param projectId project id (hash)
* @param content the new object content
* @return the new object
*/
public JSONObject createMetadataObject(String projectId, JSON content) {
l.debug("Executing createMetadataObject on project id="+projectId+ "content='"+content.toString()+"'");
PostMethod req = createPostMethod(getProjectMdUrl(projectId) + OBJ_URI + "?createAndGet=true");
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
content.toString().getBytes()));
req.setRequestEntity(request);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
return parsedResp;
} catch (HttpMethodException ex) {
l.debug("Failed executing createMetadataObject on project id="+projectId+ "content='"+content.toString()+"'");
throw new GdcRestApiException("Failed executing createMetadataObject on project id="+projectId+ "content='"+content.toString()+"'",ex);
} finally {
req.releaseConnection();
}
}
/**
* Modifies an object in the metadata server
* @param projectId project id (hash)
* @param objectId object id (integer)
* @param content the new object content
* @return the new object
*/
public JSONObject modifyMetadataObject(String projectId, int objectId, JSON content) {
l.debug("Executing modifyMetadataObject on project id="+projectId+" objectId="+objectId+" content='"+content.toString()+"'");
return modifyMetadataObject(getProjectMdUrl(projectId) + OBJ_URI + "/" + objectId, content);
}
/**
* Modifies an object in the metadata server
* @param uri object uri
* @param content the new object content
* @return the new object
*/
public JSONObject modifyMetadataObject(String uri, JSON content) {
l.debug("Executing modifyMetadataObject on uri="+uri+" content='"+content.toString()+"'");
PostMethod req = createPostMethod(getServerUrl() + uri);
InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(
content.toString().getBytes()));
req.setRequestEntity(request);
try {
String resp = executeMethodOk(req);
JSONObject parsedResp = JSONObject.fromObject(resp);
return parsedResp;
} catch (HttpMethodException ex) {
l.debug("Failed executing modifyMetadataObject on uri="+uri+" content='"+content.toString()+"'");
throw new GdcRestApiException("Failed executing modifyMetadataObject on uri="+uri+" content='"+content.toString()+"'",ex);
} finally {
req.releaseConnection();
}
}
/**
* Deletes an object in the metadata server
* @param projectId project id (hash)
* @param objectId object id (integer)
* @return the new object
*/
public void deleteMetadataObject(String projectId, int objectId) {
l.debug("Executing deleteMetadataObject on project id="+projectId+" objectId="+objectId);
deleteMetadataObject(getProjectMdUrl(projectId) + OBJ_URI + "/" + objectId);
}
/**
* Deletes an object in the metadata server
* @param uri object uri
* @return the new object
*/
public void deleteMetadataObject(String uri) {
l.debug("Executing deleteMetadataObject on project uri="+uri);
DeleteMethod req = createDeleteMethod(getServerUrl() + uri);
try {
String resp = executeMethodOk(req);
} catch (HttpMethodException ex) {
l.debug("Failed executing deleteMetadataObject on project uri="+uri);
throw new GdcRestApiException("Failed executing deleteMetadataObject on uri="+uri,ex);
} finally {
req.releaseConnection();
}
}
private static GetMethod createGetMethod(String path) {
return configureHttpMethod(new GetMethod(path));
}
private static PostMethod createPostMethod(String path) {
return configureHttpMethod(new PostMethod(path));
}
private static DeleteMethod createDeleteMethod(String path) {
return configureHttpMethod(new DeleteMethod(path));
}
private static <T extends HttpMethod> T configureHttpMethod(T request) {
request.setRequestHeader("Content-Type", "application/json");
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("User-Agent", "GoodData CL/1.2.5-SNAPSHOT");
return request;
}
public static Logger getL() {
return l;
}
}
| false | true | public void copyMetadataObjects(final String pid, String srcDir, String dstDir, final boolean overwriteExisting) throws IOException {
final Map<String,MetadataObject> storedObjectsByIdentifier = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> storedObjectsById = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> sourceObjectsByIdentifier = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> sourceObjectsById = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> processedObjectsByIdentifier = (overwriteExisting)?(new HashMap<String,MetadataObject>()):(storedObjectsByIdentifier);
loadMdIndexes(srcDir, sourceObjectsByIdentifier, sourceObjectsById);
loadMdIndexes(dstDir, storedObjectsByIdentifier, storedObjectsById);
class Store {
public String storeObjectWithDependencies(MetadataObject o) {
MetadataObject r = null;
String identifier = o.getIdentifier();
String tp = o.getType();
if(!processedObjectsByIdentifier.containsKey(identifier)) {
l.debug("Storing object identifier="+identifier+" type="+tp);
if(!tp.equalsIgnoreCase("attributeDisplayForm") && !tp.equalsIgnoreCase("attribute") &&
!tp.equalsIgnoreCase("fact") && !tp.equalsIgnoreCase("dataSet")) {
List<String> ids = o.getDependentObjectUris();
String content = o.toString();
for(String id : ids) {
MetadataObject src = sourceObjectsById.get(id);
if(src != null) {
String srcUri = id;
String newUri = storeObjectWithDependencies(src);
content = content.replace(srcUri, newUri);
}
else {
l.info("Can't find object uri="+id+" in the source!");
}
}
MetadataObject newObject = new MetadataObject(JSONObject.fromObject(content));
newObject.stripKeysForCreate();
if(storedObjectsByIdentifier.containsKey(identifier)) {
JSONObject m = newObject.getMeta();
MetadataObject eob = storedObjectsByIdentifier.get(identifier);
String uri = eob.getUri();
m.put("uri", uri);
if(overwriteExisting) {
modifyMetadataObject(uri, newObject);
}
r = newObject;
}
else {
r = new MetadataObject(createMetadataObject(pid, newObject));
String uri = r.getUri();
JSONObject m = r.getMeta();
m.put("identifier", identifier);
modifyMetadataObject(uri, r);
}
storedObjectsByIdentifier.put(identifier,r);
processedObjectsByIdentifier.put(identifier,r);
String id = r.getUri();
storedObjectsById.put(id,r);
}
else {
r = storedObjectsByIdentifier.get(identifier);
if(r == null) {
l.info("Missing LDM object in the target model identifier="+identifier+" type="+tp);
l.debug("Missing LDM object in the target model identifier="+identifier+" type="+tp);
throw new GdcRestApiException("Missing LDM object in the target model identifier="+identifier+
" type="+tp);
}
if(overwriteExisting) {
JSONObject srcMeta = o.getMeta();
JSONObject newMeta = r.getMeta();
String[] copyTags = {"title","summary","tags"};
for(String tag : copyTags) {
newMeta.put(tag,srcMeta.getString(tag));
}
if(tp.equalsIgnoreCase("attribute")) {
JSONObject srcContent = o.getContent();
JSONObject newContent = r.getContent();
if(srcContent.containsKey("drillDownStepAttributeDF")) {
String duri = srcContent.getString("drillDownStepAttributeDF");
if(duri != null && duri.length() >0) {
MetadataObject drillDownDF = sourceObjectsById.get(duri);
if(drillDownDF != null) {
String drillDownDFIdentifier = drillDownDF.getIdentifier();
MetadataObject newDrillDownDF = storedObjectsByIdentifier.get(drillDownDFIdentifier);
if(newDrillDownDF != null) {
newContent.put("drillDownStepAttributeDF",newDrillDownDF.getUri());
}
else {
l.info("The destination project doesn't contain the label with identifier "+
drillDownDFIdentifier + " that is used in the drill down for attribute with identifier "+
identifier);
}
}
else {
l.info("The source project doesn't contain the drill down label with used in " +
"the attribute with identifier "+ identifier);
}
}
}
}
modifyMetadataObject(r.getUri(), r);
storedObjectsByIdentifier.put(identifier,r);
processedObjectsByIdentifier.put(identifier,r);
}
}
}
else {
r = storedObjectsByIdentifier.get(identifier);
}
return r.getUri();
}
private String oldUriToNewUri(String oldUri) {
MetadataObject oldObj = sourceObjectsById.get(oldUri);
if(oldObj != null) {
String identifier = oldObj.getIdentifier();
if(identifier != null && identifier.length()>0) {
MetadataObject newObj = storedObjectsByIdentifier.get(identifier);
if(newObj != null) {
String newUri = newObj.getUri();
if(newUri != null && newUri.length() >0) {
return newUri;
}
else {
l.debug("The object with identifier="+identifier+" doesn't have any uri.");
throw new GdcRestApiException("The object with identifier="+identifier+" doesn't have any uri.");
}
}
else {
l.debug("Can't find the object with identifier="+identifier+" in the project metadata.");
throw new GdcRestApiException("Can't find the object with identifier="+identifier+" in the project metadata.");
}
}
else {
l.debug("The object with uri="+oldUri+" doesn't have any identifier.");
throw new GdcRestApiException("The object with uri="+oldUri+" doesn't have any identifier.");
}
}
else {
l.debug("Can't find the object with uri="+oldUri+" in the source metadata.");
throw new GdcRestApiException("Can't find the object with uri="+oldUri+" in the source metadata.");
}
}
/**
* Extracts the dependent objects uris from the content
* @return list of depenedent object uris
*/
public List<String> getVariableDependentObjectUris(JSONObject variable) {
List<String> uris = new ArrayList<String>();
String uri = variable.getString("uri");
String content = variable.toString();
Pattern p = Pattern.compile("\\\"/gdc/md/[^/]*?/obj/[0-9]+?\\\"");
Matcher m = p.matcher(content);
while(m.find()) {
String u = m.group();
u = u.replace("\"","");
if(!u.equalsIgnoreCase(uri) && !uris.contains(u))
uris.add(u);
}
return uris;
}
public void storeVariables(List<JSONObject> vars, List<JSONObject> oldVars) {
HashMap<String, JSONObject> oldVariablesByPromptIdentifier = new HashMap<String, JSONObject>();
for(JSONObject v : oldVars) {
String oldPromptUri = v.getString("prompt");
if(oldPromptUri != null && oldPromptUri.length()>0) {
MetadataObject oldPrompt = storedObjectsById.get(oldPromptUri);
if(oldPrompt != null && !oldPrompt.isEmpty() && !oldPrompt.isNullObject()) {
String oldIdentifier = oldPrompt.getIdentifier();
if(oldIdentifier != null && oldIdentifier.length()>0) {
oldVariablesByPromptIdentifier.put(oldIdentifier, v);
}
else {
l.debug("Source prompt with no identifier:"+oldPrompt.toString(2));
throw new GdcRestApiException("Source prompt with no identifier:"+oldPrompt.toString(2));
}
}
else {
l.debug("No source prompt for source variable:"+v.toString(2));
throw new GdcRestApiException("No source prompt for source variable:"+v.toString(2));
}
}
else {
l.debug("Source project variable with no prompt specification:"+v.toString(2));
throw new GdcRestApiException("Source project variable with no prompt specification:"+v.toString(2));
}
}
for(JSONObject v : vars) {
String newPromptUri = v.getString("prompt");
if(newPromptUri != null && newPromptUri.length()>0) {
MetadataObject newPrompt = sourceObjectsById.get(newPromptUri);
if(newPrompt != null && !newPrompt.isEmpty() && !newPrompt.isNullObject()) {
String newIdentifier = newPrompt.getIdentifier();
if(newIdentifier != null && newIdentifier.length()>0) {
List<String> ids = getVariableDependentObjectUris(v);
v.discard("uri");
v.discard("related");
String content = v.toString();
for(String id : ids) {
MetadataObject src = sourceObjectsById.get(id);
if(src != null) {
String newUri = oldUriToNewUri(id);
content = content.replace(id, newUri);
}
else {
l.info("Can't find object uri="+id+" in the source!");
}
}
JSONObject variableContent = JSONObject.fromObject(content);
variableContent.put("related","/gdc/projects/"+pid);
JSONObject variable = new JSONObject();
variable.put("variable",variableContent);
if(oldVariablesByPromptIdentifier.containsKey(newIdentifier)) {
if(overwriteExisting) {
JSONObject oldVariable = oldVariablesByPromptIdentifier.get(newIdentifier);
String uri = oldVariable.getString("uri");
if(uri != null && uri.length()>0) {
modifyVariable(uri, variable);
}
else {
l.debug("Source project variable with no uri:"+v.toString(2));
throw new GdcRestApiException("Source project variable with no uri:"+v.toString(2));
}
}
}
else {
createVariable(pid, variable);
}
}
else {
l.debug("Destination prompt with no identifier:"+newPrompt.toString(2));
throw new GdcRestApiException("Destination prompt with no identifier:"+newPrompt.toString(2));
}
}
else {
l.debug("No destination prompt for source variable:"+v.toString(2));
throw new GdcRestApiException("No destination prompt for source variable:"+v.toString(2));
}
}
else {
l.debug("Destination project variable with no prompt specification:"+v.toString(2));
throw new GdcRestApiException("Destination project variable with no prompt specification:"+v.toString(2));
}
}
}
}
Store storage = new Store();
for(MetadataObject obj : sourceObjectsByIdentifier.values()) {
storage.storeObjectWithDependencies(obj);
}
List<JSONObject> newVariables = loadVariables(srcDir);
List<JSONObject> oldVariables = parseVariables(getProjectVariables(pid));
if(newVariables != null && newVariables.size()>0) {
storage.storeVariables(newVariables, oldVariables);
}
}
| public void copyMetadataObjects(final String pid, String srcDir, String dstDir, final boolean overwriteExisting) throws IOException {
final Map<String,MetadataObject> storedObjectsByIdentifier = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> storedObjectsById = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> sourceObjectsByIdentifier = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> sourceObjectsById = new HashMap<String,MetadataObject>();
final Map<String,MetadataObject> processedObjectsByIdentifier = (overwriteExisting)?(new HashMap<String,MetadataObject>()):(storedObjectsByIdentifier);
loadMdIndexes(srcDir, sourceObjectsByIdentifier, sourceObjectsById);
loadMdIndexes(dstDir, storedObjectsByIdentifier, storedObjectsById);
class Store {
public String storeObjectWithDependencies(MetadataObject o) {
l.debug("Executing storeObjectWithDependencies "+o.toString());
MetadataObject r = null;
String identifier = o.getIdentifier();
String tp = o.getType();
if(!processedObjectsByIdentifier.containsKey(identifier)) {
l.debug("Storing object identifier="+identifier+" type="+tp);
if(!tp.equalsIgnoreCase("attributeDisplayForm") && !tp.equalsIgnoreCase("attribute") &&
!tp.equalsIgnoreCase("fact") && !tp.equalsIgnoreCase("dataSet")) {
List<String> ids = o.getDependentObjectUris();
String content = o.toString();
for(String id : ids) {
l.debug("storeObjectWithDependencies resolving dependent ID id="+id);
MetadataObject src = sourceObjectsById.get(id);
l.debug("storeObjectWithDependencies found id="+id+" in source objects src="+src.toString());
if(src != null) {
String srcUri = id;
String newUri = storeObjectWithDependencies(src);
l.debug("storeObjectWithDependencies replacing srcUri="+"\""+srcUri+"\""+" with newUri="+"\""+newUri+"\"");
content = content.replace("\""+srcUri+"\"", "\""+newUri+"\"");
l.debug("storeObjectWithDependencies replacing srcUri="+"["+srcUri+"]"+" with newUri="+"["+newUri+"]");
content = content.replace("["+srcUri+"]", "["+newUri+"]");
}
else {
l.info("Can't find object uri="+id+" in the source!");
}
}
MetadataObject newObject = new MetadataObject(JSONObject.fromObject(content));
newObject.stripKeysForCreate();
if(storedObjectsByIdentifier.containsKey(identifier)) {
JSONObject m = newObject.getMeta();
MetadataObject eob = storedObjectsByIdentifier.get(identifier);
String uri = eob.getUri();
m.put("uri", uri);
if(overwriteExisting) {
modifyMetadataObject(uri, newObject);
}
r = newObject;
}
else {
r = new MetadataObject(createMetadataObject(pid, newObject));
String uri = r.getUri();
JSONObject m = r.getMeta();
m.put("identifier", identifier);
modifyMetadataObject(uri, r);
}
storedObjectsByIdentifier.put(identifier,r);
processedObjectsByIdentifier.put(identifier,r);
String id = r.getUri();
storedObjectsById.put(id,r);
}
else {
r = storedObjectsByIdentifier.get(identifier);
if(r == null) {
l.info("Missing LDM object in the target model identifier="+identifier+" type="+tp);
l.debug("Missing LDM object in the target model identifier="+identifier+" type="+tp);
throw new GdcRestApiException("Missing LDM object in the target model identifier="+identifier+
" type="+tp);
}
if(overwriteExisting) {
JSONObject srcMeta = o.getMeta();
JSONObject newMeta = r.getMeta();
String[] copyTags = {"title","summary","tags"};
for(String tag : copyTags) {
newMeta.put(tag,srcMeta.getString(tag));
}
if(tp.equalsIgnoreCase("attribute")) {
JSONObject srcContent = o.getContent();
JSONObject newContent = r.getContent();
if(srcContent.containsKey("drillDownStepAttributeDF")) {
String duri = srcContent.getString("drillDownStepAttributeDF");
if(duri != null && duri.length() >0) {
MetadataObject drillDownDF = sourceObjectsById.get(duri);
if(drillDownDF != null) {
String drillDownDFIdentifier = drillDownDF.getIdentifier();
MetadataObject newDrillDownDF = storedObjectsByIdentifier.get(drillDownDFIdentifier);
if(newDrillDownDF != null) {
newContent.put("drillDownStepAttributeDF",newDrillDownDF.getUri());
}
else {
l.info("The destination project doesn't contain the label with identifier "+
drillDownDFIdentifier + " that is used in the drill down for attribute with identifier "+
identifier);
}
}
else {
l.info("The source project doesn't contain the drill down label with used in " +
"the attribute with identifier "+ identifier);
}
}
}
}
modifyMetadataObject(r.getUri(), r);
storedObjectsByIdentifier.put(identifier,r);
processedObjectsByIdentifier.put(identifier,r);
}
}
}
else {
r = storedObjectsByIdentifier.get(identifier);
}
String ruri = r.getUri();
l.debug("Executed storeObjectWithDependencies uri="+ruri);
return r.getUri();
}
private String oldUriToNewUri(String oldUri) {
MetadataObject oldObj = sourceObjectsById.get(oldUri);
if(oldObj != null) {
String identifier = oldObj.getIdentifier();
if(identifier != null && identifier.length()>0) {
MetadataObject newObj = storedObjectsByIdentifier.get(identifier);
if(newObj != null) {
String newUri = newObj.getUri();
if(newUri != null && newUri.length() >0) {
return newUri;
}
else {
l.debug("The object with identifier="+identifier+" doesn't have any uri.");
throw new GdcRestApiException("The object with identifier="+identifier+" doesn't have any uri.");
}
}
else {
l.debug("Can't find the object with identifier="+identifier+" in the project metadata.");
throw new GdcRestApiException("Can't find the object with identifier="+identifier+" in the project metadata.");
}
}
else {
l.debug("The object with uri="+oldUri+" doesn't have any identifier.");
throw new GdcRestApiException("The object with uri="+oldUri+" doesn't have any identifier.");
}
}
else {
l.debug("Can't find the object with uri="+oldUri+" in the source metadata.");
throw new GdcRestApiException("Can't find the object with uri="+oldUri+" in the source metadata.");
}
}
/**
* Extracts the dependent objects uris from the content
* @return list of depenedent object uris
*/
public List<String> getVariableDependentObjectUris(JSONObject variable) {
List<String> uris = new ArrayList<String>();
String uri = variable.getString("uri");
String content = variable.toString();
Pattern p = Pattern.compile("\\\"/gdc/md/[^/]*?/obj/[0-9]+?\\\"");
Matcher m = p.matcher(content);
while(m.find()) {
String u = m.group();
u = u.replace("\"","");
if(!u.equalsIgnoreCase(uri) && !uris.contains(u))
uris.add(u);
}
return uris;
}
public void storeVariables(List<JSONObject> vars, List<JSONObject> oldVars) {
HashMap<String, JSONObject> oldVariablesByPromptIdentifier = new HashMap<String, JSONObject>();
for(JSONObject v : oldVars) {
String oldPromptUri = v.getString("prompt");
if(oldPromptUri != null && oldPromptUri.length()>0) {
MetadataObject oldPrompt = storedObjectsById.get(oldPromptUri);
if(oldPrompt != null && !oldPrompt.isEmpty() && !oldPrompt.isNullObject()) {
String oldIdentifier = oldPrompt.getIdentifier();
if(oldIdentifier != null && oldIdentifier.length()>0) {
oldVariablesByPromptIdentifier.put(oldIdentifier, v);
}
else {
l.debug("Source prompt with no identifier:"+oldPrompt.toString(2));
throw new GdcRestApiException("Source prompt with no identifier:"+oldPrompt.toString(2));
}
}
else {
l.debug("No source prompt for source variable:"+v.toString(2));
throw new GdcRestApiException("No source prompt for source variable:"+v.toString(2));
}
}
else {
l.debug("Source project variable with no prompt specification:"+v.toString(2));
throw new GdcRestApiException("Source project variable with no prompt specification:"+v.toString(2));
}
}
for(JSONObject v : vars) {
String newPromptUri = v.getString("prompt");
if(newPromptUri != null && newPromptUri.length()>0) {
MetadataObject newPrompt = sourceObjectsById.get(newPromptUri);
if(newPrompt != null && !newPrompt.isEmpty() && !newPrompt.isNullObject()) {
String newIdentifier = newPrompt.getIdentifier();
if(newIdentifier != null && newIdentifier.length()>0) {
List<String> ids = getVariableDependentObjectUris(v);
v.discard("uri");
v.discard("related");
String content = v.toString();
for(String id : ids) {
MetadataObject src = sourceObjectsById.get(id);
if(src != null) {
String newUri = oldUriToNewUri(id);
content = content.replace(id, newUri);
}
else {
l.info("Can't find object uri="+id+" in the source!");
}
}
JSONObject variableContent = JSONObject.fromObject(content);
variableContent.put("related","/gdc/projects/"+pid);
JSONObject variable = new JSONObject();
variable.put("variable",variableContent);
if(oldVariablesByPromptIdentifier.containsKey(newIdentifier)) {
if(overwriteExisting) {
JSONObject oldVariable = oldVariablesByPromptIdentifier.get(newIdentifier);
String uri = oldVariable.getString("uri");
if(uri != null && uri.length()>0) {
modifyVariable(uri, variable);
}
else {
l.debug("Source project variable with no uri:"+v.toString(2));
throw new GdcRestApiException("Source project variable with no uri:"+v.toString(2));
}
}
}
else {
createVariable(pid, variable);
}
}
else {
l.debug("Destination prompt with no identifier:"+newPrompt.toString(2));
throw new GdcRestApiException("Destination prompt with no identifier:"+newPrompt.toString(2));
}
}
else {
l.debug("No destination prompt for source variable:"+v.toString(2));
throw new GdcRestApiException("No destination prompt for source variable:"+v.toString(2));
}
}
else {
l.debug("Destination project variable with no prompt specification:"+v.toString(2));
throw new GdcRestApiException("Destination project variable with no prompt specification:"+v.toString(2));
}
}
}
}
Store storage = new Store();
for(MetadataObject obj : sourceObjectsByIdentifier.values()) {
storage.storeObjectWithDependencies(obj);
}
List<JSONObject> newVariables = loadVariables(srcDir);
List<JSONObject> oldVariables = parseVariables(getProjectVariables(pid));
if(newVariables != null && newVariables.size()>0) {
storage.storeVariables(newVariables, oldVariables);
}
}
|
diff --git a/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/ConfigApplier.java b/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/ConfigApplier.java
index 99ed6beed..1e68b052f 100644
--- a/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/ConfigApplier.java
+++ b/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/ConfigApplier.java
@@ -1,356 +1,356 @@
/*******************************************************************************
* Copyright (c) 2007, 2009 IBM Corporation and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.simpleconfigurator;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.util.*;
import org.eclipse.equinox.internal.simpleconfigurator.utils.*;
import org.osgi.framework.*;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
class ConfigApplier {
private static final String LAST_BUNDLES_INFO = "last.bundles.info"; //$NON-NLS-1$
private static final String PROP_DEVMODE = "osgi.dev"; //$NON-NLS-1$
private final BundleContext manipulatingContext;
private final PackageAdmin packageAdminService;
private final StartLevel startLevelService;
private final boolean runningOnEquinox;
private final boolean inDevMode;
private final Bundle callingBundle;
private final URI baseLocation;
ConfigApplier(BundleContext context, Bundle callingBundle) {
manipulatingContext = context;
this.callingBundle = callingBundle;
runningOnEquinox = "Eclipse".equals(context.getProperty(Constants.FRAMEWORK_VENDOR)); //$NON-NLS-1$
inDevMode = manipulatingContext.getProperty(PROP_DEVMODE) != null;
baseLocation = runningOnEquinox ? EquinoxUtils.getInstallLocationURI(context) : null;
ServiceReference packageAdminRef = manipulatingContext.getServiceReference(PackageAdmin.class.getName());
if (packageAdminRef == null)
throw new IllegalStateException("No PackageAdmin service is available."); //$NON-NLS-1$
packageAdminService = (PackageAdmin) manipulatingContext.getService(packageAdminRef);
ServiceReference startLevelRef = manipulatingContext.getServiceReference(StartLevel.class.getName());
if (startLevelRef == null)
throw new IllegalStateException("No StartLevelService service is available."); //$NON-NLS-1$
startLevelService = (StartLevel) manipulatingContext.getService(startLevelRef);
}
void install(URL url, boolean exclusiveMode) throws IOException {
List bundleInfoList = SimpleConfiguratorUtils.readConfiguration(url, baseLocation);
if (Activator.DEBUG)
System.out.println("applyConfiguration() bundleInfoList.size()=" + bundleInfoList.size());
if (bundleInfoList.size() == 0)
return;
BundleInfo[] expectedState = Utils.getBundleInfosFromList(bundleInfoList);
HashSet toUninstall = null;
if (!exclusiveMode) {
BundleInfo[] lastInstalledBundles = getLastState();
if (lastInstalledBundles != null) {
toUninstall = new HashSet(Arrays.asList(lastInstalledBundles));
toUninstall.removeAll(Arrays.asList(expectedState));
}
saveStateAsLast(url);
}
Collection prevouslyResolved = getResolvedBundles();
Collection toRefresh = new ArrayList();
Collection toStart = new ArrayList();
if (exclusiveMode) {
toRefresh.addAll(installBundles(expectedState, toStart));
toRefresh.addAll(uninstallBundles(expectedState, packageAdminService));
} else {
toRefresh.addAll(installBundles(expectedState, toStart));
if (toUninstall != null)
toRefresh.addAll(uninstallBundles(toUninstall));
}
refreshPackages((Bundle[]) toRefresh.toArray(new Bundle[toRefresh.size()]), manipulatingContext);
if (toRefresh.size() > 0)
try {
manipulatingContext.getBundle().loadClass("org.eclipse.osgi.service.resolver.PlatformAdmin"); //$NON-NLS-1$
// now see if there are any currently resolved bundles with option imports which could be resolved or
// if there are fragments with additional constraints which conflict with an already resolved host
Bundle[] additionalRefresh = StateResolverUtils.getAdditionalRefresh(prevouslyResolved, manipulatingContext);
if (additionalRefresh.length > 0)
refreshPackages(additionalRefresh, manipulatingContext);
} catch (ClassNotFoundException cnfe) {
// do nothing; no resolver package available
}
startBundles((Bundle[]) toStart.toArray(new Bundle[toStart.size()]));
}
private Collection getResolvedBundles() {
Collection resolved = new HashSet();
Bundle[] allBundles = manipulatingContext.getBundles();
for (int i = 0; i < allBundles.length; i++)
if ((allBundles[i].getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0)
resolved.add(allBundles[i]);
return resolved;
}
private Collection uninstallBundles(HashSet toUninstall) {
Collection removedBundles = new ArrayList(toUninstall.size());
for (Iterator iterator = toUninstall.iterator(); iterator.hasNext();) {
BundleInfo current = (BundleInfo) iterator.next();
Bundle[] matchingBundles = packageAdminService.getBundles(current.getSymbolicName(), getVersionRange(current.getVersion()));
for (int j = 0; matchingBundles != null && j < matchingBundles.length; j++) {
try {
removedBundles.add(matchingBundles[j]);
matchingBundles[j].uninstall();
} catch (BundleException e) {
//TODO log in debug mode...
}
}
}
return removedBundles;
}
private void saveStateAsLast(URL url) {
InputStream sourceStream = null;
OutputStream destinationStream = null;
File lastBundlesTxt = getLastBundleInfo();
try {
try {
destinationStream = new FileOutputStream(lastBundlesTxt);
sourceStream = url.openStream();
SimpleConfiguratorUtils.transferStreams(sourceStream, destinationStream);
} finally {
if (destinationStream != null)
destinationStream.close();
if (sourceStream != null)
sourceStream.close();
}
} catch (IOException e) {
//nothing
}
}
private File getLastBundleInfo() {
return manipulatingContext.getDataFile(LAST_BUNDLES_INFO);
}
private BundleInfo[] getLastState() {
File lastBundlesInfo = getLastBundleInfo();
if (!lastBundlesInfo.isFile())
return null;
try {
return (BundleInfo[]) SimpleConfiguratorUtils.readConfiguration(lastBundlesInfo.toURL(), baseLocation).toArray(new BundleInfo[1]);
} catch (IOException e) {
return null;
}
}
private ArrayList installBundles(BundleInfo[] finalList, Collection toStart) {
ArrayList toRefresh = new ArrayList();
String useReferenceProperty = manipulatingContext.getProperty(SimpleConfiguratorConstants.PROP_KEY_USE_REFERENCE);
boolean useReference = useReferenceProperty == null ? runningOnEquinox : Boolean.valueOf(useReferenceProperty).booleanValue();
for (int i = 0; i < finalList.length; i++) {
if (finalList[i] == null)
continue;
//TODO here we do not deal with bundles that don't have a symbolic id
//TODO Need to handle the case where getBundles return multiple value
String symbolicName = finalList[i].getSymbolicName();
String version = finalList[i].getVersion();
Bundle[] matches = null;
if (symbolicName != null && version != null)
matches = packageAdminService.getBundles(symbolicName, getVersionRange(version));
String bundleLocation = SimpleConfiguratorUtils.getBundleLocation(finalList[i], useReference);
Bundle current = matches == null ? null : (matches.length == 0 ? null : matches[0]);
if (current == null) {
try {
//TODO Need to eliminate System Bundle.
// If a system bundle doesn't have a SymbolicName header, like Knopflerfish 4.0.0,
// it will be installed unfortunately.
current = manipulatingContext.installBundle(bundleLocation);
if (Activator.DEBUG)
System.out.println("installed bundle:" + finalList[i]); //$NON-NLS-1$
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't install " + symbolicName + '/' + version + " from location " + finalList[i].getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
} else if (inDevMode && current.getBundleId() != 0 && current != manipulatingContext.getBundle() && !bundleLocation.equals(current.getLocation()) && !current.getLocation().startsWith("initial@")) {
// We do not do this for the system bundle (id==0), the manipulating bundle or any bundle installed from the osgi.bundles list (locations starting with "@initial"
// The bundle exists; but the location is different. Uninstall the current and install the new one (bug 229700)
try {
current.uninstall();
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't uninstall " + symbolicName + '/' + version + " from location " + current.getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
try {
current = manipulatingContext.installBundle(bundleLocation);
if (Activator.DEBUG)
System.out.println("installed bundle:" + finalList[i]); //$NON-NLS-1$
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't install " + symbolicName + '/' + version + " from location " + finalList[i].getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
}
// Mark Started
if (finalList[i].isMarkedAsStarted()) {
toStart.add(current);
}
// Set Start Level
int startLevel = finalList[i].getStartLevel();
if (startLevel < 1)
continue;
if (current.getBundleId() == 0)
continue;
- if (current.getHeaders().get(Constants.FRAGMENT_HOST) != null)
+ if (packageAdminService.getBundleType(current) == PackageAdmin.BUNDLE_TYPE_FRAGMENT)
continue;
if (SimpleConfiguratorConstants.TARGET_CONFIGURATOR_NAME.equals(current.getSymbolicName()))
continue;
try {
startLevelService.setBundleStartLevel(current, startLevel);
} catch (IllegalArgumentException ex) {
Utils.log(4, null, null, "Failed to set start level of Bundle:" + finalList[i], ex); //$NON-NLS-1$
}
}
return toRefresh;
}
private void refreshPackages(Bundle[] bundles, BundleContext context) {
if (bundles.length == 0 || packageAdminService == null)
return;
final boolean[] flag = new boolean[] {false};
FrameworkListener listener = new FrameworkListener() {
public void frameworkEvent(FrameworkEvent event) {
if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
synchronized (flag) {
flag[0] = true;
flag.notifyAll();
}
}
}
};
context.addFrameworkListener(listener);
packageAdminService.refreshPackages(bundles);
synchronized (flag) {
while (!flag[0]) {
try {
flag.wait();
} catch (InterruptedException e) {
//ignore
}
}
}
// if (DEBUG) {
// for (int i = 0; i < bundles.length; i++) {
// System.out.println(SimpleConfiguratorUtils.getBundleStateString(bundles[i]));
// }
// }
context.removeFrameworkListener(listener);
}
private void startBundles(Bundle[] bundles) {
for (int i = 0; i < bundles.length; i++) {
Bundle bundle = bundles[i];
if (bundle.getState() == Bundle.STARTING && (bundle == callingBundle || bundle == manipulatingContext.getBundle()))
continue;
if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null)
continue;
try {
bundle.start();
if (Activator.DEBUG)
System.out.println("started Bundle:" + bundle.getSymbolicName() + '(' + bundle.getLocation() + ':' + bundle.getBundleId() + ')'); //$NON-NLS-1$
} catch (BundleException e) {
e.printStackTrace();
// FrameworkLogEntry entry = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, NLS.bind(EclipseAdaptorMsg.ECLIPSE_STARTUP_FAILED_START, bundle.getLocation()), 0, e, null);
// log.log(entry);
}
}
}
/**
* Uninstall bundles which are not listed on finalList.
*
* @param finalList bundles list not to be uninstalled.
* @param packageAdmin package admin service.
* @return Collection HashSet of bundles finally installed.
*/
private Collection uninstallBundles(BundleInfo[] finalList, PackageAdmin packageAdmin) {
Bundle[] allBundles = manipulatingContext.getBundles();
//Build a set with all the bundles from the system
Set removedBundles = new HashSet(allBundles.length);
// configurator.setPrerequisiteBundles(allBundles);
for (int i = 0; i < allBundles.length; i++) {
if (allBundles[i].getBundleId() == 0)
continue;
removedBundles.add(allBundles[i]);
}
//Remove all the bundles appearing in the final list from the set of installed bundles
for (int i = 0; i < finalList.length; i++) {
if (finalList[i] == null)
continue;
Bundle[] toAdd = packageAdmin.getBundles(finalList[i].getSymbolicName(), getVersionRange(finalList[i].getVersion()));
for (int j = 0; toAdd != null && j < toAdd.length; j++) {
removedBundles.remove(toAdd[j]);
}
}
for (Iterator iter = removedBundles.iterator(); iter.hasNext();) {
try {
Bundle bundle = ((Bundle) iter.next());
if (bundle.getLocation().startsWith("initial@")) {
if (Activator.DEBUG)
System.out.println("Simple configurator thinks a bundle installed by the boot strap should be uninstalled:" + bundle.getSymbolicName() + '(' + bundle.getLocation() + ':' + bundle.getBundleId() + ')'); //$NON-NLS-1$
// Avoid uninstalling bundles that the boot strap code thinks should be installed (bug 232191)
iter.remove();
continue;
}
bundle.uninstall();
if (Activator.DEBUG)
System.out.println("uninstalled Bundle:" + bundle.getSymbolicName() + '(' + bundle.getLocation() + ':' + bundle.getBundleId() + ')'); //$NON-NLS-1$
} catch (BundleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return removedBundles;
}
private String getVersionRange(String version) {
return version == null ? null : new StringBuffer().append('[').append(version).append(',').append(version).append(']').toString();
}
}
| true | true | private ArrayList installBundles(BundleInfo[] finalList, Collection toStart) {
ArrayList toRefresh = new ArrayList();
String useReferenceProperty = manipulatingContext.getProperty(SimpleConfiguratorConstants.PROP_KEY_USE_REFERENCE);
boolean useReference = useReferenceProperty == null ? runningOnEquinox : Boolean.valueOf(useReferenceProperty).booleanValue();
for (int i = 0; i < finalList.length; i++) {
if (finalList[i] == null)
continue;
//TODO here we do not deal with bundles that don't have a symbolic id
//TODO Need to handle the case where getBundles return multiple value
String symbolicName = finalList[i].getSymbolicName();
String version = finalList[i].getVersion();
Bundle[] matches = null;
if (symbolicName != null && version != null)
matches = packageAdminService.getBundles(symbolicName, getVersionRange(version));
String bundleLocation = SimpleConfiguratorUtils.getBundleLocation(finalList[i], useReference);
Bundle current = matches == null ? null : (matches.length == 0 ? null : matches[0]);
if (current == null) {
try {
//TODO Need to eliminate System Bundle.
// If a system bundle doesn't have a SymbolicName header, like Knopflerfish 4.0.0,
// it will be installed unfortunately.
current = manipulatingContext.installBundle(bundleLocation);
if (Activator.DEBUG)
System.out.println("installed bundle:" + finalList[i]); //$NON-NLS-1$
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't install " + symbolicName + '/' + version + " from location " + finalList[i].getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
} else if (inDevMode && current.getBundleId() != 0 && current != manipulatingContext.getBundle() && !bundleLocation.equals(current.getLocation()) && !current.getLocation().startsWith("initial@")) {
// We do not do this for the system bundle (id==0), the manipulating bundle or any bundle installed from the osgi.bundles list (locations starting with "@initial"
// The bundle exists; but the location is different. Uninstall the current and install the new one (bug 229700)
try {
current.uninstall();
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't uninstall " + symbolicName + '/' + version + " from location " + current.getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
try {
current = manipulatingContext.installBundle(bundleLocation);
if (Activator.DEBUG)
System.out.println("installed bundle:" + finalList[i]); //$NON-NLS-1$
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't install " + symbolicName + '/' + version + " from location " + finalList[i].getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
}
// Mark Started
if (finalList[i].isMarkedAsStarted()) {
toStart.add(current);
}
// Set Start Level
int startLevel = finalList[i].getStartLevel();
if (startLevel < 1)
continue;
if (current.getBundleId() == 0)
continue;
if (current.getHeaders().get(Constants.FRAGMENT_HOST) != null)
continue;
if (SimpleConfiguratorConstants.TARGET_CONFIGURATOR_NAME.equals(current.getSymbolicName()))
continue;
try {
startLevelService.setBundleStartLevel(current, startLevel);
} catch (IllegalArgumentException ex) {
Utils.log(4, null, null, "Failed to set start level of Bundle:" + finalList[i], ex); //$NON-NLS-1$
}
}
return toRefresh;
}
| private ArrayList installBundles(BundleInfo[] finalList, Collection toStart) {
ArrayList toRefresh = new ArrayList();
String useReferenceProperty = manipulatingContext.getProperty(SimpleConfiguratorConstants.PROP_KEY_USE_REFERENCE);
boolean useReference = useReferenceProperty == null ? runningOnEquinox : Boolean.valueOf(useReferenceProperty).booleanValue();
for (int i = 0; i < finalList.length; i++) {
if (finalList[i] == null)
continue;
//TODO here we do not deal with bundles that don't have a symbolic id
//TODO Need to handle the case where getBundles return multiple value
String symbolicName = finalList[i].getSymbolicName();
String version = finalList[i].getVersion();
Bundle[] matches = null;
if (symbolicName != null && version != null)
matches = packageAdminService.getBundles(symbolicName, getVersionRange(version));
String bundleLocation = SimpleConfiguratorUtils.getBundleLocation(finalList[i], useReference);
Bundle current = matches == null ? null : (matches.length == 0 ? null : matches[0]);
if (current == null) {
try {
//TODO Need to eliminate System Bundle.
// If a system bundle doesn't have a SymbolicName header, like Knopflerfish 4.0.0,
// it will be installed unfortunately.
current = manipulatingContext.installBundle(bundleLocation);
if (Activator.DEBUG)
System.out.println("installed bundle:" + finalList[i]); //$NON-NLS-1$
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't install " + symbolicName + '/' + version + " from location " + finalList[i].getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
} else if (inDevMode && current.getBundleId() != 0 && current != manipulatingContext.getBundle() && !bundleLocation.equals(current.getLocation()) && !current.getLocation().startsWith("initial@")) {
// We do not do this for the system bundle (id==0), the manipulating bundle or any bundle installed from the osgi.bundles list (locations starting with "@initial"
// The bundle exists; but the location is different. Uninstall the current and install the new one (bug 229700)
try {
current.uninstall();
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't uninstall " + symbolicName + '/' + version + " from location " + current.getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
try {
current = manipulatingContext.installBundle(bundleLocation);
if (Activator.DEBUG)
System.out.println("installed bundle:" + finalList[i]); //$NON-NLS-1$
toRefresh.add(current);
} catch (BundleException e) {
if (Activator.DEBUG) {
System.err.println("Can't install " + symbolicName + '/' + version + " from location " + finalList[i].getLocation()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
continue;
}
}
// Mark Started
if (finalList[i].isMarkedAsStarted()) {
toStart.add(current);
}
// Set Start Level
int startLevel = finalList[i].getStartLevel();
if (startLevel < 1)
continue;
if (current.getBundleId() == 0)
continue;
if (packageAdminService.getBundleType(current) == PackageAdmin.BUNDLE_TYPE_FRAGMENT)
continue;
if (SimpleConfiguratorConstants.TARGET_CONFIGURATOR_NAME.equals(current.getSymbolicName()))
continue;
try {
startLevelService.setBundleStartLevel(current, startLevel);
} catch (IllegalArgumentException ex) {
Utils.log(4, null, null, "Failed to set start level of Bundle:" + finalList[i], ex); //$NON-NLS-1$
}
}
return toRefresh;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.