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/hudson/remoting/PingThread.java b/src/main/java/hudson/remoting/PingThread.java index e673326d..7efc3c65 100644 --- a/src/main/java/hudson/remoting/PingThread.java +++ b/src/main/java/hudson/remoting/PingThread.java @@ -1,150 +1,150 @@ /* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.remoting; import java.io.IOException; import java.util.concurrent.ExecutionException; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.util.concurrent.TimeoutException; import java.util.logging.Logger; /** * Periodically perform a ping. * * <p> * Useful when a connection needs to be kept alive by sending data, * or when the disconnection is not properly detected. * * <p> * {@link #onDead()} method needs to be overrided to define * what to do when a connection appears to be dead. * * @author Kohsuke Kawaguchi * @since 1.170 */ public abstract class PingThread extends Thread { private final Channel channel; /** * Time out in milliseconds. * If the response doesn't come back by then, the channel is considered dead. */ private final long timeout; /** * Performs a check every this milliseconds. */ private final long interval; public PingThread(Channel channel, long timeout, long interval) { super("Ping thread for channel "+channel); this.channel = channel; this.timeout = timeout; this.interval = interval; setDaemon(true); } public PingThread(Channel channel, long interval) { this(channel, 4*60*1000/*4 mins*/, interval); } public PingThread(Channel channel) { this(channel,10*60*1000/*10 mins*/); } public void run() { try { while(true) { long nextCheck = System.currentTimeMillis()+interval; ping(); // wait until the next check long diff; while((diff=nextCheck-System.currentTimeMillis())>0) Thread.sleep(diff); } } catch (ChannelClosedException e) { LOGGER.fine(getName()+" is closed. Terminating"); } catch (IOException e) { onDead(e); } catch (InterruptedException e) { // use interruption as a way to terminate the ping thread. LOGGER.fine(getName()+" is interrupted. Terminating"); } } private void ping() throws IOException, InterruptedException { Future<?> f = channel.callAsync(new Ping()); long start = System.currentTimeMillis(); long end = start +timeout; long remaining; do { remaining = end-System.currentTimeMillis(); try { f.get(Math.max(0,remaining),MILLISECONDS); return; } catch (ExecutionException e) { if (e.getCause() instanceof RequestAbortedException) return; // connection has shut down orderly. onDead(e); return; } catch (TimeoutException e) { // get method waits "at most the amount specified in the timeout", // so let's make sure that it really waited enough } } while(remaining>0); - onDead(new TimeoutException("Ping started on "+start+" hasn't completed at "+System.currentTimeMillis()).initCause(e)); + onDead(new TimeoutException("Ping started on "+start+" hasn't completed at "+System.currentTimeMillis()));//.initCause(e) } /** * Called when ping failed. * * @deprecated as of 2.9 * Override {@link #onDead(Throwable)} to receive the cause, but also override this method * and provide a fallback behaviour to be backward compatible with earlier version of remoting library. */ protected abstract void onDead(); /** * Called when ping failed. * * @since 2.9 */ protected void onDead(Throwable diagnosis) { onDead(); // fall back } private static final class Ping implements Callable<Void, IOException> { private static final long serialVersionUID = 1L; public Void call() throws IOException { return null; } } private static final Logger LOGGER = Logger.getLogger(PingThread.class.getName()); }
true
true
private void ping() throws IOException, InterruptedException { Future<?> f = channel.callAsync(new Ping()); long start = System.currentTimeMillis(); long end = start +timeout; long remaining; do { remaining = end-System.currentTimeMillis(); try { f.get(Math.max(0,remaining),MILLISECONDS); return; } catch (ExecutionException e) { if (e.getCause() instanceof RequestAbortedException) return; // connection has shut down orderly. onDead(e); return; } catch (TimeoutException e) { // get method waits "at most the amount specified in the timeout", // so let's make sure that it really waited enough } } while(remaining>0); onDead(new TimeoutException("Ping started on "+start+" hasn't completed at "+System.currentTimeMillis()).initCause(e)); }
private void ping() throws IOException, InterruptedException { Future<?> f = channel.callAsync(new Ping()); long start = System.currentTimeMillis(); long end = start +timeout; long remaining; do { remaining = end-System.currentTimeMillis(); try { f.get(Math.max(0,remaining),MILLISECONDS); return; } catch (ExecutionException e) { if (e.getCause() instanceof RequestAbortedException) return; // connection has shut down orderly. onDead(e); return; } catch (TimeoutException e) { // get method waits "at most the amount specified in the timeout", // so let's make sure that it really waited enough } } while(remaining>0); onDead(new TimeoutException("Ping started on "+start+" hasn't completed at "+System.currentTimeMillis()));//.initCause(e) }
diff --git a/choco-parser/src/main/java/parser/flatzinc/para/ParaserMaster.java b/choco-parser/src/main/java/parser/flatzinc/para/ParaserMaster.java index 10c7831a1..302d79c51 100644 --- a/choco-parser/src/main/java/parser/flatzinc/para/ParaserMaster.java +++ b/choco-parser/src/main/java/parser/flatzinc/para/ParaserMaster.java @@ -1,151 +1,151 @@ /** * Copyright (c) 1999-2011, Ecole des Mines de Nantes * 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 Ecole des Mines de Nantes 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 REGENTS 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 REGENTS AND 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 parser.flatzinc.para; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import solver.ResolutionPolicy; import solver.thread.AbstractParallelMaster; import util.tools.ArrayUtils; public class ParaserMaster extends AbstractParallelMaster<ParaserSlave> { protected static final Logger LOGGER = LoggerFactory.getLogger("fzn"); //*********************************************************************************** // VARIABLES //*********************************************************************************** int bestVal; int nbSol; boolean closeWithSuccess; ResolutionPolicy policy; public final static String[][] config = new String[][]{ {"-lf"}, // fix+lf {"-lf", "-lns", "PGLNS"}, // LNS propag + fix + lf {"-lf", "-lns", "RLNS"}, // LNS random + fix + lf {}, // fix // {"-lf","-i","-bbss","1","-dv"}, // ABS on dec vars + lf // {"-lf","-i","-bbss","2","-dv"}, // IBS on dec vars + lf // {"-lf","-i","-bbss","3","-dv"}, // WDeg on dec vars + lf }; //*********************************************************************************** // CONSTRUCTORS //*********************************************************************************** public ParaserMaster(int nbCores, String[] args) { nbCores = Math.min(nbCores, config.length); slaves = new ParaserSlave[nbCores]; for (int i = 0; i < nbCores; i++) { String[] options = ArrayUtils.append(args, config[i]); slaves[i] = new ParaserSlave(this, i, options); slaves[i].workInParallel(); } wait = true; try { while (wait) mainThread.sleep(20); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } //*********************************************************************************** // METHODS //*********************************************************************************** /** * A slave has CLOSED ITS SEARCH TREE, every one should stop! */ public synchronized void wishGranted() { if (LOGGER.isInfoEnabled()) { if (nbSol == 0) { if (!closeWithSuccess) { LOGGER.info("=====UNKNOWN====="); } else { LOGGER.info("=====UNSATISFIABLE====="); } } else { if (!closeWithSuccess && (policy != null && policy != ResolutionPolicy.SATISFACTION)) { LOGGER.info("=====UNBOUNDED====="); } else { LOGGER.info("=========="); } } } System.exit(0); } /** * A solution of cost val has been found * informs slaves that they must find better * * @param val * @param policy */ public synchronized boolean newSol(int val, ResolutionPolicy policy) { this.policy = policy; if (nbSol == 0) { bestVal = val; } nbSol++; boolean isBetter = false; switch (policy) { case MINIMIZE: - if (bestVal > val) { + if (bestVal > val || nbSol==1) { bestVal = val; isBetter = true; } break; case MAXIMIZE: - if (bestVal < val) { + if (bestVal < val || nbSol==1) { bestVal = val; isBetter = true; } break; case SATISFACTION: bestVal = 1; isBetter = nbSol == 1; break; } if (isBetter) for (int i = 0; i < slaves.length; i++) if(slaves[i]!=null) slaves[i].findBetterThan(val, policy); return isBetter; } public synchronized void closeWithSuccess() { this.closeWithSuccess = true; } }
false
true
public synchronized boolean newSol(int val, ResolutionPolicy policy) { this.policy = policy; if (nbSol == 0) { bestVal = val; } nbSol++; boolean isBetter = false; switch (policy) { case MINIMIZE: if (bestVal > val) { bestVal = val; isBetter = true; } break; case MAXIMIZE: if (bestVal < val) { bestVal = val; isBetter = true; } break; case SATISFACTION: bestVal = 1; isBetter = nbSol == 1; break; } if (isBetter) for (int i = 0; i < slaves.length; i++) if(slaves[i]!=null) slaves[i].findBetterThan(val, policy); return isBetter; }
public synchronized boolean newSol(int val, ResolutionPolicy policy) { this.policy = policy; if (nbSol == 0) { bestVal = val; } nbSol++; boolean isBetter = false; switch (policy) { case MINIMIZE: if (bestVal > val || nbSol==1) { bestVal = val; isBetter = true; } break; case MAXIMIZE: if (bestVal < val || nbSol==1) { bestVal = val; isBetter = true; } break; case SATISFACTION: bestVal = 1; isBetter = nbSol == 1; break; } if (isBetter) for (int i = 0; i < slaves.length; i++) if(slaves[i]!=null) slaves[i].findBetterThan(val, policy); return isBetter; }
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/SimpleTransfer.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/SimpleTransfer.java index f7f102354..b102125e6 100644 --- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/SimpleTransfer.java +++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/SimpleTransfer.java @@ -1,47 +1,51 @@ package org.opentripplanner.routing.edgetype; import org.opentripplanner.routing.core.RoutingRequest; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.StateEditor; import org.opentripplanner.routing.graph.Edge; import org.opentripplanner.routing.vertextype.TransitStop; /** * Represents a transfer between stops that does not take the street network into account. */ public class SimpleTransfer extends Edge { private static final long serialVersionUID = 1L; private int distance; public SimpleTransfer(TransitStop from, TransitStop to, int distance) { super(from, to); this.distance = distance; } @Override public State traverse(State s0) { + // use transfer edges only to transfer + // otherwise they are used as shortcuts or break the itinerary generator + if ( ! s0.isEverBoarded()) + return null; if (s0.getBackEdge() instanceof SimpleTransfer) return null; RoutingRequest rr = s0.getOptions(); double walkspeed = rr.getWalkSpeed(); StateEditor se = s0.edit(this); int time = (int) (distance / walkspeed); se.incrementTimeInSeconds(time); se.incrementWeight(time * rr.walkReluctance); return se.makeState(); } @Override public String getName() { return "Simple Transfer"; } @Override public double weightLowerBound(RoutingRequest rr) { int time = (int) (distance / rr.getWalkSpeed()); return (time * rr.walkReluctance); } }
true
true
public State traverse(State s0) { if (s0.getBackEdge() instanceof SimpleTransfer) return null; RoutingRequest rr = s0.getOptions(); double walkspeed = rr.getWalkSpeed(); StateEditor se = s0.edit(this); int time = (int) (distance / walkspeed); se.incrementTimeInSeconds(time); se.incrementWeight(time * rr.walkReluctance); return se.makeState(); }
public State traverse(State s0) { // use transfer edges only to transfer // otherwise they are used as shortcuts or break the itinerary generator if ( ! s0.isEverBoarded()) return null; if (s0.getBackEdge() instanceof SimpleTransfer) return null; RoutingRequest rr = s0.getOptions(); double walkspeed = rr.getWalkSpeed(); StateEditor se = s0.edit(this); int time = (int) (distance / walkspeed); se.incrementTimeInSeconds(time); se.incrementWeight(time * rr.walkReluctance); return se.makeState(); }
diff --git a/src/java/davmail/ldap/LdapConnection.java b/src/java/davmail/ldap/LdapConnection.java index d26eca4..a3a1d43 100644 --- a/src/java/davmail/ldap/LdapConnection.java +++ b/src/java/davmail/ldap/LdapConnection.java @@ -1,1549 +1,1549 @@ /* * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway * Copyright (C) 2009 Mickael Guessant * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package davmail.ldap; import com.sun.jndi.ldap.Ber; import com.sun.jndi.ldap.BerDecoder; import com.sun.jndi.ldap.BerEncoder; import davmail.AbstractConnection; import davmail.BundleMessage; import davmail.Settings; import davmail.exception.DavMailException; import davmail.exchange.ExchangeSession; import davmail.exchange.ExchangeSessionFactory; import davmail.ui.tray.DavGatewayTray; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Handle a caldav connection. */ public class LdapConnection extends AbstractConnection { /** * Davmail base context */ static final String BASE_CONTEXT = "ou=people"; static final String OD_BASE_CONTEXT = "o=od"; static final String OD_USER_CONTEXT = "cn=users, o=od"; static final String COMPUTER_CONTEXT = "cn=computers, o=od"; static final List<String> NAMING_CONTEXTS = new ArrayList<String>(); static { NAMING_CONTEXTS.add(BASE_CONTEXT); NAMING_CONTEXTS.add(OD_BASE_CONTEXT); } static final List<String> PERSON_OBJECT_CLASSES = new ArrayList<String>(); static { PERSON_OBJECT_CLASSES.add("top"); PERSON_OBJECT_CLASSES.add("person"); PERSON_OBJECT_CLASSES.add("organizationalPerson"); PERSON_OBJECT_CLASSES.add("inetOrgPerson"); // OpenDirectory class for iCal PERSON_OBJECT_CLASSES.add("apple-user"); } /** * Exchange to LDAP attribute map */ static final HashMap<String, String> ATTRIBUTE_MAP = new HashMap<String, String>(); static { ATTRIBUTE_MAP.put("uid", "AN"); ATTRIBUTE_MAP.put("mail", "EM"); ATTRIBUTE_MAP.put("cn", "DN"); ATTRIBUTE_MAP.put("displayName", "DN"); ATTRIBUTE_MAP.put("telephoneNumber", "PH"); ATTRIBUTE_MAP.put("l", "OFFICE"); ATTRIBUTE_MAP.put("company", "CP"); ATTRIBUTE_MAP.put("title", "TL"); ATTRIBUTE_MAP.put("givenName", "first"); ATTRIBUTE_MAP.put("initials", "initials"); ATTRIBUTE_MAP.put("sn", "last"); ATTRIBUTE_MAP.put("street", "street"); ATTRIBUTE_MAP.put("st", "state"); ATTRIBUTE_MAP.put("postalCode", "zip"); ATTRIBUTE_MAP.put("c", "country"); ATTRIBUTE_MAP.put("departement", "department"); ATTRIBUTE_MAP.put("mobile", "mobile"); } static final HashMap<String, String> CONTACT_TO_LDAP_ATTRIBUTE_MAP = new HashMap<String, String>(); static { CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("imapUid", "uid"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("co", "countryname"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("extensionattribute1", "custom1"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("extensionattribute2", "custom2"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("extensionattribute3", "custom3"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("extensionattribute4", "custom4"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("smtpemail1", "mail"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("smtpemail2", "xmozillasecondemail"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homeCountry", "mozillahomecountryname"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homeCity", "mozillahomelocalityname"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homePostalCode", "mozillahomepostalcode"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homeState", "mozillahomestate"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("homeStreet", "mozillahomestreet"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("businesshomepage", "mozillaworkurl"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("description", "description"); CONTACT_TO_LDAP_ATTRIBUTE_MAP.put("nickname", "mozillanickname"); } static final HashMap<String, String> STATIC_ATTRIBUTE_MAP = new HashMap<String, String>(); static final String COMPUTER_GUID = "52486C30-F0AB-48E3-9C37-37E9B28CDD7B"; static final String VIRTUALHOST_GUID = "D6DD8A10-1098-11DE-8C30-0800200C9A66"; static final String SERVICEINFO = "<?xml version='1.0' encoding='UTF-8'?>" + "<!DOCTYPE plist PUBLIC '-//Apple//DTD PLIST 1.0//EN' 'http://www.apple.com/DTDs/PropertyList-1.0.dtd'>" + "<plist version='1.0'>" + "<dict>" + "<key>com.apple.macosxserver.host</key>" + "<array>" + "<string>localhost</string>" + // NOTE: Will be replaced by real hostname "</array>" + "<key>com.apple.macosxserver.virtualhosts</key>" + "<dict>" + "<key>" + VIRTUALHOST_GUID + "</key>" + "<dict>" + "<key>hostDetails</key>" + "<dict>" + "<key>http</key>" + "<dict>" + "<key>enabled</key>" + "<true/>" + "<key>port</key>" + "<integer>9999</integer>" + // NOTE: Will be replaced by real port number "</dict>" + "<key>https</key>" + "<dict>" + "<key>disabled</key>" + "<false/>" + "<key>port</key>" + "<integer>0</integer>" + "</dict>" + "</dict>" + "<key>hostname</key>" + "<string>localhost</string>" + // NOTE: Will be replaced by real hostname "<key>serviceInfo</key>" + "<dict>" + "<key>calendar</key>" + "<dict>" + "<key>enabled</key>" + "<true/>" + "<key>templates</key>" + "<dict>" + "<key>calendarUserAddresses</key>" + "<array>" + "<string>%(principaluri)s</string>" + "<string>mailto:%(email)s</string>" + "<string>urn:uuid:%(guid)s</string>" + "</array>" + "<key>principalPath</key>" + "<string>/principals/__uuids__/%(guid)s/</string>" + "</dict>" + "</dict>" + "</dict>" + "<key>serviceType</key>" + "<array>" + "<string>calendar</string>" + "</array>" + "</dict>" + "</dict>" + "</dict>" + "</plist>"; static { STATIC_ATTRIBUTE_MAP.put("apple-serviceslocator", COMPUTER_GUID + ':' + VIRTUALHOST_GUID + ":calendar"); } /** * LDAP to Exchange Criteria Map */ static final HashMap<String, String> CRITERIA_MAP = new HashMap<String, String>(); static { // assume mail starts with firstname CRITERIA_MAP.put("uid", "AN"); CRITERIA_MAP.put("mail", "FN"); CRITERIA_MAP.put("displayname", "DN"); CRITERIA_MAP.put("cn", "DN"); CRITERIA_MAP.put("givenname", "FN"); CRITERIA_MAP.put("sn", "LN"); CRITERIA_MAP.put("title", "TL"); CRITERIA_MAP.put("company", "CP"); CRITERIA_MAP.put("o", "CP"); CRITERIA_MAP.put("l", "OF"); CRITERIA_MAP.put("department", "DP"); CRITERIA_MAP.put("apple-group-realname", "DP"); } static final HashMap<String, String> LDAP_TO_CONTACT_ATTRIBUTE_MAP = new HashMap<String, String>(); static { LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("uid", "imapUid"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mail", "smtpemail1"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("displayname", "cn"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("commonname", "cn"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("givenname", "givenName"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("surname", "sn"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("company", "o"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("apple-group-realname", "department"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomelocalityname", "homeCity"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("c", "co"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("countryname", "co"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("custom1", "extensionattribute1"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("custom2", "extensionattribute2"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("custom3", "extensionattribute3"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("custom4", "extensionattribute4"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillacustom1", "extensionattribute1"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillacustom2", "extensionattribute2"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillacustom3", "extensionattribute3"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillacustom4", "extensionattribute4"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("telephonenumber", "telephoneNumber"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("orgunit", "department"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("departmentnumber", "department"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("ou", "department"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillaworkstreet2", null); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomestreet", "homeStreet"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("xmozillanickname", "nickname"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillanickname", "nickname"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("cellphone", "mobile"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("homeurl", "personalHomePage"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomeurl", "personalHomePage"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomepostalcode", "homePostalCode"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("fax", "facsimiletelephonenumber"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomecountryname", "homeCountry"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("streetaddress", "street"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillaworkurl", "businesshomepage"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("workurl", "businesshomepage"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("region", "st"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("birthmonth", "bday"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("birthday", "bday"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("birthyear", "bday"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("carphone", "othermobile"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("nsaimid", "im"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("nscpaimscreenname", "im"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("xmozillasecondemail", "email2"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("notes", "description"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("pagerphone", "pager"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("locality", "l"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("homephone", "homePhone"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillasecondemail", "email2"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("zip", "postalcode"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomestate", "homeState"); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("modifytimestamp", "lastmodified"); // ignore attribute LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("objectclass", null); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillausehtmlmail", null); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("xmozillausehtmlmail", null); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("mozillahomestreet2", null); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("labeleduri", null); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("apple-generateduid", null); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("apple-serviceslocator", null); LDAP_TO_CONTACT_ATTRIBUTE_MAP.put("uidnumber", null); } /** * LDAP filter attributes ignore map */ static final HashSet<String> IGNORE_MAP = new HashSet<String>(); static { IGNORE_MAP.add("objectclass"); IGNORE_MAP.add("apple-generateduid"); IGNORE_MAP.add("augmentconfiguration"); IGNORE_MAP.add("ou"); IGNORE_MAP.add("apple-realname"); IGNORE_MAP.add("apple-group-nestedgroup"); IGNORE_MAP.add("apple-group-memberguid"); IGNORE_MAP.add("macaddress"); IGNORE_MAP.add("memberuid"); } // LDAP version // static final int LDAP_VERSION2 = 0x02; static final int LDAP_VERSION3 = 0x03; // LDAP request operations static final int LDAP_REQ_BIND = 0x60; static final int LDAP_REQ_SEARCH = 0x63; static final int LDAP_REQ_UNBIND = 0x42; static final int LDAP_REQ_ABANDON = 0x50; // LDAP response operations static final int LDAP_REP_BIND = 0x61; static final int LDAP_REP_SEARCH = 0x64; static final int LDAP_REP_RESULT = 0x65; // LDAP return codes static final int LDAP_OTHER = 80; static final int LDAP_SUCCESS = 0; static final int LDAP_SIZE_LIMIT_EXCEEDED = 4; static final int LDAP_INVALID_CREDENTIALS = 49; static final int LDAP_FILTER_AND = 0xa0; static final int LDAP_FILTER_OR = 0xa1; // LDAP filter operators (only LDAP_FILTER_SUBSTRINGS is supported) static final int LDAP_FILTER_SUBSTRINGS = 0xa4; //static final int LDAP_FILTER_GE = 0xa5; //static final int LDAP_FILTER_LE = 0xa6; static final int LDAP_FILTER_PRESENT = 0x87; //static final int LDAP_FILTER_APPROX = 0xa8; static final int LDAP_FILTER_EQUALITY = 0xa3; // LDAP filter mode (only startsWith supported by galfind) static final int LDAP_SUBSTRING_INITIAL = 0x80; static final int LDAP_SUBSTRING_ANY = 0x81; static final int LDAP_SUBSTRING_FINAL = 0x82; // BER data types static final int LBER_ENUMERATED = 0x0a; static final int LBER_SET = 0x31; static final int LBER_SEQUENCE = 0x30; // LDAP search scope static final int SCOPE_BASE_OBJECT = 0; //static final int SCOPE_ONE_LEVEL = 1; //static final int SCOPE_SUBTREE = 2; /** * For some unknow reaseon parseIntWithTag is private ! */ static final Method PARSE_INT_WITH_TAG_METHOD; static { try { PARSE_INT_WITH_TAG_METHOD = BerDecoder.class.getDeclaredMethod("parseIntWithTag", int.class); PARSE_INT_WITH_TAG_METHOD.setAccessible(true); } catch (NoSuchMethodException e) { DavGatewayTray.error(new BundleMessage("LOG_UNABLE_TO_GET_PARSEINTWITHTAG")); throw new RuntimeException(e); } } /** * raw connection inputStream */ protected BufferedInputStream is; /** * reusable BER encoder */ protected final BerEncoder responseBer = new BerEncoder(); /** * Current LDAP version (used for String encoding) */ int ldapVersion = LDAP_VERSION3; /** * Search threads map */ protected final HashMap<Integer, SearchThread> searchThreadMap = new HashMap<Integer, SearchThread>(); /** * Initialize the streams and start the thread. * * @param clientSocket LDAP client socket */ public LdapConnection(Socket clientSocket) { super(LdapConnection.class.getSimpleName(), clientSocket); try { is = new BufferedInputStream(client.getInputStream()); os = new BufferedOutputStream(client.getOutputStream()); } catch (IOException e) { close(); DavGatewayTray.error(new BundleMessage("LOG_EXCEPTION_GETTING_SOCKET_STREAMS"), e); } } protected boolean isLdapV3() { return ldapVersion == LDAP_VERSION3; } @Override public void run() { byte[] inbuf = new byte[2048]; // Buffer for reading incoming bytes int bytesread; // Number of bytes in inbuf int bytesleft; // Number of bytes that need to read for completing resp int br; // Temp; number of bytes read from stream int offset; // Offset of where to store bytes in inbuf boolean eos; // End of stream try { ExchangeSessionFactory.checkConfig(); while (true) { offset = 0; // check that it is the beginning of a sequence bytesread = is.read(inbuf, offset, 1); if (bytesread < 0) { break; // EOF } if (inbuf[offset++] != (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR)) { continue; } // get length of sequence bytesread = is.read(inbuf, offset, 1); if (bytesread < 0) { break; // EOF } int seqlen = inbuf[offset++]; // Length of ASN sequence // if high bit is on, length is encoded in the // subsequent length bytes and the number of length bytes // is equal to & 0x80 (i.e. length byte with high bit off). if ((seqlen & 0x80) == 0x80) { int seqlenlen = seqlen & 0x7f; // number of length bytes bytesread = 0; eos = false; // Read all length bytes while (bytesread < seqlenlen) { br = is.read(inbuf, offset + bytesread, seqlenlen - bytesread); if (br < 0) { eos = true; break; // EOF } bytesread += br; } // end-of-stream reached before length bytes are read if (eos) { break; // EOF } // Add contents of length bytes to determine length seqlen = 0; for (int i = 0; i < seqlenlen; i++) { seqlen = (seqlen << 8) + (inbuf[offset + i] & 0xff); } offset += bytesread; } // read in seqlen bytes bytesleft = seqlen; if ((offset + bytesleft) > inbuf.length) { byte[] nbuf = new byte[offset + bytesleft]; System.arraycopy(inbuf, 0, nbuf, 0, offset); inbuf = nbuf; } while (bytesleft > 0) { bytesread = is.read(inbuf, offset, bytesleft); if (bytesread < 0) { break; // EOF } offset += bytesread; bytesleft -= bytesread; } DavGatewayTray.switchIcon(); //Ber.dumpBER(System.out, "request\n", inbuf, 0, offset); handleRequest(new BerDecoder(inbuf, 0, offset)); } } catch (SocketException e) { DavGatewayTray.debug(new BundleMessage("LOG_CONNECTION_CLOSED")); } catch (SocketTimeoutException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT")); } catch (Exception e) { DavGatewayTray.log(e); try { sendErr(0, LDAP_REP_BIND, e); } catch (IOException e2) { DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); } protected void handleRequest(BerDecoder reqBer) throws IOException { int currentMessageId = 0; try { reqBer.parseSeq(null); currentMessageId = reqBer.parseInt(); int requestOperation = reqBer.peekByte(); if (requestOperation == LDAP_REQ_BIND) { reqBer.parseSeq(null); ldapVersion = reqBer.parseInt(); userName = reqBer.parseString(isLdapV3()); password = reqBer.parseStringWithTag(Ber.ASN_CONTEXT, isLdapV3(), null); if (userName.length() > 0 && password.length() > 0) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_BIND_USER", currentMessageId, userName)); try { session = ExchangeSessionFactory.getInstance(userName, password); DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_BIND_SUCCESS")); sendClient(currentMessageId, LDAP_REP_BIND, LDAP_SUCCESS, ""); } catch (IOException e) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_BIND_INVALID_CREDENTIALS")); sendClient(currentMessageId, LDAP_REP_BIND, LDAP_INVALID_CREDENTIALS, ""); } } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_BIND_ANONYMOUS", currentMessageId)); // anonymous bind sendClient(currentMessageId, LDAP_REP_BIND, LDAP_SUCCESS, ""); } } else if (requestOperation == LDAP_REQ_UNBIND) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_UNBIND", currentMessageId)); if (session != null) { session = null; } } else if (requestOperation == LDAP_REQ_SEARCH) { reqBer.parseSeq(null); String dn = reqBer.parseString(isLdapV3()); int scope = reqBer.parseEnumeration(); /*int derefAliases =*/ reqBer.parseEnumeration(); int sizeLimit = reqBer.parseInt(); if (sizeLimit > 100 || sizeLimit == 0) { sizeLimit = 100; } int timelimit = reqBer.parseInt(); /*boolean typesOnly =*/ reqBer.parseBoolean(); LdapFilter ldapFilter = parseFilter(reqBer); Set<String> returningAttributes = parseReturningAttributes(reqBer); // launch search in a separate thread SearchThread searchThread = new SearchThread(getName(), currentMessageId, dn, scope, sizeLimit, timelimit, ldapFilter, returningAttributes); synchronized (searchThreadMap) { searchThreadMap.put(currentMessageId, searchThread); } searchThread.start(); } else if (requestOperation == LDAP_REQ_ABANDON) { int abandonMessageId = 0; try { abandonMessageId = (Integer) PARSE_INT_WITH_TAG_METHOD.invoke(reqBer, LDAP_REQ_ABANDON); synchronized (searchThreadMap) { SearchThread searchThread = searchThreadMap.get(abandonMessageId); if (searchThread != null) { searchThread.abandon(); searchThreadMap.remove(currentMessageId); } } } catch (IllegalAccessException e) { DavGatewayTray.error(e); } catch (InvocationTargetException e) { DavGatewayTray.error(e); } DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_ABANDON_SEARCH", currentMessageId, abandonMessageId)); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_UNSUPPORTED_OPERATION", requestOperation)); sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_OTHER, "Unsupported operation"); } } catch (IOException e) { try { sendErr(currentMessageId, LDAP_REP_RESULT, e); } catch (IOException e2) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } throw e; } } protected LdapFilter parseFilter(BerDecoder reqBer) throws IOException { LdapFilter ldapFilter; if (reqBer.peekByte() == LDAP_FILTER_PRESENT) { String attributeName = reqBer.parseStringWithTag(LDAP_FILTER_PRESENT, isLdapV3(), null).toLowerCase(); ldapFilter = new SimpleFilter(attributeName); } else { int[] seqSize = new int[1]; int ldapFilterType = reqBer.parseSeq(seqSize); int end = reqBer.getParsePosition() + seqSize[0]; ldapFilter = parseNestedFilter(reqBer, ldapFilterType, end); } return ldapFilter; } protected LdapFilter parseNestedFilter(BerDecoder reqBer, int ldapFilterType, int end) throws IOException { LdapFilter nestedFilter; if ((ldapFilterType == LDAP_FILTER_OR) || (ldapFilterType == LDAP_FILTER_AND)) { nestedFilter = new CompoundFilter(ldapFilterType); while (reqBer.getParsePosition() < end && reqBer.bytesLeft() > 0) { if (reqBer.peekByte() == LDAP_FILTER_PRESENT) { String attributeName = reqBer.parseStringWithTag(LDAP_FILTER_PRESENT, isLdapV3(), null).toLowerCase(); nestedFilter.add(new SimpleFilter(attributeName)); } else { int[] seqSize = new int[1]; int ldapFilterOperator = reqBer.parseSeq(seqSize); int subEnd = reqBer.getParsePosition() + seqSize[0]; nestedFilter.add(parseNestedFilter(reqBer, ldapFilterOperator, subEnd)); } } } else { // simple filter nestedFilter = parseSimpleFilter(reqBer, ldapFilterType); } return nestedFilter; } protected LdapFilter parseSimpleFilter(BerDecoder reqBer, int ldapFilterOperator) throws IOException { String attributeName = reqBer.parseString(isLdapV3()).toLowerCase(); int ldapFilterMode = 0; StringBuilder value = new StringBuilder(); if (ldapFilterOperator == LDAP_FILTER_SUBSTRINGS) { // Thunderbird sends values with space as separate strings, rebuild value int[] seqSize = new int[1]; /*LBER_SEQUENCE*/ reqBer.parseSeq(seqSize); int end = reqBer.getParsePosition() + seqSize[0]; while (reqBer.getParsePosition() < end && reqBer.bytesLeft() > 0) { ldapFilterMode = reqBer.peekByte(); if (value.length() > 0) { value.append(' '); } value.append(reqBer.parseStringWithTag(ldapFilterMode, isLdapV3(), null)); } } else if (ldapFilterOperator == LDAP_FILTER_EQUALITY) { value.append(reqBer.parseString(isLdapV3())); } else { DavGatewayTray.warn(new BundleMessage("LOG_LDAP_UNSUPPORTED_FILTER_VALUE")); } String sValue = value.toString(); if ("uid".equalsIgnoreCase(attributeName) && sValue.equals(userName)) { // replace with actual alias instead of login name search if (sValue.equals(userName)) { sValue = session.getAlias(); DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REPLACED_UID_FILTER", userName, sValue)); } } return new SimpleFilter(attributeName, sValue, ldapFilterOperator, ldapFilterMode); } protected Set<String> parseReturningAttributes(BerDecoder reqBer) throws IOException { Set<String> returningAttributes = new HashSet<String>(); int[] seqSize = new int[1]; reqBer.parseSeq(seqSize); int end = reqBer.getParsePosition() + seqSize[0]; while (reqBer.getParsePosition() < end && reqBer.bytesLeft() > 0) { returningAttributes.add(reqBer.parseString(isLdapV3()).toLowerCase()); } return returningAttributes; } /** * Send Root DSE * * @param currentMessageId current message id * @throws IOException on error */ protected void sendRootDSE(int currentMessageId) throws IOException { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_SEND_ROOT_DSE")); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("objectClass", "top"); attributes.put("namingContexts", NAMING_CONTEXTS); sendEntry(currentMessageId, "Root DSE", attributes); } protected void addIf(Map<String, Object> attributes, Set<String> returningAttributes, String name, Object value) { if ((returningAttributes.isEmpty()) || returningAttributes.contains(name)) { attributes.put(name, value); } } protected String hostName() throws UnknownHostException { if (client.getInetAddress().isLoopbackAddress()) { // local address, probably using localhost in iCal URL return "localhost"; } else { // remote address, send fully qualified domain name return InetAddress.getLocalHost().getCanonicalHostName(); } } /** * Send ComputerContext * * @param currentMessageId current message id * @param returningAttributes attributes to return * @throws IOException on error */ protected void sendComputerContext(int currentMessageId, Set<String> returningAttributes) throws IOException { String customServiceInfo = SERVICEINFO.replaceAll("localhost", hostName()); customServiceInfo = customServiceInfo.replaceAll("9999", Settings.getProperty("davmail.caldavPort")); List<String> objectClasses = new ArrayList<String>(); objectClasses.add("top"); objectClasses.add("apple-computer"); Map<String, Object> attributes = new HashMap<String, Object>(); addIf(attributes, returningAttributes, "objectClass", objectClasses); addIf(attributes, returningAttributes, "apple-generateduid", COMPUTER_GUID); addIf(attributes, returningAttributes, "apple-serviceinfo", customServiceInfo); addIf(attributes, returningAttributes, "apple-serviceslocator", "::anyService"); addIf(attributes, returningAttributes, "cn", hostName()); String dn = "cn=" + hostName() + ", " + COMPUTER_CONTEXT; DavGatewayTray.debug(new BundleMessage("LOG_LDAP_SEND_COMPUTER_CONTEXT", dn, attributes)); sendEntry(currentMessageId, dn, attributes); } /** * Send Base Context * * @param currentMessageId current message id * @throws IOException on error */ protected void sendBaseContext(int currentMessageId) throws IOException { List<String> objectClasses = new ArrayList<String>(); objectClasses.add("top"); objectClasses.add("organizationalUnit"); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("objectClass", objectClasses); attributes.put("description", "DavMail Gateway LDAP for " + Settings.getProperty("davmail.url")); sendEntry(currentMessageId, BASE_CONTEXT, attributes); } protected void sendEntry(int currentMessageId, String dn, Map<String, Object> attributes) throws IOException { // synchronize on responseBer synchronized (responseBer) { responseBer.reset(); responseBer.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); responseBer.encodeInt(currentMessageId); responseBer.beginSeq(LDAP_REP_SEARCH); responseBer.encodeString(dn, isLdapV3()); responseBer.beginSeq(LBER_SEQUENCE); for (Map.Entry<String, Object> entry : attributes.entrySet()) { responseBer.beginSeq(LBER_SEQUENCE); responseBer.encodeString(entry.getKey(), isLdapV3()); responseBer.beginSeq(LBER_SET); Object values = entry.getValue(); if (values instanceof String) { responseBer.encodeString((String) values, isLdapV3()); } else if (values instanceof List) { for (Object value : (List) values) { responseBer.encodeString((String) value, isLdapV3()); } } else { throw new DavMailException("EXCEPTION_UNSUPPORTED_VALUE", values); } responseBer.endSeq(); responseBer.endSeq(); } responseBer.endSeq(); responseBer.endSeq(); responseBer.endSeq(); sendResponse(); } } protected void sendErr(int currentMessageId, int responseOperation, Exception e) throws IOException { String message = e.getMessage(); if (message == null) { message = e.toString(); } sendClient(currentMessageId, responseOperation, LDAP_OTHER, message); } protected void sendClient(int currentMessageId, int responseOperation, int status, String message) throws IOException { responseBer.reset(); responseBer.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); responseBer.encodeInt(currentMessageId); responseBer.beginSeq(responseOperation); responseBer.encodeInt(status, LBER_ENUMERATED); // dn responseBer.encodeString("", isLdapV3()); // error message responseBer.encodeString(message, isLdapV3()); responseBer.endSeq(); responseBer.endSeq(); sendResponse(); } protected void sendResponse() throws IOException { //Ber.dumpBER(System.out, ">\n", responseBer.getBuf(), 0, responseBer.getDataLen()); os.write(responseBer.getBuf(), 0, responseBer.getDataLen()); os.flush(); } static interface LdapFilter { ExchangeSession.Condition getContactSearchFilter(); Map<String, ExchangeSession.Contact> findInGAL(ExchangeSession session, Set<String> returningAttributes, int sizeLimit) throws IOException; void add(LdapFilter filter); boolean isFullSearch(); boolean isMatch(Map<String, String> person); } class CompoundFilter implements LdapFilter { final Set<LdapFilter> criteria = new HashSet<LdapFilter>(); final int type; CompoundFilter(int filterType) { type = filterType; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); if (type == LDAP_FILTER_OR) { buffer.append("(|"); } else { buffer.append("(&"); } for (LdapFilter child : criteria) { buffer.append(child.toString()); } buffer.append(')'); return buffer.toString(); } /** * Add child filter * * @param filter inner filter */ public void add(LdapFilter filter) { criteria.add(filter); } /** * This is only a full search if every child * is also a full search * * @return true if full search filter */ public boolean isFullSearch() { for (LdapFilter child : criteria) { if (!child.isFullSearch()) { return false; } } return true; } /** * Build search filter for Contacts folder search. * Use Exchange SEARCH syntax * * @return contact search filter */ public ExchangeSession.Condition getContactSearchFilter() { ExchangeSession.MultiCondition condition; if (type == LDAP_FILTER_OR) { condition = session.or(); } else { condition = session.and(); } for (LdapFilter child : criteria) { condition.add(child.getContactSearchFilter()); } return condition; } /** * Test if person matches the current filter. * * @param person person attributes map * @return true if filter match */ public boolean isMatch(Map<String, String> person) { if (type == LDAP_FILTER_OR) { for (LdapFilter child : criteria) { if (!child.isFullSearch()) { if (child.isMatch(person)) { // We've found a match return true; } } } // No subconditions are met return false; } else if (type == LDAP_FILTER_AND) { for (LdapFilter child : criteria) { if (!child.isFullSearch()) { if (!child.isMatch(person)) { // We've found a miss return false; } } } // All subconditions are met return true; } return false; } /** * Find persons in Exchange GAL matching filter. * Iterate over child filters to build results. * * @param session Exchange session * @return persons map * @throws IOException on error */ public Map<String, ExchangeSession.Contact> findInGAL(ExchangeSession session, Set<String> returningAttributes, int sizeLimit) throws IOException { Map<String, ExchangeSession.Contact> persons = null; for (LdapFilter child : criteria) { int currentSizeLimit = sizeLimit; if (persons != null) { currentSizeLimit -= persons.size(); } Map<String, ExchangeSession.Contact> childFind = child.findInGAL(session, returningAttributes, currentSizeLimit); if (childFind != null) { if (persons == null) { persons = childFind; } else if (type == LDAP_FILTER_OR) { // Create the union of the existing results and the child found results persons.putAll(childFind); } else if (type == LDAP_FILTER_AND) { // Append current child filter results that match all child filters to persons. // The hard part is that, due to the 100-item-returned galFind limit // we may catch new items that match all child filters in each child search. // Thus, instead of building the intersection, we check each result against // all filters. for (ExchangeSession.Contact result : childFind.values()) { if (isMatch(result)) { // This item from the child result set matches all sub-criteria, add it persons.put(result.get("uid"), result); } } } } } if ((persons == null) && !isFullSearch()) { // return an empty map (indicating no results were found) return new HashMap<String, ExchangeSession.Contact>(); } return persons; } } class SimpleFilter implements LdapFilter { static final String STAR = "*"; final String attributeName; final String value; final int mode; final int operator; final boolean canIgnore; SimpleFilter(String attributeName) { this.attributeName = attributeName; this.value = SimpleFilter.STAR; this.operator = LDAP_FILTER_SUBSTRINGS; this.mode = 0; this.canIgnore = checkIgnore(); } SimpleFilter(String attributeName, String value, int ldapFilterOperator, int ldapFilterMode) { this.attributeName = attributeName; this.value = value; this.operator = ldapFilterOperator; this.mode = ldapFilterMode; this.canIgnore = checkIgnore(); } private boolean checkIgnore() { if ("objectclass".equals(attributeName) && STAR.equals(value)) { // ignore cases where any object class can match return true; } else if (IGNORE_MAP.contains(attributeName)) { // Ignore this specific attribute return true; } else if (CRITERIA_MAP.get(attributeName) == null && getContactAttributeName(attributeName) == null) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_UNSUPPORTED_FILTER_ATTRIBUTE", attributeName, value)); return true; } return false; } public boolean isFullSearch() { // only (objectclass=*) is a full search return "objectclass".equals(attributeName) && STAR.equals(value); } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append('('); buffer.append(attributeName); buffer.append('='); if (SimpleFilter.STAR.equals(value)) { buffer.append(SimpleFilter.STAR); } else if (operator == LDAP_FILTER_SUBSTRINGS) { if (mode == LDAP_SUBSTRING_FINAL || mode == LDAP_SUBSTRING_ANY) { buffer.append(SimpleFilter.STAR); } buffer.append(value); if (mode == LDAP_SUBSTRING_INITIAL || mode == LDAP_SUBSTRING_ANY) { buffer.append(SimpleFilter.STAR); } } else { buffer.append(value); } buffer.append(')'); return buffer.toString(); } public ExchangeSession.Condition getContactSearchFilter() { String contactAttributeName = getContactAttributeName(attributeName); if (canIgnore || (contactAttributeName == null)) { return null; } ExchangeSession.Condition condition = null; if (operator == LDAP_FILTER_EQUALITY) { condition = session.isEqualTo(contactAttributeName, value); } else if ("*".equals(value)) { condition = session.not(session.isNull(contactAttributeName)); // do not allow substring search on integer field imapUid } else if (!"imapUid".equals(contactAttributeName)) { // endsWith not supported by exchange, convert to contains if (mode == LDAP_SUBSTRING_FINAL || mode == LDAP_SUBSTRING_ANY) { condition = session.contains(contactAttributeName, value); } else { condition = session.startsWith(contactAttributeName, value); } } return condition; } public boolean isMatch(Map<String, String> person) { if (canIgnore) { // Ignore this filter return true; } String personAttributeValue = person.get(attributeName); if (personAttributeValue == null) { // No value to allow for filter match return false; } else if (value == null) { // This is a presence filter: found return true; } else if ((operator == LDAP_FILTER_EQUALITY) && personAttributeValue.equalsIgnoreCase(value)) { // Found an exact match return true; } else if ((operator == LDAP_FILTER_SUBSTRINGS) && (personAttributeValue.toLowerCase().indexOf(value.toLowerCase()) >= 0)) { // Found a substring match return true; } return false; } public Map<String, ExchangeSession.Contact> findInGAL(ExchangeSession session, Set<String> returningAttributes, int sizeLimit) throws IOException { if (canIgnore) { return null; } String galFindAttributeName = getGalFindAttributeName(); if (galFindAttributeName != null) { // quick fix for cn=* filter Map<String, ExchangeSession.Contact> galPersons = session.galFind(session.startsWith(attributeName, "*".equals(value) ? "A" : value), returningAttributes, sizeLimit); if (operator == LDAP_FILTER_EQUALITY) { // Make sure only exact matches are returned Map<String, ExchangeSession.Contact> results = new HashMap<String, ExchangeSession.Contact>(); for (ExchangeSession.Contact person : galPersons.values()) { if (isMatch(person)) { // Found an exact match results.put(person.get("uid"), person); } } return results; } else { return galPersons; } } return null; } public void add(LdapFilter filter) { // Should never be called DavGatewayTray.error(new BundleMessage("LOG_LDAP_UNSUPPORTED_FILTER", "nested simple filters")); } public String getGalFindAttributeName() { return CRITERIA_MAP.get(attributeName); } } /** * Convert contact attribute name to LDAP attribute name. * * @param ldapAttributeName ldap attribute name * @return contact attribute name */ protected static String getContactAttributeName(String ldapAttributeName) { String contactAttributeName = null; // first look in contact attributes if (ExchangeSession.CONTACT_ATTRIBUTES.contains(ldapAttributeName)) { contactAttributeName = ldapAttributeName; } else if (LDAP_TO_CONTACT_ATTRIBUTE_MAP.containsKey(ldapAttributeName)) { String mappedAttribute = LDAP_TO_CONTACT_ATTRIBUTE_MAP.get(ldapAttributeName); if (mappedAttribute != null) { contactAttributeName = mappedAttribute; } } else { DavGatewayTray.debug(new BundleMessage("UNKNOWN_ATTRIBUTE", ldapAttributeName)); } return contactAttributeName; } /** * Convert LDAP attribute name to contact attribute name. * * @param contactAttributeName ldap attribute name * @return contact attribute name */ protected static String getLdapAttributeName(String contactAttributeName) { String mappedAttributeName = CONTACT_TO_LDAP_ATTRIBUTE_MAP.get(contactAttributeName); if (mappedAttributeName != null) { return mappedAttributeName; } else { return contactAttributeName; } } protected class SearchThread extends Thread { private final int currentMessageId; private final String dn; private final int scope; private final int sizeLimit; private final int timelimit; private final LdapFilter ldapFilter; private final Set<String> returningAttributes; private boolean abandon; protected SearchThread(String threadName, int currentMessageId, String dn, int scope, int sizeLimit, int timelimit, LdapFilter ldapFilter, Set<String> returningAttributes) { super(threadName + "-Search-" + currentMessageId); this.currentMessageId = currentMessageId; this.dn = dn; this.scope = scope; this.sizeLimit = sizeLimit; this.timelimit = timelimit; this.ldapFilter = ldapFilter; this.returningAttributes = returningAttributes; } /** * Abandon search. */ protected void abandon() { abandon = true; } @Override public void run() { try { int size = 0; DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH", currentMessageId, dn, scope, sizeLimit, timelimit, ldapFilter.toString(), returningAttributes)); if (scope == SCOPE_BASE_OBJECT) { if ("".equals(dn)) { size = 1; sendRootDSE(currentMessageId); } else if (BASE_CONTEXT.equals(dn)) { size = 1; // root sendBaseContext(currentMessageId); } else if (dn.startsWith("uid=") && dn.indexOf(',') > 0) { if (session != null) { // single user request String uid = dn.substring("uid=".length(), dn.indexOf(',')); Map<String, ExchangeSession.Contact> persons = null; // first search in contact try { // check if this is a contact uid Integer.parseInt(uid); persons = contactFind(session.isEqualTo("imapUid", uid), returningAttributes, sizeLimit); } catch (NumberFormatException e) { // ignore, this is not a contact uid } // then in GAL if (persons == null || persons.isEmpty()) { persons = session.galFind(session.isEqualTo("uid", uid), returningAttributes, sizeLimit); ExchangeSession.Contact person = persons.get(uid.toLowerCase()); // filter out non exact results if (persons.size() > 1 || person == null) { persons = new HashMap<String, ExchangeSession.Contact>(); if (person != null) { persons.put(uid.toLowerCase(), person); } } } size = persons.size(); sendPersons(currentMessageId, dn.substring(dn.indexOf(',')), persons, returningAttributes); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn)); } } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn)); } } else if (COMPUTER_CONTEXT.equals(dn)) { size = 1; // computer context for iCal sendComputerContext(currentMessageId, returningAttributes); } else if ((BASE_CONTEXT.equalsIgnoreCase(dn) || OD_USER_CONTEXT.equalsIgnoreCase(dn))) { if (session != null) { Map<String, ExchangeSession.Contact> persons = new HashMap<String, ExchangeSession.Contact>(); if (ldapFilter.isFullSearch()) { // append personal contacts first for (ExchangeSession.Contact person : contactFind(null, returningAttributes, sizeLimit).values()) { persons.put(person.get("imapUid"), person); if (persons.size() == sizeLimit) { break; } } // full search - for (char c = 'A'; c < 'Z'; c++) { + for (char c = 'A'; c <= 'Z'; c++) { if (!abandon && persons.size() < sizeLimit) { for (ExchangeSession.Contact person : session.galFind(session.startsWith("uid", String.valueOf(c)), returningAttributes, sizeLimit).values()) { persons.put(person.get("uid"), person); if (persons.size() == sizeLimit) { break; } } } if (persons.size() == sizeLimit) { break; } } } else { // append personal contacts first ExchangeSession.Condition filter = ldapFilter.getContactSearchFilter(); // if ldapfilter is not a full search and filter is null, // ignored all attribute filters => return empty results if (ldapFilter.isFullSearch() || filter != null) { for (ExchangeSession.Contact person : contactFind(filter, returningAttributes, sizeLimit).values()) { persons.put(person.get("imapUid"), person); if (persons.size() == sizeLimit) { break; } } if (!abandon && persons.size() < sizeLimit) { for (ExchangeSession.Contact person : ldapFilter.findInGAL(session, returningAttributes, sizeLimit - persons.size()).values()) { if (persons.size() == sizeLimit) { break; } persons.put(person.get("uid"), person); } } } } size = persons.size(); DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_FOUND_RESULTS", currentMessageId, size)); sendPersons(currentMessageId, ", " + dn, persons, returningAttributes); DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_END", currentMessageId)); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn)); } } else if (dn != null && dn.length() > 0) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn)); } // iCal: do not send LDAP_SIZE_LIMIT_EXCEEDED on apple-computer search by cn with sizelimit 1 if (size > 1 && size == sizeLimit) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SIZE_LIMIT_EXCEEDED", currentMessageId)); sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SIZE_LIMIT_EXCEEDED, ""); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SUCCESS", currentMessageId)); sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SUCCESS, ""); } } catch (SocketException e) { // client closed connection DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION")); } catch (IOException e) { DavGatewayTray.log(e); try { sendErr(currentMessageId, LDAP_REP_RESULT, e); } catch (IOException e2) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { synchronized (searchThreadMap) { searchThreadMap.remove(currentMessageId); } } } /** * Search users in contacts folder * * @param condition search filter * @param returningAttributes requested attributes * @param maxCount maximum item count * @return List of users * @throws IOException on error */ public Map<String, ExchangeSession.Contact> contactFind(ExchangeSession.Condition condition, Set<String> returningAttributes, int maxCount) throws IOException { Set<String> contactReturningAttributes; if (returningAttributes != null && !returningAttributes.isEmpty()) { contactReturningAttributes = new HashSet<String>(); // always return uid contactReturningAttributes.add("imapUid"); for (String attribute : returningAttributes) { String contactAttributeName = getContactAttributeName(attribute); if (contactAttributeName != null) { contactReturningAttributes.add(contactAttributeName); } } } else { contactReturningAttributes = ExchangeSession.CONTACT_ATTRIBUTES; } Map<String, ExchangeSession.Contact> results = new HashMap<String, ExchangeSession.Contact>(); List<ExchangeSession.Contact> contacts = session.searchContacts(ExchangeSession.CONTACTS, contactReturningAttributes, condition, maxCount); for (ExchangeSession.Contact contact : contacts) { // use imapUid as uid String imapUid = contact.get("imapUid"); if (imapUid != null) { contact.put("uid", imapUid); contact.remove("imapUid"); results.put(imapUid, contact); } } return results; } /** * Convert to LDAP attributes and send entry * * @param currentMessageId current Message Id * @param baseContext request base context (BASE_CONTEXT or OD_BASE_CONTEXT) * @param persons persons Map * @param returningAttributes returning attributes * @throws IOException on error */ protected void sendPersons(int currentMessageId, String baseContext, Map<String, ExchangeSession.Contact> persons, Set<String> returningAttributes) throws IOException { boolean needObjectClasses = returningAttributes.contains("objectclass") || returningAttributes.isEmpty(); boolean returnAllAttributes = returningAttributes.isEmpty(); for (ExchangeSession.Contact person : persons.values()) { if (abandon) { break; } Map<String, Object> ldapPerson = new HashMap<String, Object>(); // convert GAL entries /*if (person.get("uid") != null) { // TODO: move to galFind // add detailed information, only for GAL entries if (needDetails) { session.galLookup(person); } // Process all attributes that are mapped from exchange for (Map.Entry<String, String> entry : ATTRIBUTE_MAP.entrySet()) { String ldapAttribute = entry.getKey(); String exchangeAttribute = entry.getValue(); String value = person.get(exchangeAttribute); // contactFind return ldap attributes directly if (value == null) { value = person.get(ldapAttribute); } if (value != null && (returnAllAttributes || returningAttributes.contains(ldapAttribute.toLowerCase()))) { ldapPerson.put(ldapAttribute, value); } } // TODO // iCal fix to suit both iCal 3 and 4: move cn to sn, remove cn if (iCalSearch && ldapPerson.get("cn") != null && returningAttributes.contains("sn")) { ldapPerson.put("sn", ldapPerson.get("cn")); ldapPerson.remove("cn"); } } else {*/ // convert Contact entries if (returnAllAttributes) { // just convert contact attributes to default ldap names for (Map.Entry<String, String> entry : person.entrySet()) { String ldapAttribute = getLdapAttributeName(entry.getKey()); String value = entry.getValue(); if (value != null) { ldapPerson.put(ldapAttribute, value); } } } else { // always map uid ldapPerson.put("uid", person.get("uid")); // iterate over requested attributes for (String ldapAttribute : returningAttributes) { String contactAttribute = getContactAttributeName(ldapAttribute); String value = person.get(contactAttribute); if (value != null) { if (ldapAttribute.startsWith("birth")) { SimpleDateFormat parser = ExchangeSession.getZuluDateFormat(); Calendar calendar = Calendar.getInstance(); try { calendar.setTime(parser.parse(value)); } catch (ParseException e) { throw new IOException(e); } if ("birthday".equals(ldapAttribute)) { value = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); } else if ("birthmonth".equals(ldapAttribute)) { value = String.valueOf(calendar.get(Calendar.MONTH) + 1); } else if ("birthyear".equals(ldapAttribute)) { value = String.valueOf(calendar.get(Calendar.YEAR)); } } ldapPerson.put(ldapAttribute, value); } } } //} // Process all attributes which have static mappings for (Map.Entry<String, String> entry : STATIC_ATTRIBUTE_MAP.entrySet()) { String ldapAttribute = entry.getKey(); String value = entry.getValue(); if (value != null && (returnAllAttributes || returningAttributes.contains(ldapAttribute.toLowerCase()))) { ldapPerson.put(ldapAttribute, value); } } if (needObjectClasses) { ldapPerson.put("objectClass", PERSON_OBJECT_CLASSES); } // iCal: copy email to apple-generateduid, encode @ if (returnAllAttributes || returningAttributes.contains("apple-generateduid")) { String mail = (String) ldapPerson.get("mail"); if (mail != null) { ldapPerson.put("apple-generateduid", mail.replaceAll("@", "__AT__")); } else { // failover, should not happen ldapPerson.put("apple-generateduid", ldapPerson.get("uid")); } } // iCal: replace current user alias with login name if (session.getAlias().equals(ldapPerson.get("uid"))) { if (returningAttributes.contains("uidnumber")) { ldapPerson.put("uidnumber", userName); } } DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SEND_PERSON", currentMessageId, ldapPerson.get("uid"), baseContext, ldapPerson)); sendEntry(currentMessageId, "uid=" + ldapPerson.get("uid") + baseContext, ldapPerson); } } } }
true
true
public void run() { try { int size = 0; DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH", currentMessageId, dn, scope, sizeLimit, timelimit, ldapFilter.toString(), returningAttributes)); if (scope == SCOPE_BASE_OBJECT) { if ("".equals(dn)) { size = 1; sendRootDSE(currentMessageId); } else if (BASE_CONTEXT.equals(dn)) { size = 1; // root sendBaseContext(currentMessageId); } else if (dn.startsWith("uid=") && dn.indexOf(',') > 0) { if (session != null) { // single user request String uid = dn.substring("uid=".length(), dn.indexOf(',')); Map<String, ExchangeSession.Contact> persons = null; // first search in contact try { // check if this is a contact uid Integer.parseInt(uid); persons = contactFind(session.isEqualTo("imapUid", uid), returningAttributes, sizeLimit); } catch (NumberFormatException e) { // ignore, this is not a contact uid } // then in GAL if (persons == null || persons.isEmpty()) { persons = session.galFind(session.isEqualTo("uid", uid), returningAttributes, sizeLimit); ExchangeSession.Contact person = persons.get(uid.toLowerCase()); // filter out non exact results if (persons.size() > 1 || person == null) { persons = new HashMap<String, ExchangeSession.Contact>(); if (person != null) { persons.put(uid.toLowerCase(), person); } } } size = persons.size(); sendPersons(currentMessageId, dn.substring(dn.indexOf(',')), persons, returningAttributes); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn)); } } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn)); } } else if (COMPUTER_CONTEXT.equals(dn)) { size = 1; // computer context for iCal sendComputerContext(currentMessageId, returningAttributes); } else if ((BASE_CONTEXT.equalsIgnoreCase(dn) || OD_USER_CONTEXT.equalsIgnoreCase(dn))) { if (session != null) { Map<String, ExchangeSession.Contact> persons = new HashMap<String, ExchangeSession.Contact>(); if (ldapFilter.isFullSearch()) { // append personal contacts first for (ExchangeSession.Contact person : contactFind(null, returningAttributes, sizeLimit).values()) { persons.put(person.get("imapUid"), person); if (persons.size() == sizeLimit) { break; } } // full search for (char c = 'A'; c < 'Z'; c++) { if (!abandon && persons.size() < sizeLimit) { for (ExchangeSession.Contact person : session.galFind(session.startsWith("uid", String.valueOf(c)), returningAttributes, sizeLimit).values()) { persons.put(person.get("uid"), person); if (persons.size() == sizeLimit) { break; } } } if (persons.size() == sizeLimit) { break; } } } else { // append personal contacts first ExchangeSession.Condition filter = ldapFilter.getContactSearchFilter(); // if ldapfilter is not a full search and filter is null, // ignored all attribute filters => return empty results if (ldapFilter.isFullSearch() || filter != null) { for (ExchangeSession.Contact person : contactFind(filter, returningAttributes, sizeLimit).values()) { persons.put(person.get("imapUid"), person); if (persons.size() == sizeLimit) { break; } } if (!abandon && persons.size() < sizeLimit) { for (ExchangeSession.Contact person : ldapFilter.findInGAL(session, returningAttributes, sizeLimit - persons.size()).values()) { if (persons.size() == sizeLimit) { break; } persons.put(person.get("uid"), person); } } } } size = persons.size(); DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_FOUND_RESULTS", currentMessageId, size)); sendPersons(currentMessageId, ", " + dn, persons, returningAttributes); DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_END", currentMessageId)); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn)); } } else if (dn != null && dn.length() > 0) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn)); } // iCal: do not send LDAP_SIZE_LIMIT_EXCEEDED on apple-computer search by cn with sizelimit 1 if (size > 1 && size == sizeLimit) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SIZE_LIMIT_EXCEEDED", currentMessageId)); sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SIZE_LIMIT_EXCEEDED, ""); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SUCCESS", currentMessageId)); sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SUCCESS, ""); } } catch (SocketException e) { // client closed connection DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION")); } catch (IOException e) { DavGatewayTray.log(e); try { sendErr(currentMessageId, LDAP_REP_RESULT, e); } catch (IOException e2) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { synchronized (searchThreadMap) { searchThreadMap.remove(currentMessageId); } } }
public void run() { try { int size = 0; DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH", currentMessageId, dn, scope, sizeLimit, timelimit, ldapFilter.toString(), returningAttributes)); if (scope == SCOPE_BASE_OBJECT) { if ("".equals(dn)) { size = 1; sendRootDSE(currentMessageId); } else if (BASE_CONTEXT.equals(dn)) { size = 1; // root sendBaseContext(currentMessageId); } else if (dn.startsWith("uid=") && dn.indexOf(',') > 0) { if (session != null) { // single user request String uid = dn.substring("uid=".length(), dn.indexOf(',')); Map<String, ExchangeSession.Contact> persons = null; // first search in contact try { // check if this is a contact uid Integer.parseInt(uid); persons = contactFind(session.isEqualTo("imapUid", uid), returningAttributes, sizeLimit); } catch (NumberFormatException e) { // ignore, this is not a contact uid } // then in GAL if (persons == null || persons.isEmpty()) { persons = session.galFind(session.isEqualTo("uid", uid), returningAttributes, sizeLimit); ExchangeSession.Contact person = persons.get(uid.toLowerCase()); // filter out non exact results if (persons.size() > 1 || person == null) { persons = new HashMap<String, ExchangeSession.Contact>(); if (person != null) { persons.put(uid.toLowerCase(), person); } } } size = persons.size(); sendPersons(currentMessageId, dn.substring(dn.indexOf(',')), persons, returningAttributes); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn)); } } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn)); } } else if (COMPUTER_CONTEXT.equals(dn)) { size = 1; // computer context for iCal sendComputerContext(currentMessageId, returningAttributes); } else if ((BASE_CONTEXT.equalsIgnoreCase(dn) || OD_USER_CONTEXT.equalsIgnoreCase(dn))) { if (session != null) { Map<String, ExchangeSession.Contact> persons = new HashMap<String, ExchangeSession.Contact>(); if (ldapFilter.isFullSearch()) { // append personal contacts first for (ExchangeSession.Contact person : contactFind(null, returningAttributes, sizeLimit).values()) { persons.put(person.get("imapUid"), person); if (persons.size() == sizeLimit) { break; } } // full search for (char c = 'A'; c <= 'Z'; c++) { if (!abandon && persons.size() < sizeLimit) { for (ExchangeSession.Contact person : session.galFind(session.startsWith("uid", String.valueOf(c)), returningAttributes, sizeLimit).values()) { persons.put(person.get("uid"), person); if (persons.size() == sizeLimit) { break; } } } if (persons.size() == sizeLimit) { break; } } } else { // append personal contacts first ExchangeSession.Condition filter = ldapFilter.getContactSearchFilter(); // if ldapfilter is not a full search and filter is null, // ignored all attribute filters => return empty results if (ldapFilter.isFullSearch() || filter != null) { for (ExchangeSession.Contact person : contactFind(filter, returningAttributes, sizeLimit).values()) { persons.put(person.get("imapUid"), person); if (persons.size() == sizeLimit) { break; } } if (!abandon && persons.size() < sizeLimit) { for (ExchangeSession.Contact person : ldapFilter.findInGAL(session, returningAttributes, sizeLimit - persons.size()).values()) { if (persons.size() == sizeLimit) { break; } persons.put(person.get("uid"), person); } } } } size = persons.size(); DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_FOUND_RESULTS", currentMessageId, size)); sendPersons(currentMessageId, ", " + dn, persons, returningAttributes); DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_END", currentMessageId)); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_ANONYMOUS_ACCESS_FORBIDDEN", currentMessageId, dn)); } } else if (dn != null && dn.length() > 0) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_INVALID_DN", currentMessageId, dn)); } // iCal: do not send LDAP_SIZE_LIMIT_EXCEEDED on apple-computer search by cn with sizelimit 1 if (size > 1 && size == sizeLimit) { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SIZE_LIMIT_EXCEEDED", currentMessageId)); sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SIZE_LIMIT_EXCEEDED, ""); } else { DavGatewayTray.debug(new BundleMessage("LOG_LDAP_REQ_SEARCH_SUCCESS", currentMessageId)); sendClient(currentMessageId, LDAP_REP_RESULT, LDAP_SUCCESS, ""); } } catch (SocketException e) { // client closed connection DavGatewayTray.debug(new BundleMessage("LOG_CLIENT_CLOSED_CONNECTION")); } catch (IOException e) { DavGatewayTray.log(e); try { sendErr(currentMessageId, LDAP_REP_RESULT, e); } catch (IOException e2) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { synchronized (searchThreadMap) { searchThreadMap.remove(currentMessageId); } } }
diff --git a/src/com/orangeleap/tangerine/web/common/TangerineListHelper.java b/src/com/orangeleap/tangerine/web/common/TangerineListHelper.java index b0219dbd..d95ee447 100644 --- a/src/com/orangeleap/tangerine/web/common/TangerineListHelper.java +++ b/src/com/orangeleap/tangerine/web/common/TangerineListHelper.java @@ -1,144 +1,151 @@ /* * Copyright (c) 2009. Orange Leap Inc. Active Constituent * Relationship Management Platform. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.orangeleap.tangerine.web.common; import com.orangeleap.tangerine.controller.TangerineForm; import com.orangeleap.tangerine.domain.customization.CustomField; import com.orangeleap.tangerine.domain.customization.SectionField; import com.orangeleap.tangerine.service.customization.PageCustomizationService; import com.orangeleap.tangerine.type.AccessType; import com.orangeleap.tangerine.type.PageType; import com.orangeleap.tangerine.util.HttpUtil; import com.orangeleap.tangerine.util.StringConstants; import com.orangeleap.tangerine.util.TangerineUserHelper; import com.orangeleap.tangerine.web.customization.tag.fields.handlers.ExtTypeHandler; import com.orangeleap.tangerine.web.customization.tag.fields.handlers.FieldHandler; import com.orangeleap.tangerine.web.customization.tag.fields.handlers.FieldHandlerHelper; import org.springframework.beans.BeanWrapper; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.stereotype.Component; import org.springframework.web.util.WebUtils; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Component("tangerineListHelper") public class TangerineListHelper { @Resource(name = "pageCustomizationService") protected PageCustomizationService pageCustomizationService; @Resource(name = "fieldHandlerHelper") protected FieldHandlerHelper fieldHandlerHelper; @Resource(name = "tangerineUserHelper") protected TangerineUserHelper tangerineUserHelper; public static final String SORT_KEY_PREFIX = "a"; @SuppressWarnings("unchecked") // TODO: move to annotation public boolean isAccessAllowed(HttpServletRequest request, PageType pageType) { Map<String, AccessType> pageAccess = (Map<String, AccessType>) WebUtils.getSessionAttribute(request, "pageAccess"); return pageAccess.get(pageType.getPageName()) == AccessType.ALLOWED; } // TODO: move to annotation public void checkAccess(HttpServletRequest request, PageType pageType) { if ( ! isAccessAllowed(request, pageType)) { throw new RuntimeException("You are not authorized to access this page"); } } public void addListFieldsToMap(HttpServletRequest request, List<SectionField> sectionFields, List entities, List<Map<String, Object>> paramMapList, boolean useAliasName, boolean useAliasId) { int sequence = 0; if (entities != null) { for (Object thisEntity : entities) { BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(thisEntity); /** * If useAliasId == true, set the aliasId to the ID and reset to ID to the next sequence number */ if (useAliasId && beanWrapper.isWritableProperty(StringConstants.ALIAS_ID) && beanWrapper.isReadableProperty(StringConstants.ID)) { beanWrapper.setPropertyValue(StringConstants.ALIAS_ID, beanWrapper.getPropertyValue(StringConstants.ID)); beanWrapper.setPropertyValue(StringConstants.ID, sequence++); } Map<String, Object> paramMap = new HashMap<String, Object>(); int x = 0; for (SectionField field : sectionFields) { String fieldPropertyName = field.getFieldPropertyName(); if (beanWrapper.isReadableProperty(fieldPropertyName)) { FieldHandler handler = fieldHandlerHelper.lookupFieldHandler(field.getFieldType()); + boolean isCustomField = false; Object displayValue = StringConstants.EMPTY; if (beanWrapper.isReadableProperty(field.getFieldPropertyName())) { Object fieldValue = beanWrapper.getPropertyValue(field.getFieldPropertyName()); if (fieldValue instanceof CustomField) { fieldValue = ((CustomField) fieldValue).getValue(); + isCustomField = true; } if (field.getFieldPropertyName().equals(StringConstants.ID) || field.getFieldPropertyName().equals(StringConstants.ALIAS_ID)) { displayValue = fieldValue; } else { displayValue = handler.resolveDisplayValue(request, PropertyAccessorFactory.forBeanPropertyAccess(thisEntity), field, fieldValue); } } if (displayValue instanceof String) { displayValue = HttpUtil.escapeDoubleQuoteReturns((String) displayValue); String extType = ExtTypeHandler.findExtDataType(beanWrapper.getPropertyType(field.getFieldPropertyName())); if (ExtTypeHandler.EXT_BOOLEAN.equals(extType) && ("Y".equalsIgnoreCase((String) displayValue) || "yes".equalsIgnoreCase((String) displayValue) || "T".equalsIgnoreCase((String) displayValue) || "true".equalsIgnoreCase((String) displayValue))) { displayValue = "true"; } } - String key = useAliasName && ! StringConstants.ID.equals(fieldPropertyName) && ! StringConstants.ALIAS_ID.equals(fieldPropertyName) - ? new StringBuilder(SORT_KEY_PREFIX).append(x++).toString() : TangerineForm.escapeFieldName(fieldPropertyName); + String key; + if (useAliasName && ! StringConstants.ID.equals(fieldPropertyName) && ! StringConstants.ALIAS_ID.equals(fieldPropertyName)) { + key = new StringBuilder(SORT_KEY_PREFIX).append(x++).toString(); + } + else { + key = TangerineForm.escapeFieldName(isCustomField ? fieldPropertyName + StringConstants.DOT_VALUE : fieldPropertyName); + } paramMap.put(key, displayValue); } } paramMapList.add(paramMap); } } } public Map<String, Object> initMetaData(int start, int limit) { final Map<String, Object> metaDataMap = new LinkedHashMap<String, Object>(); metaDataMap.put(StringConstants.ID_PROPERTY, StringConstants.ID); metaDataMap.put(StringConstants.ROOT, StringConstants.ROWS); metaDataMap.put(StringConstants.TOTAL_PROPERTY, StringConstants.TOTAL_ROWS); metaDataMap.put(StringConstants.SUCCESS_PROPERTY, StringConstants.SUCCESS); metaDataMap.put(StringConstants.START, start); metaDataMap.put(StringConstants.LIMIT, limit); return metaDataMap; } public List<SectionField> findSectionFields(String listPageName) { return pageCustomizationService.readSectionFieldsByPageTypeRoles(PageType.valueOf(listPageName), tangerineUserHelper.lookupUserRoles()); } }
false
true
public void addListFieldsToMap(HttpServletRequest request, List<SectionField> sectionFields, List entities, List<Map<String, Object>> paramMapList, boolean useAliasName, boolean useAliasId) { int sequence = 0; if (entities != null) { for (Object thisEntity : entities) { BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(thisEntity); /** * If useAliasId == true, set the aliasId to the ID and reset to ID to the next sequence number */ if (useAliasId && beanWrapper.isWritableProperty(StringConstants.ALIAS_ID) && beanWrapper.isReadableProperty(StringConstants.ID)) { beanWrapper.setPropertyValue(StringConstants.ALIAS_ID, beanWrapper.getPropertyValue(StringConstants.ID)); beanWrapper.setPropertyValue(StringConstants.ID, sequence++); } Map<String, Object> paramMap = new HashMap<String, Object>(); int x = 0; for (SectionField field : sectionFields) { String fieldPropertyName = field.getFieldPropertyName(); if (beanWrapper.isReadableProperty(fieldPropertyName)) { FieldHandler handler = fieldHandlerHelper.lookupFieldHandler(field.getFieldType()); Object displayValue = StringConstants.EMPTY; if (beanWrapper.isReadableProperty(field.getFieldPropertyName())) { Object fieldValue = beanWrapper.getPropertyValue(field.getFieldPropertyName()); if (fieldValue instanceof CustomField) { fieldValue = ((CustomField) fieldValue).getValue(); } if (field.getFieldPropertyName().equals(StringConstants.ID) || field.getFieldPropertyName().equals(StringConstants.ALIAS_ID)) { displayValue = fieldValue; } else { displayValue = handler.resolveDisplayValue(request, PropertyAccessorFactory.forBeanPropertyAccess(thisEntity), field, fieldValue); } } if (displayValue instanceof String) { displayValue = HttpUtil.escapeDoubleQuoteReturns((String) displayValue); String extType = ExtTypeHandler.findExtDataType(beanWrapper.getPropertyType(field.getFieldPropertyName())); if (ExtTypeHandler.EXT_BOOLEAN.equals(extType) && ("Y".equalsIgnoreCase((String) displayValue) || "yes".equalsIgnoreCase((String) displayValue) || "T".equalsIgnoreCase((String) displayValue) || "true".equalsIgnoreCase((String) displayValue))) { displayValue = "true"; } } String key = useAliasName && ! StringConstants.ID.equals(fieldPropertyName) && ! StringConstants.ALIAS_ID.equals(fieldPropertyName) ? new StringBuilder(SORT_KEY_PREFIX).append(x++).toString() : TangerineForm.escapeFieldName(fieldPropertyName); paramMap.put(key, displayValue); } } paramMapList.add(paramMap); } } }
public void addListFieldsToMap(HttpServletRequest request, List<SectionField> sectionFields, List entities, List<Map<String, Object>> paramMapList, boolean useAliasName, boolean useAliasId) { int sequence = 0; if (entities != null) { for (Object thisEntity : entities) { BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(thisEntity); /** * If useAliasId == true, set the aliasId to the ID and reset to ID to the next sequence number */ if (useAliasId && beanWrapper.isWritableProperty(StringConstants.ALIAS_ID) && beanWrapper.isReadableProperty(StringConstants.ID)) { beanWrapper.setPropertyValue(StringConstants.ALIAS_ID, beanWrapper.getPropertyValue(StringConstants.ID)); beanWrapper.setPropertyValue(StringConstants.ID, sequence++); } Map<String, Object> paramMap = new HashMap<String, Object>(); int x = 0; for (SectionField field : sectionFields) { String fieldPropertyName = field.getFieldPropertyName(); if (beanWrapper.isReadableProperty(fieldPropertyName)) { FieldHandler handler = fieldHandlerHelper.lookupFieldHandler(field.getFieldType()); boolean isCustomField = false; Object displayValue = StringConstants.EMPTY; if (beanWrapper.isReadableProperty(field.getFieldPropertyName())) { Object fieldValue = beanWrapper.getPropertyValue(field.getFieldPropertyName()); if (fieldValue instanceof CustomField) { fieldValue = ((CustomField) fieldValue).getValue(); isCustomField = true; } if (field.getFieldPropertyName().equals(StringConstants.ID) || field.getFieldPropertyName().equals(StringConstants.ALIAS_ID)) { displayValue = fieldValue; } else { displayValue = handler.resolveDisplayValue(request, PropertyAccessorFactory.forBeanPropertyAccess(thisEntity), field, fieldValue); } } if (displayValue instanceof String) { displayValue = HttpUtil.escapeDoubleQuoteReturns((String) displayValue); String extType = ExtTypeHandler.findExtDataType(beanWrapper.getPropertyType(field.getFieldPropertyName())); if (ExtTypeHandler.EXT_BOOLEAN.equals(extType) && ("Y".equalsIgnoreCase((String) displayValue) || "yes".equalsIgnoreCase((String) displayValue) || "T".equalsIgnoreCase((String) displayValue) || "true".equalsIgnoreCase((String) displayValue))) { displayValue = "true"; } } String key; if (useAliasName && ! StringConstants.ID.equals(fieldPropertyName) && ! StringConstants.ALIAS_ID.equals(fieldPropertyName)) { key = new StringBuilder(SORT_KEY_PREFIX).append(x++).toString(); } else { key = TangerineForm.escapeFieldName(isCustomField ? fieldPropertyName + StringConstants.DOT_VALUE : fieldPropertyName); } paramMap.put(key, displayValue); } } paramMapList.add(paramMap); } } }
diff --git a/src/main/java/org/basex/query/path/AxisPath.java b/src/main/java/org/basex/query/path/AxisPath.java index c1fb00ac9..a032b59d8 100644 --- a/src/main/java/org/basex/query/path/AxisPath.java +++ b/src/main/java/org/basex/query/path/AxisPath.java @@ -1,456 +1,454 @@ package org.basex.query.path; import static org.basex.query.QueryText.*; import org.basex.data.Data; import org.basex.index.Stats; import org.basex.index.path.PathNode; import org.basex.query.QueryContext; import org.basex.query.QueryException; import org.basex.query.expr.Expr; import org.basex.query.expr.Filter; import org.basex.query.expr.Pos; import org.basex.query.item.Bln; import org.basex.query.item.Empty; import org.basex.query.item.ANode; import org.basex.query.item.NodeType; import org.basex.query.item.SeqType; import org.basex.query.item.Value; import org.basex.query.iter.Iter; import org.basex.query.iter.NodeCache; import org.basex.query.iter.NodeIter; import org.basex.query.path.Test.Name; import static org.basex.query.util.Err.*; import org.basex.query.util.IndexContext; import org.basex.query.util.Var; import org.basex.util.Array; import org.basex.util.InputInfo; import org.basex.util.list.ObjList; /** * Axis path expression. * * @author BaseX Team 2005-12, BSD License * @author Christian Gruen */ public class AxisPath extends Path { /** Flag for result caching. */ private boolean cache; /** Cached result. */ private NodeCache citer; /** Last visited item. */ private Value lvalue; /** * Constructor. * @param ii input info * @param r root expression; can be a {@code null} reference * @param s axis steps */ AxisPath(final InputInfo ii, final Expr r, final Expr... s) { super(ii, r, s); } /** * If possible, converts this path expression to a path iterator. * @param ctx query context * @return resulting operator */ final AxisPath finish(final QueryContext ctx) { // evaluate number of results size = size(ctx); type = SeqType.get(steps[steps.length - 1].type().type, size); return useIterator() ? new IterPath(input, root, steps, type, size) : this; } /** * Checks if the path can be rewritten for iterative evaluation. * @return resulting operator */ private boolean useIterator() { if(root == null || root.uses(Use.VAR) || !root.iterable()) return false; final int sl = steps.length; for(int s = 0; s < sl; ++s) { switch(step(s).axis) { // reverse axes - don't iterate case ANC: case ANCORSELF: case PREC: case PRECSIBL: return false; // multiple, unsorted results - only iterate at last step, // or if last step uses attribute axis case DESC: case DESCORSELF: case FOLL: case FOLLSIBL: return s + 1 == sl || s + 2 == sl && step(s + 1).axis == Axis.ATTR; // allow iteration for CHILD, ATTR, PARENT and SELF default: } } return true; } @Override protected final Expr compPath(final QueryContext ctx) throws QueryException { for(final Expr s : steps) checkUp(s, ctx); // merge two axis paths if(root instanceof AxisPath) { Expr[] st = ((AxisPath) root).steps; root = ((AxisPath) root).root; for(final Expr s : steps) st = Array.add(st, s); steps = st; // refresh root context ctx.compInfo(OPTMERGE); ctx.value = root(ctx); } final AxisStep s = voidStep(steps); if(s != null) COMPSELF.thrw(input, s); for(int i = 0; i != steps.length; ++i) { final Expr e = steps[i].comp(ctx); if(!(e instanceof AxisStep)) return e; steps[i] = e; } optSteps(ctx); // retrieve data reference final Data data = ctx.data(); if(data != null && ctx.value.type == NodeType.DOC) { // check index access Expr e = index(ctx, data); // check children path rewriting if(e == this) e = children(ctx, data); // return optimized expression if(e != this) return e.comp(ctx); } // analyze if result set can be cached - no predicates/variables... cache = root != null && !uses(Use.VAR); // if applicable, use iterative evaluation final Path path = finish(ctx); // heuristics: wrap with filter expression if only one result is expected return size() != 1 ? path : new Filter(input, this, Pos.get(1, size(), input)).comp2(ctx); } /** * If possible, returns an expression which accesses the index. * Otherwise, returns the original expression. * @param ctx query context * @param data data reference * @return resulting expression * @throws QueryException query exception */ private Expr index(final QueryContext ctx, final Data data) throws QueryException { // disallow relative paths and numeric predicates if(root == null || uses(Use.POS)) return this; // cache index access costs IndexContext ics = null; // cheapest predicate and step int pmin = 0; int smin = 0; // check if path can be converted to an index access for(int s = 0; s < steps.length; ++s) { // find cheapest index access final AxisStep stp = step(s); if(!stp.axis.down) break; // check if resulting index path will be duplicate free final boolean i = pathNodes(data, s) != null; // choose cheapest index access for(int p = 0; p < stp.preds.length; ++p) { final IndexContext ic = new IndexContext(ctx, data, stp, i); if(!stp.preds[p].indexAccessible(ic)) continue; if(ic.costs() == 0) { if(ic.not) { // not operator... accept all results stp.preds[p] = Bln.TRUE; continue; } // no results... ctx.compInfo(OPTNOINDEX, this); return Empty.SEQ; } if(ics == null || ics.costs() > ic.costs()) { ics = ic; pmin = p; smin = s; } } } // skip if no index access is possible, or if it is too expensive if(ics == null || ics.costs() > data.meta.size) return this; // replace expressions for index access final AxisStep stp = step(smin); final Expr ie = stp.preds[pmin].indexEquivalent(ics); if(ics.seq) { // sequential evaluation; do not invert path stp.preds[pmin] = ie; } else { // inverted path, which will be represented as predicate AxisStep[] invSteps = {}; // collect remaining predicates final Expr[] newPreds = new Expr[stp.preds.length - 1]; int c = 0; for(int p = 0; p != stp.preds.length; ++p) { if(p != pmin) newPreds[c++] = stp.preds[p]; } // check if path before index step needs to be inverted and traversed final Test test = DocTest.get(ctx, data); boolean inv = true; if(test == Test.DOC && data.meta.pathindex && data.meta.uptodate) { int j = 0; for(; j <= smin; ++j) { - // invert if axis is not a child or has predicates final AxisStep s = axisStep(j); - if(s == null) break; - if(s.axis != Axis.CHILD || s.preds.length > 0 && j != smin) break; - if(s.test.test == Name.ALL || s.test.test == null) continue; - if(s.test.test != Name.NAME) break; + // step must use child axis and name test, and have no predicates + if(s == null || s.test.test != Name.NAME || s.axis != Axis.CHILD || + j != smin && s.preds.length > 0) break; // support only unique paths with nodes on the correct level final int name = data.tagindex.id(s.test.name.local()); final ObjList<PathNode> pn = data.paths.desc(name, Data.ELEM); if(pn.size() != 1 || pn.get(0).level() != j + 1) break; } inv = j <= smin; } // invert path before index step if(inv) { for(int j = smin; j >= 0; --j) { final Axis ax = step(j).axis.invert(); if(ax == null) break; if(j != 0) { final AxisStep prev = step(j - 1); invSteps = Array.add(invSteps, AxisStep.get(input, ax, prev.test, prev.preds)); } else { // add document test for collections and axes other than ancestors if(test != Test.DOC || ax != Axis.ANC && ax != Axis.ANCORSELF) invSteps = Array.add(invSteps, AxisStep.get(input, ax, test)); } } } // create resulting expression final AxisPath result; final boolean simple = invSteps.length == 0 && newPreds.length == 0; if(ie instanceof AxisPath) { result = (AxisPath) ie; } else if(smin + 1 < steps.length || !simple) { result = simple ? new AxisPath(input, ie) : new AxisPath(input, ie, AxisStep.get(input, Axis.SELF, Test.NOD)); } else { return ie; } // add remaining predicates to last step final int ls = result.steps.length - 1; if(ls >= 0) { result.steps[ls] = result.step(ls).addPreds(newPreds); // add inverted path as predicate to last step if(invSteps.length != 0) result.steps[ls] = result.step(ls).addPreds(Path.get(input, null, invSteps)); } // add remaining steps for(int s = smin + 1; s < steps.length; ++s) { result.steps = Array.add(result.steps, steps[s]); } return result; } return this; } @Override public Iter iter(final QueryContext ctx) throws QueryException { final Value cv = ctx.value; final long cs = ctx.size; final long cp = ctx.pos; try { Value r = root != null ? ctx.value(root) : cv; if(!cache || citer == null || lvalue.type != NodeType.DOC || r.type != NodeType.DOC || !((ANode) lvalue).is((ANode) r)) { lvalue = r; citer = new NodeCache().random(); if(r != null) { final Iter ir = ctx.iter(r); while((r = ir.next()) != null) { ctx.value = r; iter(0, citer, ctx); } } else { ctx.value = null; iter(0, citer, ctx); } citer.sort(); } else { citer.reset(); } return citer; } finally { ctx.value = cv; ctx.size = cs; ctx.pos = cp; } } /** * Recursive step iterator. * @param l current step * @param nc node cache * @param ctx query context * @throws QueryException query exception */ private void iter(final int l, final NodeCache nc, final QueryContext ctx) throws QueryException { // cast is safe (steps will always return a {@link NodIter} instance final NodeIter ni = (NodeIter) ctx.iter(steps[l]); final boolean more = l + 1 != steps.length; for(ANode node; (node = ni.next()) != null;) { if(more) { ctx.value = node; iter(l + 1, nc, ctx); } else { ctx.checkStop(); nc.add(node); } } } /** * Inverts a location path. * @param r new root node * @param curr current location step * @return inverted path */ public final AxisPath invertPath(final Expr r, final AxisStep curr) { // hold the steps to the end of the inverted path int s = steps.length; final Expr[] e = new Expr[s--]; // add predicates of last step to new root node final Expr rt = step(s).preds.length != 0 ? new Filter(input, r, step(s).preds) : r; // add inverted steps in a backward manner int c = 0; while(--s >= 0) { e[c++] = AxisStep.get(input, step(s + 1).axis.invert(), step(s).test, step(s).preds); } e[c] = AxisStep.get(input, step(s + 1).axis.invert(), curr.test); return new AxisPath(input, rt, e); } @Override public final Expr addText(final QueryContext ctx) { final AxisStep s = step(steps.length - 1); if(s.preds.length != 0 || !s.axis.down || s.test.type == NodeType.ATT || s.test.test != Name.NAME && s.test.test != Name.STD) return this; final Data data = ctx.data(); if(data == null || !data.meta.uptodate) return this; final Stats stats = data.tagindex.stat( data.tagindex.id(s.test.name.local())); if(stats != null && stats.isLeaf()) { steps = Array.add(steps, AxisStep.get(input, Axis.CHILD, Test.TXT)); ctx.compInfo(OPTTEXT, this); } return this; } /** * Returns the specified axis step. * @param i index * @return step */ public final AxisStep step(final int i) { return (AxisStep) steps[i]; } /** * Returns a copy of the path expression. * @return copy */ public final Path copy() { final Expr[] stps = new Expr[steps.length]; for(int s = 0; s < steps.length; ++s) stps[s] = AxisStep.get(step(s)); return get(input, root, stps); } /** * Returns the path nodes that will result from this path. * @param ctx query context * @return path nodes, or {@code null} if nodes cannot be evaluated */ public ObjList<PathNode> nodes(final QueryContext ctx) { final Value rt = root(ctx); final Data data = rt != null && rt.type == NodeType.DOC ? rt.data() : null; if(data == null || !data.meta.pathindex || !data.meta.uptodate) return null; ObjList<PathNode> nodes = data.paths.root(); for(int s = 0; s < steps.length; s++) { final AxisStep curr = axisStep(s); if(curr == null) return null; nodes = curr.nodes(nodes, data); if(nodes == null) return null; } return nodes; } @Override public final int count(final Var v) { int c = 0; for(final Expr s : steps) c += s.count(v); return c + super.count(v); } @Override public final boolean removable(final Var v) { for(final Expr s : steps) if(!s.removable(v)) return false; return super.removable(v); } @Override public final Expr remove(final Var v) { for(int s = 0; s != steps.length; ++s) steps[s].remove(v); return super.remove(v); } @Override public final boolean iterable() { return true; } @Override public final boolean sameAs(final Expr cmp) { if(!(cmp instanceof AxisPath)) return false; final AxisPath ap = (AxisPath) cmp; if((root == null || ap.root == null) && root != ap.root || steps.length != ap.steps.length || root != null && !root.sameAs(ap.root)) return false; for(int s = 0; s < steps.length; ++s) { if(!steps[s].sameAs(ap.steps[s])) return false; } return true; } }
false
true
private Expr index(final QueryContext ctx, final Data data) throws QueryException { // disallow relative paths and numeric predicates if(root == null || uses(Use.POS)) return this; // cache index access costs IndexContext ics = null; // cheapest predicate and step int pmin = 0; int smin = 0; // check if path can be converted to an index access for(int s = 0; s < steps.length; ++s) { // find cheapest index access final AxisStep stp = step(s); if(!stp.axis.down) break; // check if resulting index path will be duplicate free final boolean i = pathNodes(data, s) != null; // choose cheapest index access for(int p = 0; p < stp.preds.length; ++p) { final IndexContext ic = new IndexContext(ctx, data, stp, i); if(!stp.preds[p].indexAccessible(ic)) continue; if(ic.costs() == 0) { if(ic.not) { // not operator... accept all results stp.preds[p] = Bln.TRUE; continue; } // no results... ctx.compInfo(OPTNOINDEX, this); return Empty.SEQ; } if(ics == null || ics.costs() > ic.costs()) { ics = ic; pmin = p; smin = s; } } } // skip if no index access is possible, or if it is too expensive if(ics == null || ics.costs() > data.meta.size) return this; // replace expressions for index access final AxisStep stp = step(smin); final Expr ie = stp.preds[pmin].indexEquivalent(ics); if(ics.seq) { // sequential evaluation; do not invert path stp.preds[pmin] = ie; } else { // inverted path, which will be represented as predicate AxisStep[] invSteps = {}; // collect remaining predicates final Expr[] newPreds = new Expr[stp.preds.length - 1]; int c = 0; for(int p = 0; p != stp.preds.length; ++p) { if(p != pmin) newPreds[c++] = stp.preds[p]; } // check if path before index step needs to be inverted and traversed final Test test = DocTest.get(ctx, data); boolean inv = true; if(test == Test.DOC && data.meta.pathindex && data.meta.uptodate) { int j = 0; for(; j <= smin; ++j) { // invert if axis is not a child or has predicates final AxisStep s = axisStep(j); if(s == null) break; if(s.axis != Axis.CHILD || s.preds.length > 0 && j != smin) break; if(s.test.test == Name.ALL || s.test.test == null) continue; if(s.test.test != Name.NAME) break; // support only unique paths with nodes on the correct level final int name = data.tagindex.id(s.test.name.local()); final ObjList<PathNode> pn = data.paths.desc(name, Data.ELEM); if(pn.size() != 1 || pn.get(0).level() != j + 1) break; } inv = j <= smin; } // invert path before index step if(inv) { for(int j = smin; j >= 0; --j) { final Axis ax = step(j).axis.invert(); if(ax == null) break; if(j != 0) { final AxisStep prev = step(j - 1); invSteps = Array.add(invSteps, AxisStep.get(input, ax, prev.test, prev.preds)); } else { // add document test for collections and axes other than ancestors if(test != Test.DOC || ax != Axis.ANC && ax != Axis.ANCORSELF) invSteps = Array.add(invSteps, AxisStep.get(input, ax, test)); } } } // create resulting expression final AxisPath result; final boolean simple = invSteps.length == 0 && newPreds.length == 0; if(ie instanceof AxisPath) { result = (AxisPath) ie; } else if(smin + 1 < steps.length || !simple) { result = simple ? new AxisPath(input, ie) : new AxisPath(input, ie, AxisStep.get(input, Axis.SELF, Test.NOD)); } else { return ie; } // add remaining predicates to last step final int ls = result.steps.length - 1; if(ls >= 0) { result.steps[ls] = result.step(ls).addPreds(newPreds); // add inverted path as predicate to last step if(invSteps.length != 0) result.steps[ls] = result.step(ls).addPreds(Path.get(input, null, invSteps)); } // add remaining steps for(int s = smin + 1; s < steps.length; ++s) { result.steps = Array.add(result.steps, steps[s]); } return result; } return this; }
private Expr index(final QueryContext ctx, final Data data) throws QueryException { // disallow relative paths and numeric predicates if(root == null || uses(Use.POS)) return this; // cache index access costs IndexContext ics = null; // cheapest predicate and step int pmin = 0; int smin = 0; // check if path can be converted to an index access for(int s = 0; s < steps.length; ++s) { // find cheapest index access final AxisStep stp = step(s); if(!stp.axis.down) break; // check if resulting index path will be duplicate free final boolean i = pathNodes(data, s) != null; // choose cheapest index access for(int p = 0; p < stp.preds.length; ++p) { final IndexContext ic = new IndexContext(ctx, data, stp, i); if(!stp.preds[p].indexAccessible(ic)) continue; if(ic.costs() == 0) { if(ic.not) { // not operator... accept all results stp.preds[p] = Bln.TRUE; continue; } // no results... ctx.compInfo(OPTNOINDEX, this); return Empty.SEQ; } if(ics == null || ics.costs() > ic.costs()) { ics = ic; pmin = p; smin = s; } } } // skip if no index access is possible, or if it is too expensive if(ics == null || ics.costs() > data.meta.size) return this; // replace expressions for index access final AxisStep stp = step(smin); final Expr ie = stp.preds[pmin].indexEquivalent(ics); if(ics.seq) { // sequential evaluation; do not invert path stp.preds[pmin] = ie; } else { // inverted path, which will be represented as predicate AxisStep[] invSteps = {}; // collect remaining predicates final Expr[] newPreds = new Expr[stp.preds.length - 1]; int c = 0; for(int p = 0; p != stp.preds.length; ++p) { if(p != pmin) newPreds[c++] = stp.preds[p]; } // check if path before index step needs to be inverted and traversed final Test test = DocTest.get(ctx, data); boolean inv = true; if(test == Test.DOC && data.meta.pathindex && data.meta.uptodate) { int j = 0; for(; j <= smin; ++j) { final AxisStep s = axisStep(j); // step must use child axis and name test, and have no predicates if(s == null || s.test.test != Name.NAME || s.axis != Axis.CHILD || j != smin && s.preds.length > 0) break; // support only unique paths with nodes on the correct level final int name = data.tagindex.id(s.test.name.local()); final ObjList<PathNode> pn = data.paths.desc(name, Data.ELEM); if(pn.size() != 1 || pn.get(0).level() != j + 1) break; } inv = j <= smin; } // invert path before index step if(inv) { for(int j = smin; j >= 0; --j) { final Axis ax = step(j).axis.invert(); if(ax == null) break; if(j != 0) { final AxisStep prev = step(j - 1); invSteps = Array.add(invSteps, AxisStep.get(input, ax, prev.test, prev.preds)); } else { // add document test for collections and axes other than ancestors if(test != Test.DOC || ax != Axis.ANC && ax != Axis.ANCORSELF) invSteps = Array.add(invSteps, AxisStep.get(input, ax, test)); } } } // create resulting expression final AxisPath result; final boolean simple = invSteps.length == 0 && newPreds.length == 0; if(ie instanceof AxisPath) { result = (AxisPath) ie; } else if(smin + 1 < steps.length || !simple) { result = simple ? new AxisPath(input, ie) : new AxisPath(input, ie, AxisStep.get(input, Axis.SELF, Test.NOD)); } else { return ie; } // add remaining predicates to last step final int ls = result.steps.length - 1; if(ls >= 0) { result.steps[ls] = result.step(ls).addPreds(newPreds); // add inverted path as predicate to last step if(invSteps.length != 0) result.steps[ls] = result.step(ls).addPreds(Path.get(input, null, invSteps)); } // add remaining steps for(int s = smin + 1; s < steps.length; ++s) { result.steps = Array.add(result.steps, steps[s]); } return result; } return this; }
diff --git a/src/main/org/codehaus/groovy/syntax/lexer/StringLexer.java b/src/main/org/codehaus/groovy/syntax/lexer/StringLexer.java index fdfefeb13..5f975e624 100644 --- a/src/main/org/codehaus/groovy/syntax/lexer/StringLexer.java +++ b/src/main/org/codehaus/groovy/syntax/lexer/StringLexer.java @@ -1,401 +1,404 @@ package org.codehaus.groovy.syntax.lexer; //{{{ imports import org.codehaus.groovy.syntax.ReadException; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.GroovyBugError; //}}} /** * A Lexer for processing standard strings. * * @author Chris Poirier */ public class StringLexer extends TextLexerBase { protected String delimiter = null; protected char watchFor; protected boolean allowGStrings = false; protected boolean emptyString = true; // If set, we need to send an empty string /** * If set true, the filter will allow \\ and \$ to pass through unchanged. * You should set this appropriately BEFORE setting source! */ public void allowGStrings( boolean allow ) { allowGStrings = allow; } /** * Returns a single STRING, then null. The STRING is all of the processed * input. Backslashes are stripped, with the \r, \n, and \t converted * appropriately. */ public Token undelegatedNextToken( ) throws ReadException, LexerException { if( emptyString ) { emptyString = false; return Token.newString( "", getStartLine(), getStartColumn() ); } else if( finished ) { return null; } else { StringBuffer string = new StringBuffer(); while( la(1) != CharStream.EOS ) { string.append( consume() ); } if( la(1) == CharStream.EOS && string.length() == 0 ) { finished = true; } return Token.newString( string.toString(), getStartLine(), getStartColumn() ); } } /** * Controls delimiter search. When turned on, the first thing we do * is check for and eat our delimiter. */ public void delimit( boolean delimit ) { super.delimit( delimit ); if( delimit ) { try { if( !finished && la(1) == CharStream.EOS ) { finishUp(); // // The GStringLexer will correctly handle the empty string. // We don't. In order to ensure that an empty string is // supplied, we set a flag that is checked during // undelegatedNextToken(). if( !allowGStrings ) { emptyString = true; } } } catch( Exception e ) { finished = true; } } } /** * Sets the source lexer and identifies and consumes the opening delimiter. */ public void setSource( Lexer source ) { super.setSource( source ); emptyString = false; try { char c = source.la(); switch( c ) { case '\'': case '"': mark(); source.consume(); if( source.la() == c && source.la(2) == c ) { source.consume(); source.consume(); delimiter = new StringBuffer().append(c).append(c).append(c).toString(); } else { delimiter = new StringBuffer().append(c).toString(); } watchFor = delimiter.charAt(0); break; default: { throw new GroovyBugError( "at the time of StringLexer.setSource(), the source must be on a single or double quote" ); } } restart(); delimit( true ); } catch( Exception e ) { // // If we couldn't read our delimiter, we'll just // cancel our source. nextToken() will return null. e.printStackTrace(); unsetSource( ); } } /** * Unsets our source. */ public void unsetSource() { super.unsetSource(); delimiter = null; finished = true; emptyString = false; } //--------------------------------------------------------------------------- // STREAM ROUTINES private int lookahead = 0; // the number of characters identified private char[] characters = new char[3]; // the next characters identified by la() private int[] widths = new int[3]; // the source widths of the next characters /** * Returns the next <code>k</code>th character, without consuming any. */ public char la(int k) throws LexerException, ReadException { if( !finished && source != null ) { if( delimited ) { if( k > characters.length ) { throw new GroovyBugError( "StringLexer lookahead tolerance exceeded" ); } if( lookahead >= k ) { return characters[k-1]; } lookahead = 0; char c = ' ', c1 = ' ', c2 = ' '; int offset = 1, width = 0; for( int i = 1; i <= k; i++ ) { c1 = source.la(offset); C1_SWITCH: switch( c1 ) { case CharStream.EOS: { return c1; } case '\\': { c2 = source.la( offset + 1 ); ESCAPE_SWITCH: switch( c2 ) { case CharStream.EOS: return c2; case '\\': + c = '\\'; + width = 2; + break ESCAPE_SWITCH; case '$': { if( allowGStrings ) { c = c1; width = 1; } else { c = c2; width = 2; } break ESCAPE_SWITCH; } case 'r': c = '\r'; width = 2; break ESCAPE_SWITCH; case 't': c = '\t'; width = 2; break ESCAPE_SWITCH; case 'n': c = '\n'; width = 2; break ESCAPE_SWITCH; default: c = c2; width = 2; break ESCAPE_SWITCH; } break C1_SWITCH; } default: { if( c1 == watchFor ) { boolean atEnd = true; for( int j = 1; j < delimiter.length(); j++ ) { if( source.la(offset+j) != delimiter.charAt(j) ) { atEnd = false; break; } } if( atEnd ) { return CharStream.EOS; } } c = c1; width = 1; break C1_SWITCH; } } characters[lookahead] = c; widths[lookahead] = width; offset += width; lookahead += 1; } return c; // <<< FLOW CONTROL <<<<<<<<< } lookahead = 0; return source.la(k); } return CharStream.EOS; } /** * Eats a character from the input stream. Searches for the delimiter if * delimited. Note that turning delimiting on also checks if we are at the * delimiter, so if we aren't finished, there is something to consume. */ public char consume() throws LexerException, ReadException { if( !finished && source != null ) { char c = CharStream.EOS; if( delimited ) { if( lookahead < 1 ) { la( 1 ); } if( lookahead >= 1 ) { c = characters[0]; for( int i = 0; i < widths[0]; i++ ) { source.consume(); } lookahead = 0; } if( la(1) == CharStream.EOS ) { finishUp(); } } else { c = source.consume(); } lookahead = 0; return c; } return CharStream.EOS; } /** * Eats our delimiter from the stream and marks us finished. */ protected void finishUp() throws LexerException, ReadException { for( int i = 0; i < delimiter.length(); i++ ) { char c = source.la(1); if( c == CharStream.EOS ) { throw new UnterminatedStringLiteralException(getStartLine(), getStartColumn()); } else if( c == delimiter.charAt(i) ) { source.consume(); } else { throw new GroovyBugError( "la() said delimiter [" + delimiter + "], finishUp() found [" + c + "]" ); } } finish(); } }
true
true
public char la(int k) throws LexerException, ReadException { if( !finished && source != null ) { if( delimited ) { if( k > characters.length ) { throw new GroovyBugError( "StringLexer lookahead tolerance exceeded" ); } if( lookahead >= k ) { return characters[k-1]; } lookahead = 0; char c = ' ', c1 = ' ', c2 = ' '; int offset = 1, width = 0; for( int i = 1; i <= k; i++ ) { c1 = source.la(offset); C1_SWITCH: switch( c1 ) { case CharStream.EOS: { return c1; } case '\\': { c2 = source.la( offset + 1 ); ESCAPE_SWITCH: switch( c2 ) { case CharStream.EOS: return c2; case '\\': case '$': { if( allowGStrings ) { c = c1; width = 1; } else { c = c2; width = 2; } break ESCAPE_SWITCH; } case 'r': c = '\r'; width = 2; break ESCAPE_SWITCH; case 't': c = '\t'; width = 2; break ESCAPE_SWITCH; case 'n': c = '\n'; width = 2; break ESCAPE_SWITCH; default: c = c2; width = 2; break ESCAPE_SWITCH; } break C1_SWITCH; } default: { if( c1 == watchFor ) { boolean atEnd = true; for( int j = 1; j < delimiter.length(); j++ ) { if( source.la(offset+j) != delimiter.charAt(j) ) { atEnd = false; break; } } if( atEnd ) { return CharStream.EOS; } } c = c1; width = 1; break C1_SWITCH; } } characters[lookahead] = c; widths[lookahead] = width; offset += width; lookahead += 1; } return c; // <<< FLOW CONTROL <<<<<<<<< } lookahead = 0; return source.la(k); } return CharStream.EOS; }
public char la(int k) throws LexerException, ReadException { if( !finished && source != null ) { if( delimited ) { if( k > characters.length ) { throw new GroovyBugError( "StringLexer lookahead tolerance exceeded" ); } if( lookahead >= k ) { return characters[k-1]; } lookahead = 0; char c = ' ', c1 = ' ', c2 = ' '; int offset = 1, width = 0; for( int i = 1; i <= k; i++ ) { c1 = source.la(offset); C1_SWITCH: switch( c1 ) { case CharStream.EOS: { return c1; } case '\\': { c2 = source.la( offset + 1 ); ESCAPE_SWITCH: switch( c2 ) { case CharStream.EOS: return c2; case '\\': c = '\\'; width = 2; break ESCAPE_SWITCH; case '$': { if( allowGStrings ) { c = c1; width = 1; } else { c = c2; width = 2; } break ESCAPE_SWITCH; } case 'r': c = '\r'; width = 2; break ESCAPE_SWITCH; case 't': c = '\t'; width = 2; break ESCAPE_SWITCH; case 'n': c = '\n'; width = 2; break ESCAPE_SWITCH; default: c = c2; width = 2; break ESCAPE_SWITCH; } break C1_SWITCH; } default: { if( c1 == watchFor ) { boolean atEnd = true; for( int j = 1; j < delimiter.length(); j++ ) { if( source.la(offset+j) != delimiter.charAt(j) ) { atEnd = false; break; } } if( atEnd ) { return CharStream.EOS; } } c = c1; width = 1; break C1_SWITCH; } } characters[lookahead] = c; widths[lookahead] = width; offset += width; lookahead += 1; } return c; // <<< FLOW CONTROL <<<<<<<<< } lookahead = 0; return source.la(k); } return CharStream.EOS; }
diff --git a/idl-frontend/src/main/java/org/ow2/mind/idl/IncludeHeaderResolver.java b/idl-frontend/src/main/java/org/ow2/mind/idl/IncludeHeaderResolver.java index cf1ac20..344ee2c 100644 --- a/idl-frontend/src/main/java/org/ow2/mind/idl/IncludeHeaderResolver.java +++ b/idl-frontend/src/main/java/org/ow2/mind/idl/IncludeHeaderResolver.java @@ -1,121 +1,123 @@ /** * Copyright (C) 2009 STMicroelectronics * * This file is part of "Mind Compiler" is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: [email protected] * * Authors: Matthieu Leclercq * Contributors: */ package org.ow2.mind.idl; import static org.ow2.mind.PathHelper.getExtension; import static org.ow2.mind.PathHelper.toAbsolute; import static org.ow2.mind.idl.ast.IDLASTHelper.getIncludedPath; import static org.ow2.mind.idl.ast.Include.HEADER_EXTENSION; import java.net.URL; import java.util.Map; import org.objectweb.fractal.adl.ADLException; import org.objectweb.fractal.adl.NodeFactory; import org.ow2.mind.CommonASTHelper; import org.ow2.mind.PathHelper; import org.ow2.mind.PathHelper.InvalidRelativPathException; import org.ow2.mind.error.ErrorManager; import org.ow2.mind.idl.IncludeResolver.AbstractDelegatingIncludeResolver; import org.ow2.mind.idl.ast.Header; import org.ow2.mind.idl.ast.IDL; import org.ow2.mind.idl.ast.IDLASTHelper; import org.ow2.mind.idl.ast.Include; import com.google.inject.Inject; public class IncludeHeaderResolver extends AbstractDelegatingIncludeResolver { @Inject protected ErrorManager errorManagerItf; @Inject protected NodeFactory nodeFactoryItf; @Inject protected IDLLocator idlLocatorItf; // --------------------------------------------------------------------------- // Implementation of the UsedIDLResolver interface // --------------------------------------------------------------------------- public IDL resolve(final Include include, final IDL encapsulatingIDL, final String encapsulatingName, final Map<Object, Object> context) throws ADLException { String path = getIncludedPath(include); if (getExtension(path).equals(HEADER_EXTENSION)) { // include node references a header C file. if (IDLASTHelper.getIncludeDelimiter(include) == IDLASTHelper.IncludeDelimiter.QUOTE) { // try to find header file and update the path if needed - final String encapsulatingIDLName = encapsulatingIDL.getName(); + final String encapsulatingIDLName = (encapsulatingIDL != null) + ? encapsulatingIDL.getName() + : encapsulatingName; final String encapsulatingDir; if (encapsulatingIDLName.startsWith("/")) { encapsulatingDir = PathHelper.getParent(encapsulatingIDLName); } else { encapsulatingDir = PathHelper .fullyQualifiedNameToDirName(encapsulatingIDLName); } if (!path.startsWith("/")) { // look-for header relatively to encapsulatingDir String relPath; try { relPath = toAbsolute(encapsulatingDir, path); } catch (final InvalidRelativPathException e) { errorManagerItf.logError(IDLErrors.INVALID_INCLUDE, include, path); return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path); } URL url = idlLocatorItf.findSourceHeader(relPath, context); if (url != null) { // IDL found with relPath path = relPath; IDLASTHelper.setIncludePathPreserveDelimiter(include, path); } else if (path.startsWith("./") || path.startsWith("../")) { // the path starts with "./" or "../" which force a resolution // relatively to encapsulatingDir. the file has not been found. errorManagerItf.logError(IDLErrors.IDL_NOT_FOUND, include, path); return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path); } else { // look-for header relatively to source-path path = "/" + path; url = idlLocatorItf.findSourceHeader(path, context); if (url != null) { IDLASTHelper.setIncludePathPreserveDelimiter(include, path); } } } } // create a new Header AST node final Header header = CommonASTHelper.newNode(nodeFactoryItf, "header", Header.class); header.setName(path); return header; } else { return clientResolverItf.resolve(include, encapsulatingIDL, encapsulatingName, context); } } }
true
true
public IDL resolve(final Include include, final IDL encapsulatingIDL, final String encapsulatingName, final Map<Object, Object> context) throws ADLException { String path = getIncludedPath(include); if (getExtension(path).equals(HEADER_EXTENSION)) { // include node references a header C file. if (IDLASTHelper.getIncludeDelimiter(include) == IDLASTHelper.IncludeDelimiter.QUOTE) { // try to find header file and update the path if needed final String encapsulatingIDLName = encapsulatingIDL.getName(); final String encapsulatingDir; if (encapsulatingIDLName.startsWith("/")) { encapsulatingDir = PathHelper.getParent(encapsulatingIDLName); } else { encapsulatingDir = PathHelper .fullyQualifiedNameToDirName(encapsulatingIDLName); } if (!path.startsWith("/")) { // look-for header relatively to encapsulatingDir String relPath; try { relPath = toAbsolute(encapsulatingDir, path); } catch (final InvalidRelativPathException e) { errorManagerItf.logError(IDLErrors.INVALID_INCLUDE, include, path); return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path); } URL url = idlLocatorItf.findSourceHeader(relPath, context); if (url != null) { // IDL found with relPath path = relPath; IDLASTHelper.setIncludePathPreserveDelimiter(include, path); } else if (path.startsWith("./") || path.startsWith("../")) { // the path starts with "./" or "../" which force a resolution // relatively to encapsulatingDir. the file has not been found. errorManagerItf.logError(IDLErrors.IDL_NOT_FOUND, include, path); return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path); } else { // look-for header relatively to source-path path = "/" + path; url = idlLocatorItf.findSourceHeader(path, context); if (url != null) { IDLASTHelper.setIncludePathPreserveDelimiter(include, path); } } } } // create a new Header AST node final Header header = CommonASTHelper.newNode(nodeFactoryItf, "header", Header.class); header.setName(path); return header; } else { return clientResolverItf.resolve(include, encapsulatingIDL, encapsulatingName, context); } }
public IDL resolve(final Include include, final IDL encapsulatingIDL, final String encapsulatingName, final Map<Object, Object> context) throws ADLException { String path = getIncludedPath(include); if (getExtension(path).equals(HEADER_EXTENSION)) { // include node references a header C file. if (IDLASTHelper.getIncludeDelimiter(include) == IDLASTHelper.IncludeDelimiter.QUOTE) { // try to find header file and update the path if needed final String encapsulatingIDLName = (encapsulatingIDL != null) ? encapsulatingIDL.getName() : encapsulatingName; final String encapsulatingDir; if (encapsulatingIDLName.startsWith("/")) { encapsulatingDir = PathHelper.getParent(encapsulatingIDLName); } else { encapsulatingDir = PathHelper .fullyQualifiedNameToDirName(encapsulatingIDLName); } if (!path.startsWith("/")) { // look-for header relatively to encapsulatingDir String relPath; try { relPath = toAbsolute(encapsulatingDir, path); } catch (final InvalidRelativPathException e) { errorManagerItf.logError(IDLErrors.INVALID_INCLUDE, include, path); return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path); } URL url = idlLocatorItf.findSourceHeader(relPath, context); if (url != null) { // IDL found with relPath path = relPath; IDLASTHelper.setIncludePathPreserveDelimiter(include, path); } else if (path.startsWith("./") || path.startsWith("../")) { // the path starts with "./" or "../" which force a resolution // relatively to encapsulatingDir. the file has not been found. errorManagerItf.logError(IDLErrors.IDL_NOT_FOUND, include, path); return IDLASTHelper.newUnresolvedIDLNode(nodeFactoryItf, path); } else { // look-for header relatively to source-path path = "/" + path; url = idlLocatorItf.findSourceHeader(path, context); if (url != null) { IDLASTHelper.setIncludePathPreserveDelimiter(include, path); } } } } // create a new Header AST node final Header header = CommonASTHelper.newNode(nodeFactoryItf, "header", Header.class); header.setName(path); return header; } else { return clientResolverItf.resolve(include, encapsulatingIDL, encapsulatingName, context); } }
diff --git a/src/test/pleocmd/Testcases.java b/src/test/pleocmd/Testcases.java index 3e27002..163900e 100644 --- a/src/test/pleocmd/Testcases.java +++ b/src/test/pleocmd/Testcases.java @@ -1,15 +1,16 @@ package test.pleocmd; import org.junit.BeforeClass; import pleocmd.Log; import pleocmd.Log.Type; public class Testcases { // CS_IGNORE not an utility class @BeforeClass public static void logOnlyWarnings() { Log.setMinLogType(Type.Warn); + Log.setGUIStatusKnown(); } }
true
true
public static void logOnlyWarnings() { Log.setMinLogType(Type.Warn); }
public static void logOnlyWarnings() { Log.setMinLogType(Type.Warn); Log.setGUIStatusKnown(); }
diff --git a/branches/TekkitConverter/src/pfaeff/CBRenderer.java b/branches/TekkitConverter/src/pfaeff/CBRenderer.java index 0b26cda..6966aca 100644 --- a/branches/TekkitConverter/src/pfaeff/CBRenderer.java +++ b/branches/TekkitConverter/src/pfaeff/CBRenderer.java @@ -1,61 +1,62 @@ /* * Copyright 2011 Kai R�hr * * * This file is part of mIDas. * * mIDas 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. * * mIDas 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 mIDas. If not, see <http://www.gnu.org/licenses/>. */ package pfaeff; import java.awt.Color; import java.awt.Component; import java.io.File; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; public class CBRenderer extends JLabel implements ListCellRenderer { /** * */ private static final long serialVersionUID = -646755438286846622L; public int maxIndex = -1; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - setText(((File)value).getName()); + if (value==null)setText(""); + else setText(((File)value).getName()); setOpaque(true); if ((index % 2) == 1) { setBackground(new Color(0.6f, 1.0f, 0.6f)); } else { setBackground(Color.white); } if (isSelected) { setBackground(new Color(0.6f, 0.6f, 1.0f)); } if (index > maxIndex) { setForeground(Color.red); } else { setForeground(Color.black); } return this; } }
true
true
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setText(((File)value).getName()); setOpaque(true); if ((index % 2) == 1) { setBackground(new Color(0.6f, 1.0f, 0.6f)); } else { setBackground(Color.white); } if (isSelected) { setBackground(new Color(0.6f, 0.6f, 1.0f)); } if (index > maxIndex) { setForeground(Color.red); } else { setForeground(Color.black); } return this; }
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value==null)setText(""); else setText(((File)value).getName()); setOpaque(true); if ((index % 2) == 1) { setBackground(new Color(0.6f, 1.0f, 0.6f)); } else { setBackground(Color.white); } if (isSelected) { setBackground(new Color(0.6f, 0.6f, 1.0f)); } if (index > maxIndex) { setForeground(Color.red); } else { setForeground(Color.black); } return this; }
diff --git a/src/com/android/exchange/adapter/CalendarSyncAdapter.java b/src/com/android/exchange/adapter/CalendarSyncAdapter.java index 1d1059f..b467eb7 100644 --- a/src/com/android/exchange/adapter/CalendarSyncAdapter.java +++ b/src/com/android/exchange/adapter/CalendarSyncAdapter.java @@ -1,2172 +1,2174 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to 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.exchange.adapter; import android.content.ContentProviderClient; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Entity; import android.content.Entity.NamedContentValues; import android.content.EntityIterator; import android.content.OperationApplicationException; import android.database.Cursor; import android.database.DatabaseUtils; import android.net.Uri; import android.os.RemoteException; import android.provider.CalendarContract; import android.provider.CalendarContract.Attendees; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.provider.CalendarContract.EventsEntity; import android.provider.CalendarContract.ExtendedProperties; import android.provider.CalendarContract.Reminders; import android.provider.CalendarContract.SyncState; import android.provider.ContactsContract.RawContacts; import android.provider.SyncStateContract; import android.text.TextUtils; import android.util.Log; import com.android.emailcommon.AccountManagerTypes; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.Message; import com.android.emailcommon.utility.Utility; import com.android.exchange.CommandStatusException; import com.android.exchange.Eas; import com.android.exchange.EasOutboxService; import com.android.exchange.EasSyncService; import com.android.exchange.ExchangeService; import com.android.exchange.utility.CalendarUtilities; import com.android.exchange.utility.Duration; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.UUID; /** * Sync adapter class for EAS calendars * */ public class CalendarSyncAdapter extends AbstractSyncAdapter { private static final String TAG = "EasCalendarSyncAdapter"; private static final String EVENT_SAVED_TIMEZONE_COLUMN = Events.SYNC_DATA1; /** * Used to keep track of exception vs parent event dirtiness. */ private static final String EVENT_SYNC_MARK = Events.SYNC_DATA8; private static final String EVENT_SYNC_VERSION = Events.SYNC_DATA4; // Since exceptions will have the same _SYNC_ID as the original event we have to check that // there's no original event when finding an item by _SYNC_ID private static final String SERVER_ID_AND_CALENDAR_ID = Events._SYNC_ID + "=? AND " + Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?"; private static final String EVENT_ID_AND_CALENDAR_ID = Events._ID + "=? AND " + Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?"; private static final String DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR = "(" + Events.DIRTY + "=1 OR " + EVENT_SYNC_MARK + "= 1) AND " + Events.ORIGINAL_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?"; private static final String DIRTY_EXCEPTION_IN_CALENDAR = Events.DIRTY + "=1 AND " + Events.ORIGINAL_ID + " NOTNULL AND " + Events.CALENDAR_ID + "=?"; private static final String CLIENT_ID_SELECTION = Events.SYNC_DATA2 + "=?"; private static final String ORIGINAL_EVENT_AND_CALENDAR = Events.ORIGINAL_SYNC_ID + "=? AND " + Events.CALENDAR_ID + "=?"; private static final String ATTENDEES_EXCEPT_ORGANIZER = Attendees.EVENT_ID + "=? AND " + Attendees.ATTENDEE_RELATIONSHIP + "!=" + Attendees.RELATIONSHIP_ORGANIZER; private static final String[] ID_PROJECTION = new String[] {Events._ID}; private static final String[] ORIGINAL_EVENT_PROJECTION = new String[] {Events.ORIGINAL_ID, Events._ID}; private static final String EVENT_ID_AND_NAME = ExtendedProperties.EVENT_ID + "=? AND " + ExtendedProperties.NAME + "=?"; // Note that we use LIKE below for its case insensitivity private static final String EVENT_AND_EMAIL = Attendees.EVENT_ID + "=? AND "+ Attendees.ATTENDEE_EMAIL + " LIKE ?"; private static final int ATTENDEE_STATUS_COLUMN_STATUS = 0; private static final String[] ATTENDEE_STATUS_PROJECTION = new String[] {Attendees.ATTENDEE_STATUS}; public static final String CALENDAR_SELECTION = Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?"; private static final int CALENDAR_SELECTION_ID = 0; private static final String[] EXTENDED_PROPERTY_PROJECTION = new String[] {ExtendedProperties._ID}; private static final int EXTENDED_PROPERTY_ID = 0; private static final String CATEGORY_TOKENIZER_DELIMITER = "\\"; private static final String ATTENDEE_TOKENIZER_DELIMITER = CATEGORY_TOKENIZER_DELIMITER; private static final String EXTENDED_PROPERTY_USER_ATTENDEE_STATUS = "userAttendeeStatus"; private static final String EXTENDED_PROPERTY_ATTENDEES = "attendees"; private static final String EXTENDED_PROPERTY_DTSTAMP = "dtstamp"; private static final String EXTENDED_PROPERTY_MEETING_STATUS = "meeting_status"; private static final String EXTENDED_PROPERTY_CATEGORIES = "categories"; // Used to indicate that we removed the attendee list because it was too large private static final String EXTENDED_PROPERTY_ATTENDEES_REDACTED = "attendeesRedacted"; // Used to indicate that upsyncs aren't allowed (we catch this in sendLocalChanges) private static final String EXTENDED_PROPERTY_UPSYNC_PROHIBITED = "upsyncProhibited"; private static final ContentProviderOperation PLACEHOLDER_OPERATION = ContentProviderOperation.newInsert(Uri.EMPTY).build(); private static final Object sSyncKeyLock = new Object(); private static final TimeZone UTC_TIMEZONE = TimeZone.getTimeZone("UTC"); private final TimeZone mLocalTimeZone = TimeZone.getDefault(); // Maximum number of allowed attendees; above this number, we mark the Event with the // attendeesRedacted extended property and don't allow the event to be upsynced to the server private static final int MAX_SYNCED_ATTENDEES = 50; // We set the organizer to this when the user is the organizer and we've redacted the // attendee list. By making the meeting organizer OTHER than the user, we cause the UI to // prevent edits to this event (except local changes like reminder). private static final String BOGUS_ORGANIZER_EMAIL = "[email protected]"; // Maximum number of CPO's before we start redacting attendees in exceptions // The number 500 has been determined empirically; 1500 CPOs appears to be the limit before // binder failures occur, but we need room at any point for additional events/exceptions so // we set our limit at 1/3 of the apparent maximum for extra safety // TODO Find a better solution to this workaround private static final int MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION = 500; private long mCalendarId = -1; private String mCalendarIdString; private String[] mCalendarIdArgument; /*package*/ String mEmailAddress; private ArrayList<Long> mDeletedIdList = new ArrayList<Long>(); private ArrayList<Long> mUploadedIdList = new ArrayList<Long>(); private ArrayList<Long> mSendCancelIdList = new ArrayList<Long>(); private ArrayList<Message> mOutgoingMailList = new ArrayList<Message>(); public CalendarSyncAdapter(EasSyncService service) { super(service); mEmailAddress = mAccount.mEmailAddress; Cursor c = mService.mContentResolver.query(Calendars.CONTENT_URI, new String[] {Calendars._ID}, CALENDAR_SELECTION, new String[] {mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE}, null); if (c == null) return; try { if (c.moveToFirst()) { mCalendarId = c.getLong(CALENDAR_SELECTION_ID); } else { mCalendarId = CalendarUtilities.createCalendar(mService, mAccount, mMailbox); } mCalendarIdString = Long.toString(mCalendarId); mCalendarIdArgument = new String[] {mCalendarIdString}; } finally { c.close(); } } @Override public String getCollectionName() { return "Calendar"; } @Override public void cleanup() { } @Override public void wipe() { // Delete the calendar associated with this account // CalendarProvider2 does NOT handle selection arguments in deletions mContentResolver.delete( asSyncAdapter(Calendars.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), Calendars.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(mEmailAddress) + " AND " + Calendars.ACCOUNT_TYPE + "=" + DatabaseUtils.sqlEscapeString(AccountManagerTypes.TYPE_EXCHANGE), null); // Invalidate our calendar observers ExchangeService.unregisterCalendarObservers(); } @Override public void sendSyncOptions(Double protocolVersion, Serializer s) throws IOException { setPimSyncOptions(protocolVersion, Eas.FILTER_2_WEEKS, s); } @Override public boolean isSyncable() { return ContentResolver.getSyncAutomatically(mAccountManagerAccount, CalendarContract.AUTHORITY); } @Override public boolean parse(InputStream is) throws IOException, CommandStatusException { EasCalendarSyncParser p = new EasCalendarSyncParser(is, this); return p.parse(); } public static Uri asSyncAdapter(Uri uri, String account, String accountType) { return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") .appendQueryParameter(Calendars.ACCOUNT_NAME, account) .appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build(); } /** * Generate the uri for the data row associated with this NamedContentValues object * @param ncv the NamedContentValues object * @return a uri that can be used to refer to this row */ public Uri dataUriFromNamedContentValues(NamedContentValues ncv) { long id = ncv.values.getAsLong(RawContacts._ID); Uri dataUri = ContentUris.withAppendedId(ncv.uri, id); return dataUri; } /** * We get our SyncKey from CalendarProvider. If there's not one, we set it to "0" (the reset * state) and save that away. */ @Override public String getSyncKey() throws IOException { synchronized (sSyncKeyLock) { ContentProviderClient client = mService.mContentResolver .acquireContentProviderClient(CalendarContract.CONTENT_URI); try { byte[] data = SyncStateContract.Helpers.get( client, asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount); if (data == null || data.length == 0) { // Initialize the SyncKey setSyncKey("0", false); return "0"; } else { String syncKey = new String(data); userLog("SyncKey retrieved as ", syncKey, " from CalendarProvider"); return syncKey; } } catch (RemoteException e) { throw new IOException("Can't get SyncKey from CalendarProvider"); } } } /** * We only need to set this when we're forced to make the SyncKey "0" (a reset). In all other * cases, the SyncKey is set within Calendar */ @Override public void setSyncKey(String syncKey, boolean inCommands) throws IOException { synchronized (sSyncKeyLock) { if ("0".equals(syncKey) || !inCommands) { ContentProviderClient client = mService.mContentResolver .acquireContentProviderClient(CalendarContract.CONTENT_URI); try { SyncStateContract.Helpers.set( client, asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount, syncKey.getBytes()); userLog("SyncKey set to ", syncKey, " in CalendarProvider"); } catch (RemoteException e) { throw new IOException("Can't set SyncKey in CalendarProvider"); } } mMailbox.mSyncKey = syncKey; } } public class EasCalendarSyncParser extends AbstractSyncParser { String[] mBindArgument = new String[1]; Uri mAccountUri; CalendarOperations mOps = new CalendarOperations(); public EasCalendarSyncParser(InputStream in, CalendarSyncAdapter adapter) throws IOException { super(in, adapter); setLoggingTag("CalendarParser"); mAccountUri = Events.CONTENT_URI; } private void addOrganizerToAttendees(CalendarOperations ops, long eventId, String organizerName, String organizerEmail) { // Handle the organizer (who IS an attendee on device, but NOT in EAS) if (organizerName != null || organizerEmail != null) { ContentValues attendeeCv = new ContentValues(); if (organizerName != null) { attendeeCv.put(Attendees.ATTENDEE_NAME, organizerName); } if (organizerEmail != null) { attendeeCv.put(Attendees.ATTENDEE_EMAIL, organizerEmail); } attendeeCv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER); attendeeCv.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED); attendeeCv.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_ACCEPTED); if (eventId < 0) { ops.newAttendee(attendeeCv); } else { ops.updatedAttendee(attendeeCv, eventId); } } } /** * Set DTSTART, DTEND, DURATION and EVENT_TIMEZONE as appropriate for the given Event * The follow rules are enforced by CalendarProvider2: * Events that aren't exceptions MUST have either 1) a DTEND or 2) a DURATION * Recurring events (i.e. events with RRULE) must have a DURATION * All-day recurring events MUST have a DURATION that is in the form P<n>D * Other events MAY have a DURATION in any valid form (we use P<n>M) * All-day events MUST have hour, minute, and second = 0; in addition, they must have * the EVENT_TIMEZONE set to UTC * Also, exceptions to all-day events need to have an ORIGINAL_INSTANCE_TIME that has * hour, minute, and second = 0 and be set in UTC * @param cv the ContentValues for the Event * @param startTime the start time for the Event * @param endTime the end time for the Event * @param allDayEvent whether this is an all day event (1) or not (0) */ /*package*/ void setTimeRelatedValues(ContentValues cv, long startTime, long endTime, int allDayEvent) { // If there's no startTime, the event will be found to be invalid, so return if (startTime < 0) return; // EAS events can arrive without an end time, but CalendarProvider requires them // so we'll default to 30 minutes; this will be superceded if this is an all-day event if (endTime < 0) endTime = startTime + (30*MINUTES); // If this is an all-day event, set hour, minute, and second to zero, and use UTC if (allDayEvent != 0) { startTime = CalendarUtilities.getUtcAllDayCalendarTime(startTime, mLocalTimeZone); endTime = CalendarUtilities.getUtcAllDayCalendarTime(endTime, mLocalTimeZone); String originalTimeZone = cv.getAsString(Events.EVENT_TIMEZONE); cv.put(EVENT_SAVED_TIMEZONE_COLUMN, originalTimeZone); cv.put(Events.EVENT_TIMEZONE, UTC_TIMEZONE.getID()); } // If this is an exception, and the original was an all-day event, make sure the // original instance time has hour, minute, and second set to zero, and is in UTC if (cv.containsKey(Events.ORIGINAL_INSTANCE_TIME) && cv.containsKey(Events.ORIGINAL_ALL_DAY)) { Integer ade = cv.getAsInteger(Events.ORIGINAL_ALL_DAY); if (ade != null && ade != 0) { long exceptionTime = cv.getAsLong(Events.ORIGINAL_INSTANCE_TIME); GregorianCalendar cal = new GregorianCalendar(UTC_TIMEZONE); cal.setTimeInMillis(exceptionTime); cal.set(GregorianCalendar.HOUR_OF_DAY, 0); cal.set(GregorianCalendar.MINUTE, 0); cal.set(GregorianCalendar.SECOND, 0); cv.put(Events.ORIGINAL_INSTANCE_TIME, cal.getTimeInMillis()); } } // Always set DTSTART cv.put(Events.DTSTART, startTime); // For recurring events, set DURATION. Use P<n>D format for all day events if (cv.containsKey(Events.RRULE)) { if (allDayEvent != 0) { cv.put(Events.DURATION, "P" + ((endTime - startTime) / DAYS) + "D"); } else { cv.put(Events.DURATION, "P" + ((endTime - startTime) / MINUTES) + "M"); } // For other events, set DTEND and LAST_DATE } else { cv.put(Events.DTEND, endTime); cv.put(Events.LAST_DATE, endTime); } } public void addEvent(CalendarOperations ops, String serverId, boolean update) throws IOException { ContentValues cv = new ContentValues(); cv.put(Events.CALENDAR_ID, mCalendarId); cv.put(Events._SYNC_ID, serverId); cv.put(Events.HAS_ATTENDEE_DATA, 1); cv.put(Events.SYNC_DATA2, "0"); int allDayEvent = 0; String organizerName = null; String organizerEmail = null; int eventOffset = -1; int deleteOffset = -1; int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE; int responseType = CalendarUtilities.RESPONSE_TYPE_NONE; boolean firstTag = true; long eventId = -1; long startTime = -1; long endTime = -1; TimeZone timeZone = null; // Keep track of the attendees; exceptions will need them ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>(); int reminderMins = -1; String dtStamp = null; boolean organizerAdded = false; while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) { if (update && firstTag) { // Find the event that's being updated Cursor c = getServerIdCursor(serverId); long id = -1; try { if (c != null && c.moveToFirst()) { id = c.getLong(0); } } finally { if (c != null) c.close(); } if (id > 0) { // DTSTAMP can come first, and we simply need to track it if (tag == Tags.CALENDAR_DTSTAMP) { dtStamp = getValue(); continue; } else if (tag == Tags.CALENDAR_ATTENDEES) { // This is an attendees-only update; just // delete/re-add attendees mBindArgument[0] = Long.toString(id); ops.add(ContentProviderOperation .newDelete( asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withSelection(ATTENDEES_EXCEPT_ORGANIZER, mBindArgument) .build()); eventId = id; } else { // Otherwise, delete the original event and recreate it userLog("Changing (delete/add) event ", serverId); deleteOffset = ops.newDelete(id, serverId); // Add a placeholder event so that associated tables can reference // this as a back reference. We add the event at the end of the method eventOffset = ops.newEvent(PLACEHOLDER_OPERATION); } } else { // The changed item isn't found. We'll treat this as a new item eventOffset = ops.newEvent(PLACEHOLDER_OPERATION); userLog(TAG, "Changed item not found; treating as new."); } } else if (firstTag) { // Add a placeholder event so that associated tables can reference // this as a back reference. We add the event at the end of the method eventOffset = ops.newEvent(PLACEHOLDER_OPERATION); } firstTag = false; switch (tag) { case Tags.CALENDAR_ALL_DAY_EVENT: allDayEvent = getValueInt(); if (allDayEvent != 0 && timeZone != null) { // If the event doesn't start at midnight local time, we won't consider // this an all-day event in the local time zone (this is what OWA does) GregorianCalendar cal = new GregorianCalendar(mLocalTimeZone); cal.setTimeInMillis(startTime); userLog("All-day event arrived in: " + timeZone.getID()); if (cal.get(GregorianCalendar.HOUR_OF_DAY) != 0 || cal.get(GregorianCalendar.MINUTE) != 0) { allDayEvent = 0; userLog("Not an all-day event locally: " + mLocalTimeZone.getID()); } } cv.put(Events.ALL_DAY, allDayEvent); break; case Tags.CALENDAR_ATTACHMENTS: attachmentsParser(); break; case Tags.CALENDAR_ATTENDEES: // If eventId >= 0, this is an update; otherwise, a new Event attendeeValues = attendeesParser(ops, eventId); break; case Tags.BASE_BODY: cv.put(Events.DESCRIPTION, bodyParser()); break; case Tags.CALENDAR_BODY: cv.put(Events.DESCRIPTION, getValue()); break; case Tags.CALENDAR_TIME_ZONE: timeZone = CalendarUtilities.tziStringToTimeZone(getValue()); if (timeZone == null) { timeZone = mLocalTimeZone; } cv.put(Events.EVENT_TIMEZONE, timeZone.getID()); break; case Tags.CALENDAR_START_TIME: startTime = Utility.parseDateTimeToMillis(getValue()); break; case Tags.CALENDAR_END_TIME: endTime = Utility.parseDateTimeToMillis(getValue()); break; case Tags.CALENDAR_EXCEPTIONS: // For exceptions to show the organizer, the organizer must be added before // we call exceptionsParser addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail); organizerAdded = true; exceptionsParser(ops, cv, attendeeValues, reminderMins, busyStatus, startTime, endTime); break; case Tags.CALENDAR_LOCATION: cv.put(Events.EVENT_LOCATION, getValue()); break; case Tags.CALENDAR_RECURRENCE: String rrule = recurrenceParser(); if (rrule != null) { cv.put(Events.RRULE, rrule); } break; case Tags.CALENDAR_ORGANIZER_EMAIL: organizerEmail = getValue(); cv.put(Events.ORGANIZER, organizerEmail); break; case Tags.CALENDAR_SUBJECT: cv.put(Events.TITLE, getValue()); break; case Tags.CALENDAR_SENSITIVITY: cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt())); break; case Tags.CALENDAR_ORGANIZER_NAME: organizerName = getValue(); break; case Tags.CALENDAR_REMINDER_MINS_BEFORE: reminderMins = getValueInt(); ops.newReminder(reminderMins); cv.put(Events.HAS_ALARM, 1); break; // The following are fields we should save (for changes), though they don't // relate to data used by CalendarProvider at this point case Tags.CALENDAR_UID: cv.put(Events.SYNC_DATA2, getValue()); break; case Tags.CALENDAR_DTSTAMP: dtStamp = getValue(); break; case Tags.CALENDAR_MEETING_STATUS: ops.newExtendedProperty(EXTENDED_PROPERTY_MEETING_STATUS, getValue()); break; case Tags.CALENDAR_BUSY_STATUS: // We'll set the user's status in the Attendees table below // Don't set selfAttendeeStatus or CalendarProvider will create a duplicate // attendee! busyStatus = getValueInt(); break; case Tags.CALENDAR_RESPONSE_TYPE: // EAS 14+ uses this for the user's response status; we'll use this instead // of busy status, if it appears responseType = getValueInt(); break; case Tags.CALENDAR_CATEGORIES: String categories = categoriesParser(ops); if (categories.length() > 0) { ops.newExtendedProperty(EXTENDED_PROPERTY_CATEGORIES, categories); } break; default: skipTag(); } } // Enforce CalendarProvider required properties setTimeRelatedValues(cv, startTime, endTime, allDayEvent); // If we haven't added the organizer to attendees, do it now if (!organizerAdded) { addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail); } // Note that organizerEmail can be null with a DTSTAMP only change from the server boolean selfOrganizer = (mEmailAddress.equals(organizerEmail)); // Store email addresses of attendees (in a tokenizable string) in ExtendedProperties // If the user is an attendee, set the attendee status using busyStatus (note that the // busyStatus is inherited from the parent unless it's specified in the exception) // Add the insert/update operation for each attendee (based on whether it's add/change) int numAttendees = attendeeValues.size(); if (numAttendees > MAX_SYNCED_ATTENDEES) { // Indicate that we've redacted attendees. If we're the organizer, disable edit // by setting organizerEmail to a bogus value and by setting the upsync prohibited // extended properly. // Note that we don't set ANY attendees if we're in this branch; however, the // organizer has already been included above, and WILL show up (which is good) if (eventId < 0) { ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1"); if (selfOrganizer) { ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1"); } } else { ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1", eventId); if (selfOrganizer) { ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1", eventId); } } if (selfOrganizer) { organizerEmail = BOGUS_ORGANIZER_EMAIL; cv.put(Events.ORGANIZER, organizerEmail); } // Tell UI that we don't have any attendees cv.put(Events.HAS_ATTENDEE_DATA, "0"); mService.userLog("Maximum number of attendees exceeded; redacting"); } else if (numAttendees > 0) { StringBuilder sb = new StringBuilder(); for (ContentValues attendee: attendeeValues) { String attendeeEmail = attendee.getAsString(Attendees.ATTENDEE_EMAIL); sb.append(attendeeEmail); sb.append(ATTENDEE_TOKENIZER_DELIMITER); if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) { int attendeeStatus; // We'll use the response type (EAS 14), if we've got one; otherwise, we'll // try to infer it from busy status if (responseType != CalendarUtilities.RESPONSE_TYPE_NONE) { attendeeStatus = CalendarUtilities.attendeeStatusFromResponseType(responseType); } else if (!update) { // For new events in EAS < 14, we have no idea what the busy status // means, so we show "none", allowing the user to select an option. attendeeStatus = Attendees.ATTENDEE_STATUS_NONE; } else { // For updated events, we'll try to infer the attendee status from the // busy status attendeeStatus = CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus); } attendee.put(Attendees.ATTENDEE_STATUS, attendeeStatus); // If we're an attendee, save away our initial attendee status in the // event's ExtendedProperties (we look for differences between this and // the user's current attendee status to determine whether an email needs // to be sent to the organizer) // organizerEmail will be null in the case that this is an attendees-only // change from the server if (organizerEmail == null || !organizerEmail.equalsIgnoreCase(attendeeEmail)) { if (eventId < 0) { ops.newExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS, Integer.toString(attendeeStatus)); } else { ops.updatedExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS, Integer.toString(attendeeStatus), eventId); } } } if (eventId < 0) { ops.newAttendee(attendee); } else { ops.updatedAttendee(attendee, eventId); } } if (eventId < 0) { ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString()); ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0"); ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0"); } else { ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString(), eventId); ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0", eventId); ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0", eventId); } } // Put the real event in the proper place in the ops ArrayList if (eventOffset >= 0) { // Store away the DTSTAMP here if (dtStamp != null) { ops.newExtendedProperty(EXTENDED_PROPERTY_DTSTAMP, dtStamp); } if (isValidEventValues(cv)) { ops.set(eventOffset, ContentProviderOperation .newInsert( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withValues(cv).build()); } else { // If we can't add this event (it's invalid), remove all of the inserts // we've built for it int cnt = ops.mCount - eventOffset; userLog(TAG, "Removing " + cnt + " inserts from mOps"); for (int i = 0; i < cnt; i++) { ops.remove(eventOffset); } ops.mCount = eventOffset; // If this is a change, we need to also remove the deletion that comes // before the addition if (deleteOffset >= 0) { // Remove the deletion ops.remove(deleteOffset); // And the deletion of exceptions ops.remove(deleteOffset); userLog(TAG, "Removing deletion ops from mOps"); ops.mCount = deleteOffset; } } } } private void logEventColumns(ContentValues cv, String reason) { if (Eas.USER_LOG) { StringBuilder sb = new StringBuilder("Event invalid, " + reason + ", skipping: Columns = "); for (Entry<String, Object> entry: cv.valueSet()) { sb.append(entry.getKey()); sb.append('/'); } userLog(TAG, sb.toString()); } } /*package*/ boolean isValidEventValues(ContentValues cv) { boolean isException = cv.containsKey(Events.ORIGINAL_INSTANCE_TIME); // All events require DTSTART if (!cv.containsKey(Events.DTSTART)) { logEventColumns(cv, "DTSTART missing"); return false; // If we're a top-level event, we must have _SYNC_DATA (uid) } else if (!isException && !cv.containsKey(Events.SYNC_DATA2)) { logEventColumns(cv, "_SYNC_DATA missing"); return false; // We must also have DTEND or DURATION if we're not an exception } else if (!isException && !cv.containsKey(Events.DTEND) && !cv.containsKey(Events.DURATION)) { logEventColumns(cv, "DTEND/DURATION missing"); return false; // Exceptions require DTEND } else if (isException && !cv.containsKey(Events.DTEND)) { logEventColumns(cv, "Exception missing DTEND"); return false; // If this is a recurrence, we need a DURATION (in days if an all-day event) } else if (cv.containsKey(Events.RRULE)) { String duration = cv.getAsString(Events.DURATION); if (duration == null) return false; if (cv.containsKey(Events.ALL_DAY)) { Integer ade = cv.getAsInteger(Events.ALL_DAY); if (ade != null && ade != 0 && !duration.endsWith("D")) { return false; } } } return true; } public String recurrenceParser() throws IOException { // Turn this information into an RRULE int type = -1; int occurrences = -1; int interval = -1; int dow = -1; int dom = -1; int wom = -1; int moy = -1; String until = null; while (nextTag(Tags.CALENDAR_RECURRENCE) != END) { switch (tag) { case Tags.CALENDAR_RECURRENCE_TYPE: type = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_INTERVAL: interval = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_OCCURRENCES: occurrences = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_DAYOFWEEK: dow = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_DAYOFMONTH: dom = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_WEEKOFMONTH: wom = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_MONTHOFYEAR: moy = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_UNTIL: until = getValue(); break; default: skipTag(); } } return CalendarUtilities.rruleFromRecurrence(type, occurrences, interval, dow, dom, wom, moy, until); } private void exceptionParser(CalendarOperations ops, ContentValues parentCv, ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus, long startTime, long endTime) throws IOException { ContentValues cv = new ContentValues(); cv.put(Events.CALENDAR_ID, mCalendarId); // It appears that these values have to be copied from the parent if they are to appear // Note that they can be overridden below cv.put(Events.ORGANIZER, parentCv.getAsString(Events.ORGANIZER)); cv.put(Events.TITLE, parentCv.getAsString(Events.TITLE)); cv.put(Events.DESCRIPTION, parentCv.getAsString(Events.DESCRIPTION)); cv.put(Events.ORIGINAL_ALL_DAY, parentCv.getAsInteger(Events.ALL_DAY)); cv.put(Events.EVENT_LOCATION, parentCv.getAsString(Events.EVENT_LOCATION)); cv.put(Events.ACCESS_LEVEL, parentCv.getAsString(Events.ACCESS_LEVEL)); cv.put(Events.EVENT_TIMEZONE, parentCv.getAsString(Events.EVENT_TIMEZONE)); // Exceptions should always have this set to zero, since EAS has no concept of // separate attendee lists for exceptions; if we fail to do this, then the UI will // allow the user to change attendee data, and this change would never get reflected // on the server. cv.put(Events.HAS_ATTENDEE_DATA, 0); int allDayEvent = 0; // This column is the key that links the exception to the serverId cv.put(Events.ORIGINAL_SYNC_ID, parentCv.getAsString(Events._SYNC_ID)); String exceptionStartTime = "_noStartTime"; while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) { switch (tag) { case Tags.CALENDAR_ATTACHMENTS: attachmentsParser(); break; case Tags.CALENDAR_EXCEPTION_START_TIME: exceptionStartTime = getValue(); cv.put(Events.ORIGINAL_INSTANCE_TIME, Utility.parseDateTimeToMillis(exceptionStartTime)); break; case Tags.CALENDAR_EXCEPTION_IS_DELETED: if (getValueInt() == 1) { cv.put(Events.STATUS, Events.STATUS_CANCELED); } break; case Tags.CALENDAR_ALL_DAY_EVENT: allDayEvent = getValueInt(); cv.put(Events.ALL_DAY, allDayEvent); break; case Tags.BASE_BODY: cv.put(Events.DESCRIPTION, bodyParser()); break; case Tags.CALENDAR_BODY: cv.put(Events.DESCRIPTION, getValue()); break; case Tags.CALENDAR_START_TIME: startTime = Utility.parseDateTimeToMillis(getValue()); break; case Tags.CALENDAR_END_TIME: endTime = Utility.parseDateTimeToMillis(getValue()); break; case Tags.CALENDAR_LOCATION: cv.put(Events.EVENT_LOCATION, getValue()); break; case Tags.CALENDAR_RECURRENCE: String rrule = recurrenceParser(); if (rrule != null) { cv.put(Events.RRULE, rrule); } break; case Tags.CALENDAR_SUBJECT: cv.put(Events.TITLE, getValue()); break; case Tags.CALENDAR_SENSITIVITY: cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt())); break; case Tags.CALENDAR_BUSY_STATUS: busyStatus = getValueInt(); // Don't set selfAttendeeStatus or CalendarProvider will create a duplicate // attendee! break; // TODO How to handle these items that are linked to event id! // case Tags.CALENDAR_DTSTAMP: // ops.newExtendedProperty("dtstamp", getValue()); // break; // case Tags.CALENDAR_REMINDER_MINS_BEFORE: // ops.newReminder(getValueInt()); // break; default: skipTag(); } } // We need a _sync_id, but it can't be the parent's id, so we generate one cv.put(Events._SYNC_ID, parentCv.getAsString(Events._SYNC_ID) + '_' + exceptionStartTime); // Enforce CalendarProvider required properties setTimeRelatedValues(cv, startTime, endTime, allDayEvent); // Don't insert an invalid exception event if (!isValidEventValues(cv)) return; // Add the exception insert int exceptionStart = ops.mCount; ops.newException(cv); // Also add the attendees, because they need to be copied over from the parent event boolean attendeesRedacted = false; if (attendeeValues != null) { for (ContentValues attValues: attendeeValues) { // If this is the user, use his busy status for attendee status String attendeeEmail = attValues.getAsString(Attendees.ATTENDEE_EMAIL); // Note that the exception at which we surpass the redaction limit might have // any number of attendees shown; since this is an edge case and a workaround, // it seems to be an acceptable implementation if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) { attValues.put(Attendees.ATTENDEE_STATUS, CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus)); ops.newAttendee(attValues, exceptionStart); } else if (ops.size() < MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION) { ops.newAttendee(attValues, exceptionStart); } else { attendeesRedacted = true; } } } // And add the parent's reminder value if (reminderMins > 0) { ops.newReminder(reminderMins, exceptionStart); } if (attendeesRedacted) { mService.userLog("Attendees redacted in this exception"); } } private int encodeVisibility(int easVisibility) { int visibility = 0; switch(easVisibility) { case 0: visibility = Events.ACCESS_DEFAULT; break; case 1: visibility = Events.ACCESS_PUBLIC; break; case 2: visibility = Events.ACCESS_PRIVATE; break; case 3: visibility = Events.ACCESS_CONFIDENTIAL; break; } return visibility; } private void exceptionsParser(CalendarOperations ops, ContentValues cv, ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus, long startTime, long endTime) throws IOException { while (nextTag(Tags.CALENDAR_EXCEPTIONS) != END) { switch (tag) { case Tags.CALENDAR_EXCEPTION: exceptionParser(ops, cv, attendeeValues, reminderMins, busyStatus, startTime, endTime); break; default: skipTag(); } } } private String categoriesParser(CalendarOperations ops) throws IOException { StringBuilder categories = new StringBuilder(); while (nextTag(Tags.CALENDAR_CATEGORIES) != END) { switch (tag) { case Tags.CALENDAR_CATEGORY: // TODO Handle categories (there's no similar concept for gdata AFAIK) // We need to save them and spit them back when we update the event categories.append(getValue()); categories.append(CATEGORY_TOKENIZER_DELIMITER); break; default: skipTag(); } } return categories.toString(); } /** * For now, we ignore (but still have to parse) event attachments; these are new in EAS 14 */ private void attachmentsParser() throws IOException { while (nextTag(Tags.CALENDAR_ATTACHMENTS) != END) { switch (tag) { case Tags.CALENDAR_ATTACHMENT: skipParser(Tags.CALENDAR_ATTACHMENT); break; default: skipTag(); } } } private ArrayList<ContentValues> attendeesParser(CalendarOperations ops, long eventId) throws IOException { int attendeeCount = 0; ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>(); while (nextTag(Tags.CALENDAR_ATTENDEES) != END) { switch (tag) { case Tags.CALENDAR_ATTENDEE: ContentValues cv = attendeeParser(ops, eventId); // If we're going to redact these attendees anyway, let's avoid unnecessary // memory pressure, and not keep them around // We still need to parse them all, however attendeeCount++; // Allow one more than MAX_ATTENDEES, so that the check for "too many" will // succeed in addEvent if (attendeeCount <= (MAX_SYNCED_ATTENDEES+1)) { attendeeValues.add(cv); } break; default: skipTag(); } } return attendeeValues; } private ContentValues attendeeParser(CalendarOperations ops, long eventId) throws IOException { ContentValues cv = new ContentValues(); while (nextTag(Tags.CALENDAR_ATTENDEE) != END) { switch (tag) { case Tags.CALENDAR_ATTENDEE_EMAIL: cv.put(Attendees.ATTENDEE_EMAIL, getValue()); break; case Tags.CALENDAR_ATTENDEE_NAME: cv.put(Attendees.ATTENDEE_NAME, getValue()); break; case Tags.CALENDAR_ATTENDEE_STATUS: int status = getValueInt(); cv.put(Attendees.ATTENDEE_STATUS, (status == 2) ? Attendees.ATTENDEE_STATUS_TENTATIVE : (status == 3) ? Attendees.ATTENDEE_STATUS_ACCEPTED : (status == 4) ? Attendees.ATTENDEE_STATUS_DECLINED : (status == 5) ? Attendees.ATTENDEE_STATUS_INVITED : Attendees.ATTENDEE_STATUS_NONE); break; case Tags.CALENDAR_ATTENDEE_TYPE: int type = Attendees.TYPE_NONE; // EAS types: 1 = req'd, 2 = opt, 3 = resource switch (getValueInt()) { case 1: type = Attendees.TYPE_REQUIRED; break; case 2: type = Attendees.TYPE_OPTIONAL; break; } cv.put(Attendees.ATTENDEE_TYPE, type); break; default: skipTag(); } } cv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE); return cv; } private String bodyParser() throws IOException { String body = null; while (nextTag(Tags.BASE_BODY) != END) { switch (tag) { case Tags.BASE_DATA: body = getValue(); break; default: skipTag(); } } // Handle null data without error if (body == null) return ""; // Remove \r's from any body text return body.replace("\r\n", "\n"); } public void addParser(CalendarOperations ops) throws IOException { String serverId = null; while (nextTag(Tags.SYNC_ADD) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: // same as serverId = getValue(); break; case Tags.SYNC_APPLICATION_DATA: addEvent(ops, serverId, false); break; default: skipTag(); } } } private Cursor getServerIdCursor(String serverId) { return mContentResolver.query(mAccountUri, ID_PROJECTION, SERVER_ID_AND_CALENDAR_ID, new String[] {serverId, mCalendarIdString}, null); } private Cursor getClientIdCursor(String clientId) { mBindArgument[0] = clientId; return mContentResolver.query(mAccountUri, ID_PROJECTION, CLIENT_ID_SELECTION, mBindArgument, null); } public void deleteParser(CalendarOperations ops) throws IOException { while (nextTag(Tags.SYNC_DELETE) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: String serverId = getValue(); // Find the event with the given serverId Cursor c = getServerIdCursor(serverId); try { if (c.moveToFirst()) { userLog("Deleting ", serverId); ops.delete(c.getLong(0), serverId); } } finally { c.close(); } break; default: skipTag(); } } } /** * A change is handled as a delete (including all exceptions) and an add * This isn't as efficient as attempting to traverse the original and all of its exceptions, * but changes happen infrequently and this code is both simpler and easier to maintain * @param ops the array of pending ContactProviderOperations. * @throws IOException */ public void changeParser(CalendarOperations ops) throws IOException { String serverId = null; while (nextTag(Tags.SYNC_CHANGE) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: serverId = getValue(); break; case Tags.SYNC_APPLICATION_DATA: userLog("Changing " + serverId); addEvent(ops, serverId, true); break; default: skipTag(); } } } @Override public void commandsParser() throws IOException { while (nextTag(Tags.SYNC_COMMANDS) != END) { if (tag == Tags.SYNC_ADD) { addParser(mOps); incrementChangeCount(); } else if (tag == Tags.SYNC_DELETE) { deleteParser(mOps); incrementChangeCount(); } else if (tag == Tags.SYNC_CHANGE) { changeParser(mOps); incrementChangeCount(); } else skipTag(); } } @Override public void commit() throws IOException { userLog("Calendar SyncKey saved as: ", mMailbox.mSyncKey); // Save the syncKey here, using the Helper provider by Calendar provider mOps.add(SyncStateContract.Helpers.newSetOperation( asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount, mMailbox.mSyncKey.getBytes())); // We need to send cancellations now, because the Event won't exist after the commit for (long eventId: mSendCancelIdList) { EmailContent.Message msg; try { msg = CalendarUtilities.createMessageForEventId(mContext, eventId, EmailContent.Message.FLAG_OUTGOING_MEETING_CANCEL, null, mAccount); } catch (RemoteException e) { // Nothing to do here; the Event may no longer exist continue; } if (msg != null) { EasOutboxService.sendMessage(mContext, mAccount.mId, msg); } } // Execute these all at once... mOps.execute(); if (mOps.mResults != null) { // Clear dirty and mark flags for updates sent to server if (!mUploadedIdList.isEmpty()) { ContentValues cv = new ContentValues(); cv.put(Events.DIRTY, 0); cv.put(EVENT_SYNC_MARK, "0"); for (long eventId : mUploadedIdList) { mContentResolver.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } } // Delete events marked for deletion if (!mDeletedIdList.isEmpty()) { for (long eventId : mDeletedIdList) { mContentResolver.delete( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null); } } // Send any queued up email (invitations replies, etc.) for (Message msg: mOutgoingMailList) { EasOutboxService.sendMessage(mContext, mAccount.mId, msg); } } } public void addResponsesParser() throws IOException { String serverId = null; String clientId = null; int status = -1; ContentValues cv = new ContentValues(); while (nextTag(Tags.SYNC_ADD) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: serverId = getValue(); break; case Tags.SYNC_CLIENT_ID: clientId = getValue(); break; case Tags.SYNC_STATUS: status = getValueInt(); if (status != 1) { userLog("Attempt to add event failed with status: " + status); } break; default: skipTag(); } } if (clientId == null) return; if (serverId == null) { // TODO Reconsider how to handle this serverId = "FAIL:" + status; } Cursor c = getClientIdCursor(clientId); try { if (c.moveToFirst()) { cv.put(Events._SYNC_ID, serverId); cv.put(Events.SYNC_DATA2, clientId); long id = c.getLong(0); // Write the serverId into the Event mOps.add(ContentProviderOperation .newUpdate( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, id), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withValues(cv).build()); userLog("New event " + clientId + " was given serverId: " + serverId); } } finally { c.close(); } } public void changeResponsesParser() throws IOException { String serverId = null; String status = null; while (nextTag(Tags.SYNC_CHANGE) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: serverId = getValue(); break; case Tags.SYNC_STATUS: status = getValue(); break; default: skipTag(); } } if (serverId != null && status != null) { userLog("Changed event " + serverId + " failed with status: " + status); } } @Override public void responsesParser() throws IOException { // Handle server responses here (for Add and Change) while (nextTag(Tags.SYNC_RESPONSES) != END) { if (tag == Tags.SYNC_ADD) { addResponsesParser(); } else if (tag == Tags.SYNC_CHANGE) { changeResponsesParser(); } else skipTag(); } } } protected class CalendarOperations extends ArrayList<ContentProviderOperation> { private static final long serialVersionUID = 1L; public int mCount = 0; private ContentProviderResult[] mResults = null; private int mEventStart = 0; @Override public boolean add(ContentProviderOperation op) { super.add(op); mCount++; return true; } public int newEvent(ContentProviderOperation op) { mEventStart = mCount; add(op); return mEventStart; } public int newDelete(long id, String serverId) { int offset = mCount; delete(id, serverId); return offset; } public void newAttendee(ContentValues cv) { newAttendee(cv, mEventStart); } public void newAttendee(ContentValues cv, int eventStart) { add(ContentProviderOperation .newInsert(asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv) .withValueBackReference(Attendees.EVENT_ID, eventStart).build()); } public void updatedAttendee(ContentValues cv, long id) { cv.put(Attendees.EVENT_ID, id); add(ContentProviderOperation.newInsert(asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build()); } public void newException(ContentValues cv) { add(ContentProviderOperation.newInsert( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build()); } public void newExtendedProperty(String name, String value) { add(ContentProviderOperation .newInsert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withValue(ExtendedProperties.NAME, name) .withValue(ExtendedProperties.VALUE, value) .withValueBackReference(ExtendedProperties.EVENT_ID, mEventStart).build()); } public void updatedExtendedProperty(String name, String value, long id) { // Find an existing ExtendedProperties row for this event and property name Cursor c = mService.mContentResolver.query(ExtendedProperties.CONTENT_URI, EXTENDED_PROPERTY_PROJECTION, EVENT_ID_AND_NAME, new String[] {Long.toString(id), name}, null); long extendedPropertyId = -1; // If there is one, capture its _id if (c != null) { try { if (c.moveToFirst()) { extendedPropertyId = c.getLong(EXTENDED_PROPERTY_ID); } } finally { c.close(); } } // Either do an update or an insert, depending on whether one // already exists if (extendedPropertyId >= 0) { add(ContentProviderOperation .newUpdate( ContentUris.withAppendedId( asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), extendedPropertyId)) .withValue(ExtendedProperties.VALUE, value).build()); } else { newExtendedProperty(name, value); } } public void newReminder(int mins, int eventStart) { add(ContentProviderOperation .newInsert(asSyncAdapter(Reminders.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withValue(Reminders.MINUTES, mins) .withValue(Reminders.METHOD, Reminders.METHOD_ALERT) .withValueBackReference(ExtendedProperties.EVENT_ID, eventStart).build()); } public void newReminder(int mins) { newReminder(mins, mEventStart); } public void delete(long id, String syncId) { add(ContentProviderOperation.newDelete( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, id), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).build()); // Delete the exceptions for this Event (CalendarProvider doesn't do // this) add(ContentProviderOperation .newDelete(asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withSelection(Events.ORIGINAL_SYNC_ID + "=?", new String[] {syncId}).build()); } public void execute() { synchronized (mService.getSynchronizer()) { if (!mService.isStopped()) { try { if (!isEmpty()) { mService.userLog("Executing ", size(), " CPO's"); mResults = mContext.getContentResolver().applyBatch( CalendarContract.AUTHORITY, this); } } catch (RemoteException e) { // There is nothing sensible to be done here Log.e(TAG, "problem inserting event during server update", e); } catch (OperationApplicationException e) { // There is nothing sensible to be done here Log.e(TAG, "problem inserting event during server update", e); } } } } } private String decodeVisibility(int visibility) { int easVisibility = 0; switch(visibility) { case Events.ACCESS_DEFAULT: easVisibility = 0; break; case Events.ACCESS_PUBLIC: easVisibility = 1; break; case Events.ACCESS_PRIVATE: easVisibility = 2; break; case Events.ACCESS_CONFIDENTIAL: easVisibility = 3; break; } return Integer.toString(easVisibility); } private int getInt(ContentValues cv, String column) { Integer i = cv.getAsInteger(column); if (i == null) return 0; return i; } private void sendEvent(Entity entity, String clientId, Serializer s) throws IOException { // Serialize for EAS here // Set uid with the client id we created // 1) Serialize the top-level event // 2) Serialize attendees and reminders from subvalues // 3) Look for exceptions and serialize with the top-level event ContentValues entityValues = entity.getEntityValues(); final boolean isException = (clientId == null); boolean hasAttendees = false; final boolean isChange = entityValues.containsKey(Events._SYNC_ID); final Double version = mService.mProtocolVersionDouble; final boolean allDay = CalendarUtilities.getIntegerValueAsBoolean(entityValues, Events.ALL_DAY); // NOTE: Exchange 2003 (EAS 2.5) seems to require the "exception deleted" and "exception // start time" data before other data in exceptions. Failure to do so results in a // status 6 error during sync if (isException) { // Send exception deleted flag if necessary Integer deleted = entityValues.getAsInteger(Events.DELETED); boolean isDeleted = deleted != null && deleted == 1; Integer eventStatus = entityValues.getAsInteger(Events.STATUS); boolean isCanceled = eventStatus != null && eventStatus.equals(Events.STATUS_CANCELED); if (isDeleted || isCanceled) { s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "1"); // If we're deleted, the UI will continue to show this exception until we mark // it canceled, so we'll do that here... if (isDeleted && !isCanceled) { final long eventId = entityValues.getAsLong(Events._ID); ContentValues cv = new ContentValues(); cv.put(Events.STATUS, Events.STATUS_CANCELED); mService.mContentResolver.update( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } } else { s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "0"); } // TODO Add reminders to exceptions (allow them to be specified!) Long originalTime = entityValues.getAsLong(Events.ORIGINAL_INSTANCE_TIME); if (originalTime != null) { final boolean originalAllDay = CalendarUtilities.getIntegerValueAsBoolean(entityValues, Events.ORIGINAL_ALL_DAY); if (originalAllDay) { // For all day events, we need our local all-day time originalTime = CalendarUtilities.getLocalAllDayCalendarTime(originalTime, mLocalTimeZone); } s.data(Tags.CALENDAR_EXCEPTION_START_TIME, CalendarUtilities.millisToEasDateTime(originalTime)); } else { // Illegal; what should we do? } } // Get the event's time zone String timeZoneName = entityValues.getAsString(allDay ? EVENT_SAVED_TIMEZONE_COLUMN : Events.EVENT_TIMEZONE); if (timeZoneName == null) { timeZoneName = mLocalTimeZone.getID(); } TimeZone eventTimeZone = TimeZone.getTimeZone(timeZoneName); if (!isException) { // A time zone is required in all EAS events; we'll use the default if none is set // Exchange 2003 seems to require this first... :-) String timeZone = CalendarUtilities.timeZoneToTziString(eventTimeZone); s.data(Tags.CALENDAR_TIME_ZONE, timeZone); } s.data(Tags.CALENDAR_ALL_DAY_EVENT, allDay ? "1" : "0"); // DTSTART is always supplied long startTime = entityValues.getAsLong(Events.DTSTART); // Determine endTime; it's either provided as DTEND or we calculate using DURATION // If no DURATION is provided, we default to one hour long endTime; if (entityValues.containsKey(Events.DTEND)) { endTime = entityValues.getAsLong(Events.DTEND); } else { long durationMillis = HOURS; if (entityValues.containsKey(Events.DURATION)) { Duration duration = new Duration(); try { duration.parse(entityValues.getAsString(Events.DURATION)); durationMillis = duration.getMillis(); } catch (ParseException e) { // Can't do much about this; use the default (1 hour) } } endTime = startTime + durationMillis; } if (allDay) { TimeZone tz = mLocalTimeZone; startTime = CalendarUtilities.getLocalAllDayCalendarTime(startTime, tz); endTime = CalendarUtilities.getLocalAllDayCalendarTime(endTime, tz); } s.data(Tags.CALENDAR_START_TIME, CalendarUtilities.millisToEasDateTime(startTime)); s.data(Tags.CALENDAR_END_TIME, CalendarUtilities.millisToEasDateTime(endTime)); s.data(Tags.CALENDAR_DTSTAMP, CalendarUtilities.millisToEasDateTime(System.currentTimeMillis())); String loc = entityValues.getAsString(Events.EVENT_LOCATION); if (!TextUtils.isEmpty(loc)) { if (version < Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { // EAS 2.5 doesn't like bare line feeds loc = Utility.replaceBareLfWithCrlf(loc); } s.data(Tags.CALENDAR_LOCATION, loc); } s.writeStringValue(entityValues, Events.TITLE, Tags.CALENDAR_SUBJECT); if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { s.start(Tags.BASE_BODY); s.data(Tags.BASE_TYPE, "1"); s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.BASE_DATA); s.end(); } else { // EAS 2.5 doesn't like bare line feeds s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.CALENDAR_BODY); } if (!isException) { // For Exchange 2003, only upsync if the event is new if ((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) { s.writeStringValue(entityValues, Events.ORGANIZER, Tags.CALENDAR_ORGANIZER_EMAIL); } String rrule = entityValues.getAsString(Events.RRULE); if (rrule != null) { CalendarUtilities.recurrenceFromRrule(rrule, startTime, s); } // Handle associated data EXCEPT for attendees, which have to be grouped ArrayList<NamedContentValues> subValues = entity.getSubValues(); // The earliest of the reminders for this Event; we can only send one reminder... int earliestReminder = -1; for (NamedContentValues ncv: subValues) { Uri ncvUri = ncv.uri; ContentValues ncvValues = ncv.values; if (ncvUri.equals(ExtendedProperties.CONTENT_URI)) { String propertyName = ncvValues.getAsString(ExtendedProperties.NAME); String propertyValue = ncvValues.getAsString(ExtendedProperties.VALUE); if (TextUtils.isEmpty(propertyValue)) { continue; } if (propertyName.equals(EXTENDED_PROPERTY_CATEGORIES)) { // Send all the categories back to the server // We've saved them as a String of delimited tokens StringTokenizer st = new StringTokenizer(propertyValue, CATEGORY_TOKENIZER_DELIMITER); if (st.countTokens() > 0) { s.start(Tags.CALENDAR_CATEGORIES); while (st.hasMoreTokens()) { String category = st.nextToken(); s.data(Tags.CALENDAR_CATEGORY, category); } s.end(); } } } else if (ncvUri.equals(Reminders.CONTENT_URI)) { Integer mins = ncvValues.getAsInteger(Reminders.MINUTES); if (mins != null) { // -1 means "default", which for Exchange, is 30 if (mins < 0) { mins = 30; } // Save this away if it's the earliest reminder (greatest minutes) if (mins > earliestReminder) { earliestReminder = mins; } } } } // If we have a reminder, send it to the server if (earliestReminder >= 0) { s.data(Tags.CALENDAR_REMINDER_MINS_BEFORE, Integer.toString(earliestReminder)); } // We've got to send a UID, unless this is an exception. If the event is new, we've // generated one; if not, we should have gotten one from extended properties. if (clientId != null) { s.data(Tags.CALENDAR_UID, clientId); } // Handle attendee data here; keep track of organizer and stream it afterward String organizerName = null; String organizerEmail = null; for (NamedContentValues ncv: subValues) { Uri ncvUri = ncv.uri; ContentValues ncvValues = ncv.values; if (ncvUri.equals(Attendees.CONTENT_URI)) { Integer relationship = ncvValues.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP); // If there's no relationship, we can't create this for EAS // Similarly, we need an attendee email for each invitee if (relationship != null && ncvValues.containsKey(Attendees.ATTENDEE_EMAIL)) { // Organizer isn't among attendees in EAS if (relationship == Attendees.RELATIONSHIP_ORGANIZER) { organizerName = ncvValues.getAsString(Attendees.ATTENDEE_NAME); organizerEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL); continue; } if (!hasAttendees) { s.start(Tags.CALENDAR_ATTENDEES); hasAttendees = true; } s.start(Tags.CALENDAR_ATTENDEE); String attendeeEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL); String attendeeName = ncvValues.getAsString(Attendees.ATTENDEE_NAME); if (attendeeName == null) { attendeeName = attendeeEmail; } s.data(Tags.CALENDAR_ATTENDEE_NAME, attendeeName); s.data(Tags.CALENDAR_ATTENDEE_EMAIL, attendeeEmail); if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { s.data(Tags.CALENDAR_ATTENDEE_TYPE, "1"); // Required } s.end(); // Attendee } } } if (hasAttendees) { s.end(); // Attendees } // Get busy status from Attendees table long eventId = entityValues.getAsLong(Events._ID); int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE; Cursor c = mService.mContentResolver.query( asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), ATTENDEE_STATUS_PROJECTION, EVENT_AND_EMAIL, new String[] {Long.toString(eventId), mEmailAddress}, null); if (c != null) { try { if (c.moveToFirst()) { busyStatus = CalendarUtilities.busyStatusFromAttendeeStatus( c.getInt(ATTENDEE_STATUS_COLUMN_STATUS)); } } finally { c.close(); } } s.data(Tags.CALENDAR_BUSY_STATUS, Integer.toString(busyStatus)); // Meeting status, 0 = appointment, 1 = meeting, 3 = attendee if (mEmailAddress.equalsIgnoreCase(organizerEmail)) { s.data(Tags.CALENDAR_MEETING_STATUS, hasAttendees ? "1" : "0"); } else { s.data(Tags.CALENDAR_MEETING_STATUS, "3"); } // For Exchange 2003, only upsync if the event is new if (((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) && organizerName != null) { s.data(Tags.CALENDAR_ORGANIZER_NAME, organizerName); } // NOTE: Sensitivity must NOT be sent to the server for exceptions in Exchange 2003 // The result will be a status 6 failure during sync Integer visibility = entityValues.getAsInteger(Events.ACCESS_LEVEL); if (visibility != null) { s.data(Tags.CALENDAR_SENSITIVITY, decodeVisibility(visibility)); } else { // Default to private if not set s.data(Tags.CALENDAR_SENSITIVITY, "1"); } } } /** * Convenience method for sending an email to the organizer declining the meeting * @param entity * @param clientId */ private void sendDeclinedEmail(Entity entity, String clientId) { Message msg = CalendarUtilities.createMessageForEntity(mContext, entity, Message.FLAG_OUTGOING_MEETING_DECLINE, clientId, mAccount); if (msg != null) { userLog("Queueing declined response to " + msg.mTo); mOutgoingMailList.add(msg); } } @Override public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mService.mContentResolver; if (getSyncKey().equals("0")) { return false; } try { // We've got to handle exceptions as part of the parent when changes occur, so we need // to find new/changed exceptions and mark the parent dirty ArrayList<Long> orphanedExceptions = new ArrayList<Long>(); Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION, DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null); try { ContentValues cv = new ContentValues(); // We use _sync_mark here to distinguish dirty parents from parents with dirty // exceptions cv.put(EVENT_SYNC_MARK, "1"); while (c.moveToNext()) { // Mark the parents of dirty exceptions long parentId = c.getLong(0); int cnt = cr.update( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, EVENT_ID_AND_CALENDAR_ID, new String[] { Long.toString(parentId), mCalendarIdString }); // Keep track of any orphaned exceptions if (cnt == 0) { orphanedExceptions.add(c.getLong(1)); } } } finally { c.close(); } // Delete any orphaned exceptions for (long orphan : orphanedExceptions) { userLog(TAG, "Deleted orphaned exception: " + orphan); cr.delete( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null); } orphanedExceptions.clear(); // Now we can go through dirty/marked top-level events and send them // back to the server EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr); ContentValues cidValues = new ContentValues(); try { boolean first = true; while (eventIterator.hasNext()) { Entity entity = eventIterator.next(); // For each of these entities, create the change commands ContentValues entityValues = entity.getEntityValues(); String serverId = entityValues.getAsString(Events._SYNC_ID); // We first need to check whether we can upsync this event; our test for this // is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED // If this is set to "1", we can't upsync the event for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; if (ncvValues.getAsString(ExtendedProperties.NAME).equals( EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) { if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) { // Make sure we mark this to clear the dirty flag mUploadedIdList.add(entityValues.getAsLong(Events._ID)); continue; } } } } // Find our uid in the entity; otherwise create one String clientId = entityValues.getAsString(Events.SYNC_DATA2); if (clientId == null) { clientId = UUID.randomUUID().toString(); } // EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID // We can generate all but what we're testing for below String organizerEmail = entityValues.getAsString(Events.ORGANIZER); boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress); if (!entityValues.containsKey(Events.DTSTART) || (!entityValues.containsKey(Events.DURATION) && !entityValues.containsKey(Events.DTEND)) || organizerEmail == null) { continue; } if (first) { s.start(Tags.SYNC_COMMANDS); userLog("Sending Calendar changes to the server"); first = false; } long eventId = entityValues.getAsLong(Events._ID); if (serverId == null) { // This is a new event; create a clientId userLog("Creating new event with clientId: ", clientId); s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId); // And save it in the Event as the local id cidValues.put(Events.SYNC_DATA2, clientId); cidValues.put(EVENT_SYNC_VERSION, "0"); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); } else { if (entityValues.getAsInteger(Events.DELETED) == 1) { userLog("Deleting event with serverId: ", serverId); s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); mDeletedIdList.add(eventId); if (selfOrganizer) { mSendCancelIdList.add(eventId); } else { sendDeclinedEmail(entity, clientId); } continue; } userLog("Upsync change to event with serverId: " + serverId); // Get the current version String version = entityValues.getAsString(EVENT_SYNC_VERSION); // This should never be null, but catch this error anyway // Version should be "0" when we create the event, so use that if (version == null) { version = "0"; } else { // Increment and save try { version = Integer.toString((Integer.parseInt(version) + 1)); } catch (Exception e) { // Handle the case in which someone writes a non-integer here; // shouldn't happen, but we don't want to kill the sync for his version = "0"; } } cidValues.put(EVENT_SYNC_VERSION, version); // Also save in entityValues so that we send it this time around entityValues.put(EVENT_SYNC_VERSION, version); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId); } s.start(Tags.SYNC_APPLICATION_DATA); sendEvent(entity, clientId, s); // Now, the hard part; find exceptions for this event if (serverId != null) { EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, ORIGINAL_EVENT_AND_CALENDAR, new String[] { serverId, mCalendarIdString }, null), cr); boolean exFirst = true; while (exIterator.hasNext()) { Entity exEntity = exIterator.next(); if (exFirst) { s.start(Tags.CALENDAR_EXCEPTIONS); exFirst = false; } s.start(Tags.CALENDAR_EXCEPTION); sendEvent(exEntity, null, s); ContentValues exValues = exEntity.getEntityValues(); if (getInt(exValues, Events.DIRTY) == 1) { // This is a new/updated exception, so we've got to notify our // attendees about it long exEventId = exValues.getAsLong(Events._ID); int flag; // Copy subvalues into the exception; otherwise, we won't see the // attendees when preparing the message for (NamedContentValues ncv: entity.getSubValues()) { exEntity.addSubValue(ncv.uri, ncv.values); } if ((getInt(exValues, Events.DELETED) == 1) || (getInt(exValues, Events.STATUS) == Events.STATUS_CANCELED)) { flag = Message.FLAG_OUTGOING_MEETING_CANCEL; if (!selfOrganizer) { // Send a cancellation notice to the organizer // Since CalendarProvider2 sets the organizer of exceptions // to the user, we have to reset it first to the original // organizer exValues.put(Events.ORGANIZER, entityValues.getAsString(Events.ORGANIZER)); sendDeclinedEmail(exEntity, clientId); } } else { flag = Message.FLAG_OUTGOING_MEETING_INVITE; } // Add the eventId of the exception to the uploaded id list, so that // the dirty/mark bits are cleared mUploadedIdList.add(exEventId); // Copy version so the ics attachment shows the proper sequence # exValues.put(EVENT_SYNC_VERSION, entityValues.getAsString(EVENT_SYNC_VERSION)); // Copy location so that it's included in the outgoing email if (entityValues.containsKey(Events.EVENT_LOCATION)) { exValues.put(Events.EVENT_LOCATION, entityValues.getAsString(Events.EVENT_LOCATION)); } if (selfOrganizer) { Message msg = CalendarUtilities.createMessageForEntity(mContext, exEntity, flag, clientId, mAccount); if (msg != null) { userLog("Queueing exception update to " + msg.mTo); mOutgoingMailList.add(msg); } } } s.end(); // EXCEPTION } if (!exFirst) { s.end(); // EXCEPTIONS } } s.end().end(); // ApplicationData & Change mUploadedIdList.add(eventId); // Go through the extended properties of this Event and pull out our tokenized // attendees list and the user attendee status; we will need them later String attendeeString = null; long attendeeStringId = -1; String userAttendeeStatus = null; long userAttendeeStatusId = -1; for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; String propertyName = ncvValues.getAsString(ExtendedProperties.NAME); if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) { attendeeString = ncvValues.getAsString(ExtendedProperties.VALUE); attendeeStringId = ncvValues.getAsLong(ExtendedProperties._ID); } else if (propertyName.equals( EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) { userAttendeeStatus = ncvValues.getAsString(ExtendedProperties.VALUE); userAttendeeStatusId = ncvValues.getAsLong(ExtendedProperties._ID); } } } // Send the meeting invite if there are attendees and we're the organizer AND // if the Event itself is dirty (we might be syncing only because an exception // is dirty, in which case we DON'T send email about the Event) if (selfOrganizer && (getInt(entityValues, Events.DIRTY) == 1)) { EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId, mAccount); if (msg != null) { userLog("Queueing invitation to ", msg.mTo); mOutgoingMailList.add(msg); } // Make a list out of our tokenized attendees, if we have any ArrayList<String> originalAttendeeList = new ArrayList<String>(); if (attendeeString != null) { StringTokenizer st = new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER); while (st.hasMoreTokens()) { originalAttendeeList.add(st.nextToken()); } } StringBuilder newTokenizedAttendees = new StringBuilder(); // See if any attendees have been dropped and while we're at it, build // an updated String with tokenized attendee addresses for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(Attendees.CONTENT_URI)) { String attendeeEmail = ncv.values.getAsString(Attendees.ATTENDEE_EMAIL); // Remove all found attendees originalAttendeeList.remove(attendeeEmail); newTokenizedAttendees.append(attendeeEmail); newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER); } } // Update extended properties with the new attendee list, if we have one // Otherwise, create one (this would be the case for Events created on // device or "legacy" events (before this code was added) ContentValues cv = new ContentValues(); cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString()); if (attendeeString != null) { cr.update(asSyncAdapter(ContentUris.withAppendedId( ExtendedProperties.CONTENT_URI, attendeeStringId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } else { // If there wasn't an "attendees" property, insert one cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES); cv.put(ExtendedProperties.EVENT_ID, eventId); cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv); } // Whoever is left has been removed from the attendee list; send them // a cancellation for (String removedAttendee: originalAttendeeList) { // Send a cancellation message to each of them msg = CalendarUtilities.createMessageForEventId(mContext, eventId, Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount, removedAttendee); if (msg != null) { // Just send it to the removed attendee userLog("Queueing cancellation to removed attendee " + msg.mTo); mOutgoingMailList.add(msg); } } } else if (!selfOrganizer) { // If we're not the organizer, see if we've changed our attendee status // Our last synced attendee status is in ExtendedProperties, and we've // retrieved it above as userAttendeeStatus int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS); int syncStatus = Attendees.ATTENDEE_STATUS_NONE; if (userAttendeeStatus != null) { try { syncStatus = Integer.parseInt(userAttendeeStatus); } catch (NumberFormatException e) { // Just in case somebody else mucked with this and it's not Integer } } if ((currentStatus != syncStatus) && (currentStatus != Attendees.ATTENDEE_STATUS_NONE)) { // If so, send a meeting reply int messageFlag = 0; switch (currentStatus) { case Attendees.ATTENDEE_STATUS_ACCEPTED: messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT; break; case Attendees.ATTENDEE_STATUS_DECLINED: messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE; break; case Attendees.ATTENDEE_STATUS_TENTATIVE: messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE; break; } // Make sure we have a valid status (messageFlag should never be zero) if (messageFlag != 0 && userAttendeeStatusId >= 0) { // Save away the new status cidValues.clear(); cidValues.put(ExtendedProperties.VALUE, Integer.toString(currentStatus)); - cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI, - userAttendeeStatusId), cidValues, null, null); + cr.update(asSyncAdapter(ContentUris.withAppendedId( + ExtendedProperties.CONTENT_URI, userAttendeeStatusId), + mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), + cidValues, null, null); // Send mail to the organizer advising of the new status EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, messageFlag, clientId, mAccount); if (msg != null) { userLog("Queueing invitation reply to " + msg.mTo); mOutgoingMailList.add(msg); } } } } } if (!first) { s.end(); // Commands } } finally { eventIterator.close(); } } catch (RemoteException e) { Log.e(TAG, "Could not read dirty events."); } return false; } }
true
true
public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mService.mContentResolver; if (getSyncKey().equals("0")) { return false; } try { // We've got to handle exceptions as part of the parent when changes occur, so we need // to find new/changed exceptions and mark the parent dirty ArrayList<Long> orphanedExceptions = new ArrayList<Long>(); Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION, DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null); try { ContentValues cv = new ContentValues(); // We use _sync_mark here to distinguish dirty parents from parents with dirty // exceptions cv.put(EVENT_SYNC_MARK, "1"); while (c.moveToNext()) { // Mark the parents of dirty exceptions long parentId = c.getLong(0); int cnt = cr.update( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, EVENT_ID_AND_CALENDAR_ID, new String[] { Long.toString(parentId), mCalendarIdString }); // Keep track of any orphaned exceptions if (cnt == 0) { orphanedExceptions.add(c.getLong(1)); } } } finally { c.close(); } // Delete any orphaned exceptions for (long orphan : orphanedExceptions) { userLog(TAG, "Deleted orphaned exception: " + orphan); cr.delete( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null); } orphanedExceptions.clear(); // Now we can go through dirty/marked top-level events and send them // back to the server EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr); ContentValues cidValues = new ContentValues(); try { boolean first = true; while (eventIterator.hasNext()) { Entity entity = eventIterator.next(); // For each of these entities, create the change commands ContentValues entityValues = entity.getEntityValues(); String serverId = entityValues.getAsString(Events._SYNC_ID); // We first need to check whether we can upsync this event; our test for this // is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED // If this is set to "1", we can't upsync the event for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; if (ncvValues.getAsString(ExtendedProperties.NAME).equals( EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) { if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) { // Make sure we mark this to clear the dirty flag mUploadedIdList.add(entityValues.getAsLong(Events._ID)); continue; } } } } // Find our uid in the entity; otherwise create one String clientId = entityValues.getAsString(Events.SYNC_DATA2); if (clientId == null) { clientId = UUID.randomUUID().toString(); } // EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID // We can generate all but what we're testing for below String organizerEmail = entityValues.getAsString(Events.ORGANIZER); boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress); if (!entityValues.containsKey(Events.DTSTART) || (!entityValues.containsKey(Events.DURATION) && !entityValues.containsKey(Events.DTEND)) || organizerEmail == null) { continue; } if (first) { s.start(Tags.SYNC_COMMANDS); userLog("Sending Calendar changes to the server"); first = false; } long eventId = entityValues.getAsLong(Events._ID); if (serverId == null) { // This is a new event; create a clientId userLog("Creating new event with clientId: ", clientId); s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId); // And save it in the Event as the local id cidValues.put(Events.SYNC_DATA2, clientId); cidValues.put(EVENT_SYNC_VERSION, "0"); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); } else { if (entityValues.getAsInteger(Events.DELETED) == 1) { userLog("Deleting event with serverId: ", serverId); s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); mDeletedIdList.add(eventId); if (selfOrganizer) { mSendCancelIdList.add(eventId); } else { sendDeclinedEmail(entity, clientId); } continue; } userLog("Upsync change to event with serverId: " + serverId); // Get the current version String version = entityValues.getAsString(EVENT_SYNC_VERSION); // This should never be null, but catch this error anyway // Version should be "0" when we create the event, so use that if (version == null) { version = "0"; } else { // Increment and save try { version = Integer.toString((Integer.parseInt(version) + 1)); } catch (Exception e) { // Handle the case in which someone writes a non-integer here; // shouldn't happen, but we don't want to kill the sync for his version = "0"; } } cidValues.put(EVENT_SYNC_VERSION, version); // Also save in entityValues so that we send it this time around entityValues.put(EVENT_SYNC_VERSION, version); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId); } s.start(Tags.SYNC_APPLICATION_DATA); sendEvent(entity, clientId, s); // Now, the hard part; find exceptions for this event if (serverId != null) { EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, ORIGINAL_EVENT_AND_CALENDAR, new String[] { serverId, mCalendarIdString }, null), cr); boolean exFirst = true; while (exIterator.hasNext()) { Entity exEntity = exIterator.next(); if (exFirst) { s.start(Tags.CALENDAR_EXCEPTIONS); exFirst = false; } s.start(Tags.CALENDAR_EXCEPTION); sendEvent(exEntity, null, s); ContentValues exValues = exEntity.getEntityValues(); if (getInt(exValues, Events.DIRTY) == 1) { // This is a new/updated exception, so we've got to notify our // attendees about it long exEventId = exValues.getAsLong(Events._ID); int flag; // Copy subvalues into the exception; otherwise, we won't see the // attendees when preparing the message for (NamedContentValues ncv: entity.getSubValues()) { exEntity.addSubValue(ncv.uri, ncv.values); } if ((getInt(exValues, Events.DELETED) == 1) || (getInt(exValues, Events.STATUS) == Events.STATUS_CANCELED)) { flag = Message.FLAG_OUTGOING_MEETING_CANCEL; if (!selfOrganizer) { // Send a cancellation notice to the organizer // Since CalendarProvider2 sets the organizer of exceptions // to the user, we have to reset it first to the original // organizer exValues.put(Events.ORGANIZER, entityValues.getAsString(Events.ORGANIZER)); sendDeclinedEmail(exEntity, clientId); } } else { flag = Message.FLAG_OUTGOING_MEETING_INVITE; } // Add the eventId of the exception to the uploaded id list, so that // the dirty/mark bits are cleared mUploadedIdList.add(exEventId); // Copy version so the ics attachment shows the proper sequence # exValues.put(EVENT_SYNC_VERSION, entityValues.getAsString(EVENT_SYNC_VERSION)); // Copy location so that it's included in the outgoing email if (entityValues.containsKey(Events.EVENT_LOCATION)) { exValues.put(Events.EVENT_LOCATION, entityValues.getAsString(Events.EVENT_LOCATION)); } if (selfOrganizer) { Message msg = CalendarUtilities.createMessageForEntity(mContext, exEntity, flag, clientId, mAccount); if (msg != null) { userLog("Queueing exception update to " + msg.mTo); mOutgoingMailList.add(msg); } } } s.end(); // EXCEPTION } if (!exFirst) { s.end(); // EXCEPTIONS } } s.end().end(); // ApplicationData & Change mUploadedIdList.add(eventId); // Go through the extended properties of this Event and pull out our tokenized // attendees list and the user attendee status; we will need them later String attendeeString = null; long attendeeStringId = -1; String userAttendeeStatus = null; long userAttendeeStatusId = -1; for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; String propertyName = ncvValues.getAsString(ExtendedProperties.NAME); if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) { attendeeString = ncvValues.getAsString(ExtendedProperties.VALUE); attendeeStringId = ncvValues.getAsLong(ExtendedProperties._ID); } else if (propertyName.equals( EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) { userAttendeeStatus = ncvValues.getAsString(ExtendedProperties.VALUE); userAttendeeStatusId = ncvValues.getAsLong(ExtendedProperties._ID); } } } // Send the meeting invite if there are attendees and we're the organizer AND // if the Event itself is dirty (we might be syncing only because an exception // is dirty, in which case we DON'T send email about the Event) if (selfOrganizer && (getInt(entityValues, Events.DIRTY) == 1)) { EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId, mAccount); if (msg != null) { userLog("Queueing invitation to ", msg.mTo); mOutgoingMailList.add(msg); } // Make a list out of our tokenized attendees, if we have any ArrayList<String> originalAttendeeList = new ArrayList<String>(); if (attendeeString != null) { StringTokenizer st = new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER); while (st.hasMoreTokens()) { originalAttendeeList.add(st.nextToken()); } } StringBuilder newTokenizedAttendees = new StringBuilder(); // See if any attendees have been dropped and while we're at it, build // an updated String with tokenized attendee addresses for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(Attendees.CONTENT_URI)) { String attendeeEmail = ncv.values.getAsString(Attendees.ATTENDEE_EMAIL); // Remove all found attendees originalAttendeeList.remove(attendeeEmail); newTokenizedAttendees.append(attendeeEmail); newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER); } } // Update extended properties with the new attendee list, if we have one // Otherwise, create one (this would be the case for Events created on // device or "legacy" events (before this code was added) ContentValues cv = new ContentValues(); cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString()); if (attendeeString != null) { cr.update(asSyncAdapter(ContentUris.withAppendedId( ExtendedProperties.CONTENT_URI, attendeeStringId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } else { // If there wasn't an "attendees" property, insert one cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES); cv.put(ExtendedProperties.EVENT_ID, eventId); cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv); } // Whoever is left has been removed from the attendee list; send them // a cancellation for (String removedAttendee: originalAttendeeList) { // Send a cancellation message to each of them msg = CalendarUtilities.createMessageForEventId(mContext, eventId, Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount, removedAttendee); if (msg != null) { // Just send it to the removed attendee userLog("Queueing cancellation to removed attendee " + msg.mTo); mOutgoingMailList.add(msg); } } } else if (!selfOrganizer) { // If we're not the organizer, see if we've changed our attendee status // Our last synced attendee status is in ExtendedProperties, and we've // retrieved it above as userAttendeeStatus int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS); int syncStatus = Attendees.ATTENDEE_STATUS_NONE; if (userAttendeeStatus != null) { try { syncStatus = Integer.parseInt(userAttendeeStatus); } catch (NumberFormatException e) { // Just in case somebody else mucked with this and it's not Integer } } if ((currentStatus != syncStatus) && (currentStatus != Attendees.ATTENDEE_STATUS_NONE)) { // If so, send a meeting reply int messageFlag = 0; switch (currentStatus) { case Attendees.ATTENDEE_STATUS_ACCEPTED: messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT; break; case Attendees.ATTENDEE_STATUS_DECLINED: messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE; break; case Attendees.ATTENDEE_STATUS_TENTATIVE: messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE; break; } // Make sure we have a valid status (messageFlag should never be zero) if (messageFlag != 0 && userAttendeeStatusId >= 0) { // Save away the new status cidValues.clear(); cidValues.put(ExtendedProperties.VALUE, Integer.toString(currentStatus)); cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI, userAttendeeStatusId), cidValues, null, null); // Send mail to the organizer advising of the new status EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, messageFlag, clientId, mAccount); if (msg != null) { userLog("Queueing invitation reply to " + msg.mTo); mOutgoingMailList.add(msg); } } } } } if (!first) { s.end(); // Commands } } finally { eventIterator.close(); } } catch (RemoteException e) { Log.e(TAG, "Could not read dirty events."); } return false; }
public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mService.mContentResolver; if (getSyncKey().equals("0")) { return false; } try { // We've got to handle exceptions as part of the parent when changes occur, so we need // to find new/changed exceptions and mark the parent dirty ArrayList<Long> orphanedExceptions = new ArrayList<Long>(); Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION, DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null); try { ContentValues cv = new ContentValues(); // We use _sync_mark here to distinguish dirty parents from parents with dirty // exceptions cv.put(EVENT_SYNC_MARK, "1"); while (c.moveToNext()) { // Mark the parents of dirty exceptions long parentId = c.getLong(0); int cnt = cr.update( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, EVENT_ID_AND_CALENDAR_ID, new String[] { Long.toString(parentId), mCalendarIdString }); // Keep track of any orphaned exceptions if (cnt == 0) { orphanedExceptions.add(c.getLong(1)); } } } finally { c.close(); } // Delete any orphaned exceptions for (long orphan : orphanedExceptions) { userLog(TAG, "Deleted orphaned exception: " + orphan); cr.delete( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null); } orphanedExceptions.clear(); // Now we can go through dirty/marked top-level events and send them // back to the server EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr); ContentValues cidValues = new ContentValues(); try { boolean first = true; while (eventIterator.hasNext()) { Entity entity = eventIterator.next(); // For each of these entities, create the change commands ContentValues entityValues = entity.getEntityValues(); String serverId = entityValues.getAsString(Events._SYNC_ID); // We first need to check whether we can upsync this event; our test for this // is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED // If this is set to "1", we can't upsync the event for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; if (ncvValues.getAsString(ExtendedProperties.NAME).equals( EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) { if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) { // Make sure we mark this to clear the dirty flag mUploadedIdList.add(entityValues.getAsLong(Events._ID)); continue; } } } } // Find our uid in the entity; otherwise create one String clientId = entityValues.getAsString(Events.SYNC_DATA2); if (clientId == null) { clientId = UUID.randomUUID().toString(); } // EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID // We can generate all but what we're testing for below String organizerEmail = entityValues.getAsString(Events.ORGANIZER); boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress); if (!entityValues.containsKey(Events.DTSTART) || (!entityValues.containsKey(Events.DURATION) && !entityValues.containsKey(Events.DTEND)) || organizerEmail == null) { continue; } if (first) { s.start(Tags.SYNC_COMMANDS); userLog("Sending Calendar changes to the server"); first = false; } long eventId = entityValues.getAsLong(Events._ID); if (serverId == null) { // This is a new event; create a clientId userLog("Creating new event with clientId: ", clientId); s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId); // And save it in the Event as the local id cidValues.put(Events.SYNC_DATA2, clientId); cidValues.put(EVENT_SYNC_VERSION, "0"); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); } else { if (entityValues.getAsInteger(Events.DELETED) == 1) { userLog("Deleting event with serverId: ", serverId); s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); mDeletedIdList.add(eventId); if (selfOrganizer) { mSendCancelIdList.add(eventId); } else { sendDeclinedEmail(entity, clientId); } continue; } userLog("Upsync change to event with serverId: " + serverId); // Get the current version String version = entityValues.getAsString(EVENT_SYNC_VERSION); // This should never be null, but catch this error anyway // Version should be "0" when we create the event, so use that if (version == null) { version = "0"; } else { // Increment and save try { version = Integer.toString((Integer.parseInt(version) + 1)); } catch (Exception e) { // Handle the case in which someone writes a non-integer here; // shouldn't happen, but we don't want to kill the sync for his version = "0"; } } cidValues.put(EVENT_SYNC_VERSION, version); // Also save in entityValues so that we send it this time around entityValues.put(EVENT_SYNC_VERSION, version); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId); } s.start(Tags.SYNC_APPLICATION_DATA); sendEvent(entity, clientId, s); // Now, the hard part; find exceptions for this event if (serverId != null) { EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, ORIGINAL_EVENT_AND_CALENDAR, new String[] { serverId, mCalendarIdString }, null), cr); boolean exFirst = true; while (exIterator.hasNext()) { Entity exEntity = exIterator.next(); if (exFirst) { s.start(Tags.CALENDAR_EXCEPTIONS); exFirst = false; } s.start(Tags.CALENDAR_EXCEPTION); sendEvent(exEntity, null, s); ContentValues exValues = exEntity.getEntityValues(); if (getInt(exValues, Events.DIRTY) == 1) { // This is a new/updated exception, so we've got to notify our // attendees about it long exEventId = exValues.getAsLong(Events._ID); int flag; // Copy subvalues into the exception; otherwise, we won't see the // attendees when preparing the message for (NamedContentValues ncv: entity.getSubValues()) { exEntity.addSubValue(ncv.uri, ncv.values); } if ((getInt(exValues, Events.DELETED) == 1) || (getInt(exValues, Events.STATUS) == Events.STATUS_CANCELED)) { flag = Message.FLAG_OUTGOING_MEETING_CANCEL; if (!selfOrganizer) { // Send a cancellation notice to the organizer // Since CalendarProvider2 sets the organizer of exceptions // to the user, we have to reset it first to the original // organizer exValues.put(Events.ORGANIZER, entityValues.getAsString(Events.ORGANIZER)); sendDeclinedEmail(exEntity, clientId); } } else { flag = Message.FLAG_OUTGOING_MEETING_INVITE; } // Add the eventId of the exception to the uploaded id list, so that // the dirty/mark bits are cleared mUploadedIdList.add(exEventId); // Copy version so the ics attachment shows the proper sequence # exValues.put(EVENT_SYNC_VERSION, entityValues.getAsString(EVENT_SYNC_VERSION)); // Copy location so that it's included in the outgoing email if (entityValues.containsKey(Events.EVENT_LOCATION)) { exValues.put(Events.EVENT_LOCATION, entityValues.getAsString(Events.EVENT_LOCATION)); } if (selfOrganizer) { Message msg = CalendarUtilities.createMessageForEntity(mContext, exEntity, flag, clientId, mAccount); if (msg != null) { userLog("Queueing exception update to " + msg.mTo); mOutgoingMailList.add(msg); } } } s.end(); // EXCEPTION } if (!exFirst) { s.end(); // EXCEPTIONS } } s.end().end(); // ApplicationData & Change mUploadedIdList.add(eventId); // Go through the extended properties of this Event and pull out our tokenized // attendees list and the user attendee status; we will need them later String attendeeString = null; long attendeeStringId = -1; String userAttendeeStatus = null; long userAttendeeStatusId = -1; for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; String propertyName = ncvValues.getAsString(ExtendedProperties.NAME); if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) { attendeeString = ncvValues.getAsString(ExtendedProperties.VALUE); attendeeStringId = ncvValues.getAsLong(ExtendedProperties._ID); } else if (propertyName.equals( EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) { userAttendeeStatus = ncvValues.getAsString(ExtendedProperties.VALUE); userAttendeeStatusId = ncvValues.getAsLong(ExtendedProperties._ID); } } } // Send the meeting invite if there are attendees and we're the organizer AND // if the Event itself is dirty (we might be syncing only because an exception // is dirty, in which case we DON'T send email about the Event) if (selfOrganizer && (getInt(entityValues, Events.DIRTY) == 1)) { EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId, mAccount); if (msg != null) { userLog("Queueing invitation to ", msg.mTo); mOutgoingMailList.add(msg); } // Make a list out of our tokenized attendees, if we have any ArrayList<String> originalAttendeeList = new ArrayList<String>(); if (attendeeString != null) { StringTokenizer st = new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER); while (st.hasMoreTokens()) { originalAttendeeList.add(st.nextToken()); } } StringBuilder newTokenizedAttendees = new StringBuilder(); // See if any attendees have been dropped and while we're at it, build // an updated String with tokenized attendee addresses for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(Attendees.CONTENT_URI)) { String attendeeEmail = ncv.values.getAsString(Attendees.ATTENDEE_EMAIL); // Remove all found attendees originalAttendeeList.remove(attendeeEmail); newTokenizedAttendees.append(attendeeEmail); newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER); } } // Update extended properties with the new attendee list, if we have one // Otherwise, create one (this would be the case for Events created on // device or "legacy" events (before this code was added) ContentValues cv = new ContentValues(); cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString()); if (attendeeString != null) { cr.update(asSyncAdapter(ContentUris.withAppendedId( ExtendedProperties.CONTENT_URI, attendeeStringId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } else { // If there wasn't an "attendees" property, insert one cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES); cv.put(ExtendedProperties.EVENT_ID, eventId); cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv); } // Whoever is left has been removed from the attendee list; send them // a cancellation for (String removedAttendee: originalAttendeeList) { // Send a cancellation message to each of them msg = CalendarUtilities.createMessageForEventId(mContext, eventId, Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount, removedAttendee); if (msg != null) { // Just send it to the removed attendee userLog("Queueing cancellation to removed attendee " + msg.mTo); mOutgoingMailList.add(msg); } } } else if (!selfOrganizer) { // If we're not the organizer, see if we've changed our attendee status // Our last synced attendee status is in ExtendedProperties, and we've // retrieved it above as userAttendeeStatus int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS); int syncStatus = Attendees.ATTENDEE_STATUS_NONE; if (userAttendeeStatus != null) { try { syncStatus = Integer.parseInt(userAttendeeStatus); } catch (NumberFormatException e) { // Just in case somebody else mucked with this and it's not Integer } } if ((currentStatus != syncStatus) && (currentStatus != Attendees.ATTENDEE_STATUS_NONE)) { // If so, send a meeting reply int messageFlag = 0; switch (currentStatus) { case Attendees.ATTENDEE_STATUS_ACCEPTED: messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT; break; case Attendees.ATTENDEE_STATUS_DECLINED: messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE; break; case Attendees.ATTENDEE_STATUS_TENTATIVE: messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE; break; } // Make sure we have a valid status (messageFlag should never be zero) if (messageFlag != 0 && userAttendeeStatusId >= 0) { // Save away the new status cidValues.clear(); cidValues.put(ExtendedProperties.VALUE, Integer.toString(currentStatus)); cr.update(asSyncAdapter(ContentUris.withAppendedId( ExtendedProperties.CONTENT_URI, userAttendeeStatusId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); // Send mail to the organizer advising of the new status EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, messageFlag, clientId, mAccount); if (msg != null) { userLog("Queueing invitation reply to " + msg.mTo); mOutgoingMailList.add(msg); } } } } } if (!first) { s.end(); // Commands } } finally { eventIterator.close(); } } catch (RemoteException e) { Log.e(TAG, "Could not read dirty events."); } return false; }
diff --git a/src/com/urbanairship/octobot/QueueConsumer.java b/src/com/urbanairship/octobot/QueueConsumer.java index 5b1baa3..0327dc5 100644 --- a/src/com/urbanairship/octobot/QueueConsumer.java +++ b/src/com/urbanairship/octobot/QueueConsumer.java @@ -1,274 +1,274 @@ package com.urbanairship.octobot; // AMQP Support import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.QueueingConsumer; // Beanstalk Support import com.surftools.BeanstalkClient.BeanstalkException; import com.surftools.BeanstalkClient.Job; import com.surftools.BeanstalkClientImpl.ClientImpl; import java.io.PrintWriter; import java.io.StringWriter; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.apache.log4j.Logger; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; // This thread opens a streaming connection to a queue, which continually // pushes messages to Octobot queue workers. The tasks contained within these // messages are invoked, then acknowledged and removed from the queue. public class QueueConsumer implements Runnable { Queue queue = null; Channel channel = null; Connection connection = null; QueueingConsumer consumer = null; private final Logger logger = Logger.getLogger("Queue Consumer"); private boolean enableEmailErrors = Settings.getAsBoolean("Octobot", "email_enabled"); // Initialize the consumer with a queue object (AMQP, Beanstalk, or Redis). public QueueConsumer(Queue queue) { this.queue = queue; } // Fire up the appropriate queue listener and begin invoking tasks!. public void run() { if (queue.queueType.equals("amqp")) { channel = getAMQPChannel(queue); consumeFromAMQP(); } else if (queue.queueType.equals("beanstalk")) { consumeFromBeanstalk(); } else if (queue.queueType.equals("redis")) { consumeFromRedis(); } else { logger.error("Invalid queue type specified: " + queue.queueType); } } // Attempts to register to receive streaming messages from RabbitMQ. // In the event that RabbitMQ is unavailable the call to getChannel() // will attempt to reconnect. If it fails, the loop simply repeats. private void consumeFromAMQP() { while (true) { QueueingConsumer.Delivery task = null; try { task = consumer.nextDelivery(); } catch (Exception e){ logger.error("Error in AMQP connection; reconnecting.", e); channel = getAMQPChannel(queue); continue; } // If we've got a message, fetch the body and invoke the task. // Then, send an acknowledgement back to RabbitMQ that we got it. if (task != null && task.getBody() != null) { invokeTask(new String(task.getBody())); try { channel.basicAck(task.getEnvelope().getDeliveryTag(), false); } catch (IOException e) { logger.error("Error ack'ing message.", e); } } } } // Attempt to register to receive messages from Beanstalk and invoke tasks. private void consumeFromBeanstalk() { ClientImpl beanstalkClient = new ClientImpl(queue.host, queue.port); beanstalkClient.watch(queue.queueName); beanstalkClient.useTube(queue.queueName); logger.info("Connected to Beanstalk; waiting for jobs."); while (true) { Job job = null; try { job = beanstalkClient.reserve(1); } catch (BeanstalkException e) { logger.error("Beanstalk connection error.", e); beanstalkClient = Beanstalk.getBeanstalkChannel(queue.host, queue.port, queue.queueName); continue; } if (job != null) { String message = new String(job.getData()); try { invokeTask(message); } catch (Exception e) { logger.error("Error handling message.", e); } try { beanstalkClient.delete(job.getJobId()); } catch (BeanstalkException e) { logger.error("Error sending message receipt.", e); beanstalkClient = Beanstalk.getBeanstalkChannel(queue.host, queue.port, queue.queueName); } } } } private void consumeFromRedis() { logger.info("Connecting to Redis..."); Jedis jedis = new Jedis(queue.host, queue.port); try { jedis.connect(); } catch (IOException e) { logger.error("Unable to connect to Redis.", e); } logger.info("Connected to Redis."); jedis.subscribe(new JedisPubSub() { @Override public void onMessage(String channel, String message) { invokeTask(message); } @Override public void onPMessage(String string, String string1, String string2) { logger.info("onPMessage Triggered - Not implemented."); } @Override public void onSubscribe(String string, int i) { logger.info("onSubscribe called - Not implemented."); } @Override public void onUnsubscribe(String string, int i) { logger.info("onUnsubscribe Called - Not implemented."); } @Override public void onPUnsubscribe(String string, int i) { logger.info("onPUnsubscribe called - Not implemented."); } @Override public void onPSubscribe(String string, int i) { logger.info("onPSubscribe Triggered - Not implemented."); } }, queue.queueName); } // Invokes a task based on the name of the task passed in the message via // reflection, accounting for non-existent tasks and errors while running. public boolean invokeTask(String rawMessage) { String taskName = ""; JSONObject message; int retryCount = 0; long retryTimes = 0; long startedAt = System.nanoTime(); String errorMessage = null; Throwable lastException = null; boolean executedSuccessfully = false; while (retryCount < retryTimes + 1) { if (retryCount > 0) logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes); try { message = (JSONObject) JSONValue.parse(rawMessage); taskName = (String) message.get("task"); if (message.containsKey("retries")) retryTimes = (Long) message.get("retries"); } catch (Exception e) { logger.error("Error: Invalid message received: " + rawMessage); return executedSuccessfully; } // Locate the task, then invoke it, supplying our message. // Cache methods after lookup to avoid unnecessary reflection lookups. try { TaskExecutor.execute(taskName, message); executedSuccessfully = true; } catch (ClassNotFoundException e) { lastException = e; errorMessage = "Error: Task requested not found: " + taskName; logger.error(errorMessage); } catch (NoClassDefFoundError e) { lastException = e; errorMessage = "Error: Task requested not found: " + taskName; logger.error(errorMessage, e); } catch (NoSuchMethodException e) { lastException = e; errorMessage = "Error: Task requested does not have a static run method."; logger.error(errorMessage); - } catch (Exception e) { + } catch (Throwable e) { lastException = e; errorMessage = "An error occurred while running the task."; logger.error(errorMessage, e); } if (executedSuccessfully) break; else retryCount++; } // Deliver an e-mail error notification if enabled. if (enableEmailErrors && !executedSuccessfully) { String email = "Error running task: " + taskName + ".\n\n" + "Attempted executing " + retryCount + " times as specified.\n\n" + "The original input was: \n\n" + rawMessage + "\n\n" + "Here's the error that resulted while running the task:\n\n" + stackToString(lastException); try { MailQueue.put(email); } catch (InterruptedException e) { } } long finishedAt = System.nanoTime(); Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount); return executedSuccessfully; } // Opens up a connection to RabbitMQ, retrying every five seconds // if the queue server is unavailable. private Channel getAMQPChannel(Queue queue) { int attempts = 0; logger.info("Opening connection to AMQP / " + queue.queueName + "..."); while (true) { attempts++; logger.debug("Attempt #" + attempts); try { connection = new RabbitMQ(queue).getConnection(); channel = connection.createChannel(); consumer = new QueueingConsumer(channel); channel.exchangeDeclare(queue.queueName, "direct", true); channel.queueDeclare(queue.queueName, true, false, false, null); channel.queueBind(queue.queueName, queue.queueName, queue.queueName); channel.basicConsume(queue.queueName, false, consumer); logger.info("Connected to RabbitMQ"); return channel; } catch (Exception e) { logger.error("Cannot connect to AMQP. Retrying in 5 sec.", e); try { Thread.sleep(1000 * 5); } catch (InterruptedException ex) { } } } } // Converts a stacktrace from task invocation to a string for error logging. public String stackToString(Throwable e) { if (e == null) return "(Null)"; StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter); return stringWriter.toString(); } }
true
true
public boolean invokeTask(String rawMessage) { String taskName = ""; JSONObject message; int retryCount = 0; long retryTimes = 0; long startedAt = System.nanoTime(); String errorMessage = null; Throwable lastException = null; boolean executedSuccessfully = false; while (retryCount < retryTimes + 1) { if (retryCount > 0) logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes); try { message = (JSONObject) JSONValue.parse(rawMessage); taskName = (String) message.get("task"); if (message.containsKey("retries")) retryTimes = (Long) message.get("retries"); } catch (Exception e) { logger.error("Error: Invalid message received: " + rawMessage); return executedSuccessfully; } // Locate the task, then invoke it, supplying our message. // Cache methods after lookup to avoid unnecessary reflection lookups. try { TaskExecutor.execute(taskName, message); executedSuccessfully = true; } catch (ClassNotFoundException e) { lastException = e; errorMessage = "Error: Task requested not found: " + taskName; logger.error(errorMessage); } catch (NoClassDefFoundError e) { lastException = e; errorMessage = "Error: Task requested not found: " + taskName; logger.error(errorMessage, e); } catch (NoSuchMethodException e) { lastException = e; errorMessage = "Error: Task requested does not have a static run method."; logger.error(errorMessage); } catch (Exception e) { lastException = e; errorMessage = "An error occurred while running the task."; logger.error(errorMessage, e); } if (executedSuccessfully) break; else retryCount++; } // Deliver an e-mail error notification if enabled. if (enableEmailErrors && !executedSuccessfully) { String email = "Error running task: " + taskName + ".\n\n" + "Attempted executing " + retryCount + " times as specified.\n\n" + "The original input was: \n\n" + rawMessage + "\n\n" + "Here's the error that resulted while running the task:\n\n" + stackToString(lastException); try { MailQueue.put(email); } catch (InterruptedException e) { } } long finishedAt = System.nanoTime(); Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount); return executedSuccessfully; }
public boolean invokeTask(String rawMessage) { String taskName = ""; JSONObject message; int retryCount = 0; long retryTimes = 0; long startedAt = System.nanoTime(); String errorMessage = null; Throwable lastException = null; boolean executedSuccessfully = false; while (retryCount < retryTimes + 1) { if (retryCount > 0) logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes); try { message = (JSONObject) JSONValue.parse(rawMessage); taskName = (String) message.get("task"); if (message.containsKey("retries")) retryTimes = (Long) message.get("retries"); } catch (Exception e) { logger.error("Error: Invalid message received: " + rawMessage); return executedSuccessfully; } // Locate the task, then invoke it, supplying our message. // Cache methods after lookup to avoid unnecessary reflection lookups. try { TaskExecutor.execute(taskName, message); executedSuccessfully = true; } catch (ClassNotFoundException e) { lastException = e; errorMessage = "Error: Task requested not found: " + taskName; logger.error(errorMessage); } catch (NoClassDefFoundError e) { lastException = e; errorMessage = "Error: Task requested not found: " + taskName; logger.error(errorMessage, e); } catch (NoSuchMethodException e) { lastException = e; errorMessage = "Error: Task requested does not have a static run method."; logger.error(errorMessage); } catch (Throwable e) { lastException = e; errorMessage = "An error occurred while running the task."; logger.error(errorMessage, e); } if (executedSuccessfully) break; else retryCount++; } // Deliver an e-mail error notification if enabled. if (enableEmailErrors && !executedSuccessfully) { String email = "Error running task: " + taskName + ".\n\n" + "Attempted executing " + retryCount + " times as specified.\n\n" + "The original input was: \n\n" + rawMessage + "\n\n" + "Here's the error that resulted while running the task:\n\n" + stackToString(lastException); try { MailQueue.put(email); } catch (InterruptedException e) { } } long finishedAt = System.nanoTime(); Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount); return executedSuccessfully; }
diff --git a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java index c6ef43a..11878ff 100644 --- a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java +++ b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java @@ -1,162 +1,162 @@ /** * */ package net.nexisonline.spade.chunkproviders; import java.util.Random; import libnoiseforjava.NoiseGen.NoiseQuality; import libnoiseforjava.module.Perlin; import libnoiseforjava.module.RidgedMulti; import org.bukkit.ChunkProvider; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; /** * @author Rob * */ public class ChunkProviderMountains extends ChunkProvider { private RidgedMulti terrainNoise; private Perlin continentNoise; private int continentNoiseOctaves = 16; private NoiseQuality noiseQuality = NoiseQuality.QUALITY_STD; private double ContinentNoiseFrequency; /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#onLoad(org.bukkit.World, long) */ @Override public void onLoad(World world, long seed) { double Frequency = 0.1; double Lacunarity = 0.05; double Persistance = 0.25; int OctaveCount = continentNoiseOctaves = 4; try { terrainNoise = new RidgedMulti(); continentNoise = new Perlin(); terrainNoise.setSeed((int) seed); continentNoise.setSeed((int) seed + 2); new Random((int) seed); terrainNoise.setFrequency(Frequency); terrainNoise.setNoiseQuality(noiseQuality); terrainNoise.setOctaveCount(OctaveCount); terrainNoise.setLacunarity(Lacunarity); continentNoise.setFrequency(ContinentNoiseFrequency); continentNoise.setNoiseQuality(noiseQuality); continentNoise.setOctaveCount(continentNoiseOctaves); continentNoise.setLacunarity(Lacunarity); continentNoise.setPersistence(Persistance); } catch (Exception e) { } } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#generateChunk(int, int, byte[], * org.bukkit.block.Biome[], double[]) */ @Override public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { double heightoffset = (continentNoise.getValue( (double) (x + (X * 16)) / 10d, (double) (z + (Z * 16)) / 10d, 0) + 1d);// *5d; // 2.0 double height = 30 + heightoffset; height += (int) ((terrainNoise.getValue(x + (X * 16), z - + (Z * 16), 0) + heightoffset)); + + (Z * 16), 0) + heightoffset)*0.33); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y++) { // If below height, set rock. Otherwise, set air. byte block = (y <= height) ? (byte) 1 : (byte) 0; // Fill block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#populateChunk(int, int, byte[], * org.bukkit.block.Biome[]) */ @Override public void populateChunk(World world, int x, int z, byte[] abyte, Biome[] biomes) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#hasCustomTerrainGenerator() */ @Override public boolean hasCustomTerrainGenerator() { // TODO Auto-generated method stub return true; } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#hasCustomPopulator() */ @Override public boolean hasCustomPopulator() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#hasCustomCaves() */ @Override public boolean hasCustomCaves() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#generateCaves(java.lang.Object, int, int, * byte[]) */ @Override public void generateCaves(World world, int x, int z, byte[] abyte) { // TODO Auto-generated method stub } }
true
true
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { double heightoffset = (continentNoise.getValue( (double) (x + (X * 16)) / 10d, (double) (z + (Z * 16)) / 10d, 0) + 1d);// *5d; // 2.0 double height = 30 + heightoffset; height += (int) ((terrainNoise.getValue(x + (X * 16), z + (Z * 16), 0) + heightoffset)); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y++) { // If below height, set rock. Otherwise, set air. byte block = (y <= height) ? (byte) 1 : (byte) 0; // Fill block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } }
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { double heightoffset = (continentNoise.getValue( (double) (x + (X * 16)) / 10d, (double) (z + (Z * 16)) / 10d, 0) + 1d);// *5d; // 2.0 double height = 30 + heightoffset; height += (int) ((terrainNoise.getValue(x + (X * 16), z + (Z * 16), 0) + heightoffset)*0.33); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y++) { // If below height, set rock. Otherwise, set air. byte block = (y <= height) ? (byte) 1 : (byte) 0; // Fill block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } }
diff --git a/src/util/ConsoleReader.java b/src/util/ConsoleReader.java index 0a0d3b0..951aa4d 100755 --- a/src/util/ConsoleReader.java +++ b/src/util/ConsoleReader.java @@ -1,137 +1,146 @@ package util; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; /** * Provides variety of methods to simplify getting user input from console. * * @author Robert C. Duvall */ public class ConsoleReader { // by default, read input from the user's console private static Scanner in = new Scanner(new InputStreamReader(System.in)); /** * Prompts the user to input an integer value. * * @param prompt output to the user before waiting for input * @return the value entered, waiting if necessary until one is given */ public static int promptInt (String prompt) { System.out.print(prompt); return in.nextInt(); } /** * Prompts the user to input an real value. * * @param prompt output to the user before waiting for input * @return the value entered, waiting if necessary until one is given */ public static double promptDouble (String prompt) { System.out.print(prompt); return in.nextDouble(); } /** * Prompts the user to input a word. * * @param prompt output to the user before waiting for input * @return the value entered, waiting if necessary until one is given */ public static String promptString (String prompt) { System.out.print(prompt); return in.next(); } /** * Prompts the user to input an integer value between the given values, * inclusive. Note, repeatedly prompts the user until a valid value is * entered. * * @param prompt output to the user before waiting for input * @param low minimum possible valid value allowed * @param hi maximum possible valid value allowed * @return the value entered, waiting if necessary until one is given */ public static int promptRange (String prompt, int low, int hi) { int answer; do { answer = promptInt(prompt + " between " + low + " and " + hi + "? "); } while (low > answer || answer > hi); return answer; } /** * Prompts the user to input an real value between the given values, * inclusive. Note, repeatedly prompts the user until a valid value is * entered. * * @param prompt output to the user before waiting for input * @param low minimum possible valid value allowed * @param hi maximum possible valid value allowed * @return the value entered, waiting if necessary until one is given */ public static double promptRange (String prompt, double low, double hi) { double answer; do { answer = promptDouble(prompt + " between " + low + " and " + hi + "? "); } while (low > answer || answer > hi); return answer; } /** * Prompts the user to input one of the given choices to the question. Note, * repeatedly prompts the user until a valid choice is entered. * * @param prompt output to the user before waiting for input * @param choices possible valid responses user can enter * @return the value entered, waiting if necessary until one is given */ public static String promptOneOf (String prompt, String ... choices) { Set<String> choiceSet = new TreeSet<String>(Arrays.asList(choices)); String result; do { - result = promptString(prompt + " one of " + choices + "? "); + StringBuilder buf = new StringBuilder(); + for( int i=0; i<choices.length; i++ ) + { + if( i > 0 ) + { + buf.append( ", " ); + } + buf.append( choices[i] ); + } + result = promptString(prompt + " one of " + buf.toString() + "? "); } while (!choiceSet.contains(result)); return result; } /** * Prompts the user to input yes or no to the given question. Note, * repeatedly prompts the user until yes or no is entered. * * @param prompt output to the user before waiting for input * @return the value entered, waiting if necessary until one is given */ public static boolean promptYesNo (String prompt) { String answer = promptOneOf(prompt, "yes", "Yes", "y", "Y", "no", "No", "n", "N"); return (answer.toLowerCase().startsWith("y")); } }
true
true
public static String promptOneOf (String prompt, String ... choices) { Set<String> choiceSet = new TreeSet<String>(Arrays.asList(choices)); String result; do { result = promptString(prompt + " one of " + choices + "? "); } while (!choiceSet.contains(result)); return result; }
public static String promptOneOf (String prompt, String ... choices) { Set<String> choiceSet = new TreeSet<String>(Arrays.asList(choices)); String result; do { StringBuilder buf = new StringBuilder(); for( int i=0; i<choices.length; i++ ) { if( i > 0 ) { buf.append( ", " ); } buf.append( choices[i] ); } result = promptString(prompt + " one of " + buf.toString() + "? "); } while (!choiceSet.contains(result)); return result; }
diff --git a/src/edu/calpoly/csc/pulseman/StartMenu.java b/src/edu/calpoly/csc/pulseman/StartMenu.java index 38fbeb6..d2259ee 100644 --- a/src/edu/calpoly/csc/pulseman/StartMenu.java +++ b/src/edu/calpoly/csc/pulseman/StartMenu.java @@ -1,102 +1,102 @@ package edu.calpoly.csc.pulseman; import java.util.Timer; import java.util.TimerTask; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; public class StartMenu implements GameInterface { private Image menuButton; private Image menuBackground; private Image connectButton, connectingButton, connectedButton; private volatile int countdown = 0; private final float[] buttonLoc = { 200, 400 }, connectLoc = { 850, 30 }; @Override public void render(GameContainer gc, Graphics g) { g.drawImage(menuBackground, 0, 0); g.drawImage(menuButton, buttonLoc[0], buttonLoc[1]); if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED) { g.drawImage(connectButton, connectLoc[0], connectLoc[1]); } else if(Main.getAndroidState() == Main.AndroidStates.CONNECTING) { g.drawImage(connectingButton, connectLoc[0], connectLoc[1]); g.drawString(String.valueOf(countdown), connectLoc[0] + connectingButton.getWidth(), connectLoc[1] + connectingButton.getHeight() / 2); } else { g.drawImage(connectedButton, connectLoc[0], connectLoc[1]); } g.drawString("You are a meditating monk. Head towards the light.\n" + "Use the beat to control nature's speed.", Main.getScreenWidth() / 2, Main.getScreenHeight() / 2); } @Override public void init(GameContainer gc) throws SlickException { menuButton = new Image("res/subtitle.png"); connectButton = new Image("res/connect.png"); connectingButton = new Image("res/connecting.png"); connectedButton = new Image("res/connected.png"); menuBackground = new Image("res/mainscreen.png"); } @Override public void update(GameContainer gc, int dt) { Input input = gc.getInput(); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) { int x = input.getMouseX(); int y = input.getMouseY(); if(x >= buttonLoc[0] && x <= buttonLoc[0] + menuButton.getWidth() && y >= buttonLoc[1] && y <= buttonLoc[1] + menuButton.getHeight()) { Main.setState(Main.GameState.GAME); } - if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED || (x >= connectLoc[0] && x <= connectLoc[0] + connectButton.getWidth() && y >= connectLoc[1] && y <= connectLoc[1] + connectButton.getHeight())) + if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED && (x >= connectLoc[0] && x <= connectLoc[0] + connectButton.getWidth() && y >= connectLoc[1] && y <= connectLoc[1] + connectButton.getHeight())) { listenForConnection(); countdown = MessageHandler.SOCKET_TIMEOUT / 1000 + 1; new Timer("Countdown Timer").schedule(new TimerTask() { @Override public void run() { if(--countdown < 0) { cancel(); } } }, 0, 1000); } } } public static void listenForConnection() { new Thread(new Runnable() { @Override public void run() { Main.setAndroidConnecting(); MessageHandler.listenForConnection(); } }).start(); } }
true
true
public void update(GameContainer gc, int dt) { Input input = gc.getInput(); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) { int x = input.getMouseX(); int y = input.getMouseY(); if(x >= buttonLoc[0] && x <= buttonLoc[0] + menuButton.getWidth() && y >= buttonLoc[1] && y <= buttonLoc[1] + menuButton.getHeight()) { Main.setState(Main.GameState.GAME); } if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED || (x >= connectLoc[0] && x <= connectLoc[0] + connectButton.getWidth() && y >= connectLoc[1] && y <= connectLoc[1] + connectButton.getHeight())) { listenForConnection(); countdown = MessageHandler.SOCKET_TIMEOUT / 1000 + 1; new Timer("Countdown Timer").schedule(new TimerTask() { @Override public void run() { if(--countdown < 0) { cancel(); } } }, 0, 1000); } } }
public void update(GameContainer gc, int dt) { Input input = gc.getInput(); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) { int x = input.getMouseX(); int y = input.getMouseY(); if(x >= buttonLoc[0] && x <= buttonLoc[0] + menuButton.getWidth() && y >= buttonLoc[1] && y <= buttonLoc[1] + menuButton.getHeight()) { Main.setState(Main.GameState.GAME); } if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED && (x >= connectLoc[0] && x <= connectLoc[0] + connectButton.getWidth() && y >= connectLoc[1] && y <= connectLoc[1] + connectButton.getHeight())) { listenForConnection(); countdown = MessageHandler.SOCKET_TIMEOUT / 1000 + 1; new Timer("Countdown Timer").schedule(new TimerTask() { @Override public void run() { if(--countdown < 0) { cancel(); } } }, 0, 1000); } } }
diff --git a/server/RequestProcessor.java b/server/RequestProcessor.java index bca7c88..b8ddc46 100644 --- a/server/RequestProcessor.java +++ b/server/RequestProcessor.java @@ -1,134 +1,135 @@ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.Socket; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.LinkedList; import java.util.List; import com.trend.Packet; public class RequestProcessor implements Runnable { private static List<Socket> pool = new LinkedList<Socket>(); private File localFile = null; private String filename =""; private long filesize = 0; private BufferedOutputStream fout = null; private MessageDigest mdsum; public static void processRequest(Socket request) { synchronized(pool) { pool.add(pool.size(), request); pool.notifyAll(); } } private void writeResponse(boolean success, Packet.Ack.AckType type, BufferedOutputStream conOut) throws IOException { Packet.Ack.Builder ackBuilder = Packet.Ack.newBuilder(); ackBuilder.setType(type); ackBuilder.setSuccess(success); Packet.Ack response = ackBuilder.build(); response.writeDelimitedTo(conOut); conOut.flush(); } private Packet.Block getFileBlock(BufferedInputStream in ) throws IOException { Packet.Block.Builder blockBuilder = Packet.Block.newBuilder(); blockBuilder.mergeDelimitedFrom(in); Packet.Block block = blockBuilder.build(); System.out.println(String.format("Receive a new block(Seq:%d Size:%d Digest:%s EOF:%s)", block.getSeqNum(), block.getSize(), block.getDigest(), block.getEof())); return block; } @Override public void run() { while (true) { Socket connection; synchronized(pool) { while (pool.isEmpty()) { try { pool.wait(); } catch (InterruptedException e) { } } connection = pool.remove(0); System.out.println("Accept a client from "+connection.getInetAddress().toString()); } try { BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); if (mdsum == null) mdsum = MessageDigest.getInstance("MD5"); else mdsum.reset(); if (fout == null) { Packet.Header.Builder headerBuilder = Packet.Header.newBuilder(); headerBuilder.mergeDelimitedFrom(in); Packet.Header header = headerBuilder.build(); fout = new BufferedOutputStream(new FileOutputStream("/tmp/"+header.getFileName())); filesize = header.getFileSize(); writeResponse(true, Packet.Ack.AckType.HEADER, out); System.out.println(String.format("Receive a new Header(filename:%s size:%d)",header.getFileName(), header.getFileSize())); } if (fout != null) { while (true) { Packet.Block block = getFileBlock(in); if (block.getEof()) { String digest = String.valueOf(mdsum.digest()); if (block.getDigest().equals(digest)) writeResponse(true, Packet.Ack.AckType.EOF, out); else writeResponse(false, Packet.Ack.AckType.EOF, out); break; } byte[] content = block.getContent().toByteArray(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(content); - String digest = String.valueOf(md.digest()); + String digest = md.digest().toString() ; + System.out.println( digest ) ; if (block.getDigest().equals(digest)) { fout.write(content, 0, block.getSize()); writeResponse(true, Packet.Ack.AckType.BLOCK, out); mdsum.update(content); } else { writeResponse(false, Packet.Ack.AckType.BLOCK, out); } } } } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (connection != null) connection.close(); if (fout != null) { fout.flush(); fout.close(); fout = null; } } catch (Exception e) { // Todo: } } } // end while } }
true
true
public void run() { while (true) { Socket connection; synchronized(pool) { while (pool.isEmpty()) { try { pool.wait(); } catch (InterruptedException e) { } } connection = pool.remove(0); System.out.println("Accept a client from "+connection.getInetAddress().toString()); } try { BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); if (mdsum == null) mdsum = MessageDigest.getInstance("MD5"); else mdsum.reset(); if (fout == null) { Packet.Header.Builder headerBuilder = Packet.Header.newBuilder(); headerBuilder.mergeDelimitedFrom(in); Packet.Header header = headerBuilder.build(); fout = new BufferedOutputStream(new FileOutputStream("/tmp/"+header.getFileName())); filesize = header.getFileSize(); writeResponse(true, Packet.Ack.AckType.HEADER, out); System.out.println(String.format("Receive a new Header(filename:%s size:%d)",header.getFileName(), header.getFileSize())); } if (fout != null) { while (true) { Packet.Block block = getFileBlock(in); if (block.getEof()) { String digest = String.valueOf(mdsum.digest()); if (block.getDigest().equals(digest)) writeResponse(true, Packet.Ack.AckType.EOF, out); else writeResponse(false, Packet.Ack.AckType.EOF, out); break; } byte[] content = block.getContent().toByteArray(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(content); String digest = String.valueOf(md.digest()); if (block.getDigest().equals(digest)) { fout.write(content, 0, block.getSize()); writeResponse(true, Packet.Ack.AckType.BLOCK, out); mdsum.update(content); } else { writeResponse(false, Packet.Ack.AckType.BLOCK, out); } } } } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (connection != null) connection.close(); if (fout != null) { fout.flush(); fout.close(); fout = null; } } catch (Exception e) { // Todo: } } } // end while }
public void run() { while (true) { Socket connection; synchronized(pool) { while (pool.isEmpty()) { try { pool.wait(); } catch (InterruptedException e) { } } connection = pool.remove(0); System.out.println("Accept a client from "+connection.getInetAddress().toString()); } try { BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); if (mdsum == null) mdsum = MessageDigest.getInstance("MD5"); else mdsum.reset(); if (fout == null) { Packet.Header.Builder headerBuilder = Packet.Header.newBuilder(); headerBuilder.mergeDelimitedFrom(in); Packet.Header header = headerBuilder.build(); fout = new BufferedOutputStream(new FileOutputStream("/tmp/"+header.getFileName())); filesize = header.getFileSize(); writeResponse(true, Packet.Ack.AckType.HEADER, out); System.out.println(String.format("Receive a new Header(filename:%s size:%d)",header.getFileName(), header.getFileSize())); } if (fout != null) { while (true) { Packet.Block block = getFileBlock(in); if (block.getEof()) { String digest = String.valueOf(mdsum.digest()); if (block.getDigest().equals(digest)) writeResponse(true, Packet.Ack.AckType.EOF, out); else writeResponse(false, Packet.Ack.AckType.EOF, out); break; } byte[] content = block.getContent().toByteArray(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(content); String digest = md.digest().toString() ; System.out.println( digest ) ; if (block.getDigest().equals(digest)) { fout.write(content, 0, block.getSize()); writeResponse(true, Packet.Ack.AckType.BLOCK, out); mdsum.update(content); } else { writeResponse(false, Packet.Ack.AckType.BLOCK, out); } } } } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (connection != null) connection.close(); if (fout != null) { fout.flush(); fout.close(); fout = null; } } catch (Exception e) { // Todo: } } } // end while }
diff --git a/ini/trakem2/persistence/CacheImageMipMaps.java b/ini/trakem2/persistence/CacheImageMipMaps.java index fa54ff23..adf98a6c 100644 --- a/ini/trakem2/persistence/CacheImageMipMaps.java +++ b/ini/trakem2/persistence/CacheImageMipMaps.java @@ -1,484 +1,487 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2008 Albert Cardona and Stephan Preibisch. 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 (http://www.gnu.org/licenses/gpl.txt ) 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. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.persistence; import ini.trakem2.utils.IJError; import java.util.ArrayList; import java.util.Hashtable; import java.util.HashMap; import java.util.ListIterator; import java.util.LinkedList; import java.util.Iterator; import java.util.Map; import java.awt.Image; /** A cache for TrakEM2's rolling memory of java.awt.Image instances. * Uses both a list and a map. When the list goes beyond a certain LINEAR_SEARCH_LIMIT, then the map is used. * Each image is added as a CacheImageMipMaps.Entry, which stores the image, the corresponding Patch id and the level of the image (0, 1, 2 ... mipmap level of descresing power of 2 sizes). * The map contains unique Patch id keys versus Image arrays of values, where the array index is the index. */ public class CacheImageMipMaps { private final LinkedList<Entry> cache; private final HashMap<Long,Image[]> map = new HashMap<Long,Image[]>(); private boolean use_map = false; public static int LINEAR_SEARCH_LIMIT = 0; private class Entry { final long id; final int level; Image image; Entry (final long id, final int level, final Image image) { this.id = id; this.level = level; this.image = image; } public final boolean equals(final Object ob) { final Entry e = (Entry)ob; return e.id == id && e.level == level; } public final boolean equals(final long id, final int level) { return this.id == id && this.level == level; } } public CacheImageMipMaps(int initial_size) { cache = new LinkedList<Entry>(); } private final Entry rfind(final long id, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); // descendingIterator() is from java 1.6 ! while (li.hasPrevious()) { final Entry e = li.previous(); if (e.equals(id, level)) return e; } return null; } /** Replace or put. */ public void replace(final long id, final Image image, final int level) { final Entry e = rfind(id, level); if (null == e) put(id, image, level); else { if (null != e.image) e.image.flush(); e.image = image; } } static private final int computeLevel(final int i) { return (int)(0.5 + ((Math.log(i) - Math.log(32)) / Math.log(2))) + 1; } /** The position in the array is the Math.max(width, height) of an image. */ private final static int[] max_levels = new int[50000]; // don't change to smaller than 33. Here 50000 is the maximum width or height for which precomputed mipmap levels will exist. static { // from 0 to 31 all zeros for (int i=32; i<max_levels.length; i++) { max_levels[i] = computeLevel(i); } } private final int maxLevel(final Image image, final int starting_level) { final int w = image.getWidth(null); final int h = image.getHeight(null); /* int max_level = starting_level; while (w > 32 || h > 32) { w /= 2; h /= 2; max_level++; } return max_level; */ final int max = Math.max(w, h); if (max >= max_levels.length) { //if (max <= 32) return starting_level; return starting_level + computeLevel(max); } else { return starting_level + max_levels[max]; } } /** No duplicates allowed: if the id exists it's sended to the end and the image is first flushed (if different), then updated with the new one provided. */ public final void put(final long id, final Image image, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { // images are more likely to be close to the end final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); cache.addLast(e); if (image != e.image) { // replace e.image.flush(); e.image = image; // replace in map - if (use_map) map.get(id)[level] = image; + if (use_map) { + final Image[] im = map.get(id); + if (null != im) im[level] = image; + } } return; } } // else, new cache.addLast(new Entry(id, level, image)); if (use_map) { // add new to the map Image[] images = map.get(id); try { if (null == images) { //System.out.println("CREATION maxLevel, level, image.width: " + maxLevel(image, level) + ", " + level + ", " + image.getWidth(null)); images = new Image[maxLevel(image, level)]; images[level] = image; map.put(id, images); } else { images[level] = image; } } catch (Exception e) { System.out.println("length of images[]: " + images.length); System.out.println("level to add: " + level); System.out.println("size of the image: " + image.getWidth(null)); System.out.println("maxlevel is: " + maxLevel(image, level)); } } else if (cache.size() >= LINEAR_SEARCH_LIMIT) { // create the map one step before it's used, hence the >= not > alone. // initialize map final ListIterator<Entry> lim = cache.listIterator(0); while (lim.hasNext()) { final Entry e = lim.next(); if (!map.containsKey(e.id)) { final Image[] images = new Image[maxLevel(image, level)]; images[e.level] = e.image; map.put(e.id, images); } else { final Image[] images = map.get(e.id); images[e.level] = e.image; } } use_map = true; //System.out.println("CREATED map"); } } /** A call to this method puts the element at the end of the list, and returns it. Returns null if not found. */ public final Image get(final long id, final int level) { if (0 == LINEAR_SEARCH_LIMIT) return getFromMap(id, level); final ListIterator<Entry> li = cache.listIterator(cache.size()); int i = 0; while (li.hasPrevious()) { // images are more likely to be close to the end if (i > LINEAR_SEARCH_LIMIT) { return getFromMap(id, level); } i++; /// final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); cache.addLast(e); return e.image; } } return null; } private final Image getFromMap(final long id, final int level) { final Image[] images = map.get(id); if (null == images) return null; return level < images.length ? images[level] : null; } private final Image getAboveFromMap(final long id, final int level) { final Image[] images = map.get(id); if (null == images) return null; for (int i=Math.min(level, images.length-1); i>-1; i--) { if (null != images[i]) return images[i]; } return null; } private final Image getBelowFromMap(final long id, final int level) { final Image[] images = map.get(id); if (null == images) return null; for (int i=level; i<images.length; i++) { if (null != images[i]) return images[i]; } return null; } /** Find the cached image of the given level or its closest but smaller image (larger level), or null if none found. */ public final Image getClosestBelow(final long id, final int level) { if (0 == LINEAR_SEARCH_LIMIT) return getBelowFromMap(id, level); Entry ee = null; int lev = Integer.MAX_VALUE; final ListIterator<Entry> li = cache.listIterator(cache.size()); int i = 0; while (li.hasPrevious()) { // images are more likely to be close to the end if (i > LINEAR_SEARCH_LIMIT) { return getBelowFromMap(id, level); } i++; /// final Entry e = li.previous(); if (e.id != id) continue; if (e.level == level) return e.image; if (e.level > level) { // if smaller image (larger level) than asked, choose the less smaller if (e.level < lev) { lev = e.level; ee = e; } } } if (null != ee) { cache.remove(ee); // unfortunaelly, removeLastOcurrence is java 1.6 only cache.addLast(ee); return ee.image; } return null; } /** Find the cached image of the given level or its closest but larger image (smaller level), or null if none found. */ public final Image getClosestAbove(final long id, final int level) { if (0 == LINEAR_SEARCH_LIMIT) return getAboveFromMap(id, level); int lev = -1; Entry ee = null; final ListIterator<Entry> li = cache.listIterator(cache.size()); int i = 0; while (li.hasPrevious()) { // images are more likely to be close to the end if (i > LINEAR_SEARCH_LIMIT) { return getAboveFromMap(id, level); } i++; final Entry e = li.previous(); if (e.id != id) continue; // if equal level as asked, just return it if (e.level == level) return e.image; // if exactly one above, just return it // may hinder finding an exact one, but potentially cuts down search time a lot // if (e.level == level + 1) return e.image; // WOULD NOT BE THE PERFECT IMAGE if the actual asked level is cached at a previous entry. if (e.level < level) { if (e.level > lev) { lev = e.level; ee = e; } } } if (null != ee) { cache.remove(ee); cache.addLast(ee); return ee.image; } return null; } /** Remove the Image if found and returns it, without flushing it. Returns null if not found. */ public final Image remove(final long id, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); return e.image; } } if (use_map) { final Image[] images = map.get(id); if (images == null) return null; images[level] = null; } return null; } /** Removes and flushes all images, and shrinks arrays. */ public final void removeAndFlushAll() { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); e.image.flush(); } cache.clear(); if (use_map) map.clear(); } /** Remove all awts associated with a level different than 0 (that means all scaled down versions) for any id. */ public void removeAllPyramids() { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (e.level > 0) { e.image.flush(); li.remove(); } } if (use_map) { final Iterator<Map.Entry<Long,Image[]>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Long,Image[]> entry = it.next(); final Image[] images = entry.getValue(); if (null == images[0]) it.remove(); for (int i=1; i<images.length; i++) { images[i] = null; } } } } /** Remove all awts associated with a level different than 0 (that means all scaled down versions) for the given id. */ public void removePyramid(final long id) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id && e.level > 0) { e.image.flush(); li.remove(); } } if (use_map) { final Image[] images = map.get(id); if (null != images) { for (int i=1; i<images.length; i++) { images[i] = null; } if (null == images[0]) map.remove(id); } } } /** Remove all images that share the same id (but have different levels). */ public final ArrayList<Image> remove(final long id) { final ArrayList<Image> al = new ArrayList<Image>(); final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id) { al.add(e.image); li.remove(); } } if (use_map) { map.remove(id); } return al; } /** Returns a table of level keys and image values that share the same id (that is, belong to the same Patch). */ public final Hashtable<Integer,Image> getAll(final long id) { final Hashtable<Integer,Image> ht = new Hashtable<Integer,Image>(); if (use_map) { final Image[] images = map.get(id); if (null != images) { for (int i=0; i<images.length; i++) { if (null != images[i]) { ht.put(i, images[i]); } } } } else { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id) ht.put(e.level, e.image); } } return ht; } /** Remove and flush away all images that share the same id. */ public final void removeAndFlush(final long id) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id) { e.image.flush(); li.remove(); } } if (use_map) map.remove(id); } /** Remove the given index and return it, returns null if outside range. */ public final Image remove(int i) { if (i < 0 || i >= cache.size()) return null; final Entry e = cache.remove(i); if (use_map) { nullifyMap(e.id, e.level); } return e.image; } private final void nullifyMap(final long id, final int level) { final Image[] images = map.get(id); if (null != images) { images[level] = null; for (Image im : images) { if (null != im) return; } // all null, remove map.remove(id); } } /** Remove the first element and return it. Returns null if none. The underlaying arrays are untouched besides nullifying the proper pointer. */ public final Image removeFirst() { final Entry e = cache.removeFirst(); if (use_map) { nullifyMap(e.id, e.level); } return e.image; } /** Checks if there's any image at all for the given id. */ public final boolean contains(final long id) { if (use_map) { return map.containsKey(id); } else { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id) return true; } } return false; } /** Checks if there's any image for the given id and level. */ public final boolean contains(final long id, final int level) { if (use_map) { final Image[] images = map.get(id); if (null == images) return false; return level < images.length ? null != images[level] : false; } return -1 != cache.lastIndexOf(new Entry(id, level, null)); } public int size() { return cache.size(); } public void debug() { System.out.println("cache size: " + cache.size() + ", " + map.size()); } /** Does nothing. */ public void gc() {} }
true
true
public final void put(final long id, final Image image, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { // images are more likely to be close to the end final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); cache.addLast(e); if (image != e.image) { // replace e.image.flush(); e.image = image; // replace in map if (use_map) map.get(id)[level] = image; } return; } } // else, new cache.addLast(new Entry(id, level, image)); if (use_map) { // add new to the map Image[] images = map.get(id); try { if (null == images) { //System.out.println("CREATION maxLevel, level, image.width: " + maxLevel(image, level) + ", " + level + ", " + image.getWidth(null)); images = new Image[maxLevel(image, level)]; images[level] = image; map.put(id, images); } else { images[level] = image; } } catch (Exception e) { System.out.println("length of images[]: " + images.length); System.out.println("level to add: " + level); System.out.println("size of the image: " + image.getWidth(null)); System.out.println("maxlevel is: " + maxLevel(image, level)); } } else if (cache.size() >= LINEAR_SEARCH_LIMIT) { // create the map one step before it's used, hence the >= not > alone. // initialize map final ListIterator<Entry> lim = cache.listIterator(0); while (lim.hasNext()) { final Entry e = lim.next(); if (!map.containsKey(e.id)) { final Image[] images = new Image[maxLevel(image, level)]; images[e.level] = e.image; map.put(e.id, images); } else { final Image[] images = map.get(e.id); images[e.level] = e.image; } } use_map = true; //System.out.println("CREATED map"); } }
public final void put(final long id, final Image image, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { // images are more likely to be close to the end final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); cache.addLast(e); if (image != e.image) { // replace e.image.flush(); e.image = image; // replace in map if (use_map) { final Image[] im = map.get(id); if (null != im) im[level] = image; } } return; } } // else, new cache.addLast(new Entry(id, level, image)); if (use_map) { // add new to the map Image[] images = map.get(id); try { if (null == images) { //System.out.println("CREATION maxLevel, level, image.width: " + maxLevel(image, level) + ", " + level + ", " + image.getWidth(null)); images = new Image[maxLevel(image, level)]; images[level] = image; map.put(id, images); } else { images[level] = image; } } catch (Exception e) { System.out.println("length of images[]: " + images.length); System.out.println("level to add: " + level); System.out.println("size of the image: " + image.getWidth(null)); System.out.println("maxlevel is: " + maxLevel(image, level)); } } else if (cache.size() >= LINEAR_SEARCH_LIMIT) { // create the map one step before it's used, hence the >= not > alone. // initialize map final ListIterator<Entry> lim = cache.listIterator(0); while (lim.hasNext()) { final Entry e = lim.next(); if (!map.containsKey(e.id)) { final Image[] images = new Image[maxLevel(image, level)]; images[e.level] = e.image; map.put(e.id, images); } else { final Image[] images = map.get(e.id); images[e.level] = e.image; } } use_map = true; //System.out.println("CREATED map"); } }
diff --git a/cat-home/src/main/java/com/dianping/cat/report/page/model/transaction/HdfsTransactionService.java b/cat-home/src/main/java/com/dianping/cat/report/page/model/transaction/HdfsTransactionService.java index a9f86dc3..dfce5a86 100644 --- a/cat-home/src/main/java/com/dianping/cat/report/page/model/transaction/HdfsTransactionService.java +++ b/cat-home/src/main/java/com/dianping/cat/report/page/model/transaction/HdfsTransactionService.java @@ -1,56 +1,56 @@ package com.dianping.cat.report.page.model.transaction; import java.util.Date; import com.dianping.cat.consumer.transaction.model.entity.TransactionReport; import com.dianping.cat.consumer.transaction.model.transform.DefaultXmlParser; import com.dianping.cat.message.spi.MessagePathBuilder; import com.dianping.cat.report.page.model.spi.ModelRequest; import com.dianping.cat.report.page.model.spi.ModelResponse; import com.dianping.cat.report.page.model.spi.ModelService; import com.dianping.cat.storage.Bucket; import com.dianping.cat.storage.BucketManager; import com.site.lookup.annotation.Inject; public class HdfsTransactionService implements ModelService<TransactionReport> { @Inject private BucketManager m_bucketManager; @Inject private MessagePathBuilder m_pathBuilder; @Override public ModelResponse<TransactionReport> invoke(ModelRequest request) { String domain = request.getDomain(); long date = Long.parseLong(request.getProperty("date")); String path = m_pathBuilder.getReportPath(new Date(date)); ModelResponse<TransactionReport> response = new ModelResponse<TransactionReport>(); Bucket<byte[]> bucket = null; try { bucket = m_bucketManager.getHdfsBucket(path); byte[] data = bucket.findById("transaction-" + domain); - if (data == null) { + if (data != null) { String xml = new String(data, "utf-8"); TransactionReport report = new DefaultXmlParser().parse(xml); response.setModel(report); } } catch (Exception e) { response.setException(e); } finally { if (bucket != null) { m_bucketManager.closeBucket(bucket); } } return response; } @Override public boolean isEligable(ModelRequest request) { return request.getPeriod().isHistorical(); } }
true
true
public ModelResponse<TransactionReport> invoke(ModelRequest request) { String domain = request.getDomain(); long date = Long.parseLong(request.getProperty("date")); String path = m_pathBuilder.getReportPath(new Date(date)); ModelResponse<TransactionReport> response = new ModelResponse<TransactionReport>(); Bucket<byte[]> bucket = null; try { bucket = m_bucketManager.getHdfsBucket(path); byte[] data = bucket.findById("transaction-" + domain); if (data == null) { String xml = new String(data, "utf-8"); TransactionReport report = new DefaultXmlParser().parse(xml); response.setModel(report); } } catch (Exception e) { response.setException(e); } finally { if (bucket != null) { m_bucketManager.closeBucket(bucket); } } return response; }
public ModelResponse<TransactionReport> invoke(ModelRequest request) { String domain = request.getDomain(); long date = Long.parseLong(request.getProperty("date")); String path = m_pathBuilder.getReportPath(new Date(date)); ModelResponse<TransactionReport> response = new ModelResponse<TransactionReport>(); Bucket<byte[]> bucket = null; try { bucket = m_bucketManager.getHdfsBucket(path); byte[] data = bucket.findById("transaction-" + domain); if (data != null) { String xml = new String(data, "utf-8"); TransactionReport report = new DefaultXmlParser().parse(xml); response.setModel(report); } } catch (Exception e) { response.setException(e); } finally { if (bucket != null) { m_bucketManager.closeBucket(bucket); } } return response; }
diff --git a/frontend/src/main/java/cl/own/usi/gateway/netty/controller/RankingController.java b/frontend/src/main/java/cl/own/usi/gateway/netty/controller/RankingController.java index 0424850..eb676ba 100644 --- a/frontend/src/main/java/cl/own/usi/gateway/netty/controller/RankingController.java +++ b/frontend/src/main/java/cl/own/usi/gateway/netty/controller/RankingController.java @@ -1,86 +1,86 @@ package cl.own.usi.gateway.netty.controller; import static cl.own.usi.gateway.netty.ResponseHelper.writeResponse; import static cl.own.usi.gateway.netty.ResponseHelper.writeStringToReponse; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.http.HttpRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import cl.own.usi.gateway.client.BeforeAndAfterScores; import cl.own.usi.gateway.client.UserAndScore; import cl.own.usi.gateway.client.WorkerClient; import cl.own.usi.gateway.utils.ScoresHelper; import cl.own.usi.service.GameService; /** * Controller that return the rank and scores * * @author bperroud * @author nicolas */ @Component public class RankingController extends AbstractController { @Autowired private WorkerClient workerClient; @Autowired private GameService gameService; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); String userId = getCookie(request, COOKIE_AUTH_NAME); if (userId == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("User not authorized"); } else { if (!gameService.isRankingRequestAllowed()) { writeResponse(e, BAD_REQUEST); } else { UserAndScore userAndScore = workerClient .validateUserAndGetScore(userId); if (userAndScore.getUserId() == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("Invalid userId {}", userId); } else { StringBuilder sb = new StringBuilder("{"); sb.append(" \"my_score\" : ") .append(userAndScore.getScore()).append(", "); sb.append(" \"top_scores\" : { ") .append(gameService.getTop100AsString()) .append(" }, "); BeforeAndAfterScores beforeAndAfterScores = workerClient.get50BeforeAnd50After(userId); - sb.append(" \"before_me\" : { "); + sb.append(" \"before\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresBefore(), sb); sb.append(" }, "); - sb.append(" \"after_me\" : { "); + sb.append(" \"after\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresAfter(), sb); sb.append(" } "); sb.append(" } "); writeStringToReponse(sb.toString(), e, OK); } } } } }
false
true
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); String userId = getCookie(request, COOKIE_AUTH_NAME); if (userId == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("User not authorized"); } else { if (!gameService.isRankingRequestAllowed()) { writeResponse(e, BAD_REQUEST); } else { UserAndScore userAndScore = workerClient .validateUserAndGetScore(userId); if (userAndScore.getUserId() == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("Invalid userId {}", userId); } else { StringBuilder sb = new StringBuilder("{"); sb.append(" \"my_score\" : ") .append(userAndScore.getScore()).append(", "); sb.append(" \"top_scores\" : { ") .append(gameService.getTop100AsString()) .append(" }, "); BeforeAndAfterScores beforeAndAfterScores = workerClient.get50BeforeAnd50After(userId); sb.append(" \"before_me\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresBefore(), sb); sb.append(" }, "); sb.append(" \"after_me\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresAfter(), sb); sb.append(" } "); sb.append(" } "); writeStringToReponse(sb.toString(), e, OK); } } } }
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); String userId = getCookie(request, COOKIE_AUTH_NAME); if (userId == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("User not authorized"); } else { if (!gameService.isRankingRequestAllowed()) { writeResponse(e, BAD_REQUEST); } else { UserAndScore userAndScore = workerClient .validateUserAndGetScore(userId); if (userAndScore.getUserId() == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("Invalid userId {}", userId); } else { StringBuilder sb = new StringBuilder("{"); sb.append(" \"my_score\" : ") .append(userAndScore.getScore()).append(", "); sb.append(" \"top_scores\" : { ") .append(gameService.getTop100AsString()) .append(" }, "); BeforeAndAfterScores beforeAndAfterScores = workerClient.get50BeforeAnd50After(userId); sb.append(" \"before\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresBefore(), sb); sb.append(" }, "); sb.append(" \"after\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresAfter(), sb); sb.append(" } "); sb.append(" } "); writeStringToReponse(sb.toString(), e, OK); } } } }
diff --git a/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java b/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java index 815fa4ad..686a09b1 100644 --- a/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java +++ b/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java @@ -1,676 +1,677 @@ /* * Copyright 2006 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openqa.selenium.server; import org.mortbay.http.HttpContext; import org.mortbay.http.SocketListener; import org.mortbay.jetty.Server; import org.openqa.selenium.server.browserlaunchers.AsyncExecute; import org.openqa.selenium.server.htmlrunner.HTMLLauncher; import org.openqa.selenium.server.htmlrunner.HTMLResultsListener; import org.openqa.selenium.server.htmlrunner.SeleniumHTMLRunnerResultsHandler; import org.openqa.selenium.server.htmlrunner.SingleTestSuiteResourceHandler; import java.io.*; import java.net.URL; import java.net.URLConnection; /** * Provides a server that can launch/terminate browsers and can receive Selenese commands * over HTTP and send them on to the browser. * <p/> * <p>To run Selenium Server, run: * <p/> * <blockquote><code>java -jar selenium-server-1.0-SNAPSHOT.jar [-port 4444] [-interactive] [-timeout 1800]</code></blockquote> * <p/> * <p>Where <code>-port</code> specifies the port you wish to run the Server on (default is 4444). * <p/> * <p>Where <code>-timeout</code> specifies the number of seconds that you allow data to wait all in the * communications queues before an exception is thrown. * <p/> * <p>Using the <code>-interactive</code> flag will start the server in Interactive mode. * In this mode you can type Selenese commands on the command line (e.g. cmd=open&1=http://www.yahoo.com). * You may also interactively specify commands to run on a particular "browser session" (see below) like this: * <blockquote><code>cmd=open&1=http://www.yahoo.com&sessionId=1234</code></blockquote></p> * <p/> * <p>The server accepts three types of HTTP requests on its port: * <p/> * <ol> * <li><b>Client-Configured Proxy Requests</b>: By configuring your browser to use the * Selenium Server as an HTTP proxy, you can use the Selenium Server as a web proxy. This allows * the server to create a virtual "/selenium-server" directory on every website that you visit using * the proxy. * <li><b>Browser Selenese</b>: If the browser goes to "/selenium-server/SeleneseRunner.html?sessionId=1234" on any website * via the Client-Configured Proxy, it will ask the Selenium Server for work to do, like this: * <blockquote><code>http://www.yahoo.com/selenium-server/driver/?seleniumStart=true&sessionId=1234</code></blockquote> * The driver will then reply with a command to run in the body of the HTTP response, e.g. "|open|http://www.yahoo.com||". Once * the browser is done with this request, the browser will issue a new request for more work, this * time reporting the results of the previous command:<blockquote><code>http://www.yahoo.com/selenium-server/driver/?commandResult=OK&sessionId=1234</code></blockquote> * The action list is listed in selenium-api.js. Normal actions like "doClick" will return "OK" if * clicking was successful, or some other error string if there was an error. Assertions like * assertTextPresent or verifyTextPresent will return "PASSED" if the assertion was true, or * some other error string if the assertion was false. Getters like "getEval" will return the * result of the get command. "getAllLinks" will return a comma-delimited list of links.</li> * <li><b>Driver Commands</b>: Clients may send commands to the Selenium Server over HTTP. * Command requests should look like this:<blockquote><code>http://localhost:4444/selenium-server/driver/?commandRequest=|open|http://www.yahoo.com||&sessionId=1234</code></blockquote> * The Selenium Server will not respond to the HTTP request until the browser has finished performing the requested * command; when it does, it will reply with the result of the command (e.g. "OK" or "PASSED") in the * body of the HTTP response. (Note that <code>-interactive</code> mode also works by sending these * HTTP requests, so tests using <code>-interactive</code> mode will behave exactly like an external client driver.) * </ol> * <p>There are some special commands that only work in the Selenium Server. These commands are: * <ul><li><p><strong>getNewBrowserSession</strong>( <em>browserString</em>, <em>startURL</em> )</p> * <p>Creates a new "sessionId" number (based on the current time in milliseconds) and launches the browser specified in * <i>browserString</i>. We will then browse directly to <i>startURL</i> + "/selenium-server/SeleneseRunner.html?sessionId=###" * where "###" is the sessionId number. Only commands that are associated with the specified sessionId will be run by this browser.</p> * <p/> * <p><i>browserString</i> may be any one of the following: * <ul> * <li><code>*firefox [absolute path]</code> - Automatically launch a new Firefox process using a custom Firefox profile. * This profile will be automatically configured to use the Selenium Server as a proxy and to have all annoying prompts * ("save your password?" "forms are insecure" "make Firefox your default browser?" disabled. You may optionally specify * an absolute path to your firefox executable, or just say "*firefox". If no absolute path is specified, we'll look for * firefox.exe in a default location (normally c:\program files\mozilla firefox\firefox.exe), which you can override by * setting the Java system property <code>firefoxDefaultPath</code> to the correct path to Firefox.</li> * <li><code>*iexplore [absolute path]</code> - Automatically launch a new Internet Explorer process using custom Windows registry settings. * This process will be automatically configured to use the Selenium Server as a proxy and to have all annoying prompts * ("save your password?" "forms are insecure" "make Firefox your default browser?" disabled. You may optionally specify * an absolute path to your iexplore executable, or just say "*iexplore". If no absolute path is specified, we'll look for * iexplore.exe in a default location (normally c:\program files\internet explorer\iexplore.exe), which you can override by * setting the Java system property <code>iexploreDefaultPath</code> to the correct path to Internet Explorer.</li> * <li><code>/path/to/my/browser [other arguments]</code> - You may also simply specify the absolute path to your browser * executable, or use a relative path to your executable (which we'll try to find on your path). <b>Warning:</b> If you * specify your own custom browser, it's up to you to configure it correctly. At a minimum, you'll need to configure your * browser to use the Selenium Server as a proxy, and disable all browser-specific prompting. * </ul> * </li> * <li><p><strong>testComplete</strong>( )</p> * <p>Kills the currently running browser and erases the old browser session. If the current browser session was not * launched using <code>getNewBrowserSession</code>, or if that session number doesn't exist in the server, this * command will return an error.</p> * </li> * <li><p><strong>shutDown</strong>( )</p> * <p>Causes the server to shut itself down, killing itself and all running browsers along with it.</p> * </li> * </ul> * <p>Example:<blockquote><code>cmd=getNewBrowserSession&1=*firefox&2=http://www.google.com * <br/>Got result: 1140738083345 * <br/>cmd=open&1=http://www.google.com&sessionId=1140738083345 * <br/>Got result: OK * <br/>cmd=type&1=q&2=hello world&sessionId=1140738083345 * <br/>Got result: OK * <br/>cmd=testComplete&sessionId=1140738083345 * <br/>Got result: OK * </code></blockquote></p> * <p/> * <h4>The "null" session</h4> * <p/> * <p>If you open a browser manually and do not specify a session ID, it will look for * commands using the "null" session. You may then similarly send commands to this * browser by not specifying a sessionId when issuing commands.</p> * * @author plightbo */ public class SeleniumServer { private Server server; private SeleniumDriverResourceHandler driver; private SeleniumHTMLRunnerResultsHandler postResultsHandler; private StaticContentHandler staticContentHandler; private int port; private boolean multiWindow = false; private static String debugURL = ""; // add special tracing for debug when this URL is requested private static boolean debugMode = false; private static boolean proxyInjectionMode = false; public static final int DEFAULT_PORT = 4444; // The following port is the one which drivers and browsers should use when they contact the selenium server. // Under normal circumstances, this port will be the same as the port which the selenium server listens on. // But if a developer wants to monitor traffic into and out of the selenium server, he can set this port from // the command line to be a different value and then use a tool like tcptrace to link this port with the // server listening port, thereby opening a window into the raw HTTP traffic. // // For example, if the selenium server is invoked with -portDriversShouldContact 4445, then traffic going // into the selenium server will be routed to port 4445, although the selenium server will still be listening // to the default port 4444. At this point, you would open tcptrace to bridge the gap and be able to watch // all the data coming in and out: private static int portDriversShouldContact = DEFAULT_PORT; private static PrintStream logOut = null; private static String defaultBrowserString = null; public static final int DEFAULT_TIMEOUT = (30 * 60); public static int timeout = DEFAULT_TIMEOUT; private static Boolean reusingBrowserSessions = null; /** * Starts up the server on the specified port (or default if no port was specified) * and then starts interactive mode if specified. * * @param args - either "-port" followed by a number, or "-interactive" * @throws Exception - you know, just in case. */ public static void main(String[] args) throws Exception { int port = DEFAULT_PORT; boolean interactive = false; boolean htmlSuite = false; boolean multiWindow = false; String browserString = null; String startURL = null; String suiteFilePath = null; String resultFilePath = null; File userExtensions = null; boolean proxyInjectionModeArg = false; int portDriversShouldContactArg = 0; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-help".equals(arg)) { usage(null); System.exit(1); } else if ("-defaultBrowserString".equals(arg)) { for (i++; i < args.length; i++) { if (SeleniumServer.defaultBrowserString == null) SeleniumServer.defaultBrowserString = ""; else SeleniumServer.defaultBrowserString += " "; SeleniumServer.defaultBrowserString += args[i]; } SeleniumServer.log("\"" + defaultBrowserString + "\" will be used as the browser " + "mode for all sessions, no matter what is passed to getNewBrowserSession."); } else if ("-log".equals(arg)) { logOut = new PrintStream(getArg(args, ++i)); } else if ("-port".equals(arg)) { port = Integer.parseInt(getArg(args, ++i)); } else if ("-multiWindow".equals(arg)) { multiWindow = true; } else if ("-proxyInjectionMode".equals(arg)) { proxyInjectionModeArg = true; } else if ("-portDriversShouldContact".equals(arg)) { // to facilitate tcptrace interception of interaction between // injected js and the selenium server portDriversShouldContactArg = Integer.parseInt(getArg(args, ++i)); } else if ("-noBrowserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.FALSE; } else if ("-browserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.TRUE; } else if ("-debug".equals(arg)) { SeleniumServer.setDebugMode(true); } else if ("-debugURL".equals(arg)) { debugURL = getArg(args, ++i); } else if ("-timeout".equals(arg)) { timeout = Integer.parseInt(getArg(args, ++i)); } else if ("-userJsInjection".equals(arg)) { if (!InjectionHelper.addUserJsInjectionFile(getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userContentTransformation".equals(arg)) { if (!InjectionHelper.addUserContentTransformation(getArg(args, ++i), getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userExtensions".equals(arg)) { userExtensions = new File(getArg(args, ++i)); if (!userExtensions.exists()) { System.err.println("User Extensions file doesn't exist: " + userExtensions.getAbsolutePath()); System.exit(1); } if (!"user-extensions.js".equals(userExtensions.getName())) { System.err.println("User extensions file MUST be called \"user-extensions.js\": " + userExtensions.getAbsolutePath()); System.exit(1); } } else if ("-htmlSuite".equals(arg)) { try { browserString = args[++i]; startURL = args[++i]; suiteFilePath = args[++i]; resultFilePath = args[++i]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Not enough command line arguments for -htmlSuite"); System.err.println("-htmlSuite requires you to specify:"); System.err.println("* browserString (e.g. \"*firefox\")"); System.err.println("* startURL (e.g. \"http://www.google.com\")"); System.err.println("* suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\")"); System.err.println("* resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\")"); System.exit(1); } htmlSuite = true; } else if ("-interactive".equals(arg)) { timeout = Integer.MAX_VALUE; interactive = true; } else if (arg.startsWith("-D")) { setSystemProperty(arg); } else { usage("unrecognized argument " + arg); System.exit(1); } } if (portDriversShouldContactArg == 0) { portDriversShouldContactArg = port; } System.setProperty("org.mortbay.http.HttpRequest.maxFormContentSize", "0"); // default max is 200k; zero is infinite final SeleniumServer seleniumProxy = new SeleniumServer(port); + seleniumProxy.multiWindow = multiWindow; checkArgsSanity(port, interactive, htmlSuite, proxyInjectionModeArg, portDriversShouldContactArg, seleniumProxy); Thread jetty = new Thread(new Runnable() { public void run() { try { seleniumProxy.start(); } catch (Exception e) { System.err.println("jetty run exception seen:"); e.printStackTrace(); } } }); if (interactive) { jetty.setDaemon(true); } jetty.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { System.out.println("Shutting down..."); seleniumProxy.stop(); } catch (InterruptedException e) { System.err.println("run exception seen:"); e.printStackTrace(); } } })); if (userExtensions != null) { seleniumProxy.addNewStaticContent(userExtensions.getParentFile()); } if (htmlSuite) { String result = null; try { File suiteFile = new File(suiteFilePath); seleniumProxy.addNewStaticContent(suiteFile.getParentFile()); String suiteURL = startURL + "/selenium-server/" + suiteFile.getName(); HTMLLauncher launcher = new HTMLLauncher(seleniumProxy); result = launcher.runHTMLSuite(browserString, startURL, suiteURL, new File(resultFilePath), timeout, multiWindow); } catch (Exception e) { System.err.println("HTML suite exception seen:"); e.printStackTrace(); System.exit(1); } if (!"PASSED".equals(result)) { System.err.println("Tests failed"); System.exit(1); } else { System.exit(0); } } if (interactive) { AsyncExecute.sleepTight(500); System.out.println("Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; final String[] lastSessionId = new String[]{""}; while ((userInput = stdIn.readLine()) != null) { if ("quit".equals(userInput)) { System.out.println("Stopping..."); seleniumProxy.stop(); System.exit(0); } if ("".equals(userInput)) continue; if (!userInput.startsWith("cmd=") && !userInput.startsWith("commandResult=")) { System.err.println("ERROR - Invalid command: \"" + userInput + "\""); continue; } final boolean newBrowserSession = userInput.indexOf("getNewBrowserSession") != -1; if (userInput.indexOf("sessionId") == -1 && !newBrowserSession) { userInput = userInput + "&sessionId=" + lastSessionId[0]; } final URL url = new URL("http://localhost:" + port + "/selenium-server/driver?" + userInput); Thread t = new Thread(new Runnable() { public void run() { try { SeleniumServer.log("---> Requesting " + url.toString()); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = -1; while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); } is.close(); String output = out.toString(); if (newBrowserSession) { if (output.startsWith("OK,")) { lastSessionId[0] = output.substring(3); } } } catch (IOException e) { System.err.println(e.getMessage()); if (SeleniumServer.isDebugMode()) { e.printStackTrace(); } } } }); t.start(); } } } private static void checkArgsSanity(int port, boolean interactive, boolean htmlSuite, boolean proxyInjectionModeArg, int portDriversShouldContactArg, SeleniumServer seleniumProxy) throws Exception { if (interactive && htmlSuite) { System.err.println("You can't use -interactive and -htmlSuite on the same line!"); System.exit(1); } SingleEntryAsyncQueue.setDefaultTimeout(timeout); seleniumProxy.setProxyInjectionMode(proxyInjectionModeArg); SeleniumServer.setPortDriversShouldContact(portDriversShouldContactArg); if (!isProxyInjectionMode() && (InjectionHelper.userContentTransformationsExist() || InjectionHelper.userJsInjectionsExist())) { usage("-userJsInjection and -userContentTransformation are only " + "valid in combination with -proxyInjectionMode"); System.exit(1); } if (!isProxyInjectionMode() && reusingBrowserSessions()) { usage("-reusingBrowserSessions only valid in combination with -proxyInjectionMode" + " (because of the need for multiple domain support, which only -proxyInjectionMode" + " provides)."); System.exit(1); } if (reusingBrowserSessions()) { SeleniumServer.log("Will recycle browser sessions when possible."); } } private static String getArg(String[] args, int i) { if (i >= args.length) { usage("expected at least one more argument"); System.exit(-1); } return args[i]; } private static void proxyInjectionSpeech() { SeleniumServer.log("The selenium server will execute in proxyInjection mode."); } private static void setSystemProperty(String arg) { if (arg.indexOf('=') == -1) { usage("poorly formatted Java property setting (I expect to see '=') " + arg); System.exit(1); } String property = arg.replaceFirst("-D", "").replaceFirst("=.*", ""); String value = arg.replaceFirst("[^=]*=", ""); System.err.println("Setting system property " + property + " to " + value); System.setProperty(property, value); } private static void usage(String msg) { if (msg != null) { System.err.println(msg + ":"); } System.err.println("Usage: java -jar selenium-server.jar -debug [-port nnnn] [-timeout nnnn] [-interactive]" + " [-defaultBrowserString browserString] [-log logfile] [-proxyInjectionMode [-browserSessionReuse|-noBrowserSessionReuse][-userContentTransformation your-before-regexp-string your-after-string] [-userJsInjection your-js-filename]] [-htmlSuite browserString (e.g. \"*firefox\") startURL (e.g. \"http://www.google.com\") " + "suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\") resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\"]\n" + "where:\n" + "the argument for timeout is an integer number of seconds before we should give up\n" + "the argument for port is the port number the selenium server should use (default 4444)" + "\n\t-interactive puts you into interactive mode. See the tutorial for more details" + "\n\t-defaultBrowserString (e.g., *iexplore) sets the browser mode for all sessions, no matter what is passed to getNewBrowserSession" + "\n\t-browserSessionReuse stops re-initialization and spawning of the browser between tests" + "\n\t-debug puts you into debug mode, with more trace information and diagnostics" + "\n\t-proxyInjectionMode puts you into proxy injection mode, a mode where the selenium server acts as a proxy server " + "\n\t\tfor all content going to the test application. Under this mode, multiple domains can be visited, and the " + "\n\t\tfollowing additional flags are supported:" + "\n\t\t\tThe -userJsInjection flag allows you to point at a JavaScript file which will then be injected into all pages. " + "\n\t\t\tThe -userContentTransformation flag takes two arguments: the first is a regular expression which is matched " + "\n\t\t\t\tagainst all test HTML content; the second is a string which will replace matches. These flags can be used any " + "\n\t\t\t\tnumber of times. A simple example of how this could be useful: if you add" + "\n" + "\n\t\t\t\t -userContentTransformation https http" + "\n" + "\n\t\t\t\tthen all \"https\" strings in the HTML of the test application will be changed to be \"http\".\n" + "\n\t-debug puts you into debug mode, with more trace information and diagnostics" + "\n\t-proxyInjectionMode puts you into proxy injection mode, a mode where the selenium server acts as a proxy server " + "\n\t\tfor all content going to the test application. Under this mode, multiple domains can be visited, and the " + "\n\t\tfollowing additional flags are supported:" + "\n\t\t\tThe -userJsInjection flag allows you to point at a JavaScript file which will then be injected into all pages. " + "\n\t\t\tThe -userContentTransformation flag takes two arguments: the first is a regular expression which is matched " + "\n\t\t\t\tagainst all AUT content; the second is a string which will replace matches. These flags can be used any " + "\n\t\t\t\tnumber of times. A simple example of how this could be useful: if you add" + "\n\n" + " -userContentTransformation https http\r\n" + "\n\n" + "\n\t\t\t\tthen all \"https\" strings in the HTML of the test application will be changed to be \"http\".\n"); } /** * Prepares a Jetty server with its HTTP handlers. * * @param port the port to start on * @param slowResources should the webserver return static resources more slowly? (Note that this will not slow down ordinary RC test runs; this setting is used to debug Selenese HTML tests.) * @param multiWindow run the tests in the "multi-Window" layout, without using the embedded iframe * @throws Exception you know, just in case */ public SeleniumServer(int port, boolean slowResources, boolean multiWindow) throws Exception { this.port = port; this.multiWindow = multiWindow; server = new Server(); SocketListener socketListener = new SocketListener(); socketListener.setMaxIdleTimeMs(60000); socketListener.setPort(port); server.addListener(socketListener); configServer(); assembleHandlers(slowResources); } public SeleniumServer(int port, boolean slowResources) throws Exception { this(port, slowResources, false); } private void assembleHandlers(boolean slowResources) { HttpContext root = new HttpContext(); root.setContextPath("/"); ProxyHandler rootProxy = new ProxyHandler(); root.addHandler(rootProxy); server.addContext(root); HttpContext context = new HttpContext(); context.setContextPath("/selenium-server"); staticContentHandler = new StaticContentHandler(slowResources); String overrideJavascriptDir = System.getProperty("selenium.javascript.dir"); if (overrideJavascriptDir != null) { staticContentHandler.addStaticContent(new FsResourceLocator(new File(overrideJavascriptDir))); } staticContentHandler.addStaticContent(new ClasspathResourceLocator()); context.addHandler(staticContentHandler); context.addHandler(new SingleTestSuiteResourceHandler()); postResultsHandler = new SeleniumHTMLRunnerResultsHandler(); context.addHandler(postResultsHandler); // Associate the SeleniumDriverResourceHandler with the /selenium-server/driver context HttpContext driverContext = new HttpContext(); driverContext.setContextPath("/selenium-server/driver"); driver = new SeleniumDriverResourceHandler(this); context.addHandler(driver); server.addContext(context); server.addContext(driverContext); } private void configServer() { if (getDefaultBrowser() == null) { SeleniumServer.setDefaultBrowser(System.getProperty("selenium.defaultBrowserString")); } if (!isProxyInjectionMode() && System.getProperty("selenium.proxyInjectionMode") != null) { setProxyInjectionMode("true".equals(System.getProperty("selenium.proxyInjectionMode"))); } if (!isDebugMode() && System.getProperty("selenium.debugMode") != null) { setDebugMode("true".equals(System.getProperty("selenium.debugMode"))); } } public SeleniumServer(int port) throws Exception { this(port, slowResourceProperty()); } public SeleniumServer() throws Exception { this(SeleniumServer.DEFAULT_PORT, slowResourceProperty()); } private static boolean slowResourceProperty() { return ("true".equals(System.getProperty("slowResources"))); } public void addNewStaticContent(File directory) { staticContentHandler.addStaticContent(new FsResourceLocator(directory)); } public void handleHTMLRunnerResults(HTMLResultsListener listener) { postResultsHandler.addListener(listener); } /** * Starts the Jetty server */ public void start() throws Exception { server.start(); } /** * Stops the Jetty server */ public void stop() throws InterruptedException { server.stop(); driver.stopAllBrowsers(); } public int getPort() { return port; } public boolean isMultiWindow() { return multiWindow; } /** * Exposes the internal Jetty server used by Selenium. * This lets users add their own webapp to the Selenium Server jetty instance. * It is also a minor violation of encapsulation principles (what if we stop * using Jetty?) but life is too short to worry about such things. * * @return the internal Jetty server, pre-configured with the /selenium-server context as well as * the proxy server on / */ public Server getServer() { return server; } public static boolean isDebugMode() { return SeleniumServer.debugMode; } static public void setDebugMode(boolean debugMode) { SeleniumServer.debugMode = debugMode; if (debugMode) { SeleniumServer.log("Selenium server running in debug mode."); System.err.println("Standard error test."); } } public static boolean isProxyInjectionMode() { return proxyInjectionMode; } public static int getPortDriversShouldContact() { return portDriversShouldContact; } private static void setPortDriversShouldContact(int port) { SeleniumServer.portDriversShouldContact = port; } public void setProxyInjectionMode(boolean proxyInjectionMode) { if (proxyInjectionMode) { proxyInjectionSpeech(); } SeleniumServer.proxyInjectionMode = proxyInjectionMode; } public static String getDefaultBrowser() { return defaultBrowserString; } public static int getTimeoutInSeconds() { return timeout; } public static void setDefaultBrowser(String defaultBrowserString) { SeleniumServer.defaultBrowserString = defaultBrowserString; } public static boolean reusingBrowserSessions() { if (reusingBrowserSessions == null) { // if (isProxyInjectionMode()) { turn off this default until we are stable. Too many variables spoils the soup. // reusingBrowserSessions = Boolean.TRUE; // default in pi mode // } // else { reusingBrowserSessions = Boolean.FALSE; // default in non-pi mode // } } return reusingBrowserSessions; } public static String getDebugURL() { return debugURL; } public static void log(String logMessages) { PrintStream out = (logOut != null) ? logOut : System.out; if (logMessages.endsWith("\n")) { out.print(logMessages); } else { out.println(logMessages); } } }
true
true
public static void main(String[] args) throws Exception { int port = DEFAULT_PORT; boolean interactive = false; boolean htmlSuite = false; boolean multiWindow = false; String browserString = null; String startURL = null; String suiteFilePath = null; String resultFilePath = null; File userExtensions = null; boolean proxyInjectionModeArg = false; int portDriversShouldContactArg = 0; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-help".equals(arg)) { usage(null); System.exit(1); } else if ("-defaultBrowserString".equals(arg)) { for (i++; i < args.length; i++) { if (SeleniumServer.defaultBrowserString == null) SeleniumServer.defaultBrowserString = ""; else SeleniumServer.defaultBrowserString += " "; SeleniumServer.defaultBrowserString += args[i]; } SeleniumServer.log("\"" + defaultBrowserString + "\" will be used as the browser " + "mode for all sessions, no matter what is passed to getNewBrowserSession."); } else if ("-log".equals(arg)) { logOut = new PrintStream(getArg(args, ++i)); } else if ("-port".equals(arg)) { port = Integer.parseInt(getArg(args, ++i)); } else if ("-multiWindow".equals(arg)) { multiWindow = true; } else if ("-proxyInjectionMode".equals(arg)) { proxyInjectionModeArg = true; } else if ("-portDriversShouldContact".equals(arg)) { // to facilitate tcptrace interception of interaction between // injected js and the selenium server portDriversShouldContactArg = Integer.parseInt(getArg(args, ++i)); } else if ("-noBrowserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.FALSE; } else if ("-browserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.TRUE; } else if ("-debug".equals(arg)) { SeleniumServer.setDebugMode(true); } else if ("-debugURL".equals(arg)) { debugURL = getArg(args, ++i); } else if ("-timeout".equals(arg)) { timeout = Integer.parseInt(getArg(args, ++i)); } else if ("-userJsInjection".equals(arg)) { if (!InjectionHelper.addUserJsInjectionFile(getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userContentTransformation".equals(arg)) { if (!InjectionHelper.addUserContentTransformation(getArg(args, ++i), getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userExtensions".equals(arg)) { userExtensions = new File(getArg(args, ++i)); if (!userExtensions.exists()) { System.err.println("User Extensions file doesn't exist: " + userExtensions.getAbsolutePath()); System.exit(1); } if (!"user-extensions.js".equals(userExtensions.getName())) { System.err.println("User extensions file MUST be called \"user-extensions.js\": " + userExtensions.getAbsolutePath()); System.exit(1); } } else if ("-htmlSuite".equals(arg)) { try { browserString = args[++i]; startURL = args[++i]; suiteFilePath = args[++i]; resultFilePath = args[++i]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Not enough command line arguments for -htmlSuite"); System.err.println("-htmlSuite requires you to specify:"); System.err.println("* browserString (e.g. \"*firefox\")"); System.err.println("* startURL (e.g. \"http://www.google.com\")"); System.err.println("* suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\")"); System.err.println("* resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\")"); System.exit(1); } htmlSuite = true; } else if ("-interactive".equals(arg)) { timeout = Integer.MAX_VALUE; interactive = true; } else if (arg.startsWith("-D")) { setSystemProperty(arg); } else { usage("unrecognized argument " + arg); System.exit(1); } } if (portDriversShouldContactArg == 0) { portDriversShouldContactArg = port; } System.setProperty("org.mortbay.http.HttpRequest.maxFormContentSize", "0"); // default max is 200k; zero is infinite final SeleniumServer seleniumProxy = new SeleniumServer(port); checkArgsSanity(port, interactive, htmlSuite, proxyInjectionModeArg, portDriversShouldContactArg, seleniumProxy); Thread jetty = new Thread(new Runnable() { public void run() { try { seleniumProxy.start(); } catch (Exception e) { System.err.println("jetty run exception seen:"); e.printStackTrace(); } } }); if (interactive) { jetty.setDaemon(true); } jetty.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { System.out.println("Shutting down..."); seleniumProxy.stop(); } catch (InterruptedException e) { System.err.println("run exception seen:"); e.printStackTrace(); } } })); if (userExtensions != null) { seleniumProxy.addNewStaticContent(userExtensions.getParentFile()); } if (htmlSuite) { String result = null; try { File suiteFile = new File(suiteFilePath); seleniumProxy.addNewStaticContent(suiteFile.getParentFile()); String suiteURL = startURL + "/selenium-server/" + suiteFile.getName(); HTMLLauncher launcher = new HTMLLauncher(seleniumProxy); result = launcher.runHTMLSuite(browserString, startURL, suiteURL, new File(resultFilePath), timeout, multiWindow); } catch (Exception e) { System.err.println("HTML suite exception seen:"); e.printStackTrace(); System.exit(1); } if (!"PASSED".equals(result)) { System.err.println("Tests failed"); System.exit(1); } else { System.exit(0); } } if (interactive) { AsyncExecute.sleepTight(500); System.out.println("Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; final String[] lastSessionId = new String[]{""}; while ((userInput = stdIn.readLine()) != null) { if ("quit".equals(userInput)) { System.out.println("Stopping..."); seleniumProxy.stop(); System.exit(0); } if ("".equals(userInput)) continue; if (!userInput.startsWith("cmd=") && !userInput.startsWith("commandResult=")) { System.err.println("ERROR - Invalid command: \"" + userInput + "\""); continue; } final boolean newBrowserSession = userInput.indexOf("getNewBrowserSession") != -1; if (userInput.indexOf("sessionId") == -1 && !newBrowserSession) { userInput = userInput + "&sessionId=" + lastSessionId[0]; } final URL url = new URL("http://localhost:" + port + "/selenium-server/driver?" + userInput); Thread t = new Thread(new Runnable() { public void run() { try { SeleniumServer.log("---> Requesting " + url.toString()); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = -1; while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); } is.close(); String output = out.toString(); if (newBrowserSession) { if (output.startsWith("OK,")) { lastSessionId[0] = output.substring(3); } } } catch (IOException e) { System.err.println(e.getMessage()); if (SeleniumServer.isDebugMode()) { e.printStackTrace(); } } } }); t.start(); } } }
public static void main(String[] args) throws Exception { int port = DEFAULT_PORT; boolean interactive = false; boolean htmlSuite = false; boolean multiWindow = false; String browserString = null; String startURL = null; String suiteFilePath = null; String resultFilePath = null; File userExtensions = null; boolean proxyInjectionModeArg = false; int portDriversShouldContactArg = 0; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-help".equals(arg)) { usage(null); System.exit(1); } else if ("-defaultBrowserString".equals(arg)) { for (i++; i < args.length; i++) { if (SeleniumServer.defaultBrowserString == null) SeleniumServer.defaultBrowserString = ""; else SeleniumServer.defaultBrowserString += " "; SeleniumServer.defaultBrowserString += args[i]; } SeleniumServer.log("\"" + defaultBrowserString + "\" will be used as the browser " + "mode for all sessions, no matter what is passed to getNewBrowserSession."); } else if ("-log".equals(arg)) { logOut = new PrintStream(getArg(args, ++i)); } else if ("-port".equals(arg)) { port = Integer.parseInt(getArg(args, ++i)); } else if ("-multiWindow".equals(arg)) { multiWindow = true; } else if ("-proxyInjectionMode".equals(arg)) { proxyInjectionModeArg = true; } else if ("-portDriversShouldContact".equals(arg)) { // to facilitate tcptrace interception of interaction between // injected js and the selenium server portDriversShouldContactArg = Integer.parseInt(getArg(args, ++i)); } else if ("-noBrowserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.FALSE; } else if ("-browserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.TRUE; } else if ("-debug".equals(arg)) { SeleniumServer.setDebugMode(true); } else if ("-debugURL".equals(arg)) { debugURL = getArg(args, ++i); } else if ("-timeout".equals(arg)) { timeout = Integer.parseInt(getArg(args, ++i)); } else if ("-userJsInjection".equals(arg)) { if (!InjectionHelper.addUserJsInjectionFile(getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userContentTransformation".equals(arg)) { if (!InjectionHelper.addUserContentTransformation(getArg(args, ++i), getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userExtensions".equals(arg)) { userExtensions = new File(getArg(args, ++i)); if (!userExtensions.exists()) { System.err.println("User Extensions file doesn't exist: " + userExtensions.getAbsolutePath()); System.exit(1); } if (!"user-extensions.js".equals(userExtensions.getName())) { System.err.println("User extensions file MUST be called \"user-extensions.js\": " + userExtensions.getAbsolutePath()); System.exit(1); } } else if ("-htmlSuite".equals(arg)) { try { browserString = args[++i]; startURL = args[++i]; suiteFilePath = args[++i]; resultFilePath = args[++i]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Not enough command line arguments for -htmlSuite"); System.err.println("-htmlSuite requires you to specify:"); System.err.println("* browserString (e.g. \"*firefox\")"); System.err.println("* startURL (e.g. \"http://www.google.com\")"); System.err.println("* suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\")"); System.err.println("* resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\")"); System.exit(1); } htmlSuite = true; } else if ("-interactive".equals(arg)) { timeout = Integer.MAX_VALUE; interactive = true; } else if (arg.startsWith("-D")) { setSystemProperty(arg); } else { usage("unrecognized argument " + arg); System.exit(1); } } if (portDriversShouldContactArg == 0) { portDriversShouldContactArg = port; } System.setProperty("org.mortbay.http.HttpRequest.maxFormContentSize", "0"); // default max is 200k; zero is infinite final SeleniumServer seleniumProxy = new SeleniumServer(port); seleniumProxy.multiWindow = multiWindow; checkArgsSanity(port, interactive, htmlSuite, proxyInjectionModeArg, portDriversShouldContactArg, seleniumProxy); Thread jetty = new Thread(new Runnable() { public void run() { try { seleniumProxy.start(); } catch (Exception e) { System.err.println("jetty run exception seen:"); e.printStackTrace(); } } }); if (interactive) { jetty.setDaemon(true); } jetty.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { System.out.println("Shutting down..."); seleniumProxy.stop(); } catch (InterruptedException e) { System.err.println("run exception seen:"); e.printStackTrace(); } } })); if (userExtensions != null) { seleniumProxy.addNewStaticContent(userExtensions.getParentFile()); } if (htmlSuite) { String result = null; try { File suiteFile = new File(suiteFilePath); seleniumProxy.addNewStaticContent(suiteFile.getParentFile()); String suiteURL = startURL + "/selenium-server/" + suiteFile.getName(); HTMLLauncher launcher = new HTMLLauncher(seleniumProxy); result = launcher.runHTMLSuite(browserString, startURL, suiteURL, new File(resultFilePath), timeout, multiWindow); } catch (Exception e) { System.err.println("HTML suite exception seen:"); e.printStackTrace(); System.exit(1); } if (!"PASSED".equals(result)) { System.err.println("Tests failed"); System.exit(1); } else { System.exit(0); } } if (interactive) { AsyncExecute.sleepTight(500); System.out.println("Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; final String[] lastSessionId = new String[]{""}; while ((userInput = stdIn.readLine()) != null) { if ("quit".equals(userInput)) { System.out.println("Stopping..."); seleniumProxy.stop(); System.exit(0); } if ("".equals(userInput)) continue; if (!userInput.startsWith("cmd=") && !userInput.startsWith("commandResult=")) { System.err.println("ERROR - Invalid command: \"" + userInput + "\""); continue; } final boolean newBrowserSession = userInput.indexOf("getNewBrowserSession") != -1; if (userInput.indexOf("sessionId") == -1 && !newBrowserSession) { userInput = userInput + "&sessionId=" + lastSessionId[0]; } final URL url = new URL("http://localhost:" + port + "/selenium-server/driver?" + userInput); Thread t = new Thread(new Runnable() { public void run() { try { SeleniumServer.log("---> Requesting " + url.toString()); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = -1; while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); } is.close(); String output = out.toString(); if (newBrowserSession) { if (output.startsWith("OK,")) { lastSessionId[0] = output.substring(3); } } } catch (IOException e) { System.err.println(e.getMessage()); if (SeleniumServer.isDebugMode()) { e.printStackTrace(); } } } }); t.start(); } } }
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryValueFactory.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryValueFactory.java index 84df8f7469..f54ef09c86 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryValueFactory.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryValueFactory.java @@ -1,102 +1,102 @@ /* * 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.jackrabbit.oak.plugins.memory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import javax.jcr.PropertyType; import org.apache.jackrabbit.oak.api.CoreValue; import org.apache.jackrabbit.oak.api.CoreValueFactory; public class MemoryValueFactory implements CoreValueFactory { public static final CoreValueFactory INSTANCE = new MemoryValueFactory(); @Override public CoreValue createValue(String value) { return new StringValue(value); } @Override public CoreValue createValue(double value) { return new DoubleValue(value); } @Override public CoreValue createValue(long value) { return new LongValue(value); } @Override public CoreValue createValue(boolean value) { if (value) { return BooleanValue.TRUE; } else { return BooleanValue.FALSE; } } @Override public CoreValue createValue(BigDecimal value) { return new DecimalValue(value); } @Override public CoreValue createValue(InputStream value) throws IOException { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] b = new byte[4096]; int n = value.read(b); while (n != -1) { buffer.write(b, 0, n); n = value.read(b); } return new BinaryValue(buffer.toByteArray()); } finally { value.close(); } } @Override public CoreValue createValue(String value, final int type) { if (type == PropertyType.BINARY) { try { return new BinaryValue(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is not supported", e); } - } else if (type == PropertyType.DECIMAL) { - return createValue(createValue(value).getDecimal()); + } else if (type == PropertyType.BOOLEAN) { + return createValue(createValue(value).getBoolean()); } else if (type == PropertyType.DECIMAL) { return createValue(createValue(value).getDecimal()); } else if (type == PropertyType.DOUBLE) { return createValue(createValue(value).getDouble()); } else if (type == PropertyType.LONG) { return createValue(createValue(value).getLong()); } else if (type == PropertyType.STRING) { return createValue(value); } else { return new GenericValue(type, value); } } }
true
true
public CoreValue createValue(String value, final int type) { if (type == PropertyType.BINARY) { try { return new BinaryValue(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is not supported", e); } } else if (type == PropertyType.DECIMAL) { return createValue(createValue(value).getDecimal()); } else if (type == PropertyType.DECIMAL) { return createValue(createValue(value).getDecimal()); } else if (type == PropertyType.DOUBLE) { return createValue(createValue(value).getDouble()); } else if (type == PropertyType.LONG) { return createValue(createValue(value).getLong()); } else if (type == PropertyType.STRING) { return createValue(value); } else { return new GenericValue(type, value); } }
public CoreValue createValue(String value, final int type) { if (type == PropertyType.BINARY) { try { return new BinaryValue(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is not supported", e); } } else if (type == PropertyType.BOOLEAN) { return createValue(createValue(value).getBoolean()); } else if (type == PropertyType.DECIMAL) { return createValue(createValue(value).getDecimal()); } else if (type == PropertyType.DOUBLE) { return createValue(createValue(value).getDouble()); } else if (type == PropertyType.LONG) { return createValue(createValue(value).getLong()); } else if (type == PropertyType.STRING) { return createValue(value); } else { return new GenericValue(type, value); } }
diff --git a/src/plugins/WebOfTrust/Identity.java b/src/plugins/WebOfTrust/Identity.java index a9366ebe..0a5b2bea 100644 --- a/src/plugins/WebOfTrust/Identity.java +++ b/src/plugins/WebOfTrust/Identity.java @@ -1,1007 +1,1010 @@ /* This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. */ package plugins.WebOfTrust; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import plugins.WebOfTrust.exceptions.InvalidParameterException; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.support.Base64; import freenet.support.CurrentTimeUTC; import freenet.support.IllegalBase64Exception; import freenet.support.Logger; import freenet.support.StringValidityChecker; import freenet.support.codeshortification.IfNull; /** * An identity as handled by the WoT (a USK). * * It has a nickname and as many custom properties as needed (set by the user). * * @author xor ([email protected]) * @author Julien Cornuwel ([email protected]) */ public class Identity extends Persistent implements Cloneable { public static transient final int MAX_NICKNAME_LENGTH = 30; public static transient final int MAX_CONTEXT_NAME_LENGTH = 32; public static transient final int MAX_CONTEXT_AMOUNT = 32; public static transient final int MAX_PROPERTY_NAME_LENGTH = 256; public static transient final int MAX_PROPERTY_VALUE_LENGTH = 10 * 1024; public static transient final int MAX_PROPERTY_AMOUNT = 64; /** A unique identifier used to query this Identity from the database. In fact, it is simply a String representing its routing key. */ @IndexedField protected final String mID; /** The USK requestURI used to fetch this identity from Freenet. It's edition number is the one of the data which we have currently stored * in the database (the values of this identity, trust values, etc.) if mCurrentEditionFetchState is Fetched or ParsingFailed, otherwise it * is the next edition number which should be downloaded. */ protected FreenetURI mRequestURI; public static enum FetchState { NotFetched, ParsingFailed, Fetched }; protected FetchState mCurrentEditionFetchState; /** When obtaining identities through other people's trust lists instead of identity introduction, we store the edition number they have * specified and pass it as a hint to the USKManager. */ protected long mLatestEditionHint; /** Date of the last time we successfully fetched the XML of this identity */ @IndexedField protected Date mLastFetchedDate; /** Date of this identity's last modification, for example when it has received new contexts, etc.*/ protected Date mLastChangedDate; /** The nickname of this Identity */ @IndexedField protected String mNickname; /** Whether this Identity publishes its trust list or not */ protected boolean mDoesPublishTrustList; /** A list of contexts (eg. client apps) this Identity is used for */ protected ArrayList<String> mContexts; /** A list of this Identity's custom properties */ protected HashMap<String, String> mProperties; /** * @see Identity#activateProperties() */ private transient boolean mPropertiesActivated; /* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */ private static transient volatile boolean logDEBUG = false; private static transient volatile boolean logMINOR = false; static { Logger.registerClass(Identity.class); } /** * A class for generating and validating Identity IDs. * Its purpose is NOT to be stored in the database: That would make the queries significantly slower. * We store the IDs as Strings instead for fast queries. * * Its purpose is to allow validation of IdentityIDs which we obtain from the database or from the network. * * TODO: This was added after we already had manual ID-generation / checking in the code everywhere. Use this class instead. */ public static final class IdentityID { /** * Length in characters of an ID, which is a SSK public key hash. */ public static transient final int LENGTH = 43; private final String mID; /** * Constructs an identityID from the given String. This is the inverse of IdentityID.toString(). * Checks whether the String matches the length limit. * Checks whether it is valid Base64-encoding. */ private IdentityID(String id) { if(id.length() > LENGTH) throw new IllegalArgumentException("ID is too long, length: " + id.length()); try { Base64.decode(id); } catch (IllegalBase64Exception e) { throw new RuntimeException("ID does not contain valid Base64: " + id); } mID = id; } /** * Constructs an IdentityID from the given {@link FreenetURI}. * Checks whether the URI is of the right type: Only USK or SSK is accepted. */ private IdentityID(FreenetURI uri) { if(!uri.isUSK() && !uri.isSSK()) throw new IllegalArgumentException("URI must be USK or SSK!"); try { uri = uri.deriveRequestURIFromInsertURI(); } catch(MalformedURLException e) { // It is already a request URI } /* WARNING: When changing this, also update Freetalk.WoT.WoTIdentity.getUIDFromURI()! */ mID = Base64.encode(uri.getRoutingKey()); } /** * Constructs an identityID from the given String. This is the inverse of IdentityID.toString(). * Checks whether the String matches the length limit. * Checks whether it is valid Base64-encoding. */ public static IdentityID constructAndValidateFromString(String id) { return new IdentityID(id); } /** * Generates a unique ID from a {@link FreenetURI}, which is the routing key of the author encoded with the Freenet-variant of Base64 * We use this to identify identities and perform requests on the database. * * Checks whether the URI is of the right type: Only USK or SSK is accepted. * * @param uri The requestURI or insertURI of the Identity * @return An IdentityID to uniquely identify the identity. */ public static IdentityID constructAndValidateFromURI(FreenetURI uri) { return new IdentityID(uri); } @Override public String toString() { return mID; } @Override public final boolean equals(final Object o) { if(o instanceof IdentityID) return mID.equals(((IdentityID)o).mID); if(o instanceof String) return mID.equals((String)o); return false; } /** * Gets the routing key to which this ID is equivalent. * * It is equivalent because: * An identity is uniquely identified by the USK URI which belongs to it and an USK URI is uniquely identified by its routing key. */ public byte[] getRoutingKey() throws IllegalBase64Exception { return Base64.decode(mID); } } /** * Creates an Identity. Only for being used by the WoT package and unit tests, not for user interfaces! * * @param newRequestURI A {@link FreenetURI} to fetch this Identity * @param newNickname The nickname of this identity * @param doesPublishTrustList Whether this identity publishes its trustList or not * @throws InvalidParameterException if a supplied parameter is invalid * @throws MalformedURLException if newRequestURI isn't a valid request URI */ protected Identity(WebOfTrust myWoT, FreenetURI newRequestURI, String newNickname, boolean doesPublishTrustList) throws InvalidParameterException, MalformedURLException { initializeTransient(myWoT); if (!newRequestURI.isUSK() && !newRequestURI.isSSK()) throw new IllegalArgumentException("Identity URI keytype not supported: " + newRequestURI); // We only use the passed edition number as a hint to prevent attackers from spreading bogus very-high edition numbers. mRequestURI = newRequestURI.setKeyType("USK").setDocName(WebOfTrust.WOT_NAME).setSuggestedEdition(0).setMetaString(null); //Check that mRequestURI really is a request URI USK.create(mRequestURI); mID = IdentityID.constructAndValidateFromURI(mRequestURI).toString(); try { mLatestEditionHint = Math.max(newRequestURI.getEdition(), 0); } catch (IllegalStateException e) { mLatestEditionHint = 0; } mCurrentEditionFetchState = FetchState.NotFetched; mLastFetchedDate = new Date(0); mLastChangedDate = (Date)mCreationDate.clone(); // Don't re-use objects which are stored by db4o to prevent issues when they are being deleted. if(newNickname == null) { mNickname = null; } else { setNickname(newNickname); } setPublishTrustList(doesPublishTrustList); mContexts = new ArrayList<String>(4); /* Currently we have: Introduction, Freetalk */ mProperties = new HashMap<String, String>(); if(logDEBUG) Logger.debug(this, "New identity: " + mNickname + ", URI: " + mRequestURI); } /** * Creates an Identity. Only for being used by the WoT package and unit tests, not for user interfaces! * * @param newRequestURI A String that will be converted to {@link FreenetURI} before creating the identity * @param newNickname The nickname of this identity * @param doesPublishTrustList Whether this identity publishes its trustList or not * @throws InvalidParameterException if a supplied parameter is invalid * @throws MalformedURLException if the supplied requestURI isn't a valid request URI */ public Identity(WebOfTrust myWoT, String newRequestURI, String newNickname, boolean doesPublishTrustList) throws InvalidParameterException, MalformedURLException { this(myWoT, new FreenetURI(newRequestURI), newNickname, doesPublishTrustList); } /** * Gets this Identity's ID, which is the routing key of the author encoded with the Freenet-variant of Base64. * We use this to identify identities and perform requests on the database. * * @return A unique identifier for this Identity. */ public final String getID() { checkedActivate(1); // String is a db4o primitive type so 1 is enough return mID; } /** * @return The requestURI ({@link FreenetURI}) to fetch this Identity */ public final FreenetURI getRequestURI() { checkedActivate(1); checkedActivate(mRequestURI, 2); return mRequestURI; } /** * Get the edition number of the request URI of this identity. * Safe to be called without any additional synchronization. */ public final long getEdition() { return getRequestURI().getEdition(); } public final FetchState getCurrentEditionFetchState() { checkedActivate(1); return mCurrentEditionFetchState; } /** * Sets the edition of the last fetched version of this identity. * That number is published in trustLists to limit the number of editions a newbie has to fetch before he actually gets ans Identity. * * @param newEdition A long representing the last fetched version of this identity. * @throws InvalidParameterException If the new edition is less than the current one. TODO: Evaluate whether we shouldn't be throwing a RuntimeException instead */ protected void setEdition(long newEdition) throws InvalidParameterException { checkedActivate(1); checkedActivate(mRequestURI, 2); // checkedActivate(mCurrentEditionFetchState, 1); is not needed, has no members // checkedActivate(mLatestEditionHint, 1); is not needed, long is a db4o primitive type long currentEdition = mRequestURI.getEdition(); if (newEdition < currentEdition) { throw new InvalidParameterException("The edition of an identity cannot be lowered."); } if (newEdition > currentEdition) { mRequestURI = mRequestURI.setSuggestedEdition(newEdition); mCurrentEditionFetchState = FetchState.NotFetched; if (newEdition > mLatestEditionHint) { // Do not call setNewEditionHint() to prevent confusing logging. mLatestEditionHint = newEdition; } updated(); } } public final long getLatestEditionHint() { checkedActivate(1); // long is a db4o primitive type so 1 is enough return mLatestEditionHint; } /** * Set the "edition hint" of the identity to the given new one. * The "edition hint" is an edition number of which other identities have told us that it is the latest edition. * We only consider it as a hint because they might lie about the edition number, i.e. specify one which is way too high so that the identity won't be * fetched anymore. * * @return True, if the given hint was newer than the already stored one. You have to tell the {@link IdentityFetcher} about that then. */ protected final boolean setNewEditionHint(long newLatestEditionHint) { checkedActivate(1); // long is a db4o primitive type so 1 is enough if (newLatestEditionHint > mLatestEditionHint) { mLatestEditionHint = newLatestEditionHint; if(logDEBUG) Logger.debug(this, "Received a new edition hint of " + newLatestEditionHint + " (current: " + mLatestEditionHint + ") for "+ this); return true; } return false; } /** * Decrease the current edition by one. Used by {@link #markForRefetch()}. */ private final void decreaseEdition() { checkedActivate(1); checkedActivate(mRequestURI, 2); mRequestURI = mRequestURI.setSuggestedEdition(Math.max(mRequestURI.getEdition() - 1, 0)); // TODO: I decided that we should not decrease the edition hint here. Think about that again. } /** * Marks the current edition of this identity as not fetched if it was fetched already. * If it was not fetched, decreases the edition of the identity by one. * * Called by the {@link WebOfTrust} when the {@link Score} of an identity changes from negative or 0 to > 0 to make the {@link IdentityFetcher} re-download it's * current trust list. This is necessary because we do not create the trusted identities of someone if he has a negative score. */ protected void markForRefetch() { checkedActivate(1); // checkedActivate(mCurrentEditionFetchState, 1); not needed, it has no members if (mCurrentEditionFetchState == FetchState.Fetched) { mCurrentEditionFetchState = FetchState.NotFetched; } else { decreaseEdition(); } } /** * @return The date when this identity was first seen in a trust list of someone. */ public final Date getAddedDate() { return (Date)getCreationDate().clone(); } /** * @return The date of this Identity's last modification. */ public final Date getLastFetchedDate() { checkedActivate(1); // Date is a db4o primitive type so 1 is enough return (Date)mLastFetchedDate.clone(); } /** * @return The date of this Identity's last modification. */ public final Date getLastChangeDate() { checkedActivate(1); // Date is a db4o primitive type so 1 is enough return (Date)mLastChangedDate.clone(); } /** * Has to be called when the identity was fetched and parsed successfully. Must not be called before setEdition! */ protected final void onFetched() { onFetched(CurrentTimeUTC.get()); } /** * Can be used for restoring the last-fetched date from a copy of the identity. * When an identity is fetched in normal operation, please use the version without a parameter. * * Must not be called before setEdition! */ protected final void onFetched(Date fetchDate) { checkedActivate(1); mCurrentEditionFetchState = FetchState.Fetched; // checkedDelete(mLastFetchedDate); /* Not stored because db4o considers it as a primitive */ mLastFetchedDate = (Date)fetchDate.clone(); // Clone it to prevent duplicate usage of db4o-stored objects updated(); } /** * Has to be called when the identity was fetched and parsing failed. Must not be called before setEdition! */ protected final void onParsingFailed() { checkedActivate(1); mCurrentEditionFetchState = FetchState.ParsingFailed; // checkedDelete(mLastFetchedDate); /* Not stored because db4o considers it as a primitive */ mLastFetchedDate = CurrentTimeUTC.get(); updated(); } /** * @return The Identity's nickName */ public final String getNickname() { checkedActivate(1); // String is a db4o primitive type so 1 is enough return mNickname; } /* IMPORTANT: This code is duplicated in plugins.Freetalk.WoT.WoTIdentity.validateNickname(). * Please also modify it there if you modify it here */ public static final boolean isNicknameValid(String newNickname) { return newNickname.length() > 0 && newNickname.length() <= MAX_NICKNAME_LENGTH && StringValidityChecker.containsNoIDNBlacklistCharacters(newNickname) && StringValidityChecker.containsNoInvalidCharacters(newNickname) && StringValidityChecker.containsNoLinebreaks(newNickname) && StringValidityChecker.containsNoControlCharacters(newNickname) && StringValidityChecker.containsNoInvalidFormatting(newNickname) && !newNickname.contains("@"); // Must not be allowed since we use it to generate "identity@public-key-hash" unique nicknames; } /** * Sets the nickName of this Identity. * * @param newNickname A String containing this Identity's NickName. Setting it to null means that it was not retrieved yet. * @throws InvalidParameterException If the nickname contains invalid characters, is empty or longer than MAX_NICKNAME_LENGTH characters. */ public final void setNickname(String newNickname) throws InvalidParameterException { if (newNickname == null) { throw new NullPointerException("Nickname is null"); } newNickname = newNickname.trim(); if(newNickname.length() == 0) { throw new InvalidParameterException("Blank nickname"); } if(newNickname.length() > MAX_NICKNAME_LENGTH) { throw new InvalidParameterException("Nickname is too long (" + MAX_NICKNAME_LENGTH + " chars max)"); } if(!isNicknameValid(newNickname)) { throw new InvalidParameterException("Nickname contains illegal characters."); } checkedActivate(1); // String is a db4o primitive type so 1 is enough if (mNickname != null && !mNickname.equals(newNickname)) { throw new InvalidParameterException("Changing the nickname of an identity is not allowed."); } mNickname = newNickname; updated(); } /** * Checks whether this identity publishes a trust list. * * @return Whether this Identity publishes its trustList or not. */ public final boolean doesPublishTrustList() { checkedActivate(1); // boolean is a db4o primitive type so 1 is enough return mDoesPublishTrustList; } /** * Sets if this Identity publishes its trust list or not. */ public final void setPublishTrustList(boolean doesPublishTrustList) { checkedActivate(1); // boolean is a db4o primitive type so 1 is enough if (mDoesPublishTrustList == doesPublishTrustList) { return; } mDoesPublishTrustList = doesPublishTrustList; updated(); } /** * Checks whether this identity offers the given contexts. * * @param context The context we want to know if this Identity has it or not * @return Whether this Identity has that context or not */ public final boolean hasContext(String context) { checkedActivate(1); checkedActivate(mContexts, 2); return mContexts.contains(context.trim()); } /** * Gets all this Identity's contexts. * * @return A copy of the ArrayList<String> of all contexts of this identity. */ @SuppressWarnings("unchecked") public final ArrayList<String> getContexts() { /* TODO: If this is used often - which it probably is, we might verify that no code corrupts the HashMap and return the original one * instead of a copy */ checkedActivate(1); checkedActivate(mContexts, 2); return (ArrayList<String>)mContexts.clone(); } /** * Adds a context to this identity. A context is a string, the identities contexts are a set of strings - no context will be added more than * once. * Contexts are used by client applications to identify what identities are relevant for their use. * Currently known contexts: * - WoT adds the "Introduction" context if an identity publishes catpchas to allow other to get on it's trust list * - Freetalk, the messaging system for Freenet, adds the "Freetalk" context to identities which use it. * * @param newContext Name of the context. Must be latin letters and numbers only. * @throws InvalidParameterException If the context name is empty */ public final void addContext(String newContext) throws InvalidParameterException { newContext = newContext.trim(); final int length = newContext.length(); if (length == 0) { throw new InvalidParameterException("A blank context cannot be added to an identity."); } if (length > MAX_CONTEXT_NAME_LENGTH) { throw new InvalidParameterException("Context names must not be longer than " + MAX_CONTEXT_NAME_LENGTH + " characters."); } if (!StringValidityChecker.isLatinLettersAndNumbersOnly(newContext)) { throw new InvalidParameterException("Context names must be latin letters and numbers only"); } checkedActivate(1); checkedActivate(mContexts, 2); if (!mContexts.contains(newContext)) { if (mContexts.size() >= MAX_CONTEXT_AMOUNT) { throw new InvalidParameterException("An identity may not have more than " + MAX_CONTEXT_AMOUNT + " contexts."); } mContexts.add(newContext); updated(); } } /** * Clears the list of contexts and sets it to the new list of contexts which was passed to the function. * Duplicate contexts are ignored. For invalid contexts an error is logged, all valid ones will be added. * * IMPORTANT: This always marks the identity as updated so it should not be used on OwnIdentities because it would result in * a re-insert even if nothing was changed. */ protected final void setContexts(List<String> newContexts) { checkedActivate(1); checkedActivate(mContexts, 2); mContexts.clear(); for (String context : newContexts) { try { addContext(context); } catch (InvalidParameterException e) { Logger.error(this, "setContexts(): addContext() failed.", e); } } mContexts.trimToSize(); } /** * Removes a context from this Identity, does nothing if it does not exist. * If this Identity is no longer used by a client application, the user can tell it and others won't try to fetch it anymore. * * @param context Name of the context. */ public final void removeContext(String context) throws InvalidParameterException { context = context.trim(); checkedActivate(1); checkedActivate(mContexts, 2); if (mContexts.contains(context)) { mContexts.remove(context); updated(); } } private synchronized final void activateProperties() { // We must not deactivate mProperties if it was already modified by a setter so we need this guard if(mPropertiesActivated) return; // TODO: As soon as the db4o bug with hashmaps is fixed, remove this workaround function & replace with: // checkedActivate(1); // checkedActivate(mProperties, 3); checkedActivate(1); if(mDB.isStored(mProperties)) { mDB.deactivate(mProperties); checkedActivate(mProperties, 3); } mPropertiesActivated = true; } /** * Gets the value of one of this Identity's properties. * * @param key The name of the requested custom property * @return The value of the requested custom property * @throws InvalidParameterException if this Identity doesn't have the required property */ public final String getProperty(String key) throws InvalidParameterException { key = key.trim(); activateProperties(); if (!mProperties.containsKey(key)) { throw new InvalidParameterException("The property '" + key +"' isn't set on this identity."); } return mProperties.get(key); } /** * Gets all custom properties from this Identity. * * @return A copy of the HashMap<String, String> referencing all this Identity's custom properties. */ @SuppressWarnings("unchecked") public final HashMap<String, String> getProperties() { activateProperties(); /* TODO: If this is used often, we might verify that no code corrupts the HashMap and return the original one instead of a copy */ return (HashMap<String, String>)mProperties.clone(); } /** * Sets a custom property on this Identity. Custom properties keys have to be unique. * This can be used by client applications that need to store additional informations on their Identities (crypto keys, avatar, whatever...). * The key is always trimmed before storage, the value is stored as passed. * * @param key Name of the custom property. Must be latin letters, numbers and periods only. Periods may only appear if surrounded by other characters. * @param value Value of the custom property. * @throws InvalidParameterException If the key or the value is empty. */ public final void setProperty(String key, String value) throws InvalidParameterException { // Double check in case someone removes the implicit checks... IfNull.thenThrow(key, "Key"); IfNull.thenThrow(value, "Value"); key = key.trim(); final int keyLength = key.length(); if (keyLength == 0) { throw new InvalidParameterException("Property names must not be empty."); } if (keyLength > MAX_PROPERTY_NAME_LENGTH) { throw new InvalidParameterException("Property names must not be longer than " + MAX_PROPERTY_NAME_LENGTH + " characters."); } String[] keyTokens = key.split("[.]", -1); // The 1-argument-version wont return empty tokens for (String token : keyTokens) { if (token.length() == 0) { throw new InvalidParameterException("Property names which contain periods must have at least one character before and after each period."); } if(!StringValidityChecker.isLatinLettersAndNumbersOnly(token)) throw new InvalidParameterException("Property names must contain only latin letters, numbers and periods."); } final int valueLength = value.length(); if (valueLength == 0) { throw new InvalidParameterException("Property values must not be empty."); } if (valueLength > MAX_PROPERTY_VALUE_LENGTH) { throw new InvalidParameterException("Property values must not be longer than " + MAX_PROPERTY_VALUE_LENGTH + " characters"); } activateProperties(); String oldValue = mProperties.get(key); if (oldValue == null && mProperties.size() >= MAX_PROPERTY_AMOUNT) { throw new InvalidParameterException("An identity may not have more than " + MAX_PROPERTY_AMOUNT + " properties."); } if (oldValue == null || oldValue.equals(value) == false) { mProperties.put(key, value); updated(); } } /** * Clears the list of properties and sets it to the new list of properties which was passed to the function. * For invalid properties an error is logged, all valid ones will be added. * * IMPORTANT: This always marks the identity as updated so it should not be used on OwnIdentities because it would result in * a re-insert even if nothing was changed. */ protected final void setProperties(HashMap<String, String> newProperties) { activateProperties(); checkedDelete(mProperties); mProperties = new HashMap<String, String>(newProperties.size() * 2); for (Entry<String, String> property : newProperties.entrySet()) { try { setProperty(property.getKey(), property.getValue()); } catch (InvalidParameterException e) { Logger.error(this, "setProperties(): setProperty() failed.", e); } } } /** * Removes a custom property from this Identity, does nothing if it does not exist. * * @param key Name of the custom property. */ public final void removeProperty(String key) throws InvalidParameterException { activateProperties(); key = key.trim(); if (mProperties.remove(key) != null) { updated(); } } /** * Tell that this Identity has been updated. * * Updated OwnIdentities will be reinserted by the IdentityInserter automatically. */ public final void updated() { checkedActivate(1); // Date is a db4o primitive type so 1 is enough // checkedDelete(mLastChangedDate); /* Not stored because db4o considers it as a primitive */ mLastChangedDate = CurrentTimeUTC.get(); } public final String toString() { checkedActivate(1); // String is a db4o primitive type so 1 is enough return mNickname + "(" + mID + ")"; } /** * Compares whether two identities are equal. * This checks <b>all</b> properties of the identities <b>excluding</b> the {@link Date} properties. */ public boolean equals(Object obj) { if (obj == this) { return true; } - if (!(obj instanceof Identity)) { + // - We need to return false when someone tries to compare an OwnIdentity to a non-own one. + // - We must also make sure that OwnIdentity can safely use this equals() function as foundation. + // Both cases are ensured by this check: + if (obj.getClass() != this.getClass()) { return false; } Identity other = (Identity)obj; if (!getID().equals(other.getID())) { return false; } if (!getRequestURI().equals(other.getRequestURI())) { return false; } if (getCurrentEditionFetchState() != other.getCurrentEditionFetchState()) { return false; } if (getLatestEditionHint() != other.getLatestEditionHint()) { return false; } final String nickname = getNickname(); final String otherNickname = other.getNickname(); if ((nickname == null) != (otherNickname == null)) { return false; } if(nickname != null && !nickname.equals(otherNickname)) { return false; } if (doesPublishTrustList() != other.doesPublishTrustList()) { return false; } String[] myContexts = (String[])getContexts().toArray(new String[1]); String[] otherContexts = (String[])other.getContexts().toArray(new String[1]); Arrays.sort(myContexts); Arrays.sort(otherContexts); if (!Arrays.deepEquals(myContexts, otherContexts)) { return false; } if (!getProperties().equals(other.getProperties())) { return false; } return true; } public int hashCode() { return getID().hashCode(); } /** * Clones this identity. Does <b>not</b> clone the {@link Date} attributes, they are initialized to the current time! */ public Identity clone() { try { Identity clone = new Identity(mWebOfTrust, getRequestURI(), getNickname(), doesPublishTrustList()); checkedActivate(4); // For performance only clone.mCurrentEditionFetchState = getCurrentEditionFetchState(); clone.mLastChangedDate = (Date)getLastChangeDate().clone(); clone.mLatestEditionHint = getLatestEditionHint(); // Don't use the setter since it won't lower the current edition hint. clone.setContexts(getContexts()); clone.setProperties(getProperties()); return clone; } catch (InvalidParameterException e) { throw new RuntimeException(e); } catch (MalformedURLException e) { /* This should never happen since we checked when this object was created */ Logger.error(this, "Caugth MalformedURLException in clone()", e); throw new IllegalStateException(e); } } /** * Stores this identity in the database without committing the transaction * You must synchronize on the WoT, on the identity and then on the database when using this function! */ protected void storeWithoutCommit() { try { // 4 is the maximal depth of all getter functions. You have to adjust this when introducing new member variables. checkedActivate(4); activateProperties(); // checkedStore(mID); /* Not stored because db4o considers it as a primitive and automatically stores it. */ checkedStore(mRequestURI); // checkedStore(mFirstFetchedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedStore(mLastFetchedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedStore(mLastChangedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedStore(mNickname); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedStore(mDoesPublishTrustList); /* Not stored because db4o considers it as a primitive and automatically stores it. */ checkedStore(mProperties); checkedStore(mContexts); checkedStore(); } catch(final RuntimeException e) { checkedRollbackAndThrow(e); } } /** * Locks the WoT, locks the database and stores the identity. */ public final void storeAndCommit() { synchronized(mWebOfTrust) { synchronized(Persistent.transactionLock(mDB)) { try { storeWithoutCommit(); checkedCommit(this); } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } } } /** * You have to lock the WoT and the IntroductionPuzzleStore before calling this function. * @param identity */ protected void deleteWithoutCommit() { try { // 4 is the maximal depth of all getter functions. You have to adjust this when introducing new member variables. checkedActivate(4); activateProperties(); // checkedDelete(mID); /* Not stored because db4o considers it as a primitive and automatically stores it. */ mRequestURI.removeFrom(mDB); checkedDelete(mCurrentEditionFetchState); // TODO: Is this still necessary? // checkedDelete(mLastFetchedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedDelete(mLastChangedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedDelete(mNickname); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedDelete(mDoesPublishTrustList); /* Not stored because db4o considers it as a primitive and automatically stores it. */ checkedDelete(mProperties); checkedDelete(mContexts); checkedDelete(); } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } @Override public void startupDatabaseIntegrityTest() { checkedActivate(4); if(mID == null) throw new NullPointerException("mID==null"); if(mRequestURI == null) throw new NullPointerException("mRequestURI==null"); if(!mID.equals(IdentityID.constructAndValidateFromURI(mRequestURI).toString())) throw new IllegalStateException("ID does not match request URI!"); IdentityID.constructAndValidateFromString(mID); // Throws if invalid if(mCurrentEditionFetchState == null) throw new NullPointerException("mCurrentEditionFetchState==null"); if(mLatestEditionHint < 0 || mLatestEditionHint < mRequestURI.getEdition()) throw new IllegalStateException("Invalid edition hint: " + mLatestEditionHint + "; current edition: " + mRequestURI.getEdition()); if(mLastFetchedDate == null) throw new NullPointerException("mLastFetchedDate==null"); if(mLastFetchedDate.after(CurrentTimeUTC.get())) throw new IllegalStateException("mLastFetchedDate is in the future: " + mLastFetchedDate); if(mLastChangedDate == null) throw new NullPointerException("mLastChangedDate==null"); if(mLastChangedDate.before(mCreationDate)) throw new IllegalStateException("mLastChangedDate is before mCreationDate!"); if(mLastChangedDate.before(mLastFetchedDate)) throw new IllegalStateException("mLastChangedDate is before mLastFetchedDate!"); if(mLastChangedDate.after(CurrentTimeUTC.get())) throw new IllegalStateException("mLastChangedDate is in the future: " + mLastChangedDate); if(mNickname != null && !isNicknameValid(mNickname)) throw new IllegalStateException("Invalid nickname: " + mNickname); if(mContexts == null) throw new NullPointerException("mContexts==null"); if(mProperties == null) throw new NullPointerException("mProperties==null"); if(mContexts.size() > MAX_CONTEXT_AMOUNT) throw new IllegalStateException("Too many contexts: " + mContexts.size()); if(mProperties.size() > MAX_PROPERTY_AMOUNT) throw new IllegalStateException("Too many properties: " + mProperties.size()); // TODO: Verify context/property names/values } }
true
true
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Identity)) { return false; } Identity other = (Identity)obj; if (!getID().equals(other.getID())) { return false; } if (!getRequestURI().equals(other.getRequestURI())) { return false; } if (getCurrentEditionFetchState() != other.getCurrentEditionFetchState()) { return false; } if (getLatestEditionHint() != other.getLatestEditionHint()) { return false; } final String nickname = getNickname(); final String otherNickname = other.getNickname(); if ((nickname == null) != (otherNickname == null)) { return false; } if(nickname != null && !nickname.equals(otherNickname)) { return false; } if (doesPublishTrustList() != other.doesPublishTrustList()) { return false; } String[] myContexts = (String[])getContexts().toArray(new String[1]); String[] otherContexts = (String[])other.getContexts().toArray(new String[1]); Arrays.sort(myContexts); Arrays.sort(otherContexts); if (!Arrays.deepEquals(myContexts, otherContexts)) { return false; } if (!getProperties().equals(other.getProperties())) { return false; } return true; }
public boolean equals(Object obj) { if (obj == this) { return true; } // - We need to return false when someone tries to compare an OwnIdentity to a non-own one. // - We must also make sure that OwnIdentity can safely use this equals() function as foundation. // Both cases are ensured by this check: if (obj.getClass() != this.getClass()) { return false; } Identity other = (Identity)obj; if (!getID().equals(other.getID())) { return false; } if (!getRequestURI().equals(other.getRequestURI())) { return false; } if (getCurrentEditionFetchState() != other.getCurrentEditionFetchState()) { return false; } if (getLatestEditionHint() != other.getLatestEditionHint()) { return false; } final String nickname = getNickname(); final String otherNickname = other.getNickname(); if ((nickname == null) != (otherNickname == null)) { return false; } if(nickname != null && !nickname.equals(otherNickname)) { return false; } if (doesPublishTrustList() != other.doesPublishTrustList()) { return false; } String[] myContexts = (String[])getContexts().toArray(new String[1]); String[] otherContexts = (String[])other.getContexts().toArray(new String[1]); Arrays.sort(myContexts); Arrays.sort(otherContexts); if (!Arrays.deepEquals(myContexts, otherContexts)) { return false; } if (!getProperties().equals(other.getProperties())) { return false; } return true; }
diff --git a/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java b/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java index 02fcaff..599b00c 100644 --- a/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java +++ b/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java @@ -1,82 +1,82 @@ /** * */ package javax.jmdns.test; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import javax.jmdns.impl.DNSStatefulObject.DNSStatefulObjectSemaphore; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * */ public class DNSStatefulObjectTest { public static final class WaitingThread extends Thread { private final DNSStatefulObjectSemaphore _semaphore; private final long _timeout; private boolean _hasFinished; public WaitingThread(DNSStatefulObjectSemaphore semaphore, long timeout) { super("Waiting thread"); _semaphore = semaphore; _timeout = timeout; _hasFinished = false; } @Override public void run() { _semaphore.waitForEvent(_timeout); _hasFinished = true; } /** * @return the hasFinished */ public boolean hasFinished() { return _hasFinished; } } DNSStatefulObjectSemaphore _semaphore; @Before public void setup() { _semaphore = new DNSStatefulObjectSemaphore("test"); } @After public void teardown() { _semaphore = null; } @Test public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 0); thread.start(); - Thread.sleep(1); + Thread.sleep(2); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); - Thread.sleep(1); + Thread.sleep(2); assertTrue("The thread should have finished.", thread.hasFinished()); } @Test public void testWaitAndTimeout() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 100); thread.start(); Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); Thread.sleep(150); assertTrue("The thread should have finished.", thread.hasFinished()); } }
false
true
public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 0); thread.start(); Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); Thread.sleep(1); assertTrue("The thread should have finished.", thread.hasFinished()); }
public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 0); thread.start(); Thread.sleep(2); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); Thread.sleep(2); assertTrue("The thread should have finished.", thread.hasFinished()); }
diff --git a/src/main/java/com/intelix/digihdmi/app/views/PresetLoadListView.java b/src/main/java/com/intelix/digihdmi/app/views/PresetLoadListView.java index b21fef2..a83ffdc 100644 --- a/src/main/java/com/intelix/digihdmi/app/views/PresetLoadListView.java +++ b/src/main/java/com/intelix/digihdmi/app/views/PresetLoadListView.java @@ -1,20 +1,20 @@ package com.intelix.digihdmi.app.views; import com.intelix.digihdmi.util.IconImageButton; import javax.swing.JButton; import org.jdesktop.application.Application; public class PresetLoadListView extends ButtonListView { @Override protected void initializeHomePanel() { super.initializeHomePanel(); IconImageButton matrixView = new IconImageButton("MatrixIconBtn"); matrixView.setAction( - Application.getInstance().getContext().getActionMap().get("showMatrixView") + Application.getInstance().getContext().getActionMap().get("showAndLoadMatrixView") ); this.homePanel.add(matrixView); } }
true
true
protected void initializeHomePanel() { super.initializeHomePanel(); IconImageButton matrixView = new IconImageButton("MatrixIconBtn"); matrixView.setAction( Application.getInstance().getContext().getActionMap().get("showMatrixView") ); this.homePanel.add(matrixView); }
protected void initializeHomePanel() { super.initializeHomePanel(); IconImageButton matrixView = new IconImageButton("MatrixIconBtn"); matrixView.setAction( Application.getInstance().getContext().getActionMap().get("showAndLoadMatrixView") ); this.homePanel.add(matrixView); }
diff --git a/core/src/main/java/hudson/util/UnbufferedBase64InputStream.java b/core/src/main/java/hudson/util/UnbufferedBase64InputStream.java index fa6645432..14103da5c 100644 --- a/core/src/main/java/hudson/util/UnbufferedBase64InputStream.java +++ b/core/src/main/java/hudson/util/UnbufferedBase64InputStream.java @@ -1,58 +1,59 @@ package hudson.util; import org.apache.commons.codec.binary.Base64; import java.io.DataInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * Filter InputStream that decodes base64 without doing any buffering. * * <p> * This is slower implementation, but it won't consume unnecessary bytes from the underlying {@link InputStream}, * allowing the reader to switch between the unencoded bytes and base64 bytes. * * @author Kohsuke Kawaguchi * @since 1.349 */ public class UnbufferedBase64InputStream extends FilterInputStream { private byte[] encoded = new byte[4]; private byte[] decoded; private int pos; private final DataInputStream din; public UnbufferedBase64InputStream(InputStream in) { super(in); din = new DataInputStream(in); // initial placement to force the decoding in the next read() pos = 4; decoded = encoded; } @Override public int read() throws IOException { if (decoded.length==0) return -1; // EOF if (pos==decoded.length) { din.readFully(encoded); decoded = Base64.decodeBase64(encoded); + if (decoded.length==0) return -1; // EOF pos = 0; } return (decoded[pos++])&0xFF; } @Override public int read(byte[] b, int off, int len) throws IOException { int i; for (i=0; i<len; i++) { int ch = read(); if (ch<0) break; b[off+i] = (byte)ch; } return i==0 ? -1 : i; } }
true
true
public int read() throws IOException { if (decoded.length==0) return -1; // EOF if (pos==decoded.length) { din.readFully(encoded); decoded = Base64.decodeBase64(encoded); pos = 0; } return (decoded[pos++])&0xFF; }
public int read() throws IOException { if (decoded.length==0) return -1; // EOF if (pos==decoded.length) { din.readFully(encoded); decoded = Base64.decodeBase64(encoded); if (decoded.length==0) return -1; // EOF pos = 0; } return (decoded[pos++])&0xFF; }
diff --git a/src/cytoscape/actions/CreateNetworkViewAction.java b/src/cytoscape/actions/CreateNetworkViewAction.java index b33baacb5..4922258d6 100644 --- a/src/cytoscape/actions/CreateNetworkViewAction.java +++ b/src/cytoscape/actions/CreateNetworkViewAction.java @@ -1,53 +1,53 @@ package cytoscape.actions; import cytoscape.CyNetwork; import cytoscape.Cytoscape; import cytoscape.CytoscapeInit; import cytoscape.util.CytoscapeAction; import javax.swing.*; import java.awt.event.ActionEvent; import java.text.NumberFormat; import java.text.DecimalFormat; public class CreateNetworkViewAction extends CytoscapeAction { public CreateNetworkViewAction() { super("Create View"); setPreferredMenu("Edit"); setAcceleratorCombo(java.awt.event.KeyEvent.VK_V, ActionEvent.ALT_MASK); } public CreateNetworkViewAction(boolean label) { super(); } public void actionPerformed(ActionEvent e) { CyNetwork cyNetwork = Cytoscape.getCurrentNetwork(); createViewFromCurrentNetwork(cyNetwork); } public static void createViewFromCurrentNetwork(CyNetwork cyNetwork) { - System.out.println("Secondary View Threshold: " - + CytoscapeInit.getSecondaryViewThreshold()); NumberFormat formatter = new DecimalFormat("#,###,###"); if (cyNetwork.getNodeCount() > CytoscapeInit.getSecondaryViewThreshold()) { int n = JOptionPane.showConfirmDialog(Cytoscape.getDesktop(), "Network contains " + formatter.format(cyNetwork.getNodeCount()) + " nodes and " + formatter.format (cyNetwork.getEdgeCount()) + " edges. " + "\nRendering a network this size may take several " + "minutes.\n" + "Do you wish to proceed?", "Rendering Large Network", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } else { JOptionPane.showMessageDialog(Cytoscape.getDesktop(), "Create View Request Cancelled by User."); } + } else { + Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } } }
false
true
public static void createViewFromCurrentNetwork(CyNetwork cyNetwork) { System.out.println("Secondary View Threshold: " + CytoscapeInit.getSecondaryViewThreshold()); NumberFormat formatter = new DecimalFormat("#,###,###"); if (cyNetwork.getNodeCount() > CytoscapeInit.getSecondaryViewThreshold()) { int n = JOptionPane.showConfirmDialog(Cytoscape.getDesktop(), "Network contains " + formatter.format(cyNetwork.getNodeCount()) + " nodes and " + formatter.format (cyNetwork.getEdgeCount()) + " edges. " + "\nRendering a network this size may take several " + "minutes.\n" + "Do you wish to proceed?", "Rendering Large Network", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } else { JOptionPane.showMessageDialog(Cytoscape.getDesktop(), "Create View Request Cancelled by User."); } } }
public static void createViewFromCurrentNetwork(CyNetwork cyNetwork) { NumberFormat formatter = new DecimalFormat("#,###,###"); if (cyNetwork.getNodeCount() > CytoscapeInit.getSecondaryViewThreshold()) { int n = JOptionPane.showConfirmDialog(Cytoscape.getDesktop(), "Network contains " + formatter.format(cyNetwork.getNodeCount()) + " nodes and " + formatter.format (cyNetwork.getEdgeCount()) + " edges. " + "\nRendering a network this size may take several " + "minutes.\n" + "Do you wish to proceed?", "Rendering Large Network", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } else { JOptionPane.showMessageDialog(Cytoscape.getDesktop(), "Create View Request Cancelled by User."); } } else { Cytoscape.createNetworkView(Cytoscape.getCurrentNetwork()); } }
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/area/impl/RowArea.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/area/impl/RowArea.java index 45b39714b..1bf72c150 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/area/impl/RowArea.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/area/impl/RowArea.java @@ -1,43 +1,48 @@ /*********************************************************************** * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.report.engine.layout.area.impl; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.layout.area.IArea; public class RowArea extends ContainerArea { public void addChild( IArea area ) { super.addChild( area ); } RowArea( IRowContent row ) { super( row ); style.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_LEFT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_RIGHT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_BOTTOM_WIDTH, IStyle.NUMBER_0 ); + // Row does not support margin, remove them. + style.setProperty( IStyle.STYLE_MARGIN_TOP, IStyle.NUMBER_0); + style.setProperty( IStyle.STYLE_MARGIN_LEFT, IStyle.NUMBER_0); + style.setProperty( IStyle.STYLE_MARGIN_RIGHT, IStyle.NUMBER_0); + style.setProperty( IStyle.STYLE_MARGIN_BOTTOM, IStyle.NUMBER_0); } public int getRowID( ) { if ( content != null ) { return ( (IRowContent) content ).getRowID( ); } return 0; } }
true
true
RowArea( IRowContent row ) { super( row ); style.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_LEFT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_RIGHT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_BOTTOM_WIDTH, IStyle.NUMBER_0 ); }
RowArea( IRowContent row ) { super( row ); style.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_LEFT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_RIGHT_WIDTH, IStyle.NUMBER_0 ); style.setProperty( IStyle.STYLE_BORDER_BOTTOM_WIDTH, IStyle.NUMBER_0 ); // Row does not support margin, remove them. style.setProperty( IStyle.STYLE_MARGIN_TOP, IStyle.NUMBER_0); style.setProperty( IStyle.STYLE_MARGIN_LEFT, IStyle.NUMBER_0); style.setProperty( IStyle.STYLE_MARGIN_RIGHT, IStyle.NUMBER_0); style.setProperty( IStyle.STYLE_MARGIN_BOTTOM, IStyle.NUMBER_0); }
diff --git a/dspace/src/org/dspace/content/InstallItem.java b/dspace/src/org/dspace/content/InstallItem.java index b1b62c5dd..07842a1b8 100644 --- a/dspace/src/org/dspace/content/InstallItem.java +++ b/dspace/src/org/dspace/content/InstallItem.java @@ -1,178 +1,178 @@ /* * InstallItem.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2001, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.content; import java.io.IOException; import java.sql.SQLException; import java.util.List; import org.dspace.browse.Browse; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.core.Context; import org.dspace.core.Constants; import org.dspace.eperson.EPerson; import org.dspace.handle.HandleManager; import org.dspace.search.DSIndexer; import org.dspace.storage.rdbms.TableRowIterator; import org.dspace.storage.rdbms.DatabaseManager; /** * Support to install item in the archive * * @author dstuve * @version $Revision$ */ public class InstallItem { public static Item installItem(Context c, InProgressSubmission is) throws SQLException, IOException, AuthorizeException { return installItem(c, is, c.getCurrentUser()); } public static Item installItem(Context c, InProgressSubmission is, EPerson e) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if(currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // create handle String handle = HandleManager.createHandle(c, item); String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value - item.addDC("identifier", "uri", null, handle); + item.addDC("identifier", "uri", null, handleref); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i].getSize())); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // create date.available // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexItem(c, item); // item.update() above adds item to browse indices //Browse.itemChanged(c, item); // remove in-progress submission is.deleteWrapper(); // remove the submit authorization policies // and replace them with the collection's READ // policies // FIXME: this is an inelegant hack, but out of time! List policies = AuthorizeManager.getPoliciesActionFilter(c, is.getCollection(), Constants.READ ); item.replaceAllPolicies(policies); return item; } /** generate provenance-worthy description of the bitstreams * contained in an item */ public static String getBitstreamProvenanceMessage(Item myitem) { // Get non-internal format bitstreams Bitstream[] bitstreams = myitem.getNonInternalBitstreams(); // Create provenance description String mymessage = "No. of bitstreams: " + bitstreams.length + "\n"; // Add sizes and checksums of bitstreams for (int j = 0; j < bitstreams.length; j++) { mymessage = mymessage + bitstreams[j].getName() + ": " + bitstreams[j].getSize() + " bytes, checksum: " + bitstreams[j].getChecksum() + " (" + bitstreams[j].getChecksumAlgorithm() + ")\n"; } return mymessage; } }
true
true
public static Item installItem(Context c, InProgressSubmission is, EPerson e) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if(currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // create handle String handle = HandleManager.createHandle(c, item); String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value item.addDC("identifier", "uri", null, handle); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i].getSize())); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // create date.available // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexItem(c, item); // item.update() above adds item to browse indices //Browse.itemChanged(c, item); // remove in-progress submission is.deleteWrapper(); // remove the submit authorization policies // and replace them with the collection's READ // policies // FIXME: this is an inelegant hack, but out of time! List policies = AuthorizeManager.getPoliciesActionFilter(c, is.getCollection(), Constants.READ ); item.replaceAllPolicies(policies); return item; }
public static Item installItem(Context c, InProgressSubmission is, EPerson e) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if(currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // create handle String handle = HandleManager.createHandle(c, item); String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value item.addDC("identifier", "uri", null, handleref); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i].getSize())); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // create date.available // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexItem(c, item); // item.update() above adds item to browse indices //Browse.itemChanged(c, item); // remove in-progress submission is.deleteWrapper(); // remove the submit authorization policies // and replace them with the collection's READ // policies // FIXME: this is an inelegant hack, but out of time! List policies = AuthorizeManager.getPoliciesActionFilter(c, is.getCollection(), Constants.READ ); item.replaceAllPolicies(policies); return item; }
diff --git a/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToolbarCheckboxButton.java b/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToolbarCheckboxButton.java index ec755fe..a9192a4 100644 --- a/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToolbarCheckboxButton.java +++ b/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/widgets/SWTBotToolbarCheckboxButton.java @@ -1,129 +1,129 @@ /******************************************************************************* * Copyright (c) 2009 Ketan Padegaonkar 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: * Ketan Padegaonkar - initial API and implementation *******************************************************************************/ package org.eclipse.swtbot.swt.finder.widgets; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swtbot.swt.finder.ReferenceBy; import org.eclipse.swtbot.swt.finder.SWTBotWidget; import org.eclipse.swtbot.swt.finder.Style; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.results.BoolResult; import org.eclipse.swtbot.swt.finder.results.VoidResult; import org.eclipse.swtbot.swt.finder.utils.MessageFormat; import org.eclipse.swtbot.swt.finder.utils.SWTUtils; import org.eclipse.swtbot.swt.finder.utils.internal.Assert; import org.hamcrest.SelfDescribing; /** * Represents a tool item of type checkbox * * @author Ketan Padegaonkar &lt;KetanPadegaonkar [at] gmail [dot] com&gt; * @version $Id$ */ @SWTBotWidget(clasz = ToolItem.class, preferredName = "toolbarToggleButton", style = @Style(name = "SWT.CHECK", value = SWT.CHECK), referenceBy = { ReferenceBy.MNEMONIC, ReferenceBy.TOOLTIP }) public class SWTBotToolbarCheckboxButton extends SWTBotToolbarButton { /** * Construcst an new instance of this item. * * @param w the tool item. * @throws WidgetNotFoundException if the widget is <code>null</code> or widget has been disposed. */ public SWTBotToolbarCheckboxButton(ToolItem w) throws WidgetNotFoundException { this(w, null); } /** * Construcst an new instance of this item. * * @param w the tool item. * @param description the description of the widget, this will be reported by {@link #toString()} * @throws WidgetNotFoundException if the widget is <code>null</code> or widget has been disposed. */ public SWTBotToolbarCheckboxButton(ToolItem w, SelfDescribing description) throws WidgetNotFoundException { super(w, description); Assert.isTrue(SWTUtils.hasStyle(w, SWT.CHECK), "Expecting a checkbox."); //$NON-NLS-1$ } /** * Click on the tool item. This will toggle the tool item. * * @return itself */ public SWTBotToolbarCheckboxButton toggle() { log.debug(MessageFormat.format("Clicking on {0}", this)); //$NON-NLS-1$ assertEnabled(); + internalToggle(); notify(SWT.MouseEnter); notify(SWT.MouseMove); notify(SWT.Activate); notify(SWT.MouseDown); notify(SWT.MouseUp); notify(SWT.Selection); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); - internalToggle(); log.debug(MessageFormat.format("Clicked on {0}", this)); //$NON-NLS-1$ return this; } public SWTBotToolbarCheckboxButton click() { return toggle(); } private void internalToggle() { syncExec(new VoidResult() { public void run() { widget.setSelection(!widget.getSelection()); } }); } /** * Selects the checkbox button. */ public void select() { if (!isChecked()) toggle(); } /** * Deselects the checkbox button. */ public void deselect() { if (isChecked()) toggle(); } /** * @return <code>true</code> if the button is checked, <code>false</code> otherwise. */ public boolean isChecked() { return syncExec(new BoolResult() { public Boolean run() { return widget.getSelection(); } }); } @Override public boolean isEnabled() { return syncExec(new BoolResult() { public Boolean run() { return widget.isEnabled(); } }); } }
false
true
public SWTBotToolbarCheckboxButton toggle() { log.debug(MessageFormat.format("Clicking on {0}", this)); //$NON-NLS-1$ assertEnabled(); notify(SWT.MouseEnter); notify(SWT.MouseMove); notify(SWT.Activate); notify(SWT.MouseDown); notify(SWT.MouseUp); notify(SWT.Selection); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); internalToggle(); log.debug(MessageFormat.format("Clicked on {0}", this)); //$NON-NLS-1$ return this; }
public SWTBotToolbarCheckboxButton toggle() { log.debug(MessageFormat.format("Clicking on {0}", this)); //$NON-NLS-1$ assertEnabled(); internalToggle(); notify(SWT.MouseEnter); notify(SWT.MouseMove); notify(SWT.Activate); notify(SWT.MouseDown); notify(SWT.MouseUp); notify(SWT.Selection); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); log.debug(MessageFormat.format("Clicked on {0}", this)); //$NON-NLS-1$ return this; }
diff --git a/src/net/reichholf/dreamdroid/activities/FragmentMainActivity.java b/src/net/reichholf/dreamdroid/activities/FragmentMainActivity.java index 07c111a8..85d315f7 100644 --- a/src/net/reichholf/dreamdroid/activities/FragmentMainActivity.java +++ b/src/net/reichholf/dreamdroid/activities/FragmentMainActivity.java @@ -1,336 +1,342 @@ /* © 2010 Stephan Reichholf <stephan at reichholf dot net> * * Licensed under the Create-Commons Attribution-Noncommercial-Share Alike 3.0 Unported * http://creativecommons.org/licenses/by-nc-sa/3.0/ */ package net.reichholf.dreamdroid.activities; import net.reichholf.dreamdroid.DreamDroid; import net.reichholf.dreamdroid.R; import net.reichholf.dreamdroid.abstivities.MultiPaneHandler; import net.reichholf.dreamdroid.fragment.ActivityCallbackHandler; import net.reichholf.dreamdroid.fragment.NavigationFragment; import net.reichholf.dreamdroid.helpers.ExtendedHashMap; import net.reichholf.dreamdroid.helpers.enigma2.CheckProfile; import android.app.Dialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.view.Window; import android.widget.TextView; /** * @author sre * */ public class FragmentMainActivity extends FragmentActivity implements MultiPaneHandler { private boolean mMultiPane; private Fragment mCurrentDetailFragment; private FragmentManager mFragmentManager; private NavigationFragment mNavigationFragment; private ActivityCallbackHandler mCallBackHandler; private TextView mActiveProfile; private TextView mConnectionState; private CheckProfileTask mCheckProfileTask; private boolean isNavigationDialog = false; private class CheckProfileTask extends AsyncTask<Void, String, ExtendedHashMap> { /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected ExtendedHashMap doInBackground(Void... params) { publishProgress(getText(R.string.checking).toString()); return CheckProfile.checkProfile(DreamDroid.PROFILE); } /* * (non-Javadoc) * * @see android.os.AsyncTask#onProgressUpdate(Progress[]) */ @Override protected void onProgressUpdate(String... progress) { setConnectionState(progress[0]); } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(ExtendedHashMap result) { Log.i(DreamDroid.LOG_TAG, result.toString()); if ((Boolean) result.get(CheckProfile.KEY_HAS_ERROR)) { String error = getText((Integer) result.get(CheckProfile.KEY_ERROR_TEXT)).toString(); setConnectionState(error); } else { setConnectionState(getText(R.string.ok).toString()); } } } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); mFragmentManager = getSupportFragmentManager(); if(savedInstanceState != null){ mNavigationFragment = (NavigationFragment) mFragmentManager.getFragment(savedInstanceState, "navigation"); } if(mNavigationFragment == null){ mNavigationFragment = new NavigationFragment(); } if(savedInstanceState != null){ mCurrentDetailFragment = mFragmentManager.getFragment(savedInstanceState, "current"); } initViews(); mNavigationFragment.setHighlightCurrent(mMultiPane); } private void initViews(){ setContentView(R.layout.dualpane); if(findViewById(R.id.detail_view) != null){ mMultiPane = true; } else { mMultiPane = false; } //Force Multipane Layout if User selected the option for it if(!mMultiPane && DreamDroid.SP.getBoolean("force_multipane", false)){ setContentView(R.layout.forced_dualpane); mMultiPane = true; } FragmentTransaction ft = mFragmentManager.beginTransaction(); showFragment(ft, R.id.navigation_view, mNavigationFragment); if(mCurrentDetailFragment != null){ showFragment(ft, R.id.detail_view, mCurrentDetailFragment); mCallBackHandler = (ActivityCallbackHandler) mCurrentDetailFragment; } else { } ft.commit(); mActiveProfile = (TextView) findViewById(R.id.TextViewProfile); + if(mActiveProfile == null){ + mActiveProfile = new TextView(this); + } mConnectionState = (TextView) findViewById(R.id.TextViewConnectionState); + if(mConnectionState == null){ + mConnectionState = new TextView(this); + } checkActiveProfile(); } private void showFragment(FragmentTransaction ft, int viewId, Fragment fragment){ if( fragment.isAdded() ){ Log.i(DreamDroid.LOG_TAG, "Fragment already added, showing"); ft.show(fragment); } else { Log.i(DreamDroid.LOG_TAG, "Fragment not added, adding"); ft.replace(viewId, fragment, fragment.getClass().getSimpleName()); } } /* * (non-Javadoc) * * @see net.reichholf.dreamdroid.abstivities.AbstractHttpListActivity# * onSaveInstanceState(android.os.Bundle) */ @Override public void onSaveInstanceState(Bundle outState) { mFragmentManager.putFragment(outState, "navigation", mNavigationFragment); if(mCurrentDetailFragment != null){ mFragmentManager.putFragment(outState, "current", mCurrentDetailFragment); } super.onSaveInstanceState(outState); } @Override public void onResume(){ super.onResume(); } /** * */ public void checkActiveProfile() { setProfileName(); if (mCheckProfileTask != null) { mCheckProfileTask.cancel(true); } mCheckProfileTask = new CheckProfileTask(); mCheckProfileTask.execute(); } /** * */ public void setProfileName() { mActiveProfile.setText(DreamDroid.PROFILE.getName()); } /** * @param state */ private void setConnectionState(String state) { mConnectionState.setText(state); setProgressBarIndeterminateVisibility(false); // TODO setAvailableFeatures(); } /** * @param fragmentClass */ @SuppressWarnings("rawtypes") public void showDetails(Class fragmentClass){ if(mMultiPane){ try { Fragment fragment = (Fragment) fragmentClass.newInstance(); showDetails(fragment); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Intent intent = new Intent(this, SimpleFragmentActivity.class); intent.putExtra("fragmentClass", fragmentClass); startActivity(intent); } } @Override public void showDetails(Fragment fragment){ showDetails(fragment, false); } public void back(){ mFragmentManager.popBackStackImmediate(); } /** * @param fragment * @throws IllegalAccessException * @throws InstantiationException */ @Override public void showDetails(Fragment fragment, boolean addToBackStack){ mCallBackHandler = (ActivityCallbackHandler) fragment; if(mMultiPane){ FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if(mCurrentDetailFragment != null){ if(mCurrentDetailFragment.isVisible()){ //TODO fix this hack (remove current fragment just to readd it in showFragment, do we really have to do that?) ft.remove(mCurrentDetailFragment); } } mCurrentDetailFragment = fragment; showFragment(ft, R.id.detail_view, fragment); if(addToBackStack){ ft.addToBackStack(null); } ft.commit(); } else { //TODO Error Handling Intent intent = new Intent(this, SimpleFragmentActivity.class); intent.putExtra("fragmentClass", fragment.getClass()); intent.putExtras(fragment.getArguments()); startActivity(intent); } } @Override public void setTitle(CharSequence title){ if(mMultiPane){ TextView t = (TextView) findViewById(R.id.detail_title); t.bringToFront(); String replaceMe = getText(R.string.app_name) + "::"; t.setText(title.toString().replace(replaceMe, "")); return; } super.setTitle(title); } public void setIsNavgationDialog(boolean is){ isNavigationDialog = is; } @Override protected Dialog onCreateDialog(int id){ Dialog dialog = null; if(isNavigationDialog){ dialog = mNavigationFragment.onCreateDialog(id); isNavigationDialog = false; } else { dialog = mCallBackHandler.onCreateDialog(id); } if(dialog == null){ dialog = super.onCreateDialog(id); } return dialog; } @Override public boolean onKeyDown(int keyCode, KeyEvent event){ if(mCallBackHandler != null){ if(mCallBackHandler.onKeyDown(keyCode, event)){ return true; } } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event){ if(mCallBackHandler != null){ if(mCallBackHandler.onKeyUp(keyCode, event)){ return true; } } return super.onKeyUp(keyCode, event); } public void onProfileChanged(){ checkActiveProfile(); } public boolean isMultiPane(){ return mMultiPane; } public void finish(boolean finishFragment){ if(mMultiPane && finishFragment){ //TODO finish() for Fragment // mFragmentManager.popBackStackImmediate(); } else { super.finish(); } } }
false
true
private void initViews(){ setContentView(R.layout.dualpane); if(findViewById(R.id.detail_view) != null){ mMultiPane = true; } else { mMultiPane = false; } //Force Multipane Layout if User selected the option for it if(!mMultiPane && DreamDroid.SP.getBoolean("force_multipane", false)){ setContentView(R.layout.forced_dualpane); mMultiPane = true; } FragmentTransaction ft = mFragmentManager.beginTransaction(); showFragment(ft, R.id.navigation_view, mNavigationFragment); if(mCurrentDetailFragment != null){ showFragment(ft, R.id.detail_view, mCurrentDetailFragment); mCallBackHandler = (ActivityCallbackHandler) mCurrentDetailFragment; } else { } ft.commit(); mActiveProfile = (TextView) findViewById(R.id.TextViewProfile); mConnectionState = (TextView) findViewById(R.id.TextViewConnectionState); checkActiveProfile(); }
private void initViews(){ setContentView(R.layout.dualpane); if(findViewById(R.id.detail_view) != null){ mMultiPane = true; } else { mMultiPane = false; } //Force Multipane Layout if User selected the option for it if(!mMultiPane && DreamDroid.SP.getBoolean("force_multipane", false)){ setContentView(R.layout.forced_dualpane); mMultiPane = true; } FragmentTransaction ft = mFragmentManager.beginTransaction(); showFragment(ft, R.id.navigation_view, mNavigationFragment); if(mCurrentDetailFragment != null){ showFragment(ft, R.id.detail_view, mCurrentDetailFragment); mCallBackHandler = (ActivityCallbackHandler) mCurrentDetailFragment; } else { } ft.commit(); mActiveProfile = (TextView) findViewById(R.id.TextViewProfile); if(mActiveProfile == null){ mActiveProfile = new TextView(this); } mConnectionState = (TextView) findViewById(R.id.TextViewConnectionState); if(mConnectionState == null){ mConnectionState = new TextView(this); } checkActiveProfile(); }
diff --git a/src/com/oresomecraft/maps/battles/maps/Equator.java b/src/com/oresomecraft/maps/battles/maps/Equator.java index 97271b2..4b81d41 100644 --- a/src/com/oresomecraft/maps/battles/maps/Equator.java +++ b/src/com/oresomecraft/maps/battles/maps/Equator.java @@ -1,117 +1,110 @@ package com.oresomecraft.maps.battles.maps; import com.oresomecraft.maps.MapConfig; import com.oresomecraft.maps.battles.BattleMap; import com.oresomecraft.maps.battles.IBattleMap; import org.bukkit.*; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.*; import com.oresomecraft.OresomeBattles.api.*; @MapConfig public class Equator extends BattleMap implements IBattleMap, Listener { public Equator() { super.initiate(this, name, fullName, creators, modes); setTDMTime(8); setAllowBuild(false); disableDrops(new Material[]{Material.GLASS, Material.LEATHER_HELMET, Material.STONE_SWORD}); setAutoSpawnProtection(4); } String name = "equator"; String fullName = "Equator"; String creators = "Afridge1O1, SuperDuckFace, Numinex, XUHAVON, beadycottonwood and ViolentShadow"; Gamemode[] modes = {Gamemode.TDM, Gamemode.CTF}; public void readyTDMSpawns() { redSpawns.add(new Location(w, 53, 75, -24)); redSpawns.add(new Location(w, 26, 74, -50)); redSpawns.add(new Location(w, 60, 75, 12)); blueSpawns.add(new Location(w, -53, 75, 24)); blueSpawns.add(new Location(w, -26, 74, 50)); blueSpawns.add(new Location(w, -60, 74, -12)); Location redFlag = new Location(w, 75, 76, -4); Location blueFlag = new Location(w, -75, 76, 4); setCTFFlags(name, redFlag, blueFlag); setKoTHMonument(new Location(w, 0, 69, 0)); } public void readyFFASpawns() { FFASpawns.add(new Location(w, 2, 84, -48)); FFASpawns.add(new Location(w, -3, 84, 58)); } public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); - ItemStack BLUE_GLASS = new ItemStack(Material.GLASS, (short) 11); - ItemStack RED_GLASS = new ItemStack(Material.GLASS, (short) 14); + ItemStack BLUE_GLASS = new ItemStack(Material.GLASS, 1, (short) 11); + ItemStack RED_GLASS = new ItemStack(Material.GLASS, 1, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); ItemStack LEATHER_PANTS = new ItemStack(Material.LEATHER_LEGGINGS, 1); ItemStack LEATHER_BOOTS = new ItemStack(Material.LEATHER_BOOTS, 1); ItemStack SWORD = new ItemStack(Material.STONE_SWORD, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 5); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack HEALTH = new ItemStack(Material.GOLDEN_APPLE, 3); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack TORCH = new ItemStack(Material.TORCH, 1); - ItemStack OPSWORD = new ItemStack(Material.DIAMOND_SWORD, 1); ItemMeta torch = TORCH.getItemMeta(); torch.setDisplayName(ChatColor.RED + "Blazing Stick"); TORCH.setItemMeta(torch); TORCH.addUnsafeEnchantment(Enchantment.FIRE_ASPECT, 1); - ItemMeta opsword = OPSWORD.getItemMeta(); - opsword.setDisplayName(ChatColor.BLUE + "Soul Destroyer"); - OPSWORD.setItemMeta(opsword); - OPSWORD.setDurability((short) 1561); - OPSWORD.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 10); - InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS}); + InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS, TORCH}); p.getInventory().setBoots(LEATHER_BOOTS); p.getInventory().setLeggings(LEATHER_PANTS); p.getInventory().setChestplate(LEATHER_CHESTPLATE); if(p.getTeam() == Team.TDM_RED); p.getInventory().setHelmet(RED_GLASS); if(p.getTeam() == Team.TDM_BLUE); p.getInventory().setHelmet(BLUE_GLASS); i.setItem(0, SWORD); - i.setItem(1, OPSWORD); - i.setItem(2, BOW); - i.setItem(3, STEAK); - i.setItem(4, HEALTH); - i.setItem(5, EXP); - i.setItem(6, TORCH); + i.setItem(1, BOW); + i.setItem(2, STEAK); + i.setItem(3, HEALTH); + i.setItem(4, EXP); + i.setItem(5, TORCH); i.setItem(10, ARROWS); } // Region. (Top corner block and bottom corner block. // Top left corner. public int x1 = 103; public int y1 = 115; public int z1 = 103; //Bottom right corner. public int x2 = -103; public int y2 = 0; public int z2 = -103; }
false
true
public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack BLUE_GLASS = new ItemStack(Material.GLASS, (short) 11); ItemStack RED_GLASS = new ItemStack(Material.GLASS, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); ItemStack LEATHER_PANTS = new ItemStack(Material.LEATHER_LEGGINGS, 1); ItemStack LEATHER_BOOTS = new ItemStack(Material.LEATHER_BOOTS, 1); ItemStack SWORD = new ItemStack(Material.STONE_SWORD, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 5); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack HEALTH = new ItemStack(Material.GOLDEN_APPLE, 3); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack TORCH = new ItemStack(Material.TORCH, 1); ItemStack OPSWORD = new ItemStack(Material.DIAMOND_SWORD, 1); ItemMeta torch = TORCH.getItemMeta(); torch.setDisplayName(ChatColor.RED + "Blazing Stick"); TORCH.setItemMeta(torch); TORCH.addUnsafeEnchantment(Enchantment.FIRE_ASPECT, 1); ItemMeta opsword = OPSWORD.getItemMeta(); opsword.setDisplayName(ChatColor.BLUE + "Soul Destroyer"); OPSWORD.setItemMeta(opsword); OPSWORD.setDurability((short) 1561); OPSWORD.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, 10); InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS}); p.getInventory().setBoots(LEATHER_BOOTS); p.getInventory().setLeggings(LEATHER_PANTS); p.getInventory().setChestplate(LEATHER_CHESTPLATE); if(p.getTeam() == Team.TDM_RED); p.getInventory().setHelmet(RED_GLASS); if(p.getTeam() == Team.TDM_BLUE); p.getInventory().setHelmet(BLUE_GLASS); i.setItem(0, SWORD); i.setItem(1, OPSWORD); i.setItem(2, BOW); i.setItem(3, STEAK); i.setItem(4, HEALTH); i.setItem(5, EXP); i.setItem(6, TORCH); i.setItem(10, ARROWS); }
public void applyInventory(final BattlePlayer p) { Inventory i = p.getInventory(); ItemStack BLUE_GLASS = new ItemStack(Material.GLASS, 1, (short) 11); ItemStack RED_GLASS = new ItemStack(Material.GLASS, 1, (short) 14); ItemStack LEATHER_CHESTPLATE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); ItemStack LEATHER_PANTS = new ItemStack(Material.LEATHER_LEGGINGS, 1); ItemStack LEATHER_BOOTS = new ItemStack(Material.LEATHER_BOOTS, 1); ItemStack SWORD = new ItemStack(Material.STONE_SWORD, 1); ItemStack BOW = new ItemStack(Material.BOW, 1); ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 5); ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5); ItemStack HEALTH = new ItemStack(Material.GOLDEN_APPLE, 3); ItemStack ARROWS = new ItemStack(Material.ARROW, 64); ItemStack TORCH = new ItemStack(Material.TORCH, 1); ItemMeta torch = TORCH.getItemMeta(); torch.setDisplayName(ChatColor.RED + "Blazing Stick"); TORCH.setItemMeta(torch); TORCH.addUnsafeEnchantment(Enchantment.FIRE_ASPECT, 1); InvUtils.colourArmourAccordingToTeam(p, new ItemStack[]{LEATHER_CHESTPLATE, LEATHER_PANTS, LEATHER_BOOTS, TORCH}); p.getInventory().setBoots(LEATHER_BOOTS); p.getInventory().setLeggings(LEATHER_PANTS); p.getInventory().setChestplate(LEATHER_CHESTPLATE); if(p.getTeam() == Team.TDM_RED); p.getInventory().setHelmet(RED_GLASS); if(p.getTeam() == Team.TDM_BLUE); p.getInventory().setHelmet(BLUE_GLASS); i.setItem(0, SWORD); i.setItem(1, BOW); i.setItem(2, STEAK); i.setItem(3, HEALTH); i.setItem(4, EXP); i.setItem(5, TORCH); i.setItem(10, ARROWS); }
diff --git a/org.keplerproject.ldt.core/src/org/keplerproject/ldt/core/luadoc/LuadocGenerator.java b/org.keplerproject.ldt.core/src/org/keplerproject/ldt/core/luadoc/LuadocGenerator.java index cdbc17d..50092d4 100644 --- a/org.keplerproject.ldt.core/src/org/keplerproject/ldt/core/luadoc/LuadocGenerator.java +++ b/org.keplerproject.ldt.core/src/org/keplerproject/ldt/core/luadoc/LuadocGenerator.java @@ -1,195 +1,195 @@ /* * Copyright (C) 2003-2007 Kepler Project. * * 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 org.keplerproject.ldt.core.luadoc; import java.util.HashMap; import java.util.Map; import org.keplerproject.ldt.core.ILuaEntry; import org.keplerproject.ldt.core.lua.modules.LuaModuleLoader; import org.keplerproject.luajava.JavaFunction; import org.keplerproject.luajava.LuaException; import org.keplerproject.luajava.LuaObject; import org.keplerproject.luajava.LuaState; import org.keplerproject.luajava.LuaStateFactory; import org.keplerproject.luajava.luafilesystem.JLuaFileSystem; /** * Runs a luadoc engine to generate entries. * * @author jasonsantos * @version $Id$ */ public class LuadocGenerator { private static LuadocGenerator singleton; protected Map<String, ILuaEntry> luaEntryIndex; public LuadocGenerator() { super(); luaEntryIndex = new HashMap<String, ILuaEntry>(); } public static LuadocGenerator getInstance() { if (singleton == null) singleton = new LuadocGenerator(); return singleton; } // register the java functions to create the entries public Map<String, ILuaEntry> generate(String fileName) { final Map<String, ILuaEntry> m = new HashMap<String, ILuaEntry>(); try { LuaState L = LuaStateFactory.newLuaState(); L.openLibs(); JLuaFileSystem.register(L); LuaModuleLoader.register(L); L.pushJavaFunction(new JavaFunction(L) { @Override public int execute() throws LuaException { // String t = getParam(1).toString(); LuaObject fileOrModuleName = getParam(2); LuaObject entryName = getParam(3); LuaObject entryType = getParam(4); LuaObject entrySummary = getParam(5); LuaObject entryDescription = getParam(6); LuaObject entryComment = getParam(7); LuaObject entryCode = getParam(8); LuadocEntry e = new LuadocEntry(); e.setModule(fileOrModuleName.toString()); e.setEntryType(entryType.toString()); e.setName(entryName.toString()); e.setSummary(entrySummary.toString()); e.setDescription(entryDescription.toString()); e.setComment(entryComment.toString()); e.setCode(entryCode.toString()); m.put(entryName.toString(), e); return 0; } }); L.setGlobal("addDocumentationEntry"); int result = L.LdoString("require 'lfs' " + "\n" + "require 'luadoc' " + "\n" + "local files = {'" + fileName + "'}" + "\n" - + "require 'luadoc.config'" - + "local options = luadoc.config\n" + + "local options = require 'luadoc.config'" + + "\n" + "module ('loopback.doclet', package.seeall)" + "\n" + "t = {}" + "\n" + "function start(doc)" + "\n" + "local fileOrModuleName = ''" + "\n" + "r = function(d)" + "\n" + "for k, v in pairs(d) do" + "\n" + "if type(v)=='table' then" + "\n" + "if v.class=='function' then" + "\n" + "addDocumentationEntry(" + "fileOrModuleName, " + "v.name, " + "v.class, " + "v.summary," + "v.description," + "table.concat(v.comment, '\\n')," + "table.concat(v.code, '\\n')" + ")" + "\n" + "elseif v.type == 'file' or v.type == 'module' then" + "\n" + "fileOrModuleName = v.name" + "\n" + "end" + "\n" + "r(v)" + "\n" + "end" + "\n" + "end" + "\n" + "end" + "\n" + "r(doc)" + "end" + "\n" + "options.doclet = 'loopback.doclet'" + "\n" + "luadoc.main(files, options)"); if (result != 0) { String s = L.toString(-1); System.out.println(s); } L.close(); return m; } catch (LuaException e) { } // collect the documentation blocks, indexed by name // load the documentation blocks into the resulting map return null; } public Map<String, ILuaEntry> getLuaEntryIndex() { return luaEntryIndex; } public String getDocumentationText(String token) { LuadocEntry l = (LuadocEntry) getLuaEntryIndex().get(token); String doc = null; if (l != null) { // TODO: enhance the summary with HTML formatting doc = l.getComment(); // TODO: enhance the non-summary value with module information if (doc == null || doc.length() == 0) doc = l.getCode(); if (doc == null || doc.length() == 0) doc = l.getName(); } return doc; } }
true
true
public Map<String, ILuaEntry> generate(String fileName) { final Map<String, ILuaEntry> m = new HashMap<String, ILuaEntry>(); try { LuaState L = LuaStateFactory.newLuaState(); L.openLibs(); JLuaFileSystem.register(L); LuaModuleLoader.register(L); L.pushJavaFunction(new JavaFunction(L) { @Override public int execute() throws LuaException { // String t = getParam(1).toString(); LuaObject fileOrModuleName = getParam(2); LuaObject entryName = getParam(3); LuaObject entryType = getParam(4); LuaObject entrySummary = getParam(5); LuaObject entryDescription = getParam(6); LuaObject entryComment = getParam(7); LuaObject entryCode = getParam(8); LuadocEntry e = new LuadocEntry(); e.setModule(fileOrModuleName.toString()); e.setEntryType(entryType.toString()); e.setName(entryName.toString()); e.setSummary(entrySummary.toString()); e.setDescription(entryDescription.toString()); e.setComment(entryComment.toString()); e.setCode(entryCode.toString()); m.put(entryName.toString(), e); return 0; } }); L.setGlobal("addDocumentationEntry"); int result = L.LdoString("require 'lfs' " + "\n" + "require 'luadoc' " + "\n" + "local files = {'" + fileName + "'}" + "\n" + "require 'luadoc.config'" + "local options = luadoc.config\n" + "module ('loopback.doclet', package.seeall)" + "\n" + "t = {}" + "\n" + "function start(doc)" + "\n" + "local fileOrModuleName = ''" + "\n" + "r = function(d)" + "\n" + "for k, v in pairs(d) do" + "\n" + "if type(v)=='table' then" + "\n" + "if v.class=='function' then" + "\n" + "addDocumentationEntry(" + "fileOrModuleName, " + "v.name, " + "v.class, " + "v.summary," + "v.description," + "table.concat(v.comment, '\\n')," + "table.concat(v.code, '\\n')" + ")" + "\n" + "elseif v.type == 'file' or v.type == 'module' then" + "\n" + "fileOrModuleName = v.name" + "\n" + "end" + "\n" + "r(v)" + "\n" + "end" + "\n" + "end" + "\n" + "end" + "\n" + "r(doc)" + "end" + "\n" + "options.doclet = 'loopback.doclet'" + "\n" + "luadoc.main(files, options)"); if (result != 0) { String s = L.toString(-1); System.out.println(s); } L.close(); return m; } catch (LuaException e) { } // collect the documentation blocks, indexed by name // load the documentation blocks into the resulting map return null; }
public Map<String, ILuaEntry> generate(String fileName) { final Map<String, ILuaEntry> m = new HashMap<String, ILuaEntry>(); try { LuaState L = LuaStateFactory.newLuaState(); L.openLibs(); JLuaFileSystem.register(L); LuaModuleLoader.register(L); L.pushJavaFunction(new JavaFunction(L) { @Override public int execute() throws LuaException { // String t = getParam(1).toString(); LuaObject fileOrModuleName = getParam(2); LuaObject entryName = getParam(3); LuaObject entryType = getParam(4); LuaObject entrySummary = getParam(5); LuaObject entryDescription = getParam(6); LuaObject entryComment = getParam(7); LuaObject entryCode = getParam(8); LuadocEntry e = new LuadocEntry(); e.setModule(fileOrModuleName.toString()); e.setEntryType(entryType.toString()); e.setName(entryName.toString()); e.setSummary(entrySummary.toString()); e.setDescription(entryDescription.toString()); e.setComment(entryComment.toString()); e.setCode(entryCode.toString()); m.put(entryName.toString(), e); return 0; } }); L.setGlobal("addDocumentationEntry"); int result = L.LdoString("require 'lfs' " + "\n" + "require 'luadoc' " + "\n" + "local files = {'" + fileName + "'}" + "\n" + "local options = require 'luadoc.config'" + "\n" + "module ('loopback.doclet', package.seeall)" + "\n" + "t = {}" + "\n" + "function start(doc)" + "\n" + "local fileOrModuleName = ''" + "\n" + "r = function(d)" + "\n" + "for k, v in pairs(d) do" + "\n" + "if type(v)=='table' then" + "\n" + "if v.class=='function' then" + "\n" + "addDocumentationEntry(" + "fileOrModuleName, " + "v.name, " + "v.class, " + "v.summary," + "v.description," + "table.concat(v.comment, '\\n')," + "table.concat(v.code, '\\n')" + ")" + "\n" + "elseif v.type == 'file' or v.type == 'module' then" + "\n" + "fileOrModuleName = v.name" + "\n" + "end" + "\n" + "r(v)" + "\n" + "end" + "\n" + "end" + "\n" + "end" + "\n" + "r(doc)" + "end" + "\n" + "options.doclet = 'loopback.doclet'" + "\n" + "luadoc.main(files, options)"); if (result != 0) { String s = L.toString(-1); System.out.println(s); } L.close(); return m; } catch (LuaException e) { } // collect the documentation blocks, indexed by name // load the documentation blocks into the resulting map return null; }
diff --git a/src/main/java/utilits/service/EquipmentService.java b/src/main/java/utilits/service/EquipmentService.java index 3a082cb..af5ac3b 100644 --- a/src/main/java/utilits/service/EquipmentService.java +++ b/src/main/java/utilits/service/EquipmentService.java @@ -1,105 +1,104 @@ package utilits.service; import org.apache.log4j.Logger; import org.apache.poi.ss.usermodel.*; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import utilits.entity.Equipment; import javax.annotation.Resource; import java.io.InputStream; import java.util.List; /** * Here will be javadoc * * @author karlovsky * @since 1.0 */ @Service("equipmentService") @Transactional public class EquipmentService { protected static Logger logger = Logger.getLogger(EquipmentService.class); @Resource(name = "sessionFactory") private SessionFactory sessionFactory; @SuppressWarnings("unchecked") public List<Equipment> getEquipment() { logger.debug("Start loading equipment..."); Session session = sessionFactory.getCurrentSession(); return session.createCriteria(Equipment.class).list(); } public boolean importFile(InputStream is) { try { Workbook wb = WorkbookFactory.create(is); Sheet sheet = wb.getSheetAt(0); int i = 0; for (Row row : sheet) { i++; if (i > 1) { - int j = 0; Equipment equipment = new Equipment(); - for (Cell cell : row) { + for (int j = 0; j <= 8; j++) { + Cell cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK); String value = cell.getStringCellValue(); switch (j) { case 0: equipment.setIpAddress(value); break; case 1: equipment.setType(value); break; case 2: equipment.setUsername(value); break; case 3: equipment.setLogin(value); break; case 4: equipment.setPassword(value); break; case 5: equipment.setClientName(value); break; case 6: equipment.setPlacementAddress(value); break; case 7: equipment.setApplicationNumber(value); break; case 8: equipment.setDescription(value); break; } - j++; } Session session = sessionFactory.getCurrentSession(); Equipment oldEquipment = (Equipment) session.createCriteria(Equipment.class) .add(Restrictions.eq("ipAddress", equipment.getIpAddress())) .uniqueResult(); if (oldEquipment != null) { oldEquipment.setType(equipment.getType()); oldEquipment.setUsername(equipment.getUsername()); oldEquipment.setLogin(equipment.getLogin()); oldEquipment.setPassword(equipment.getPassword()); oldEquipment.setClientName(equipment.getClientName()); oldEquipment.setPlacementAddress(equipment.getPlacementAddress()); oldEquipment.setApplicationNumber(equipment.getApplicationNumber()); oldEquipment.setDescription(equipment.getDescription()); } else { session.save(equipment); } } } return true; } catch (Exception e) { logger.error("Importiong error...", e); return false; } } }
false
true
public boolean importFile(InputStream is) { try { Workbook wb = WorkbookFactory.create(is); Sheet sheet = wb.getSheetAt(0); int i = 0; for (Row row : sheet) { i++; if (i > 1) { int j = 0; Equipment equipment = new Equipment(); for (Cell cell : row) { String value = cell.getStringCellValue(); switch (j) { case 0: equipment.setIpAddress(value); break; case 1: equipment.setType(value); break; case 2: equipment.setUsername(value); break; case 3: equipment.setLogin(value); break; case 4: equipment.setPassword(value); break; case 5: equipment.setClientName(value); break; case 6: equipment.setPlacementAddress(value); break; case 7: equipment.setApplicationNumber(value); break; case 8: equipment.setDescription(value); break; } j++; } Session session = sessionFactory.getCurrentSession(); Equipment oldEquipment = (Equipment) session.createCriteria(Equipment.class) .add(Restrictions.eq("ipAddress", equipment.getIpAddress())) .uniqueResult(); if (oldEquipment != null) { oldEquipment.setType(equipment.getType()); oldEquipment.setUsername(equipment.getUsername()); oldEquipment.setLogin(equipment.getLogin()); oldEquipment.setPassword(equipment.getPassword()); oldEquipment.setClientName(equipment.getClientName()); oldEquipment.setPlacementAddress(equipment.getPlacementAddress()); oldEquipment.setApplicationNumber(equipment.getApplicationNumber()); oldEquipment.setDescription(equipment.getDescription()); } else { session.save(equipment); } } } return true; } catch (Exception e) { logger.error("Importiong error...", e); return false; } }
public boolean importFile(InputStream is) { try { Workbook wb = WorkbookFactory.create(is); Sheet sheet = wb.getSheetAt(0); int i = 0; for (Row row : sheet) { i++; if (i > 1) { Equipment equipment = new Equipment(); for (int j = 0; j <= 8; j++) { Cell cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK); String value = cell.getStringCellValue(); switch (j) { case 0: equipment.setIpAddress(value); break; case 1: equipment.setType(value); break; case 2: equipment.setUsername(value); break; case 3: equipment.setLogin(value); break; case 4: equipment.setPassword(value); break; case 5: equipment.setClientName(value); break; case 6: equipment.setPlacementAddress(value); break; case 7: equipment.setApplicationNumber(value); break; case 8: equipment.setDescription(value); break; } } Session session = sessionFactory.getCurrentSession(); Equipment oldEquipment = (Equipment) session.createCriteria(Equipment.class) .add(Restrictions.eq("ipAddress", equipment.getIpAddress())) .uniqueResult(); if (oldEquipment != null) { oldEquipment.setType(equipment.getType()); oldEquipment.setUsername(equipment.getUsername()); oldEquipment.setLogin(equipment.getLogin()); oldEquipment.setPassword(equipment.getPassword()); oldEquipment.setClientName(equipment.getClientName()); oldEquipment.setPlacementAddress(equipment.getPlacementAddress()); oldEquipment.setApplicationNumber(equipment.getApplicationNumber()); oldEquipment.setDescription(equipment.getDescription()); } else { session.save(equipment); } } } return true; } catch (Exception e) { logger.error("Importiong error...", e); return false; } }
diff --git a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/utils/EditingUtils.java b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/utils/EditingUtils.java index 97f929aab..81ac802bc 100644 --- a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/utils/EditingUtils.java +++ b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/ui/utils/EditingUtils.java @@ -1,111 +1,111 @@ /******************************************************************************* * Copyright (c) 2008, 2011 Obeo. * 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: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.emf.eef.runtime.ui.utils; import org.eclipse.emf.edit.domain.EditingDomain; import org.eclipse.emf.edit.domain.IEditingDomainProvider; import org.eclipse.emf.eef.runtime.ui.UIConstants; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; /** * @author <a href="mailto:[email protected]">Goulwen Le Fur</a> */ public class EditingUtils { /** * @param part * the workbench part managing the editing domain * @return if provided the editingDomain of the given workbench part */ public static EditingDomain getResourceSetFromEditor(IWorkbenchPart part) { EditingDomain editingDomain = null; - if (part instanceof IEditingDomainProvider) + if (part instanceof IEditingDomainProvider) { editingDomain = ((IEditingDomainProvider)part).getEditingDomain(); - if (part instanceof IEditorPart) { - if ((((IEditorPart)part).getAdapter(IEditingDomainProvider.class)) != null) - editingDomain = ((IEditingDomainProvider)((IEditorPart)part) + } else { + if (part.getAdapter(IEditingDomainProvider.class) != null) + editingDomain = ((IEditingDomainProvider)part .getAdapter(IEditingDomainProvider.class)).getEditingDomain(); - else if ((((IEditorPart)part).getAdapter(EditingDomain.class)) != null) - editingDomain = (EditingDomain)((IEditorPart)part).getAdapter(EditingDomain.class); + else if (part.getAdapter(EditingDomain.class) != null) + editingDomain = (EditingDomain)part.getAdapter(EditingDomain.class); } return editingDomain; } /** * Set an id to a given widget. * * @param widget * the widget where put the ID * @param value * the ID to put */ public static void setID(Control widget, Object value) { if (widget != null) widget.setData(UIConstants.EEF_WIDGET_ID_KEY, value); } /** * Return the ID of a widget? * * @param widget * the widget to inspect * @return the ID of the widget */ public static Object getID(Control widget) { if (widget != null) return widget.getData(UIConstants.EEF_WIDGET_ID_KEY); return null; } /** * Set the EEF type of widget. * * @param widget * the widget where put the ID * @param value * the type of the widget */ public static void setEEFtype(Control widget, String value) { if (widget != null) widget.setData(UIConstants.EEF_WIDGET_TYPE_KEY, value); } /** * Return the ID of a widget? * * @param widget * the widget to inspect * @return the ID of the widget */ public static String getEEFType(Control widget) { if (widget != null) { Object data = widget.getData(UIConstants.EEF_WIDGET_ID_KEY); if (data instanceof String) return (String)data; } return UIConstants.UNKNOW_EEF_TYPE; } /** * @return platform shell */ public static Shell getShell() { Shell theShell = null; if (PlatformUI.getWorkbench() != null && PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) theShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); theShell = new Shell(); return theShell; } }
false
true
public static EditingDomain getResourceSetFromEditor(IWorkbenchPart part) { EditingDomain editingDomain = null; if (part instanceof IEditingDomainProvider) editingDomain = ((IEditingDomainProvider)part).getEditingDomain(); if (part instanceof IEditorPart) { if ((((IEditorPart)part).getAdapter(IEditingDomainProvider.class)) != null) editingDomain = ((IEditingDomainProvider)((IEditorPart)part) .getAdapter(IEditingDomainProvider.class)).getEditingDomain(); else if ((((IEditorPart)part).getAdapter(EditingDomain.class)) != null) editingDomain = (EditingDomain)((IEditorPart)part).getAdapter(EditingDomain.class); } return editingDomain; }
public static EditingDomain getResourceSetFromEditor(IWorkbenchPart part) { EditingDomain editingDomain = null; if (part instanceof IEditingDomainProvider) { editingDomain = ((IEditingDomainProvider)part).getEditingDomain(); } else { if (part.getAdapter(IEditingDomainProvider.class) != null) editingDomain = ((IEditingDomainProvider)part .getAdapter(IEditingDomainProvider.class)).getEditingDomain(); else if (part.getAdapter(EditingDomain.class) != null) editingDomain = (EditingDomain)part.getAdapter(EditingDomain.class); } return editingDomain; }
diff --git a/src/me/neatmonster/spacertk/plugins/PluginsRequester.java b/src/me/neatmonster/spacertk/plugins/PluginsRequester.java index 8de3b6a..227d002 100644 --- a/src/me/neatmonster/spacertk/plugins/PluginsRequester.java +++ b/src/me/neatmonster/spacertk/plugins/PluginsRequester.java @@ -1,51 +1,47 @@ /* * This file is part of SpaceRTK (http://spacebukkit.xereo.net/). * * SpaceRTK is free software: you can redistribute it and/or modify it under the terms of the * Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license as published by the Creative * Common organization, either version 3.0 of the license, or (at your option) any later version. * * SpaceRTK 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 * Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license for more details. * * You should have received a copy of the Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) * license along with this program. If not, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>. */ package me.neatmonster.spacertk.plugins; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import org.json.simple.JSONArray; import org.json.simple.JSONValue; /** * Requests a list of plugins from BukGet */ public class PluginsRequester implements Runnable { @Override @SuppressWarnings("unchecked") public void run() { try { final URLConnection connection = new URL("http://bukget.org/api/plugins").openConnection(); final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) stringBuffer.append(line); bufferedReader.close(); PluginsManager.pluginsNames = (JSONArray) JSONValue.parse(stringBuffer.toString()); } catch (final Exception e) { - if (e instanceof IOException) { System.out.println("[SpaceBukkit] Unable to connect to BukGet, BukGet features will be disabled"); - } else { - e.printStackTrace(); - } } } }
false
true
public void run() { try { final URLConnection connection = new URL("http://bukget.org/api/plugins").openConnection(); final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) stringBuffer.append(line); bufferedReader.close(); PluginsManager.pluginsNames = (JSONArray) JSONValue.parse(stringBuffer.toString()); } catch (final Exception e) { if (e instanceof IOException) { System.out.println("[SpaceBukkit] Unable to connect to BukGet, BukGet features will be disabled"); } else { e.printStackTrace(); } } }
public void run() { try { final URLConnection connection = new URL("http://bukget.org/api/plugins").openConnection(); final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) stringBuffer.append(line); bufferedReader.close(); PluginsManager.pluginsNames = (JSONArray) JSONValue.parse(stringBuffer.toString()); } catch (final Exception e) { System.out.println("[SpaceBukkit] Unable to connect to BukGet, BukGet features will be disabled"); } }
diff --git a/src/main/java/com/twilio/sdk/TwilioUtils.java b/src/main/java/com/twilio/sdk/TwilioUtils.java index 26d6226f3..7cfa68370 100644 --- a/src/main/java/com/twilio/sdk/TwilioUtils.java +++ b/src/main/java/com/twilio/sdk/TwilioUtils.java @@ -1,91 +1,91 @@ package com.twilio.sdk; /* Copyright (c) 2013 Twilio, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class TwilioUtils { protected String authToken; public TwilioUtils(String authToken){ this.authToken = authToken; } public boolean validateRequest(String expectedSignature, String url, Map<String,String> params){ SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1"); try { - //initialize the hash algortihm + //initialize the hash algorithm Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); //sort the params alphabetically, and append the key and value of each to the url StringBuffer data = new StringBuffer(url); if(params!=null){ List<String> sortedKeys = new ArrayList<String>( params.keySet()); Collections.sort(sortedKeys); for(String s: sortedKeys){ data.append(s); String v=""; if(params.get(s)!=null ) v=params.get(s); data.append(v); } } //compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.toString().getBytes("UTF-8")); //base64-encode the hmac String signature = new String(Base64.encodeBase64(rawHmac)); return signature.equals(expectedSignature); } catch (NoSuchAlgorithmException e) { return false; } catch (InvalidKeyException e) { return false; } catch (UnsupportedEncodingException e) { return false; } } }
true
true
public boolean validateRequest(String expectedSignature, String url, Map<String,String> params){ SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1"); try { //initialize the hash algortihm Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); //sort the params alphabetically, and append the key and value of each to the url StringBuffer data = new StringBuffer(url); if(params!=null){ List<String> sortedKeys = new ArrayList<String>( params.keySet()); Collections.sort(sortedKeys); for(String s: sortedKeys){ data.append(s); String v=""; if(params.get(s)!=null ) v=params.get(s); data.append(v); } } //compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.toString().getBytes("UTF-8")); //base64-encode the hmac String signature = new String(Base64.encodeBase64(rawHmac)); return signature.equals(expectedSignature); } catch (NoSuchAlgorithmException e) { return false; } catch (InvalidKeyException e) { return false; } catch (UnsupportedEncodingException e) { return false; } }
public boolean validateRequest(String expectedSignature, String url, Map<String,String> params){ SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1"); try { //initialize the hash algorithm Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); //sort the params alphabetically, and append the key and value of each to the url StringBuffer data = new StringBuffer(url); if(params!=null){ List<String> sortedKeys = new ArrayList<String>( params.keySet()); Collections.sort(sortedKeys); for(String s: sortedKeys){ data.append(s); String v=""; if(params.get(s)!=null ) v=params.get(s); data.append(v); } } //compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.toString().getBytes("UTF-8")); //base64-encode the hmac String signature = new String(Base64.encodeBase64(rawHmac)); return signature.equals(expectedSignature); } catch (NoSuchAlgorithmException e) { return false; } catch (InvalidKeyException e) { return false; } catch (UnsupportedEncodingException e) { return false; } }
diff --git a/src/se/slashat/slashat/service/PersonalService.java b/src/se/slashat/slashat/service/PersonalService.java index 89649b2..a6ef548 100644 --- a/src/se/slashat/slashat/service/PersonalService.java +++ b/src/se/slashat/slashat/service/PersonalService.java @@ -1,59 +1,59 @@ package se.slashat.slashat.service; import se.slashat.slashat.R; import se.slashat.slashat.model.Personal; public class PersonalService { public static Personal[] getPersonal() { // Create static entries for every person. Personal[] personal = new Personal[4]; personal[0] = new Personal( - "Jezper Söderlund", + "Jezper S�derlund", R.drawable.jezper, "[email protected]", "jezperse", "http://www.jezper.se", - "En glad och bekväm herre, årsmodell 1980. Jobbar som originalare men är också aktiv inom dansmusikscenen som producenten och DJ:n Airbase." - + "\n\nHan spenderar orimligt mycket tid framför datorer och har numer helt och hållet lämnat PC-land för en hundraprocentig Apple-miljö." - + "Några Linux-dojor har han aldrig velat ha. Intresset för datorer och teknik har hängt med sedan Amiga 500:an." - + "\n\nÖvriga intressen innefattar musik, film, resor, gott öl och vin, motorcyklar, golf och egentligen allt som hör livsnjutning till."); + "En glad och bekv�m herre, �rsmodell 1980. Jobbar som originalare men �r ocks� aktiv inom dansmusikscenen som producenten och DJ:n Airbase." + + "\n\nHan spenderar orimligt mycket tid framf�r datorer och har numer helt och h�llet l�mnat PC-land f�r en hundraprocentig Apple-milj�." + + "N�gra Linux-dojor har han aldrig velat ha. Intresset f�r datorer och teknik har h�ngt med sedan Amiga 500:an." + + "\n\n�vriga intressen innefattar musik, film, resor, gott �l och vin, motorcyklar, golf och egentligen allt som h�r livsnjutning till."); personal[1] = new Personal( "Tommie Podziemski", R.drawable.tommie, "[email protected]", "tommienu", "http://www.tommie.nu", - "Tommie en tjötig och sportig serie-entreprenör med visst huvud för kod." - + "Vilket allt som oftast innebär att Tommie får en idé på fredagen, spenderar hela helgen på att koda den för att sedan lägga ner allt på måndagen." - + "\n\nKör uteslutande PC (Ubuntu och Windows), och är vad man kallar en Android-fanboy." - + "\n\nHan har en viss förkärlek till att pyssla med linux-kärror och jobbar som IT-ansvarig på ett medelstort svenskt företag och säger sällan, t.om aldrig, nej till en öl."); + "Tommie en tj�tig och sportig serie-entrepren�r med visst huvud f�r kod." + + "Vilket allt som oftast inneb�r att Tommie f�r en id� p� fredagen, spenderar hela helgen p� att koda den f�r att sedan l�gga ner allt p� m�ndagen." + + "\n\nK�r uteslutande PC (Ubuntu och Windows), och �r vad man kallar en Android-fanboy." + + "\n\nHan har en viss f�rk�rlek till att pyssla med linux-k�rror och jobbar som IT-ansvarig p� ett medelstort svenskt f�retag och s�ger s�llan, t.om aldrig, nej till en �l."); personal[2] = new Personal( "Magnus Jonasson", R.drawable.magnus, "[email protected]", "magnusjonasson", "http://www.magnusjonasson.com", - "Killen som drar upp medelåldern på Slashat-redaktionen då han är den enda i gänget som är född på 70-talet." - + "\n\nMagnus jobbar till vardags som IT-tekniker och konsult med affärssystem och Windows Server-miljöer som specialitet, men föredrar faktiskt Mac privat." - + "\n\nBeskriver sig själv som en prylnörd och är alltid hungrig på nya prylar att integrera med sitt digitala liv." - + "\n\nFörutom teknik så har en kärlek till matlagning har funnits länge och inte mycket slår hemlagat med en kall öl till. Eller två."); + "Killen som drar upp medel�ldern p� Slashat-redaktionen d� han �r den enda i g�nget som �r f�dd p� 70-talet." + + "\n\nMagnus jobbar till vardags som IT-tekniker och konsult med aff�rssystem och Windows Server-milj�er som specialitet, men f�redrar faktiskt Mac privat." + + "\n\nBeskriver sig sj�lv som en pryln�rd och �r alltid hungrig p� nya prylar att integrera med sitt digitala liv." + + "\n\nF�rutom teknik s� har en k�rlek till matlagning har funnits l�nge och inte mycket sl�r hemlagat med en kall �l till. Eller tv�."); personal[3] = new Personal( "Johan Larsson", R.drawable.johan, "[email protected]", "kottkrig", "http://johanl.se", - "Älskar allt som är interaktivt. Utvecklar till vardags multimediaproduktioner och till sängdags så utvecklar jag annat smått och gott." - + "\n\nÄr biOS så jag använder (och utvecklar) lika gärna med Android som iOS. Det finns styrkor och svagheter med allt men jag försöker att använda det som känns mest spännande för stunden." - + "\n\nArbetar hellre i OS X och Linux än i Windows när jag vill vara produktiv. Använder hellre Windows än annat när det kommer till lek & spel."); + "�lskar allt som �r interaktivt. Utvecklar till vardags multimediaproduktioner och till s�ngdags s� utvecklar jag annat sm�tt och gott." + + "\n\n�r biOS s� jag anv�nder (och utvecklar) lika g�rna med Android som iOS. Det finns styrkor och svagheter med allt men jag f�rs�ker att anv�nda det som k�nns mest sp�nnande f�r stunden." + + "\n\nArbetar hellre i OS X och Linux �n i Windows n�r jag vill vara produktiv. Anv�nder hellre Windows �n annat n�r det kommer till lek & spel."); return personal; } }
false
true
public static Personal[] getPersonal() { // Create static entries for every person. Personal[] personal = new Personal[4]; personal[0] = new Personal( "Jezper Söderlund", R.drawable.jezper, "[email protected]", "jezperse", "http://www.jezper.se", "En glad och bekväm herre, årsmodell 1980. Jobbar som originalare men är också aktiv inom dansmusikscenen som producenten och DJ:n Airbase." + "\n\nHan spenderar orimligt mycket tid framför datorer och har numer helt och hållet lämnat PC-land för en hundraprocentig Apple-miljö." + "Några Linux-dojor har han aldrig velat ha. Intresset för datorer och teknik har hängt med sedan Amiga 500:an." + "\n\nÖvriga intressen innefattar musik, film, resor, gott öl och vin, motorcyklar, golf och egentligen allt som hör livsnjutning till."); personal[1] = new Personal( "Tommie Podziemski", R.drawable.tommie, "[email protected]", "tommienu", "http://www.tommie.nu", "Tommie en tjötig och sportig serie-entreprenör med visst huvud för kod." + "Vilket allt som oftast innebär att Tommie får en idé på fredagen, spenderar hela helgen på att koda den för att sedan lägga ner allt på måndagen." + "\n\nKör uteslutande PC (Ubuntu och Windows), och är vad man kallar en Android-fanboy." + "\n\nHan har en viss förkärlek till att pyssla med linux-kärror och jobbar som IT-ansvarig på ett medelstort svenskt företag och säger sällan, t.om aldrig, nej till en öl."); personal[2] = new Personal( "Magnus Jonasson", R.drawable.magnus, "[email protected]", "magnusjonasson", "http://www.magnusjonasson.com", "Killen som drar upp medelåldern på Slashat-redaktionen då han är den enda i gänget som är född på 70-talet." + "\n\nMagnus jobbar till vardags som IT-tekniker och konsult med affärssystem och Windows Server-miljöer som specialitet, men föredrar faktiskt Mac privat." + "\n\nBeskriver sig själv som en prylnörd och är alltid hungrig på nya prylar att integrera med sitt digitala liv." + "\n\nFörutom teknik så har en kärlek till matlagning har funnits länge och inte mycket slår hemlagat med en kall öl till. Eller två."); personal[3] = new Personal( "Johan Larsson", R.drawable.johan, "[email protected]", "kottkrig", "http://johanl.se", "Älskar allt som är interaktivt. Utvecklar till vardags multimediaproduktioner och till sängdags så utvecklar jag annat smått och gott." + "\n\nÄr biOS så jag använder (och utvecklar) lika gärna med Android som iOS. Det finns styrkor och svagheter med allt men jag försöker att använda det som känns mest spännande för stunden." + "\n\nArbetar hellre i OS X och Linux än i Windows när jag vill vara produktiv. Använder hellre Windows än annat när det kommer till lek & spel."); return personal; }
public static Personal[] getPersonal() { // Create static entries for every person. Personal[] personal = new Personal[4]; personal[0] = new Personal( "Jezper S�derlund", R.drawable.jezper, "[email protected]", "jezperse", "http://www.jezper.se", "En glad och bekv�m herre, �rsmodell 1980. Jobbar som originalare men �r ocks� aktiv inom dansmusikscenen som producenten och DJ:n Airbase." + "\n\nHan spenderar orimligt mycket tid framf�r datorer och har numer helt och h�llet l�mnat PC-land f�r en hundraprocentig Apple-milj�." + "N�gra Linux-dojor har han aldrig velat ha. Intresset f�r datorer och teknik har h�ngt med sedan Amiga 500:an." + "\n\n�vriga intressen innefattar musik, film, resor, gott �l och vin, motorcyklar, golf och egentligen allt som h�r livsnjutning till."); personal[1] = new Personal( "Tommie Podziemski", R.drawable.tommie, "[email protected]", "tommienu", "http://www.tommie.nu", "Tommie en tj�tig och sportig serie-entrepren�r med visst huvud f�r kod." + "Vilket allt som oftast inneb�r att Tommie f�r en id� p� fredagen, spenderar hela helgen p� att koda den f�r att sedan l�gga ner allt p� m�ndagen." + "\n\nK�r uteslutande PC (Ubuntu och Windows), och �r vad man kallar en Android-fanboy." + "\n\nHan har en viss f�rk�rlek till att pyssla med linux-k�rror och jobbar som IT-ansvarig p� ett medelstort svenskt f�retag och s�ger s�llan, t.om aldrig, nej till en �l."); personal[2] = new Personal( "Magnus Jonasson", R.drawable.magnus, "[email protected]", "magnusjonasson", "http://www.magnusjonasson.com", "Killen som drar upp medel�ldern p� Slashat-redaktionen d� han �r den enda i g�nget som �r f�dd p� 70-talet." + "\n\nMagnus jobbar till vardags som IT-tekniker och konsult med aff�rssystem och Windows Server-milj�er som specialitet, men f�redrar faktiskt Mac privat." + "\n\nBeskriver sig sj�lv som en pryln�rd och �r alltid hungrig p� nya prylar att integrera med sitt digitala liv." + "\n\nF�rutom teknik s� har en k�rlek till matlagning har funnits l�nge och inte mycket sl�r hemlagat med en kall �l till. Eller tv�."); personal[3] = new Personal( "Johan Larsson", R.drawable.johan, "[email protected]", "kottkrig", "http://johanl.se", "�lskar allt som �r interaktivt. Utvecklar till vardags multimediaproduktioner och till s�ngdags s� utvecklar jag annat sm�tt och gott." + "\n\n�r biOS s� jag anv�nder (och utvecklar) lika g�rna med Android som iOS. Det finns styrkor och svagheter med allt men jag f�rs�ker att anv�nda det som k�nns mest sp�nnande f�r stunden." + "\n\nArbetar hellre i OS X och Linux �n i Windows n�r jag vill vara produktiv. Anv�nder hellre Windows �n annat n�r det kommer till lek & spel."); return personal; }
diff --git a/src/com/ACM/binarycalculator/Utilities/InfixToPostfix.java b/src/com/ACM/binarycalculator/Utilities/InfixToPostfix.java index 09b4acc..71fd933 100644 --- a/src/com/ACM/binarycalculator/Utilities/InfixToPostfix.java +++ b/src/com/ACM/binarycalculator/Utilities/InfixToPostfix.java @@ -1,310 +1,310 @@ package com.ACM.binarycalculator.Utilities; /** * @author James Van Gaasbeck, ACM at UCF <[email protected]> */ import java.util.Stack; import java.util.StringTokenizer; import android.content.Context; import android.widget.Toast; import com.ACM.binarycalculator.R; import com.ACM.binarycalculator.Fragments.CalculatorBinaryFragment; import com.ACM.binarycalculator.Fragments.CalculatorDecimalFragment; import com.ACM.binarycalculator.Fragments.CalculatorHexFragment; import com.ACM.binarycalculator.Fragments.CalculatorOctalFragment; /* * This class is meant to be used to convert an infix expression into it's post fix (RPN) equivalent. * The "convertToPostfix(String infixExpression)" method is very similar to this java blog article: * http://java.macteki.com/2011/06/arithmetic-evaluator-infix-to-postfix.html * Of course it didn't fit inside our application perfectly so there are modifications to it. * * Handles negative numbers, and fractions. Also counts the number of operators * for expression grammar checks, and adds implicit multiplication signs where * needed. * * * Example: * infix = ( 6.6 + 2 ) * .5 - -8 / 4 * postFix = 6.6 2 + .5 * -8 4 / - */ public class InfixToPostfix { private static String TAG = "InfixToPostfix"; /** * Method to convert an infix expression to post-fix (RPN). Convert to * base-10 before calling this method. * * @param infixExpression * - The infix expression that is meant to be converted into it's * postFix equivalent. * @return - The postFix equivalent of the infix expression. */ public static String convertToPostfix(String infixExpression, Context appContext) { infixExpression = addImplicitMultiplicationSigns(infixExpression, appContext); if (infixExpression.length() == 0) { return ""; } // stack we use to convert Stack<String> theStack = new Stack<String>(); // the postFix string that will be returned String postfix = new String(""); // just a variable used to add space buffers String space = new String(" "); // flag variables to tell if the number is negative, and if the operator // isn't a minus/negative sign. boolean isNegative = false, safeOperator = false; // StringTokenizer to split up the expression StringTokenizer toke = new StringTokenizer(infixExpression, "x+-/)( \n", true); // loop that walks the entire expression while (toke.hasMoreElements()) { // get a token (element) String currentToken = toke.nextElement().toString(); // if the token is a number if (!(currentToken.equals("+") || currentToken.equals("x") || currentToken.equals("-") || currentToken.equals("/") || currentToken.equals("\n") || currentToken.equals(space) || currentToken.equals("(") || currentToken.equals(")"))) { // since the current token was a number, add it to the postFix // expression postfix += currentToken + space; } // if the token is an open parenthesis else if (currentToken.equals("(")) { theStack.push(currentToken); } // if the token is an operator else if (currentToken.equals("+") || currentToken.equals("x") || currentToken.equals("-") || currentToken.equals("/") || currentToken.equals("\n")) { // temporary variable to hold the minus/negative String minusOrNegativeSign = null; // if we are dealing with a minus/negative sign if (currentToken.equals("-")) { // utilize the temporary variable minusOrNegativeSign = currentToken; // check the next token to see if we are dealing with a // minus sign or a negative sign currentToken = toke.nextElement().toString(); if (!currentToken.equals(space)) { // if the next token isn't a space then we are dealing // with a negative number. // so add the number with the negative sign in front of // it isNegative = true; postfix += minusOrNegativeSign + currentToken + space; } } else { // flag variable to indicate that we aren't dealing with a // minus/negative sign safeOperator = true; } // this case means that the minus sign we've encountered is in // fact JUST a minus sign and not a negative sign. if (!isNegative && !safeOperator) { while (!theStack.isEmpty() && operatorPrecedence(theStack.peek()) >= operatorPrecedence(minusOrNegativeSign)) { postfix += theStack.pop() + space; } theStack.push(minusOrNegativeSign); } // this case means we've encountered a regular/safe // operator i.e "+ x /" if (safeOperator && !isNegative) { while (!theStack.isEmpty() && operatorPrecedence(theStack.peek()) >= operatorPrecedence(currentToken)) { postfix += theStack.pop() + space; } theStack.push(currentToken); } // reset our flag variables isNegative = false; safeOperator = false; } // if the token is a closed parenthesis else if (currentToken.equals(")")) { while (!theStack.peek().equals("(")) { postfix += theStack.pop() + space; } theStack.pop(); } // if the token is a space else if (currentToken.equals(space)) { // do nothing } } // closes while() loop // add what's in the stack to the postFix expression while (!theStack.isEmpty()) { postfix += theStack.pop() + space; } // return the new post-fix expression return postfix; } // method to assign a precedence to each operator so we can handle order of // operations correctly private static int operatorPrecedence(String operator) { int precedence = 0; if (operator.equals("+")) { precedence = 1; } else if (operator.equals("-")) { precedence = 1; } else if (operator.equals("x")) { precedence = 2; } else if (operator.equals("/")) { precedence = 2; } return precedence; } /** * This expression not only adds in implicit multiplication signs where * needed, it also counts the number of operators, which is a necessary task * for checking expression grammar rules. So this method needs to be called * every time before converting to post-fix. * * @param expression * - The expression that needs to have implicit multiplication * signs added. * @return - A new expression with implicit multiplication signs added where * needed. Example: "4.4 ( 5 ) .1" returns "4.4 x ( 5 ) x .1" */ private static String addImplicitMultiplicationSigns(String expression, Context context) { StringBuilder retVal = new StringBuilder(); for (int i = 0; i < expression.length(); i++) { Character testChar = expression.charAt(i); if (testChar.equals('x') || testChar.equals('/') || testChar.equals('+') || testChar.equals('-')) { // check if it's a negative or minus sign. if (testChar.equals('-')) { Character isNegativeOrMinusSign = expression.charAt(i + 1); if (Character.isSpaceChar(isNegativeOrMinusSign)) { CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } } else { CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } // check if there is division by 0. Let's just not allow this. if (testChar.equals('/')) { // quick and simple check to see if the expression ends with // so variation of division by zero. if (expression.endsWith("/ 0") || expression.endsWith("/ -0") || expression.endsWith("/ .0") || expression.endsWith("/ 0.0") || expression.endsWith("/ -.0") || expression.endsWith("/ -0.0")) { Toast.makeText(context, R.string.division_by_zero_error, Toast.LENGTH_SHORT).show(); return ""; } else { // check to see if the expression has division by zero // in the middle of the expression if (expression.length() > i + 2) { int zeroTestIterator = i + 2; Character isTheNumberZero = expression .charAt(zeroTestIterator); if (isTheNumberZero.equals('0') || isTheNumberZero.equals('.') || isTheNumberZero.equals('-')) { while (zeroTestIterator < expression.length() - 1 && expression .charAt(++zeroTestIterator) != ' ') { isTheNumberZero = expression .charAt(zeroTestIterator); } if (isTheNumberZero.equals('0')) { Toast.makeText(context, R.string.division_by_zero_error, Toast.LENGTH_SHORT).show(); return ""; } } } } } // closes division check. } if (testChar.equals('(')) { if (i < 2) { retVal.append(testChar.toString()); continue; } // test if most recent char was a number, if was then we // need to // add an implicit 'x' testChar = retVal.toString().charAt(i - 2); if (Character.isDigit(testChar)) { retVal.append("x ("); CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } else retVal.append("("); } else if (Character.isDigit(testChar) || testChar.toString().equals(".")) { // test if most recent char was a ")", if was then we need // to // add an implicit 'x' if (i < 2) { retVal.append(testChar.toString()); continue; } - Character implicit = retVal.toString().charAt(i - 2); + Character implicit = retVal.toString().charAt(retVal.toString().length() - 2); if (implicit.equals(')')) { retVal.append("x " + testChar.toString()); CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } else retVal.append(testChar.toString()); } else { // otherwise just add the char to the string retVal.append(testChar.toString()); } } return retVal.toString(); } }
true
true
private static String addImplicitMultiplicationSigns(String expression, Context context) { StringBuilder retVal = new StringBuilder(); for (int i = 0; i < expression.length(); i++) { Character testChar = expression.charAt(i); if (testChar.equals('x') || testChar.equals('/') || testChar.equals('+') || testChar.equals('-')) { // check if it's a negative or minus sign. if (testChar.equals('-')) { Character isNegativeOrMinusSign = expression.charAt(i + 1); if (Character.isSpaceChar(isNegativeOrMinusSign)) { CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } } else { CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } // check if there is division by 0. Let's just not allow this. if (testChar.equals('/')) { // quick and simple check to see if the expression ends with // so variation of division by zero. if (expression.endsWith("/ 0") || expression.endsWith("/ -0") || expression.endsWith("/ .0") || expression.endsWith("/ 0.0") || expression.endsWith("/ -.0") || expression.endsWith("/ -0.0")) { Toast.makeText(context, R.string.division_by_zero_error, Toast.LENGTH_SHORT).show(); return ""; } else { // check to see if the expression has division by zero // in the middle of the expression if (expression.length() > i + 2) { int zeroTestIterator = i + 2; Character isTheNumberZero = expression .charAt(zeroTestIterator); if (isTheNumberZero.equals('0') || isTheNumberZero.equals('.') || isTheNumberZero.equals('-')) { while (zeroTestIterator < expression.length() - 1 && expression .charAt(++zeroTestIterator) != ' ') { isTheNumberZero = expression .charAt(zeroTestIterator); } if (isTheNumberZero.equals('0')) { Toast.makeText(context, R.string.division_by_zero_error, Toast.LENGTH_SHORT).show(); return ""; } } } } } // closes division check. } if (testChar.equals('(')) { if (i < 2) { retVal.append(testChar.toString()); continue; } // test if most recent char was a number, if was then we // need to // add an implicit 'x' testChar = retVal.toString().charAt(i - 2); if (Character.isDigit(testChar)) { retVal.append("x ("); CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } else retVal.append("("); } else if (Character.isDigit(testChar) || testChar.toString().equals(".")) { // test if most recent char was a ")", if was then we need // to // add an implicit 'x' if (i < 2) { retVal.append(testChar.toString()); continue; } Character implicit = retVal.toString().charAt(i - 2); if (implicit.equals(')')) { retVal.append("x " + testChar.toString()); CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } else retVal.append(testChar.toString()); } else { // otherwise just add the char to the string retVal.append(testChar.toString()); } } return retVal.toString(); }
private static String addImplicitMultiplicationSigns(String expression, Context context) { StringBuilder retVal = new StringBuilder(); for (int i = 0; i < expression.length(); i++) { Character testChar = expression.charAt(i); if (testChar.equals('x') || testChar.equals('/') || testChar.equals('+') || testChar.equals('-')) { // check if it's a negative or minus sign. if (testChar.equals('-')) { Character isNegativeOrMinusSign = expression.charAt(i + 1); if (Character.isSpaceChar(isNegativeOrMinusSign)) { CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } } else { CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } // check if there is division by 0. Let's just not allow this. if (testChar.equals('/')) { // quick and simple check to see if the expression ends with // so variation of division by zero. if (expression.endsWith("/ 0") || expression.endsWith("/ -0") || expression.endsWith("/ .0") || expression.endsWith("/ 0.0") || expression.endsWith("/ -.0") || expression.endsWith("/ -0.0")) { Toast.makeText(context, R.string.division_by_zero_error, Toast.LENGTH_SHORT).show(); return ""; } else { // check to see if the expression has division by zero // in the middle of the expression if (expression.length() > i + 2) { int zeroTestIterator = i + 2; Character isTheNumberZero = expression .charAt(zeroTestIterator); if (isTheNumberZero.equals('0') || isTheNumberZero.equals('.') || isTheNumberZero.equals('-')) { while (zeroTestIterator < expression.length() - 1 && expression .charAt(++zeroTestIterator) != ' ') { isTheNumberZero = expression .charAt(zeroTestIterator); } if (isTheNumberZero.equals('0')) { Toast.makeText(context, R.string.division_by_zero_error, Toast.LENGTH_SHORT).show(); return ""; } } } } } // closes division check. } if (testChar.equals('(')) { if (i < 2) { retVal.append(testChar.toString()); continue; } // test if most recent char was a number, if was then we // need to // add an implicit 'x' testChar = retVal.toString().charAt(i - 2); if (Character.isDigit(testChar)) { retVal.append("x ("); CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } else retVal.append("("); } else if (Character.isDigit(testChar) || testChar.toString().equals(".")) { // test if most recent char was a ")", if was then we need // to // add an implicit 'x' if (i < 2) { retVal.append(testChar.toString()); continue; } Character implicit = retVal.toString().charAt(retVal.toString().length() - 2); if (implicit.equals(')')) { retVal.append("x " + testChar.toString()); CalculatorDecimalFragment.numberOfOperators++; CalculatorBinaryFragment.numberOfOperators++; CalculatorHexFragment.numberOfOperators++; CalculatorOctalFragment.numberOfOperators++; } else retVal.append(testChar.toString()); } else { // otherwise just add the char to the string retVal.append(testChar.toString()); } } return retVal.toString(); }
diff --git a/org.ollabaca.on.lang.ui/src/org/ollabaca/on/lang/ui/TextHoverProvider.java b/org.ollabaca.on.lang.ui/src/org/ollabaca/on/lang/ui/TextHoverProvider.java index bde0e73..895be18 100644 --- a/org.ollabaca.on.lang.ui/src/org/ollabaca/on/lang/ui/TextHoverProvider.java +++ b/org.ollabaca.on.lang.ui/src/org/ollabaca/on/lang/ui/TextHoverProvider.java @@ -1,40 +1,40 @@ package org.ollabaca.on.lang.ui; import org.eclipse.emf.ecore.EModelElement; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.documentation.IEObjectDocumentationProvider; import org.eclipse.xtext.ui.editor.hover.html.DefaultEObjectHoverProvider; import org.ollabaca.on.Import; import org.ollabaca.on.Instance; import org.ollabaca.on.Slot; import org.ollabaca.on.Units; public class TextHoverProvider extends DefaultEObjectHoverProvider { Units units = new Units(); @Override protected String getFirstLine(EObject o) { EModelElement element = null; if (o instanceof Import) { Import self = (Import) o; element = units.getPackage(self); } else if (o instanceof Instance) { Instance self = (Instance) o; element = units.getClassifier(self); - } else if (element instanceof Slot) { - Slot self = (Slot) element; + } else if (o instanceof Slot) { + Slot self = (Slot) o; element = units.getFeature(self); } if (element != null) { String doc = units.getDocumentation(element); if (doc != null) { return doc; } } return super.getFirstLine(o); } }
true
true
protected String getFirstLine(EObject o) { EModelElement element = null; if (o instanceof Import) { Import self = (Import) o; element = units.getPackage(self); } else if (o instanceof Instance) { Instance self = (Instance) o; element = units.getClassifier(self); } else if (element instanceof Slot) { Slot self = (Slot) element; element = units.getFeature(self); } if (element != null) { String doc = units.getDocumentation(element); if (doc != null) { return doc; } } return super.getFirstLine(o); }
protected String getFirstLine(EObject o) { EModelElement element = null; if (o instanceof Import) { Import self = (Import) o; element = units.getPackage(self); } else if (o instanceof Instance) { Instance self = (Instance) o; element = units.getClassifier(self); } else if (o instanceof Slot) { Slot self = (Slot) o; element = units.getFeature(self); } if (element != null) { String doc = units.getDocumentation(element); if (doc != null) { return doc; } } return super.getFirstLine(o); }
diff --git a/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java b/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java index 3b17e754..7a877c3f 100644 --- a/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java +++ b/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java @@ -1,196 +1,196 @@ /* * Created on 2004-12-03 * */ package org.hibernate.tool.hbm2x; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.RootClass; /** * @author max * */ public class HibernateConfigurationExporter extends AbstractExporter { private Writer output; private Properties customProperties = new Properties(); public HibernateConfigurationExporter(Configuration configuration, File outputdir) { super(configuration, outputdir); } public HibernateConfigurationExporter() { } public Properties getCustomProperties() { return customProperties; } public void setCustomProperties(Properties customProperties) { this.customProperties = customProperties; } public Writer getOutput() { return output; } public void setOutput(Writer output) { this.output = output; } /* (non-Javadoc) * @see org.hibernate.tool.hbm2x.Exporter#finish() */ public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + - " \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\r\n" + + " \"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } } /** * @param pw * @param element */ private void dump(PrintWriter pw, boolean useClass, PersistentClass element) { if(useClass) { pw.println("<mapping class=\"" + element.getClassName() + "\"/>"); } else { pw.println("<mapping resource=\"" + getMappingFileResource(element) + "\"/>"); } Iterator directSubclasses = element.getDirectSubclasses(); while (directSubclasses.hasNext() ) { PersistentClass subclass = (PersistentClass) directSubclasses.next(); dump(pw, useClass, subclass); } } /** * @param element * @return */ private String getMappingFileResource(PersistentClass element) { return element.getClassName().replace('.', '/') + ".hbm.xml"; } public String getName() { return "cfg2cfgxml"; } /** * * @param text * @return String with escaped [<,>] special characters. */ public static String forXML(String text) { if (text == null) return null; final StringBuilder result = new StringBuilder(); char[] chars = text.toCharArray(); for (int i = 0; i < chars.length; i++){ char character = chars[i]; if (character == '<') { result.append("&lt;"); } else if (character == '>'){ result.append("&gt;"); } else { result.append(character); } } return result.toString(); } }
true
true
public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + " \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } }
public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + " \"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } }
diff --git a/cdm/src/test/java/ucar/nc2/dt/grid/TestReadandCountGrib.java b/cdm/src/test/java/ucar/nc2/dt/grid/TestReadandCountGrib.java index 8ede68781..4e209133a 100644 --- a/cdm/src/test/java/ucar/nc2/dt/grid/TestReadandCountGrib.java +++ b/cdm/src/test/java/ucar/nc2/dt/grid/TestReadandCountGrib.java @@ -1,89 +1,89 @@ /* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "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 UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package ucar.nc2.dt.grid; import junit.framework.*; import ucar.nc2.TestAll; /** Count geogrid objects - sanity check when anything changes. */ public class TestReadandCountGrib extends TestCase { public TestReadandCountGrib( String name) { super(name); } public void testRead() throws Exception { // our grib reader doOne("grib1/data/","cfs.wmo", 51, 4, 6, 3); doOne("grib1/data/","eta218.grb", 14, 5, 7, 4); doOne("grib1/data/","extended.wmo", 8, 6, 10, 4); doOne("grib1/data/","ensemble.wmo", 24, 16, 18, 10); // doOne("grib1/data/","ecmf.wmo", 56, 44, 116, 58); doOne("grib1/data/","don_ETA.wmo", 28, 11, 13, 8); doOne("grib1/data/","pgbanl.fnl", 76, 15, 17, 14); doOne("grib1/data/","radar_national_rcm.grib", 1, 1, 3, 0); doOne("grib1/data/","radar_national.grib", 1, 1, 3, 0); //doOne("grib1/data/","thin.wmo", 240, 87, 117, 63); - doOne("grib1/data/","ukm.wmo", 96, 49, 69, 32); + doOne("grib1/data/","ukm.wmo", 96, 49, 72, 32); doOne("grib1/data/","AVN.wmo", 22, 9, 11, 7); doOne("grib1/data/","AVN-I.wmo", 20, 8, 10, 7); // doOne("grib1/data/","MRF.wmo", 15, 8, 10, 6); // doOne("grib1/data/","OCEAN.wmo", 4, 4, 12, 0); doOne("grib1/data/","RUC.wmo", 27, 7, 10, 5); doOne("grib1/data/","RUC2.wmo", 44, 10, 13, 5); doOne("grib1/data/","WAVE.wmo", 28, 12, 24, 4); // doOne("grib2/data/","eta2.wmo", 35, 8, 10, 7); doOne("grib2/data/","ndfd.wmo", 1, 1, 3, 0); // doOne("grib2/data/","eta218.wmo", 57, 13, 18, 10); doOne("grib2/data/","PMSL_000", 1, 1, 3, 0); doOne("grib2/data/","CLDGRIB2.2005040905", 5, 1, 3, 0); doOne("grib2/data/","LMPEF_CLM_050518_1200.grb", 1, 1, 3, 0); doOne("grib2/data/","AVOR_000.grb", 1, 2, 4, 1); // doOne("grib2/data/","AVN.5deg.wmo", 117, 13, 15, 12); // */ //TestReadandCount.doOne(TestAll.upcShareTestDataDir+"ncml/nc/narr/", "narr-a_221_20070411_0600_000.grb", 48, 13, 15, 12); } private void doOne(String dir, String filename, int ngrids, int ncoordSys, int ncoordAxes, int nVertCooordAxes) throws Exception { dir = TestAll.upcShareTestDataDir+ "grid/grib/" + dir; TestReadandCount.doOne(dir, filename, ngrids, ncoordSys, ncoordAxes, nVertCooordAxes); } public static void main( String arg[]) throws Exception { // new TestReadandCount("dummy").doOne("C:/data/conventions/wrf/","wrf.nc", 33, 5, 7, 7); // missing TSLB new TestReadandCountGrib("dummy").testRead(); // missing TSLB //new TestReadandCount("dummy").doOne(TestAll.upcShareTestDataDir+"grid/grib/grib1/data/","ukm.wmo", 96, 49, 69, 32); } }
true
true
public void testRead() throws Exception { // our grib reader doOne("grib1/data/","cfs.wmo", 51, 4, 6, 3); doOne("grib1/data/","eta218.grb", 14, 5, 7, 4); doOne("grib1/data/","extended.wmo", 8, 6, 10, 4); doOne("grib1/data/","ensemble.wmo", 24, 16, 18, 10); // doOne("grib1/data/","ecmf.wmo", 56, 44, 116, 58); doOne("grib1/data/","don_ETA.wmo", 28, 11, 13, 8); doOne("grib1/data/","pgbanl.fnl", 76, 15, 17, 14); doOne("grib1/data/","radar_national_rcm.grib", 1, 1, 3, 0); doOne("grib1/data/","radar_national.grib", 1, 1, 3, 0); //doOne("grib1/data/","thin.wmo", 240, 87, 117, 63); doOne("grib1/data/","ukm.wmo", 96, 49, 69, 32); doOne("grib1/data/","AVN.wmo", 22, 9, 11, 7); doOne("grib1/data/","AVN-I.wmo", 20, 8, 10, 7); // doOne("grib1/data/","MRF.wmo", 15, 8, 10, 6); // doOne("grib1/data/","OCEAN.wmo", 4, 4, 12, 0); doOne("grib1/data/","RUC.wmo", 27, 7, 10, 5); doOne("grib1/data/","RUC2.wmo", 44, 10, 13, 5); doOne("grib1/data/","WAVE.wmo", 28, 12, 24, 4); // doOne("grib2/data/","eta2.wmo", 35, 8, 10, 7); doOne("grib2/data/","ndfd.wmo", 1, 1, 3, 0); // doOne("grib2/data/","eta218.wmo", 57, 13, 18, 10); doOne("grib2/data/","PMSL_000", 1, 1, 3, 0); doOne("grib2/data/","CLDGRIB2.2005040905", 5, 1, 3, 0); doOne("grib2/data/","LMPEF_CLM_050518_1200.grb", 1, 1, 3, 0); doOne("grib2/data/","AVOR_000.grb", 1, 2, 4, 1); // doOne("grib2/data/","AVN.5deg.wmo", 117, 13, 15, 12); // */ //TestReadandCount.doOne(TestAll.upcShareTestDataDir+"ncml/nc/narr/", "narr-a_221_20070411_0600_000.grb", 48, 13, 15, 12); }
public void testRead() throws Exception { // our grib reader doOne("grib1/data/","cfs.wmo", 51, 4, 6, 3); doOne("grib1/data/","eta218.grb", 14, 5, 7, 4); doOne("grib1/data/","extended.wmo", 8, 6, 10, 4); doOne("grib1/data/","ensemble.wmo", 24, 16, 18, 10); // doOne("grib1/data/","ecmf.wmo", 56, 44, 116, 58); doOne("grib1/data/","don_ETA.wmo", 28, 11, 13, 8); doOne("grib1/data/","pgbanl.fnl", 76, 15, 17, 14); doOne("grib1/data/","radar_national_rcm.grib", 1, 1, 3, 0); doOne("grib1/data/","radar_national.grib", 1, 1, 3, 0); //doOne("grib1/data/","thin.wmo", 240, 87, 117, 63); doOne("grib1/data/","ukm.wmo", 96, 49, 72, 32); doOne("grib1/data/","AVN.wmo", 22, 9, 11, 7); doOne("grib1/data/","AVN-I.wmo", 20, 8, 10, 7); // doOne("grib1/data/","MRF.wmo", 15, 8, 10, 6); // doOne("grib1/data/","OCEAN.wmo", 4, 4, 12, 0); doOne("grib1/data/","RUC.wmo", 27, 7, 10, 5); doOne("grib1/data/","RUC2.wmo", 44, 10, 13, 5); doOne("grib1/data/","WAVE.wmo", 28, 12, 24, 4); // doOne("grib2/data/","eta2.wmo", 35, 8, 10, 7); doOne("grib2/data/","ndfd.wmo", 1, 1, 3, 0); // doOne("grib2/data/","eta218.wmo", 57, 13, 18, 10); doOne("grib2/data/","PMSL_000", 1, 1, 3, 0); doOne("grib2/data/","CLDGRIB2.2005040905", 5, 1, 3, 0); doOne("grib2/data/","LMPEF_CLM_050518_1200.grb", 1, 1, 3, 0); doOne("grib2/data/","AVOR_000.grb", 1, 2, 4, 1); // doOne("grib2/data/","AVN.5deg.wmo", 117, 13, 15, 12); // */ //TestReadandCount.doOne(TestAll.upcShareTestDataDir+"ncml/nc/narr/", "narr-a_221_20070411_0600_000.grb", 48, 13, 15, 12); }
diff --git a/src/org/irmacard/androidmanagement/SettingsActivity.java b/src/org/irmacard/androidmanagement/SettingsActivity.java index e3221aa..6d65de6 100644 --- a/src/org/irmacard/androidmanagement/SettingsActivity.java +++ b/src/org/irmacard/androidmanagement/SettingsActivity.java @@ -1,88 +1,88 @@ /** * CredentialDetailActivity.java * * 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/>. * * Copyright (C) Wouter Lueks, Radboud University Nijmegen, Februari 2013. */ package org.irmacard.androidmanagement; import android.os.Bundle; import android.support.v4.app.FragmentActivity; /** * An activity representing a single Credential detail screen. This activity is * only used on handset devices. On tablet-size devices, item details are * presented side-by-side with a list of items in a * {@link CredentialListActivity}. * <p> * This activity is mostly just a 'shell' activity containing nothing more than * a {@link CredentialDetailFragment}. */ public class SettingsActivity extends FragmentActivity implements SettingsFragmentActivityI { public static final int RESULT_CHANGE_CARD_PIN = RESULT_FIRST_USER; public static final int RESULT_CHANGE_CRED_PIN = RESULT_FIRST_USER + 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_log); + setContentView(R.layout.activity_settings); // Show the Up button in the action bar. if(getActionBar() != null) { // TODO: workaround for now, figure out what is really going on here. getActionBar().setDisplayHomeAsUpEnabled(true); } // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. SettingsFragment fragment = new SettingsFragment(); Bundle arguments = new Bundle(); arguments.putSerializable( SettingsFragment.ARG_CARD_VERSION, getIntent().getSerializableExtra( SettingsFragment.ARG_CARD_VERSION)); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.settings_container, fragment).commit(); } } @Override public void onChangeCardPIN() { setResult(RESULT_CHANGE_CARD_PIN); finish(); } @Override public void onChangeCredPIN() { setResult(RESULT_CHANGE_CRED_PIN); finish(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log); // Show the Up button in the action bar. if(getActionBar() != null) { // TODO: workaround for now, figure out what is really going on here. getActionBar().setDisplayHomeAsUpEnabled(true); } // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. SettingsFragment fragment = new SettingsFragment(); Bundle arguments = new Bundle(); arguments.putSerializable( SettingsFragment.ARG_CARD_VERSION, getIntent().getSerializableExtra( SettingsFragment.ARG_CARD_VERSION)); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.settings_container, fragment).commit(); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); // Show the Up button in the action bar. if(getActionBar() != null) { // TODO: workaround for now, figure out what is really going on here. getActionBar().setDisplayHomeAsUpEnabled(true); } // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. SettingsFragment fragment = new SettingsFragment(); Bundle arguments = new Bundle(); arguments.putSerializable( SettingsFragment.ARG_CARD_VERSION, getIntent().getSerializableExtra( SettingsFragment.ARG_CARD_VERSION)); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.settings_container, fragment).commit(); } }
diff --git a/src/net/slipcor/pvparena/classes/PACheck.java b/src/net/slipcor/pvparena/classes/PACheck.java index e596ea3e..4b07e07f 100644 --- a/src/net/slipcor/pvparena/classes/PACheck.java +++ b/src/net/slipcor/pvparena/classes/PACheck.java @@ -1,542 +1,544 @@ package net.slipcor.pvparena.classes; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.entity.PlayerDeathEvent; import com.nodinchan.ncbukkit.loader.Loadable; 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.commands.PAA_Region; import net.slipcor.pvparena.core.Debug; import net.slipcor.pvparena.core.Language; import net.slipcor.pvparena.core.Config.CFG; import net.slipcor.pvparena.core.Language.MSG; import net.slipcor.pvparena.loadables.ArenaGoal; import net.slipcor.pvparena.loadables.ArenaModule; import net.slipcor.pvparena.managers.StatisticsManager; import net.slipcor.pvparena.managers.TeamManager; /** * <pre>PVP Arena Check class</pre> * * This class parses a complex check. * * It is called staticly to iterate over all needed/possible modules * to return one committing module (inside the result) and to make * modules listen to the checked events if necessary * * @author slipcor * * @version v0.9.3 */ public class PACheck { private int priority = 0; private String error = null; private String modName = null; private Debug db = new Debug(9); /** * * @return the error message */ public String getError() { return error; } /** * * @return the module name returning the current result */ public String getModName() { return modName; } /** * * @return the PACR priority */ public int getPriority() { return priority; } /** * * @return true if there was an error */ public boolean hasError() { return error != null; } /** * set the error message * @param error the error message */ public void setError(Loadable loadable, String error) { modName = loadable.getName(); db.i(modName + " is setting error to: " + error); this.error = error; this.priority += 1000; } /** * set the priority * @param priority the priority */ public void setPriority(Loadable loadable, int priority) { modName = loadable.getName(); db.i(modName + " is setting priority to: " + priority); this.priority = priority; } public static boolean handleCommand(Arena arena, CommandSender sender, String[] args) { int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkCommand(res, args[0]); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(Bukkit.getConsoleSender(), Language.parse(MSG.ERROR_ERROR, res.getError())); return false; } if (commit == null) return false; commit.commitCommand(sender, args); return true; } public static boolean handleEnd(Arena arena, boolean force) { int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkEnd(res); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(Bukkit.getConsoleSender(), Language.parse(MSG.ERROR_ERROR, res.getError())); return false; } if (commit == null) { return false; } commit.commitEnd(force); return true; } public static int handleGetLives(Arena arena, ArenaPlayer ap) { PACheck res = new PACheck(); int priority = 0; for (ArenaGoal mod : arena.getGoals()) { res = mod.getLives(res, ap); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); } } if (res.hasError()) { return Integer.valueOf(res.getError()); } return 0; } public static void handleInteract(Arena arena, Player player, Block clickedBlock) { int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkInteract(res, player, clickedBlock); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(Bukkit.getConsoleSender(), Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (commit == null) { return; } commit.commitInteract(player, clickedBlock); } public static void handleJoin(Arena arena, CommandSender sender, String[] args) { int priority = 0; PACheck res = new PACheck(); ArenaModule commModule = null; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkJoin(arena, sender, res, true); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commModule = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commModule = null; } } } if (res.hasError() && !res.getModName().equals("LateLounge")) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.NOTICE_NOTICE, res.getError())); return; } ArenaGoal commGoal = null; for (ArenaGoal mod : PVPArena.instance.getAgm().getTypes()) { res = mod.checkJoin(sender, res); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commGoal = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commGoal = null; } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (args.length < 1) { // usage: /pa {arenaname} join | join an arena args = new String[]{TeamManager.calcFreeTeam(arena)}; } ArenaTeam team = arena.getTeam(args[0]); - if (team == null) { + if (team == null && args != null) { arena.msg(sender, Language.parse(MSG.ERROR_TEAMNOTFOUND, args[0])); return; + } else if (team == null) { + arena.msg(sender, Language.parse(MSG.ERROR_JOIN_ARENA_FULL)); } if ((commModule == null) || (commGoal == null)) { if (commModule != null) { commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); return; } if (commGoal != null) { commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(sender, team); return; } // both null, just put the joiner to some spawn if (!arena.tryJoin((Player) sender, team)) { return; } if (arena.isFreeForAll()) { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINED)); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINED, sender.getName())); } else { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINEDTEAM).replace("%1%", team.getColoredName() + "�r")); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINEDTEAM, sender.getName(), team.getColoredName() + "�r")); } PVPArena.instance.getAgm().initiate(arena, (Player) sender); if (arena.getFighters().size() == 2) { arena.broadcast(Language.parse(MSG.FIGHT_BEGINS)); arena.setFightInProgress(true); for (ArenaPlayer p : arena.getFighters()) { if (p.getName().equals(sender.getName())) { continue; } arena.tpPlayerToCoordName(p.get(), (arena.isFreeForAll()?"":p.getArenaTeam().getName()) + "spawn"); } } return; } commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(res, arena, (Player) sender, team); } public static void handlePlayerDeath(Arena arena, Player player, PlayerDeathEvent event) { boolean doesRespawn = true; int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkPlayerDeath(res, player); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { // lives if (res.getError().equals("0")) { doesRespawn = false; } } StatisticsManager.kill(arena, player.getLastDamageCause().getEntity(), player, doesRespawn); event.setDeathMessage(null); if (!arena.getArenaConfig().getBoolean(CFG.PLAYER_DROPSINVENTORY)) { event.getDrops().clear(); } if (commit == null) { // no mod handles player deaths, default to infinite lives. Respawn player arena.unKillPlayer(player, event.getEntity().getLastDamageCause().getCause(), player.getKiller()); return; } commit.commitPlayerDeath(player, doesRespawn, res.getError(), event); for (ArenaGoal g : arena.getGoals()) { g.parsePlayerDeath(player, player.getLastDamageCause()); } for (ArenaModule m : PVPArena.instance.getAmm().getModules()) { if (m.isActive(arena)) { m.parsePlayerDeath(arena, player, player.getLastDamageCause()); } } } public static boolean handleSetFlag(Player player, Block block) { Arena arena = PAA_Region.activeSelections.get(player.getName()); if (arena == null) { return false; } int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkSetFlag(res, player, block); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(Bukkit.getConsoleSender(), Language.parse(MSG.ERROR_ERROR, res.getError())); return false; } if (commit == null) { return false; } return commit.commitSetFlag(player, block); } public static void handleSpectate(Arena arena, CommandSender sender) { int priority = 0; PACheck res = new PACheck(); // priority will be set by flags, the max priority will be called ArenaModule commit = null; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkJoin(arena, sender, res, false); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (commit == null) { return; } commit.commitSpectate(arena, (Player) sender); /* for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { commit.parseSpectate(arena, (Player) sender); } }*/ } public static void handleStart(Arena arena, ArenaPlayer ap, CommandSender sender) { PACheck res = new PACheck(); ArenaModule commit = null; int priority = 0; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkStart(arena, ap, res); } if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (commit == null) { return; } arena.teleportAllToSpawn(); } } /* * AVAILABLE PACheckResults: * * ArenaGoal.checkCommand() => ArenaGoal.commitCommand() * ( onCommand() ) * > default: nothing * * * ArenaGoal.checkEnd() => ArenaGoal.commitEnd() * ( ArenaGoalManager.checkEndAndCommit(arena) ) < used * > 1: PlayerLives * > 2: PlayerDeathMatch * > 3: TeamLives * > 4: TeamDeathMatch * > 5: Flags * * ArenaGoal.checkInteract() => ArenaGoal.commitInteract() * ( PlayerListener.onPlayerInteract() ) * > 5: Flags * * ArenaGoal.checkJoin() => ArenaGoal.commitJoin() * ( PAG_Join ) < used * > default: tp inside * * ArenaGoal.checkPlayerDeath() => ArenaGoal.commitPlayerDeath() * ( PlayerLister.onPlayerDeath() ) * > 1: PlayerLives * > 2: PlayerDeathMatch * > 3: TeamLives * > 4: TeamDeathMatch * > 5: Flags * * ArenaGoal.checkSetFlag() => ArenaGoal.commitSetFlag() * ( PlayerListener.onPlayerInteract() ) * > 5: Flags * * ================================= * * ArenaModule.checkJoin() * ( PAG_Join | PAG_Spectate ) < used * > 1: StandardLounge * > 2: BattlefieldJoin * > default: nothing * * ArenaModule.checkStart() * ( PAI_Ready ) < used * > default: nothing * */
false
true
public static void handleJoin(Arena arena, CommandSender sender, String[] args) { int priority = 0; PACheck res = new PACheck(); ArenaModule commModule = null; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkJoin(arena, sender, res, true); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commModule = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commModule = null; } } } if (res.hasError() && !res.getModName().equals("LateLounge")) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.NOTICE_NOTICE, res.getError())); return; } ArenaGoal commGoal = null; for (ArenaGoal mod : PVPArena.instance.getAgm().getTypes()) { res = mod.checkJoin(sender, res); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commGoal = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commGoal = null; } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (args.length < 1) { // usage: /pa {arenaname} join | join an arena args = new String[]{TeamManager.calcFreeTeam(arena)}; } ArenaTeam team = arena.getTeam(args[0]); if (team == null) { arena.msg(sender, Language.parse(MSG.ERROR_TEAMNOTFOUND, args[0])); return; } if ((commModule == null) || (commGoal == null)) { if (commModule != null) { commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); return; } if (commGoal != null) { commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(sender, team); return; } // both null, just put the joiner to some spawn if (!arena.tryJoin((Player) sender, team)) { return; } if (arena.isFreeForAll()) { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINED)); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINED, sender.getName())); } else { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINEDTEAM).replace("%1%", team.getColoredName() + "�r")); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINEDTEAM, sender.getName(), team.getColoredName() + "�r")); } PVPArena.instance.getAgm().initiate(arena, (Player) sender); if (arena.getFighters().size() == 2) { arena.broadcast(Language.parse(MSG.FIGHT_BEGINS)); arena.setFightInProgress(true); for (ArenaPlayer p : arena.getFighters()) { if (p.getName().equals(sender.getName())) { continue; } arena.tpPlayerToCoordName(p.get(), (arena.isFreeForAll()?"":p.getArenaTeam().getName()) + "spawn"); } } return; } commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(res, arena, (Player) sender, team); }
public static void handleJoin(Arena arena, CommandSender sender, String[] args) { int priority = 0; PACheck res = new PACheck(); ArenaModule commModule = null; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkJoin(arena, sender, res, true); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commModule = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commModule = null; } } } if (res.hasError() && !res.getModName().equals("LateLounge")) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.NOTICE_NOTICE, res.getError())); return; } ArenaGoal commGoal = null; for (ArenaGoal mod : PVPArena.instance.getAgm().getTypes()) { res = mod.checkJoin(sender, res); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commGoal = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commGoal = null; } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (args.length < 1) { // usage: /pa {arenaname} join | join an arena args = new String[]{TeamManager.calcFreeTeam(arena)}; } ArenaTeam team = arena.getTeam(args[0]); if (team == null && args != null) { arena.msg(sender, Language.parse(MSG.ERROR_TEAMNOTFOUND, args[0])); return; } else if (team == null) { arena.msg(sender, Language.parse(MSG.ERROR_JOIN_ARENA_FULL)); } if ((commModule == null) || (commGoal == null)) { if (commModule != null) { commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); return; } if (commGoal != null) { commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(sender, team); return; } // both null, just put the joiner to some spawn if (!arena.tryJoin((Player) sender, team)) { return; } if (arena.isFreeForAll()) { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINED)); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINED, sender.getName())); } else { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINEDTEAM).replace("%1%", team.getColoredName() + "�r")); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINEDTEAM, sender.getName(), team.getColoredName() + "�r")); } PVPArena.instance.getAgm().initiate(arena, (Player) sender); if (arena.getFighters().size() == 2) { arena.broadcast(Language.parse(MSG.FIGHT_BEGINS)); arena.setFightInProgress(true); for (ArenaPlayer p : arena.getFighters()) { if (p.getName().equals(sender.getName())) { continue; } arena.tpPlayerToCoordName(p.get(), (arena.isFreeForAll()?"":p.getArenaTeam().getName()) + "spawn"); } } return; } commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(res, arena, (Player) sender, team); }
diff --git a/solr/src/java/org/apache/solr/handler/component/TermsComponent.java b/solr/src/java/org/apache/solr/handler/component/TermsComponent.java index 3386b81bf..1ac33c13a 100644 --- a/solr/src/java/org/apache/solr/handler/component/TermsComponent.java +++ b/solr/src/java/org/apache/solr/handler/component/TermsComponent.java @@ -1,488 +1,488 @@ package org.apache.solr.handler.component; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.index.*; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.StringHelper; import org.apache.noggit.CharArr; import org.apache.solr.common.SolrException; import org.apache.solr.common.params.*; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.common.util.StrUtils; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.StrField; import org.apache.solr.request.SimpleFacets.CountPair; import org.apache.solr.search.SolrIndexReader; import org.apache.solr.util.BoundedTreeSet; import org.apache.solr.client.solrj.response.TermsResponse; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; /** * Return TermEnum information, useful for things like auto suggest. * * @see org.apache.solr.common.params.TermsParams * See Lucene's TermEnum class */ public class TermsComponent extends SearchComponent { public static final int UNLIMITED_MAX_COUNT = -1; public static final String COMPONENT_NAME = "terms"; @Override public void prepare(ResponseBuilder rb) throws IOException { SolrParams params = rb.req.getParams(); if (params.getBool(TermsParams.TERMS, false)) { rb.doTerms = true; } // TODO: temporary... this should go in a different component. String shards = params.get(ShardParams.SHARDS); if (shards != null) { if (params.get(ShardParams.SHARDS_QT) == null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No shards.qt parameter specified"); } List<String> lst = StrUtils.splitSmart(shards, ",", true); rb.shards = lst.toArray(new String[lst.size()]); } } public void process(ResponseBuilder rb) throws IOException { SolrParams params = rb.req.getParams(); if (!params.getBool(TermsParams.TERMS, false)) return; String[] fields = params.getParams(TermsParams.TERMS_FIELD); NamedList termsResult = new SimpleOrderedMap(); rb.rsp.add("terms", termsResult); if (fields == null || fields.length==0) return; int limit = params.getInt(TermsParams.TERMS_LIMIT, 10); if (limit < 0) { limit = Integer.MAX_VALUE; } String lowerStr = params.get(TermsParams.TERMS_LOWER); String upperStr = params.get(TermsParams.TERMS_UPPER); boolean upperIncl = params.getBool(TermsParams.TERMS_UPPER_INCLUSIVE, false); boolean lowerIncl = params.getBool(TermsParams.TERMS_LOWER_INCLUSIVE, true); boolean sort = !TermsParams.TERMS_SORT_INDEX.equals( params.get(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT)); int freqmin = params.getInt(TermsParams.TERMS_MINCOUNT, 1); int freqmax = params.getInt(TermsParams.TERMS_MAXCOUNT, UNLIMITED_MAX_COUNT); if (freqmax<0) { freqmax = Integer.MAX_VALUE; } String prefix = params.get(TermsParams.TERMS_PREFIX_STR); String regexp = params.get(TermsParams.TERMS_REGEXP_STR); Pattern pattern = regexp != null ? Pattern.compile(regexp, resolveRegexpFlags(params)) : null; boolean raw = params.getBool(TermsParams.TERMS_RAW, false); SolrIndexReader sr = rb.req.getSearcher().getReader(); Fields lfields = MultiFields.getFields(sr); for (String field : fields) { NamedList fieldTerms = new NamedList(); termsResult.add(field, fieldTerms); - Terms terms = lfields.terms(field); + Terms terms = lfields == null ? null : lfields.terms(field); if (terms == null) { // no terms for this field continue; } FieldType ft = raw ? null : rb.req.getSchema().getFieldTypeNoEx(field); if (ft==null) ft = new StrField(); // prefix must currently be text BytesRef prefixBytes = prefix==null ? null : new BytesRef(prefix); BytesRef upperBytes = null; if (upperStr != null) { upperBytes = new BytesRef(); ft.readableToIndexed(upperStr, upperBytes); } BytesRef lowerBytes; if (lowerStr == null) { // If no lower bound was specified, use the prefix lowerBytes = prefixBytes; } else { lowerBytes = new BytesRef(); if (raw) { // TODO: how to handle binary? perhaps we don't for "raw"... or if the field exists // perhaps we detect if the FieldType is non-character and expect hex if so? lowerBytes = new BytesRef(lowerStr); } else { lowerBytes = new BytesRef(); ft.readableToIndexed(lowerStr, lowerBytes); } } TermsEnum termsEnum = terms.iterator(); BytesRef term = null; if (lowerBytes != null) { if (termsEnum.seek(lowerBytes, true) == TermsEnum.SeekStatus.END) { termsEnum = null; } else { term = termsEnum.term(); //Only advance the enum if we are excluding the lower bound and the lower Term actually matches if (lowerIncl == false && term.equals(lowerBytes)) { term = termsEnum.next(); } } } else { // position termsEnum on first term term = termsEnum.next(); } int i = 0; BoundedTreeSet<CountPair<BytesRef, Integer>> queue = (sort ? new BoundedTreeSet<CountPair<BytesRef, Integer>>(limit) : null); CharArr external = new CharArr(); while (term != null && (i<limit || sort)) { boolean externalized = false; // did we fill in "external" yet for this term? // stop if the prefix doesn't match if (prefixBytes != null && !term.startsWith(prefixBytes)) break; if (pattern != null) { // indexed text or external text? // TODO: support "raw" mode? external.reset(); ft.indexedToReadable(term, external); if (!pattern.matcher(external).matches()) { term = termsEnum.next(); continue; } } if (upperBytes != null) { int upperCmp = term.compareTo(upperBytes); // if we are past the upper term, or equal to it (when don't include upper) then stop. if (upperCmp>0 || (upperCmp==0 && !upperIncl)) break; } // This is a good term in the range. Check if mincount/maxcount conditions are satisfied. int docFreq = termsEnum.docFreq(); if (docFreq >= freqmin && docFreq <= freqmax) { // add the term to the list if (sort) { queue.add(new CountPair<BytesRef, Integer>(new BytesRef(term), docFreq)); } else { // TODO: handle raw somehow if (!externalized) { external.reset(); ft.indexedToReadable(term, external); } String label = external.toString(); fieldTerms.add(label, docFreq); i++; } } term = termsEnum.next(); } if (sort) { for (CountPair<BytesRef, Integer> item : queue) { if (i >= limit) break; external.reset(); ft.indexedToReadable(item.key, external); fieldTerms.add(external.toString(), item.val); i++; } } } } int resolveRegexpFlags(SolrParams params) { String[] flagParams = params.getParams(TermsParams.TERMS_REGEXP_FLAG); if (flagParams == null) { return 0; } int flags = 0; for (String flagParam : flagParams) { try { flags |= TermsParams.TermsRegexpFlag.valueOf(flagParam.toUpperCase(Locale.ENGLISH)).getValue(); } catch (IllegalArgumentException iae) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unknown terms regex flag '" + flagParam + "'"); } } return flags; } @Override public int distributedProcess(ResponseBuilder rb) throws IOException { if (!rb.doTerms) { return ResponseBuilder.STAGE_DONE; } if (rb.stage == ResponseBuilder.STAGE_EXECUTE_QUERY) { TermsHelper th = rb._termsHelper; if (th == null) { th = rb._termsHelper = new TermsHelper(); th.init(rb.req.getParams()); } ShardRequest sreq = createShardQuery(rb.req.getParams()); rb.addRequest(this, sreq); } if (rb.stage < ResponseBuilder.STAGE_EXECUTE_QUERY) { return ResponseBuilder.STAGE_EXECUTE_QUERY; } else { return ResponseBuilder.STAGE_DONE; } } @Override public void handleResponses(ResponseBuilder rb, ShardRequest sreq) { if (!rb.doTerms || (sreq.purpose & ShardRequest.PURPOSE_GET_TERMS) == 0) { return; } TermsHelper th = rb._termsHelper; if (th != null) { for (ShardResponse srsp : sreq.responses) { th.parse((NamedList) srsp.getSolrResponse().getResponse().get("terms")); } } } @Override public void finishStage(ResponseBuilder rb) { if (!rb.doTerms || rb.stage != ResponseBuilder.STAGE_EXECUTE_QUERY) { return; } TermsHelper ti = rb._termsHelper; NamedList terms = ti.buildResponse(); rb.rsp.add("terms", terms); rb._termsHelper = null; } private ShardRequest createShardQuery(SolrParams params) { ShardRequest sreq = new ShardRequest(); sreq.purpose = ShardRequest.PURPOSE_GET_TERMS; // base shard request on original parameters sreq.params = new ModifiableSolrParams(params); // don't pass through the shards param sreq.params.remove(ShardParams.SHARDS); // remove any limits for shards, we want them to return all possible // responses // we want this so we can calculate the correct counts // dont sort by count to avoid that unnecessary overhead on the shards sreq.params.remove(TermsParams.TERMS_MAXCOUNT); sreq.params.remove(TermsParams.TERMS_MINCOUNT); sreq.params.set(TermsParams.TERMS_LIMIT, -1); sreq.params.set(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_INDEX); // TODO: is there a better way to handle this? String qt = params.get(CommonParams.QT); if (qt != null) { sreq.params.add(CommonParams.QT, qt); } return sreq; } public class TermsHelper { // map to store returned terms private HashMap<String, HashMap<String, TermsResponse.Term>> fieldmap; private SolrParams params; public TermsHelper() { fieldmap = new HashMap<String, HashMap<String, TermsResponse.Term>>(5); } public void init(SolrParams params) { this.params = params; String[] fields = params.getParams(TermsParams.TERMS_FIELD); if (fields != null) { for (String field : fields) { // TODO: not sure 128 is the best starting size // It use it because that is what is used for facets fieldmap.put(field, new HashMap<String, TermsResponse.Term>(128)); } } } public void parse(NamedList terms) { // exit if there is no terms if (terms == null) { return; } TermsResponse termsResponse = new TermsResponse(terms); // loop though each field and add each term+freq to map for (String key : fieldmap.keySet()) { HashMap<String, TermsResponse.Term> termmap = fieldmap.get(key); List<TermsResponse.Term> termlist = termsResponse.getTerms(key); // skip this field if there are no terms if (termlist == null) { continue; } // loop though each term for (TermsResponse.Term tc : termlist) { String term = tc.getTerm(); if (termmap.containsKey(term)) { TermsResponse.Term oldtc = termmap.get(term); oldtc.addFrequency(tc.getFrequency()); termmap.put(term, oldtc); } else { termmap.put(term, tc); } } } } public NamedList buildResponse() { NamedList response = new SimpleOrderedMap(); // determine if we are going index or count sort boolean sort = !TermsParams.TERMS_SORT_INDEX.equals(params.get( TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT)); // init minimum frequency long freqmin = 1; String s = params.get(TermsParams.TERMS_MINCOUNT); if (s != null) freqmin = Long.parseLong(s); // init maximum frequency, default to max int long freqmax = -1; s = params.get(TermsParams.TERMS_MAXCOUNT); if (s != null) freqmax = Long.parseLong(s); if (freqmax < 0) { freqmax = Long.MAX_VALUE; } // init limit, default to max int long limit = 10; s = params.get(TermsParams.TERMS_LIMIT); if (s != null) limit = Long.parseLong(s); if (limit < 0) { limit = Long.MAX_VALUE; } // loop though each field we want terms from for (String key : fieldmap.keySet()) { NamedList fieldterms = new SimpleOrderedMap(); TermsResponse.Term[] data = null; if (sort) { data = getCountSorted(fieldmap.get(key)); } else { data = getLexSorted(fieldmap.get(key)); } // loop though each term until we hit limit int cnt = 0; for (TermsResponse.Term tc : data) { if (tc.getFrequency() >= freqmin && tc.getFrequency() <= freqmax) { fieldterms.add(tc.getTerm(), num(tc.getFrequency())); cnt++; } if (cnt >= limit) { break; } } response.add(key, fieldterms); } return response; } // use <int> tags for smaller facet counts (better back compatibility) private Number num(long val) { if (val < Integer.MAX_VALUE) return (int) val; else return val; } // based on code from facets public TermsResponse.Term[] getLexSorted(HashMap<String, TermsResponse.Term> data) { TermsResponse.Term[] arr = data.values().toArray(new TermsResponse.Term[data.size()]); Arrays.sort(arr, new Comparator<TermsResponse.Term>() { public int compare(TermsResponse.Term o1, TermsResponse.Term o2) { return o1.getTerm().compareTo(o2.getTerm()); } }); return arr; } // based on code from facets public TermsResponse.Term[] getCountSorted(HashMap<String, TermsResponse.Term> data) { TermsResponse.Term[] arr = data.values().toArray(new TermsResponse.Term[data.size()]); Arrays.sort(arr, new Comparator<TermsResponse.Term>() { public int compare(TermsResponse.Term o1, TermsResponse.Term o2) { long freq1 = o1.getFrequency(); long freq2 = o2.getFrequency(); if (freq2 < freq1) { return -1; } else if (freq1 < freq2) { return 1; } else { return o1.getTerm().compareTo(o2.getTerm()); } } }); return arr; } } public String getVersion() { return "$Revision$"; } public String getSourceId() { return "$Id$"; } public String getSource() { return "$URL$"; } public String getDescription() { return "A Component for working with Term Enumerators"; } }
true
true
public void process(ResponseBuilder rb) throws IOException { SolrParams params = rb.req.getParams(); if (!params.getBool(TermsParams.TERMS, false)) return; String[] fields = params.getParams(TermsParams.TERMS_FIELD); NamedList termsResult = new SimpleOrderedMap(); rb.rsp.add("terms", termsResult); if (fields == null || fields.length==0) return; int limit = params.getInt(TermsParams.TERMS_LIMIT, 10); if (limit < 0) { limit = Integer.MAX_VALUE; } String lowerStr = params.get(TermsParams.TERMS_LOWER); String upperStr = params.get(TermsParams.TERMS_UPPER); boolean upperIncl = params.getBool(TermsParams.TERMS_UPPER_INCLUSIVE, false); boolean lowerIncl = params.getBool(TermsParams.TERMS_LOWER_INCLUSIVE, true); boolean sort = !TermsParams.TERMS_SORT_INDEX.equals( params.get(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT)); int freqmin = params.getInt(TermsParams.TERMS_MINCOUNT, 1); int freqmax = params.getInt(TermsParams.TERMS_MAXCOUNT, UNLIMITED_MAX_COUNT); if (freqmax<0) { freqmax = Integer.MAX_VALUE; } String prefix = params.get(TermsParams.TERMS_PREFIX_STR); String regexp = params.get(TermsParams.TERMS_REGEXP_STR); Pattern pattern = regexp != null ? Pattern.compile(regexp, resolveRegexpFlags(params)) : null; boolean raw = params.getBool(TermsParams.TERMS_RAW, false); SolrIndexReader sr = rb.req.getSearcher().getReader(); Fields lfields = MultiFields.getFields(sr); for (String field : fields) { NamedList fieldTerms = new NamedList(); termsResult.add(field, fieldTerms); Terms terms = lfields.terms(field); if (terms == null) { // no terms for this field continue; } FieldType ft = raw ? null : rb.req.getSchema().getFieldTypeNoEx(field); if (ft==null) ft = new StrField(); // prefix must currently be text BytesRef prefixBytes = prefix==null ? null : new BytesRef(prefix); BytesRef upperBytes = null; if (upperStr != null) { upperBytes = new BytesRef(); ft.readableToIndexed(upperStr, upperBytes); } BytesRef lowerBytes; if (lowerStr == null) { // If no lower bound was specified, use the prefix lowerBytes = prefixBytes; } else { lowerBytes = new BytesRef(); if (raw) { // TODO: how to handle binary? perhaps we don't for "raw"... or if the field exists // perhaps we detect if the FieldType is non-character and expect hex if so? lowerBytes = new BytesRef(lowerStr); } else { lowerBytes = new BytesRef(); ft.readableToIndexed(lowerStr, lowerBytes); } } TermsEnum termsEnum = terms.iterator(); BytesRef term = null; if (lowerBytes != null) { if (termsEnum.seek(lowerBytes, true) == TermsEnum.SeekStatus.END) { termsEnum = null; } else { term = termsEnum.term(); //Only advance the enum if we are excluding the lower bound and the lower Term actually matches if (lowerIncl == false && term.equals(lowerBytes)) { term = termsEnum.next(); } } } else { // position termsEnum on first term term = termsEnum.next(); } int i = 0; BoundedTreeSet<CountPair<BytesRef, Integer>> queue = (sort ? new BoundedTreeSet<CountPair<BytesRef, Integer>>(limit) : null); CharArr external = new CharArr(); while (term != null && (i<limit || sort)) { boolean externalized = false; // did we fill in "external" yet for this term? // stop if the prefix doesn't match if (prefixBytes != null && !term.startsWith(prefixBytes)) break; if (pattern != null) { // indexed text or external text? // TODO: support "raw" mode? external.reset(); ft.indexedToReadable(term, external); if (!pattern.matcher(external).matches()) { term = termsEnum.next(); continue; } } if (upperBytes != null) { int upperCmp = term.compareTo(upperBytes); // if we are past the upper term, or equal to it (when don't include upper) then stop. if (upperCmp>0 || (upperCmp==0 && !upperIncl)) break; } // This is a good term in the range. Check if mincount/maxcount conditions are satisfied. int docFreq = termsEnum.docFreq(); if (docFreq >= freqmin && docFreq <= freqmax) { // add the term to the list if (sort) { queue.add(new CountPair<BytesRef, Integer>(new BytesRef(term), docFreq)); } else { // TODO: handle raw somehow if (!externalized) { external.reset(); ft.indexedToReadable(term, external); } String label = external.toString(); fieldTerms.add(label, docFreq); i++; } } term = termsEnum.next(); } if (sort) { for (CountPair<BytesRef, Integer> item : queue) { if (i >= limit) break; external.reset(); ft.indexedToReadable(item.key, external); fieldTerms.add(external.toString(), item.val); i++; } } } }
public void process(ResponseBuilder rb) throws IOException { SolrParams params = rb.req.getParams(); if (!params.getBool(TermsParams.TERMS, false)) return; String[] fields = params.getParams(TermsParams.TERMS_FIELD); NamedList termsResult = new SimpleOrderedMap(); rb.rsp.add("terms", termsResult); if (fields == null || fields.length==0) return; int limit = params.getInt(TermsParams.TERMS_LIMIT, 10); if (limit < 0) { limit = Integer.MAX_VALUE; } String lowerStr = params.get(TermsParams.TERMS_LOWER); String upperStr = params.get(TermsParams.TERMS_UPPER); boolean upperIncl = params.getBool(TermsParams.TERMS_UPPER_INCLUSIVE, false); boolean lowerIncl = params.getBool(TermsParams.TERMS_LOWER_INCLUSIVE, true); boolean sort = !TermsParams.TERMS_SORT_INDEX.equals( params.get(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT)); int freqmin = params.getInt(TermsParams.TERMS_MINCOUNT, 1); int freqmax = params.getInt(TermsParams.TERMS_MAXCOUNT, UNLIMITED_MAX_COUNT); if (freqmax<0) { freqmax = Integer.MAX_VALUE; } String prefix = params.get(TermsParams.TERMS_PREFIX_STR); String regexp = params.get(TermsParams.TERMS_REGEXP_STR); Pattern pattern = regexp != null ? Pattern.compile(regexp, resolveRegexpFlags(params)) : null; boolean raw = params.getBool(TermsParams.TERMS_RAW, false); SolrIndexReader sr = rb.req.getSearcher().getReader(); Fields lfields = MultiFields.getFields(sr); for (String field : fields) { NamedList fieldTerms = new NamedList(); termsResult.add(field, fieldTerms); Terms terms = lfields == null ? null : lfields.terms(field); if (terms == null) { // no terms for this field continue; } FieldType ft = raw ? null : rb.req.getSchema().getFieldTypeNoEx(field); if (ft==null) ft = new StrField(); // prefix must currently be text BytesRef prefixBytes = prefix==null ? null : new BytesRef(prefix); BytesRef upperBytes = null; if (upperStr != null) { upperBytes = new BytesRef(); ft.readableToIndexed(upperStr, upperBytes); } BytesRef lowerBytes; if (lowerStr == null) { // If no lower bound was specified, use the prefix lowerBytes = prefixBytes; } else { lowerBytes = new BytesRef(); if (raw) { // TODO: how to handle binary? perhaps we don't for "raw"... or if the field exists // perhaps we detect if the FieldType is non-character and expect hex if so? lowerBytes = new BytesRef(lowerStr); } else { lowerBytes = new BytesRef(); ft.readableToIndexed(lowerStr, lowerBytes); } } TermsEnum termsEnum = terms.iterator(); BytesRef term = null; if (lowerBytes != null) { if (termsEnum.seek(lowerBytes, true) == TermsEnum.SeekStatus.END) { termsEnum = null; } else { term = termsEnum.term(); //Only advance the enum if we are excluding the lower bound and the lower Term actually matches if (lowerIncl == false && term.equals(lowerBytes)) { term = termsEnum.next(); } } } else { // position termsEnum on first term term = termsEnum.next(); } int i = 0; BoundedTreeSet<CountPair<BytesRef, Integer>> queue = (sort ? new BoundedTreeSet<CountPair<BytesRef, Integer>>(limit) : null); CharArr external = new CharArr(); while (term != null && (i<limit || sort)) { boolean externalized = false; // did we fill in "external" yet for this term? // stop if the prefix doesn't match if (prefixBytes != null && !term.startsWith(prefixBytes)) break; if (pattern != null) { // indexed text or external text? // TODO: support "raw" mode? external.reset(); ft.indexedToReadable(term, external); if (!pattern.matcher(external).matches()) { term = termsEnum.next(); continue; } } if (upperBytes != null) { int upperCmp = term.compareTo(upperBytes); // if we are past the upper term, or equal to it (when don't include upper) then stop. if (upperCmp>0 || (upperCmp==0 && !upperIncl)) break; } // This is a good term in the range. Check if mincount/maxcount conditions are satisfied. int docFreq = termsEnum.docFreq(); if (docFreq >= freqmin && docFreq <= freqmax) { // add the term to the list if (sort) { queue.add(new CountPair<BytesRef, Integer>(new BytesRef(term), docFreq)); } else { // TODO: handle raw somehow if (!externalized) { external.reset(); ft.indexedToReadable(term, external); } String label = external.toString(); fieldTerms.add(label, docFreq); i++; } } term = termsEnum.next(); } if (sort) { for (CountPair<BytesRef, Integer> item : queue) { if (i >= limit) break; external.reset(); ft.indexedToReadable(item.key, external); fieldTerms.add(external.toString(), item.val); i++; } } } }
diff --git a/src/contributions/resources/timeline/src/java/edu/mit/simile/yanel/impl/resources/timeline/TimelineResource.java b/src/contributions/resources/timeline/src/java/edu/mit/simile/yanel/impl/resources/timeline/TimelineResource.java index ec40131ae..e418d7b2a 100644 --- a/src/contributions/resources/timeline/src/java/edu/mit/simile/yanel/impl/resources/timeline/TimelineResource.java +++ b/src/contributions/resources/timeline/src/java/edu/mit/simile/yanel/impl/resources/timeline/TimelineResource.java @@ -1,187 +1,187 @@ /* * Copyright 2007 Wyona */ package edu.mit.simile.yanel.impl.resources.timeline; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.api.attributes.IntrospectableV1; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.util.PathUtil; import org.apache.log4j.Category; /** * */ public class TimelineResource extends Resource implements ViewableV2, IntrospectableV1 { private static Category log = Category.getInstance(TimelineResource.class); /** * */ public TimelineResource() { } /** * */ public boolean exists() { log.warn("Not really implemented yet! Needs to check if events XML exists."); return true; } /** * */ public String getMimeType(String viewId) { if (viewId != null) { if (viewId.equals("xml")) return "application/xml"; } return "application/xhtml+xml"; } /** * */ public long getSize() { log.warn("Not implemented yet!"); return -1; } /** * */ public ViewDescriptor[] getViewDescriptors() { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType(getMimeType(null)); vd[1] = new ViewDescriptor("xml"); vd[1].setMimeType(getMimeType("xml")); return vd; } /** * */ public View getView(String viewId) { View view = new View(); try { view.setInputStream(new java.io.StringBufferInputStream(getXHTML().toString())); //view.setInputStream(getRealm().getRepository().getNode("/timeline.xhtml").getInputStream()); view.setMimeType(getMimeType(null)); } catch (Exception e) { log.error(e.getMessage(), e); } return view; } /** * */ private StringBuffer getXHTML() throws Exception { //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy hh:mm:ss z"); //String todaysDate = sdf.format(new java.util.Date()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy"); String todaysDate = sdf.format(new java.util.Date()) + " 00:00:00 GMT"; StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); if (getResourceConfigProperty("introspection-url") != null) { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"" + getResourceConfigProperty("introspection-url") + "\"/>"); } else { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"?yanel.resource.usecase=introspection\"/>"); } //sb.append("<script src=\"http://simile.mit.edu/timeline/api/timeline-api.js\" type=\"text/javascript\"></script>"); - sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPath(this) + "timeline-api.js\" type=\"text/javascript\"></script>"); + sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPathURLencoded(this) + "timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script type=\"text/javascript\">"); sb.append("var tl;"); sb.append("var resizeTimerID = null;"); sb.append("function onResize() {"); sb.append(" if (resizeTimerID == null) {"); sb.append(" resizeTimerID = window.setTimeout(function() {"); sb.append(" resizeTimerID = null;"); sb.append(" tl.layout();"); sb.append(" }, 500);"); sb.append(" }"); sb.append("}"); sb.append("function onLoad() {"); sb.append(" var eventSource = new Timeline.DefaultEventSource();"); sb.append(" var bandInfos = ["); sb.append(" Timeline.createBandInfo({"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"70%\","); sb.append(" intervalUnit: Timeline.DateTime.MONTH,"); sb.append(" intervalPixels: 100"); sb.append(" }),"); sb.append(" Timeline.createBandInfo({"); sb.append("showEventText: false,"); sb.append(" trackHeight: 0.5,"); sb.append(" trackGap: 0.2,"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"30%\","); sb.append(" intervalUnit: Timeline.DateTime.YEAR,"); sb.append(" intervalPixels: 200"); sb.append(" })"); sb.append(" ];"); sb.append(" bandInfos[1].syncWith = 0;"); sb.append(" bandInfos[1].highlight = true;"); sb.append(" tl = Timeline.create(document.getElementById(\"my-timeline\"), bandInfos);"); // TODO: Check first if a query string already exists! sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "?do-not-cache-timestamp=" + new java.util.Date().getTime() + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); //sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); sb.append("}"); sb.append("</script>"); sb.append("<title>" + getResourceConfigProperty("title") + "</title>"); sb.append("</head>"); sb.append("<body onload=\"onLoad();\" onresize=\"onResize();\">"); sb.append("<h3>" + getResourceConfigProperty("title") + "</h3>"); sb.append("<p>Today's Date (server time): " + todaysDate + "</p>"); sb.append("<p>XML: <a href=\"" + getResourceConfigProperty("href") + "\">" + getResourceConfigProperty("href") + "</a></p>"); String height = getResourceConfigProperty("height"); if (height == null) height = "250px"; sb.append("<div id=\"my-timeline\" style=\"height: " + height + "; border: 1px solid #aaa\"></div>"); sb.append("</body>"); sb.append("</html>"); return sb; } /** * Get introspection for Introspectable interface */ public String getIntrospection() throws Exception { String name = PathUtil.getName(getPath()); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<introspection xmlns=\"http://www.wyona.org/neutron/2.0\">"); sb.append("<navigation>"); sb.append(" <sitetree href=\"./\" method=\"PROPFIND\"/>"); sb.append("</navigation>"); sb.append("<resource name=\"" + name + "\">"); sb.append("<edit mime-type=\"application/xml\">"); sb.append("<checkout url=\"" + getResourceConfigProperty("href") + "?yanel.resource.usecase=checkout\" method=\"GET\"/>"); sb.append("<checkin url=\"" + getResourceConfigProperty("href") + "?yanel.resource.usecase=checkin\" method=\"PUT\"/>"); sb.append("<release-lock url=\"" + getResourceConfigProperty("href") + "?yanel.resource.usecase=release-lock\" method=\"GET\"/>"); sb.append("</edit>"); sb.append("</resource>"); sb.append("</introspection>"); return sb.toString(); } }
true
true
private StringBuffer getXHTML() throws Exception { //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy hh:mm:ss z"); //String todaysDate = sdf.format(new java.util.Date()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy"); String todaysDate = sdf.format(new java.util.Date()) + " 00:00:00 GMT"; StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); if (getResourceConfigProperty("introspection-url") != null) { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"" + getResourceConfigProperty("introspection-url") + "\"/>"); } else { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"?yanel.resource.usecase=introspection\"/>"); } //sb.append("<script src=\"http://simile.mit.edu/timeline/api/timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPath(this) + "timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script type=\"text/javascript\">"); sb.append("var tl;"); sb.append("var resizeTimerID = null;"); sb.append("function onResize() {"); sb.append(" if (resizeTimerID == null) {"); sb.append(" resizeTimerID = window.setTimeout(function() {"); sb.append(" resizeTimerID = null;"); sb.append(" tl.layout();"); sb.append(" }, 500);"); sb.append(" }"); sb.append("}"); sb.append("function onLoad() {"); sb.append(" var eventSource = new Timeline.DefaultEventSource();"); sb.append(" var bandInfos = ["); sb.append(" Timeline.createBandInfo({"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"70%\","); sb.append(" intervalUnit: Timeline.DateTime.MONTH,"); sb.append(" intervalPixels: 100"); sb.append(" }),"); sb.append(" Timeline.createBandInfo({"); sb.append("showEventText: false,"); sb.append(" trackHeight: 0.5,"); sb.append(" trackGap: 0.2,"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"30%\","); sb.append(" intervalUnit: Timeline.DateTime.YEAR,"); sb.append(" intervalPixels: 200"); sb.append(" })"); sb.append(" ];"); sb.append(" bandInfos[1].syncWith = 0;"); sb.append(" bandInfos[1].highlight = true;"); sb.append(" tl = Timeline.create(document.getElementById(\"my-timeline\"), bandInfos);"); // TODO: Check first if a query string already exists! sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "?do-not-cache-timestamp=" + new java.util.Date().getTime() + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); //sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); sb.append("}"); sb.append("</script>"); sb.append("<title>" + getResourceConfigProperty("title") + "</title>"); sb.append("</head>"); sb.append("<body onload=\"onLoad();\" onresize=\"onResize();\">"); sb.append("<h3>" + getResourceConfigProperty("title") + "</h3>"); sb.append("<p>Today's Date (server time): " + todaysDate + "</p>"); sb.append("<p>XML: <a href=\"" + getResourceConfigProperty("href") + "\">" + getResourceConfigProperty("href") + "</a></p>"); String height = getResourceConfigProperty("height"); if (height == null) height = "250px"; sb.append("<div id=\"my-timeline\" style=\"height: " + height + "; border: 1px solid #aaa\"></div>"); sb.append("</body>"); sb.append("</html>"); return sb; }
private StringBuffer getXHTML() throws Exception { //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy hh:mm:ss z"); //String todaysDate = sdf.format(new java.util.Date()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy"); String todaysDate = sdf.format(new java.util.Date()) + " 00:00:00 GMT"; StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); if (getResourceConfigProperty("introspection-url") != null) { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"" + getResourceConfigProperty("introspection-url") + "\"/>"); } else { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"?yanel.resource.usecase=introspection\"/>"); } //sb.append("<script src=\"http://simile.mit.edu/timeline/api/timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPathURLencoded(this) + "timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script type=\"text/javascript\">"); sb.append("var tl;"); sb.append("var resizeTimerID = null;"); sb.append("function onResize() {"); sb.append(" if (resizeTimerID == null) {"); sb.append(" resizeTimerID = window.setTimeout(function() {"); sb.append(" resizeTimerID = null;"); sb.append(" tl.layout();"); sb.append(" }, 500);"); sb.append(" }"); sb.append("}"); sb.append("function onLoad() {"); sb.append(" var eventSource = new Timeline.DefaultEventSource();"); sb.append(" var bandInfos = ["); sb.append(" Timeline.createBandInfo({"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"70%\","); sb.append(" intervalUnit: Timeline.DateTime.MONTH,"); sb.append(" intervalPixels: 100"); sb.append(" }),"); sb.append(" Timeline.createBandInfo({"); sb.append("showEventText: false,"); sb.append(" trackHeight: 0.5,"); sb.append(" trackGap: 0.2,"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"30%\","); sb.append(" intervalUnit: Timeline.DateTime.YEAR,"); sb.append(" intervalPixels: 200"); sb.append(" })"); sb.append(" ];"); sb.append(" bandInfos[1].syncWith = 0;"); sb.append(" bandInfos[1].highlight = true;"); sb.append(" tl = Timeline.create(document.getElementById(\"my-timeline\"), bandInfos);"); // TODO: Check first if a query string already exists! sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "?do-not-cache-timestamp=" + new java.util.Date().getTime() + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); //sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); sb.append("}"); sb.append("</script>"); sb.append("<title>" + getResourceConfigProperty("title") + "</title>"); sb.append("</head>"); sb.append("<body onload=\"onLoad();\" onresize=\"onResize();\">"); sb.append("<h3>" + getResourceConfigProperty("title") + "</h3>"); sb.append("<p>Today's Date (server time): " + todaysDate + "</p>"); sb.append("<p>XML: <a href=\"" + getResourceConfigProperty("href") + "\">" + getResourceConfigProperty("href") + "</a></p>"); String height = getResourceConfigProperty("height"); if (height == null) height = "250px"; sb.append("<div id=\"my-timeline\" style=\"height: " + height + "; border: 1px solid #aaa\"></div>"); sb.append("</body>"); sb.append("</html>"); return sb; }
diff --git a/proxy/src/test/java/org/fedoraproject/candlepin/pinsetter/tasks/MigrateOwnerJobTest.java b/proxy/src/test/java/org/fedoraproject/candlepin/pinsetter/tasks/MigrateOwnerJobTest.java index 219735d67..d16a8ffb1 100644 --- a/proxy/src/test/java/org/fedoraproject/candlepin/pinsetter/tasks/MigrateOwnerJobTest.java +++ b/proxy/src/test/java/org/fedoraproject/candlepin/pinsetter/tasks/MigrateOwnerJobTest.java @@ -1,176 +1,176 @@ /** * Copyright (c) 2009 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.fedoraproject.candlepin.pinsetter.tasks; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.fedoraproject.candlepin.client.CandlepinConnection; import org.fedoraproject.candlepin.client.OwnerClient; import org.fedoraproject.candlepin.config.Config; import org.fedoraproject.candlepin.config.ConfigProperties; import org.fedoraproject.candlepin.exceptions.BadRequestException; import org.fedoraproject.candlepin.exceptions.NotFoundException; import org.fedoraproject.candlepin.model.Owner; import org.fedoraproject.candlepin.model.OwnerCurator; import org.apache.commons.httpclient.Credentials; import org.jboss.resteasy.client.ClientResponse; import org.junit.Before; import org.junit.Test; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.spi.TriggerFiredBundle; import java.util.HashMap; /** * MigrateOwnerJobTest */ public class MigrateOwnerJobTest { private OwnerCurator ownerCurator; private CandlepinConnection conn; private MigrateOwnerJob moj; private Config config; @Before public void init() { config = new ConfigForTesting(); ownerCurator = mock(OwnerCurator.class); conn = mock(CandlepinConnection.class); moj = new MigrateOwnerJob(ownerCurator, conn, config); } @Test public void testMigrateOwner() { JobDetail jd = moj.migrateOwner("admin", "http://foo.example.com/candlepin"); assertNotNull(jd); assertNotNull(jd.getJobDataMap()); assertEquals("admin", jd.getJobDataMap().get("owner_key")); assertEquals("http://foo.example.com/candlepin", jd.getJobDataMap().get("uri")); } @Test(expected = Exception.class) public void nullOwner() { moj.migrateOwner(null, "http://foo.example.com/candlepin"); } @Test(expected = BadRequestException.class) public void nullUrl() { moj.migrateOwner("admin", null); } @Test(expected = BadRequestException.class) public void inavlidUrlFormat() { moj.migrateOwner("admin", "foo"); } // used by execute tests private JobExecutionContext buildContext(JobDataMap map) { Scheduler s = mock(Scheduler.class); TriggerFiredBundle bundle = mock(TriggerFiredBundle.class); JobDetail detail = mock(JobDetail.class); Trigger trig = mock(Trigger.class); when(detail.getJobDataMap()).thenReturn(map); when(bundle.getJobDetail()).thenReturn(detail); when(bundle.getTrigger()).thenReturn(trig); when(trig.getJobDataMap()).thenReturn(new JobDataMap()); return new JobExecutionContext(s, bundle, null); } @Test @SuppressWarnings("unchecked") public void execute() throws JobExecutionException { OwnerClient client = mock(OwnerClient.class); when(conn.connect(any(Credentials.class), any(String.class))).thenReturn(client); ClientResponse<Owner> resp = mock(ClientResponse.class); when(client.exportOwner(eq("admin"))).thenReturn(resp); when(resp.getStatus()).thenReturn(200); JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("uri", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); verify(conn).connect(any(Credentials.class), eq("http://foo.example.com/candlepin")); - verify(ownerCurator, atLeastOnce()).merge(any(Owner.class)); + verify(ownerCurator, atLeastOnce()).importOwner(any(Owner.class)); } @Test(expected = Exception.class) public void executeInvalidKey() throws JobExecutionException { JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("badurikey", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); } @Test(expected = BadRequestException.class) public void executeBadValues() throws JobExecutionException { JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("uri", ""); moj.execute(buildContext(map)); } @Test(expected = NotFoundException.class) @SuppressWarnings("unchecked") public void executeNonExistentOwner() throws JobExecutionException { OwnerClient client = mock(OwnerClient.class); when(conn.connect(any(Credentials.class), any(String.class))).thenReturn(client); ClientResponse<Owner> resp = mock(ClientResponse.class); when(client.exportOwner(eq("doesnotexist"))).thenReturn(resp); when(resp.getStatus()).thenReturn(404); JobDataMap map = new JobDataMap(); map.put("owner_key", "doesnotexist"); map.put("uri", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); } private static class ConfigForTesting extends Config { public ConfigForTesting() { super(new HashMap<String, String>() { private static final long serialVersionUID = 1L; { this.put(ConfigProperties.SHARD_USERNAME, "admin"); this.put(ConfigProperties.SHARD_PASSWORD, "admin"); this.put(ConfigProperties.SHARD_WEBAPP, "candlepin"); } }); } } }
true
true
public void execute() throws JobExecutionException { OwnerClient client = mock(OwnerClient.class); when(conn.connect(any(Credentials.class), any(String.class))).thenReturn(client); ClientResponse<Owner> resp = mock(ClientResponse.class); when(client.exportOwner(eq("admin"))).thenReturn(resp); when(resp.getStatus()).thenReturn(200); JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("uri", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); verify(conn).connect(any(Credentials.class), eq("http://foo.example.com/candlepin")); verify(ownerCurator, atLeastOnce()).merge(any(Owner.class)); }
public void execute() throws JobExecutionException { OwnerClient client = mock(OwnerClient.class); when(conn.connect(any(Credentials.class), any(String.class))).thenReturn(client); ClientResponse<Owner> resp = mock(ClientResponse.class); when(client.exportOwner(eq("admin"))).thenReturn(resp); when(resp.getStatus()).thenReturn(200); JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("uri", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); verify(conn).connect(any(Credentials.class), eq("http://foo.example.com/candlepin")); verify(ownerCurator, atLeastOnce()).importOwner(any(Owner.class)); }
diff --git a/src/Code/ChessTable.java b/src/Code/ChessTable.java index ca0883f..e790af9 100644 --- a/src/Code/ChessTable.java +++ b/src/Code/ChessTable.java @@ -1,750 +1,750 @@ package Code; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPanel; public class ChessTable { private PieceLabel[] table; private String[] log; private PieceLabel[][] twoTable; public ChessTable() { this.table = new PieceLabel[64]; this.log = new String[2]; this.twoTable = new PieceLabel[8][8]; } public void updateTable(PieceLabel piece, int indeks) { table[indeks] = piece; } public void newTable(PieceLabel[] table2){ table = table2; } public PieceLabel[] getTable(){ return table; } public void testTwoTable() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (twoTable[i][j] instanceof PieceLabel) { System.out.println("i: " + i + " j: " + j + " " + twoTable[i][j].getPiece()); } } } } public void updateTwoTable() { int a = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { twoTable[i][j] = table[a]; a++; } } } public void updateLog(String log2, int indeks) { log[indeks] = log2; } public String getLog(int index) { return log[index]; } public Component getTable(int index) { if (table[index] instanceof PieceLabel) { return table[index]; } else { JPanel square = new JPanel(new BorderLayout()); square.setOpaque(false); return square; } } public void reset() { for (int i = 0; i < table.length; i++) { table[i] = null; } } public void changeUI(int a) { switch (a) { case 1: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingB.png"))); } if (table[i].getPiece() instanceof BishopW) { - table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BadassW.png"))); + table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/LolW.png"))); } if (table[i].getPiece() instanceof BishopB) { - table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BadassB.png"))); + table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/LolB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaB.png"))); } } } break; case 2: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookB.png"))); } } } break; } } public boolean checkW(int i) { if (checkBishopW(i)) { System.out.println("Bishop"); return true; } if (checkRookW(i)) { System.out.println("ROOK"); return true; } if (checkKnightW(i)) { System.out.println("KNIGHT"); return true; } if (checkPawnW(i)) { System.out.println("PAWN"); return true; } if (checkKingW(i)) { System.out.println("KING"); return true; } return false; } public boolean checkB(int i) { if (checkBishopB(i)) { System.out.println("Bishop"); return true; } if (checkRookB(i)) { System.out.println("ROOK"); return true; } if (checkKnightB(i)) { System.out.println("KNIGHT"); return true; } if (checkPawnB(i)) { System.out.println("PAWN"); return true; } if (checkKingB(i)) { System.out.println("KING"); return true; } return false; } public boolean checkKnightW(int i) { if ((i + 15) <= 63 && (i + 15) >= 0) { if (table[i + 15] instanceof PieceLabel) { if (table[i + 15].getPiece() instanceof KnightB) { return true; } } } if ((i + 6) <= 63 && (i + 6) >= 0) { if (table[i + 6] instanceof PieceLabel) { if (table[i + 6].getPiece() instanceof KnightB) { return true; } } } if ((i - 10) <= 63 && (i + -10) >= 0) { if (table[i - 10] instanceof PieceLabel) { if (table[i - 10].getPiece() instanceof KnightB) { return true; } } } if ((i - 17) <= 63 && (i - 17) >= 0) { if (table[i - 17] instanceof PieceLabel) { if (table[i - 17].getPiece() instanceof KnightB) { return true; } } } if ((i - 15) <= 63 && (i - 15) >= 0) { if (table[i - 15] instanceof PieceLabel) { if (table[i - 15].getPiece() instanceof KnightB) { return true; } } } if ((i + 10) <= 63 && (i + 10) >= 0) { if (table[i + 10] instanceof PieceLabel) { if (table[i + 10].getPiece() instanceof KnightB) { return true; } } } if ((i + 17) <= 63 && (i + 17) >= 0) { if (table[i + 17] instanceof PieceLabel) { if (table[i + 17].getPiece() instanceof KnightB) { return true; } } } if ((i - 6) <= 63 && (i - 6) >= 0) { if (table[i - 6] instanceof PieceLabel) { if (table[i - 6].getPiece() instanceof KnightB) { return true; } } } return false; } public boolean checkPawnW(int i) { if ((i - 7) <= 63 && (i - 7) >= 0) { if (table[i - 7] instanceof PieceLabel) { if (table[i - 7].getPiece() instanceof PawnB) { return true; } } } if ((i - 9) <= 63 && (i - 9) >= 0) { if (table[i - 9] instanceof PieceLabel) { if (table[i - 9].getPiece() instanceof PawnB) { return true; } } } return false; } public boolean checkRookW(int i) { int a = 0; int b = 0; if (i > 7) { a = i / 8; b = i - (a * 8); } else { b = i; a = 0; } for (int j = b; j < 8; j++) { if (twoTable[a][j] instanceof PieceLabel) { if (twoTable[a][j].getPiece() instanceof RookB || twoTable[a][j].getPiece() instanceof QueenB) { return true; } if ((twoTable[a][j].getPiece() instanceof RookB) == false && (twoTable[a][j].getPiece() instanceof KingW) == false) { break; } } } for (int j = b; j >= 0; j--) { if (twoTable[a][j] instanceof PieceLabel) { if (twoTable[a][j].getPiece() instanceof RookB || twoTable[a][j].getPiece() instanceof QueenB) { return true; } if ((twoTable[a][j].getPiece() instanceof RookB) == false && (twoTable[a][j].getPiece() instanceof KingW) == false) { break; } } } for (int j = a; j < 8; j++) { if (twoTable[j][b] instanceof PieceLabel) { if (twoTable[j][b].getPiece() instanceof RookB || twoTable[j][b].getPiece() instanceof QueenB) { return true; } if ((twoTable[j][b].getPiece() instanceof RookB) == false && (twoTable[j][b].getPiece() instanceof KingW) == false) { break; } } } for (int j = a; j >= 0; j--) { if (twoTable[j][b] instanceof PieceLabel) { if (twoTable[j][b].getPiece() instanceof RookB || twoTable[j][b].getPiece() instanceof QueenB) { return true; } if ((twoTable[j][b].getPiece() instanceof RookB) == false && (twoTable[j][b].getPiece() instanceof KingW) == false) { break; } } } return false; } public boolean checkBishopW(int i) { int a = 0; int b = 0; if (i > 7) { a = i / 8; b = i - (a * 8); } else { b = i; a = 0; } int c = a; int d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopB || twoTable[c][d].getPiece() instanceof QueenB) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopB) == false && (twoTable[c][d].getPiece() instanceof KingW) == false) { break; } } if (c > 0 && d > 0) { c--; d--; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopB || twoTable[c][d].getPiece() instanceof QueenB) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopB) == false && (twoTable[c][d].getPiece() instanceof KingW) == false) { break; } } if (c < 7 && d < 7) { c++; d++; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopB || twoTable[c][d].getPiece() instanceof QueenB) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopB) == false && (twoTable[c][d].getPiece() instanceof KingW) == false) { break; } } if (c < 7 && d > 0) { c++; d--; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopB || twoTable[c][d].getPiece() instanceof QueenB) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopB) == false && (twoTable[c][d].getPiece() instanceof KingW) == false) { break; } } if (c > 0 && d < 7) { c--; d++; } } return false; } public boolean checkKingW(int i) { if ((i - 7) <= 63 && (i - 7) >= 0) { if (table[i - 7] instanceof PieceLabel) { if (table[i - 7].getPiece() instanceof KingB) { return true; } } } if ((i - 8) <= 63 && (i - 8) >= 0) { if (table[i - 8] instanceof PieceLabel) { if (table[i - 8].getPiece() instanceof KingB) { return true; } } } if ((i - 9) <= 63 && (i - 9) >= 0) { if (table[i - 9] instanceof PieceLabel) { if (table[i - 9].getPiece() instanceof KingB) { return true; } } } if ((i - 1) <= 63 && (i - 1) >= 0) { if (table[i - 1] instanceof PieceLabel) { if (table[i - 1].getPiece() instanceof KingB) { return true; } } } if ((i + 1) <= 63 && (i + 1) >= 0) { if (table[i + 1] instanceof PieceLabel) { if (table[i + 1].getPiece() instanceof KingB) { return true; } } } if ((i + 7) <= 63 && (i + 7) >= 0) { if (table[i + 7] instanceof PieceLabel) { if (table[i + 7].getPiece() instanceof KingB) { return true; } } } if ((i + 8) <= 63 && (i + 8) >= 0) { if (table[i + 8] instanceof PieceLabel) { if (table[i + 8].getPiece() instanceof KingB) { return true; } } } if ((i + 9) <= 63 && (i + 9) >= 0) { if (table[i + 9] instanceof PieceLabel) { if (table[i + 9].getPiece() instanceof KingB) { return true; } } } return false; } public boolean checkKnightB(int i) { if ((i + 15) <= 63 && (i + 15) >= 0) { if (table[i + 15] instanceof PieceLabel) { if (table[i + 15].getPiece() instanceof KnightW) { return true; } } } if ((i + 6) <= 63 && (i + 6) >= 0) { if (table[i + 6] instanceof PieceLabel) { if (table[i + 6].getPiece() instanceof KnightW) { return true; } } } if ((i - 10) <= 63 && (i + -10) >= 0) { if (table[i - 10] instanceof PieceLabel) { if (table[i - 10].getPiece() instanceof KnightW) { return true; } } } if ((i - 17) <= 63 && (i - 17) >= 0) { if (table[i - 17] instanceof PieceLabel) { if (table[i - 17].getPiece() instanceof KnightW) { return true; } } } if ((i - 15) <= 63 && (i - 15) >= 0) { if (table[i - 15] instanceof PieceLabel) { if (table[i - 15].getPiece() instanceof KnightW) { return true; } } } if ((i + 10) <= 63 && (i + 10) >= 0) { if (table[i + 10] instanceof PieceLabel) { if (table[i + 10].getPiece() instanceof KnightW) { return true; } } } if ((i + 17) <= 63 && (i + 17) >= 0) { if (table[i + 17] instanceof PieceLabel) { if (table[i + 17].getPiece() instanceof KnightW) { return true; } } } if ((i - 6) <= 63 && (i - 6) >= 0) { if (table[i - 6] instanceof PieceLabel) { if (table[i - 6].getPiece() instanceof KnightW) { return true; } } } return false; } public boolean checkPawnB(int i) { if ((i + 7) <= 63 && (i + 7) >= 0) { if (table[i + 7] instanceof PieceLabel) { if (table[i + 7].getPiece() instanceof PawnW) { return true; } } } if ((i + 9) <= 63 && (i + 9) >= 0) { if (table[i + 9] instanceof PieceLabel) { if (table[i + 9].getPiece() instanceof PawnW) { return true; } } } return false; } public boolean checkRookB(int i) { int a = 0; int b = 0; if (i > 7) { a = i / 8; b = i - (a * 8); } else { b = i; a = 0; } for (int j = b; j < 8; j++) { if (twoTable[a][j] instanceof PieceLabel) { if (twoTable[a][j].getPiece() instanceof RookW || twoTable[a][j].getPiece() instanceof QueenW) { return true; } if ((twoTable[a][j].getPiece() instanceof RookW) == false && (twoTable[a][j].getPiece() instanceof KingB) == false) { break; } } } for (int j = b; j >= 0; j--) { if (twoTable[a][j] instanceof PieceLabel) { if (twoTable[a][j].getPiece() instanceof RookW || twoTable[a][j].getPiece() instanceof QueenW) { return true; } if ((twoTable[a][j].getPiece() instanceof RookW) == false && (twoTable[a][j].getPiece() instanceof KingB) == false) { break; } } } for (int j = a; j < 8; j++) { if (twoTable[j][b] instanceof PieceLabel) { if (twoTable[j][b].getPiece() instanceof RookW || twoTable[j][b].getPiece() instanceof QueenW) { return true; } if ((twoTable[j][b].getPiece() instanceof RookW) == false && (twoTable[j][b].getPiece() instanceof KingB) == false) { break; } } } for (int j = a; j >= 0; j--) { if (twoTable[j][b] instanceof PieceLabel) { if (twoTable[j][b].getPiece() instanceof RookW || twoTable[j][b].getPiece() instanceof QueenW) { return true; } if ((twoTable[j][b].getPiece() instanceof RookW) == false && (twoTable[j][b].getPiece() instanceof KingB) == false) { break; } } } return false; } public boolean checkBishopB(int i) { int a = 0; int b = 0; if (i > 7) { a = i / 8; b = i - (a * 8); } else { b = i; a = 0; } int c = a; int d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopW || twoTable[c][d].getPiece() instanceof QueenW) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopW) == false && (twoTable[c][d].getPiece() instanceof KingB) == false) { break; } } if (c > 0 && d > 0) { c--; d--; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopW || twoTable[c][d].getPiece() instanceof QueenW) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopW) == false && (twoTable[c][d].getPiece() instanceof KingB) == false) { break; } } if (c < 7 && d < 7) { c++; d++; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopW || twoTable[c][d].getPiece() instanceof QueenW) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopW) == false && (twoTable[c][d].getPiece() instanceof KingB) == false) { break; } } if (c < 7 && d > 0) { c++; d--; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopW || twoTable[c][d].getPiece() instanceof QueenW) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopW) == false && (twoTable[c][d].getPiece() instanceof KingB) == false) { break; } } if (c > 0 && d < 7) { c--; d++; } } return false; } public boolean checkKingB(int i) { if ((i - 7) <= 63 && (i - 7) >= 0) { if (table[i - 7] instanceof PieceLabel) { if (table[i - 7].getPiece() instanceof KingW) { return true; } } } if ((i - 8) <= 63 && (i - 8) >= 0) { if (table[i - 8] instanceof PieceLabel) { if (table[i - 8].getPiece() instanceof KingW) { return true; } } } if ((i - 9) <= 63 && (i - 9) >= 0) { if (table[i - 9] instanceof PieceLabel) { if (table[i - 9].getPiece() instanceof KingW) { return true; } } } if ((i - 1) <= 63 && (i - 1) >= 0) { if (table[i - 1] instanceof PieceLabel) { if (table[i - 1].getPiece() instanceof KingW) { return true; } } } if ((i + 1) <= 63 && (i + 1) >= 0) { if (table[i + 1] instanceof PieceLabel) { if (table[i + 1].getPiece() instanceof KingW) { return true; } } } if ((i + 7) <= 63 && (i + 7) >= 0) { if (table[i + 7] instanceof PieceLabel) { if (table[i + 7].getPiece() instanceof KingW) { return true; } } } if ((i + 8) <= 63 && (i + 8) >= 0) { if (table[i + 8] instanceof PieceLabel) { if (table[i + 8].getPiece() instanceof KingW) { return true; } } } if ((i + 9) <= 63 && (i + 9) >= 0) { if (table[i + 9] instanceof PieceLabel) { if (table[i + 9].getPiece() instanceof KingW) { return true; } } } return false; } }
false
true
public void changeUI(int a) { switch (a) { case 1: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BadassW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BadassB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaB.png"))); } } } break; case 2: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookB.png"))); } } } break; } }
public void changeUI(int a) { switch (a) { case 1: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/LolW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/LolB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaB.png"))); } } } break; case 2: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookB.png"))); } } } break; } }
diff --git a/src/com/android/gallery3d/app/PhotoPage.java b/src/com/android/gallery3d/app/PhotoPage.java index b43cf2a70..506d1ca6f 100644 --- a/src/com/android/gallery3d/app/PhotoPage.java +++ b/src/com/android/gallery3d/app/PhotoPage.java @@ -1,1496 +1,1498 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.app; import android.annotation.TargetApi; import android.app.ActionBar.OnMenuVisibilityListener; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Rect; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcAdapter.CreateBeamUrisCallback; import android.nfc.NfcEvent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.view.Menu; import android.view.MenuItem; import android.widget.RelativeLayout; import android.widget.Toast; import com.android.camera.CameraActivity; import com.android.camera.ProxyLauncher; import com.android.gallery3d.R; import com.android.gallery3d.common.ApiHelper; import com.android.gallery3d.data.ComboAlbum; import com.android.gallery3d.data.DataManager; import com.android.gallery3d.data.FilterDeleteSet; import com.android.gallery3d.data.FilterSource; import com.android.gallery3d.data.LocalImage; import com.android.gallery3d.data.MediaDetails; import com.android.gallery3d.data.MediaItem; import com.android.gallery3d.data.MediaObject; import com.android.gallery3d.data.MediaObject.PanoramaSupportCallback; import com.android.gallery3d.data.MediaSet; import com.android.gallery3d.data.MtpSource; import com.android.gallery3d.data.Path; import com.android.gallery3d.data.SecureAlbum; import com.android.gallery3d.data.SecureSource; import com.android.gallery3d.data.SnailAlbum; import com.android.gallery3d.data.SnailItem; import com.android.gallery3d.data.SnailSource; import com.android.gallery3d.filtershow.FilterShowActivity; import com.android.gallery3d.picasasource.PicasaSource; import com.android.gallery3d.ui.DetailsHelper; import com.android.gallery3d.ui.DetailsHelper.CloseListener; import com.android.gallery3d.ui.DetailsHelper.DetailsSource; import com.android.gallery3d.ui.GLView; import com.android.gallery3d.ui.ImportCompleteListener; import com.android.gallery3d.ui.MenuExecutor; import com.android.gallery3d.ui.PhotoView; import com.android.gallery3d.ui.SelectionManager; import com.android.gallery3d.ui.SynchronizedHandler; import com.android.gallery3d.util.GalleryUtils; public class PhotoPage extends ActivityState implements PhotoView.Listener, AppBridge.Server, PhotoPageBottomControls.Delegate, GalleryActionBar.OnAlbumModeSelectedListener { private static final String TAG = "PhotoPage"; private static final int MSG_HIDE_BARS = 1; private static final int MSG_ON_FULL_SCREEN_CHANGED = 4; private static final int MSG_UPDATE_ACTION_BAR = 5; private static final int MSG_UNFREEZE_GLROOT = 6; private static final int MSG_WANT_BARS = 7; private static final int MSG_REFRESH_BOTTOM_CONTROLS = 8; private static final int MSG_ON_CAMERA_CENTER = 9; private static final int MSG_ON_PICTURE_CENTER = 10; private static final int MSG_REFRESH_IMAGE = 11; private static final int MSG_UPDATE_PHOTO_UI = 12; private static final int MSG_UPDATE_PROGRESS = 13; private static final int MSG_UPDATE_DEFERRED = 14; private static final int MSG_UPDATE_SHARE_URI = 15; private static final int MSG_UPDATE_PANORAMA_UI = 16; private static final int HIDE_BARS_TIMEOUT = 3500; private static final int UNFREEZE_GLROOT_TIMEOUT = 250; private static final int REQUEST_SLIDESHOW = 1; private static final int REQUEST_CROP = 2; private static final int REQUEST_CROP_PICASA = 3; private static final int REQUEST_EDIT = 4; private static final int REQUEST_PLAY_VIDEO = 5; private static final int REQUEST_TRIM = 6; public static final String KEY_MEDIA_SET_PATH = "media-set-path"; public static final String KEY_MEDIA_ITEM_PATH = "media-item-path"; public static final String KEY_INDEX_HINT = "index-hint"; public static final String KEY_OPEN_ANIMATION_RECT = "open-animation-rect"; public static final String KEY_APP_BRIDGE = "app-bridge"; public static final String KEY_TREAT_BACK_AS_UP = "treat-back-as-up"; public static final String KEY_START_IN_FILMSTRIP = "start-in-filmstrip"; public static final String KEY_RETURN_INDEX_HINT = "return-index-hint"; public static final String KEY_SHOW_WHEN_LOCKED = "show_when_locked"; public static final String KEY_IN_CAMERA_ROLL = "in_camera_roll"; public static final String KEY_ALBUMPAGE_TRANSITION = "albumpage-transition"; public static final int MSG_ALBUMPAGE_NONE = 0; public static final int MSG_ALBUMPAGE_STARTED = 1; public static final int MSG_ALBUMPAGE_RESUMED = 2; public static final int MSG_ALBUMPAGE_PICKED = 4; public static final String ACTION_NEXTGEN_EDIT = "action_nextgen_edit"; private GalleryApp mApplication; private SelectionManager mSelectionManager; private PhotoView mPhotoView; private PhotoPage.Model mModel; private DetailsHelper mDetailsHelper; private boolean mShowDetails; // mMediaSet could be null if there is no KEY_MEDIA_SET_PATH supplied. // E.g., viewing a photo in gmail attachment private FilterDeleteSet mMediaSet; // The mediaset used by camera launched from secure lock screen. private SecureAlbum mSecureAlbum; private int mCurrentIndex = 0; private Handler mHandler; private boolean mShowBars = true; private volatile boolean mActionBarAllowed = true; private GalleryActionBar mActionBar; private boolean mIsMenuVisible; private boolean mHaveImageEditor; private PhotoPageBottomControls mBottomControls; private PhotoPageProgressBar mProgressBar; private MediaItem mCurrentPhoto = null; private MenuExecutor mMenuExecutor; private boolean mIsActive; private boolean mShowSpinner; private String mSetPathString; // This is the original mSetPathString before adding the camera preview item. private String mOriginalSetPathString; private AppBridge mAppBridge; private SnailItem mScreenNailItem; private SnailAlbum mScreenNailSet; private OrientationManager mOrientationManager; private boolean mTreatBackAsUp; private boolean mStartInFilmstrip; private boolean mHasCameraScreennailOrPlaceholder = false; private boolean mRecenterCameraOnResume = true; // These are only valid after the panorama callback private boolean mIsPanorama; private boolean mIsPanorama360; private long mCameraSwitchCutoff = 0; private boolean mSkipUpdateCurrentPhoto = false; private static final long CAMERA_SWITCH_CUTOFF_THRESHOLD_MS = 300; private static final long DEFERRED_UPDATE_MS = 250; private boolean mDeferredUpdateWaiting = false; private long mDeferUpdateUntil = Long.MAX_VALUE; // The item that is deleted (but it can still be undeleted before commiting) private Path mDeletePath; private boolean mDeleteIsFocus; // whether the deleted item was in focus private Uri[] mNfcPushUris = new Uri[1]; private final MyMenuVisibilityListener mMenuVisibilityListener = new MyMenuVisibilityListener(); private UpdateProgressListener mProgressListener; private final PanoramaSupportCallback mUpdatePanoramaMenuItemsCallback = new PanoramaSupportCallback() { @Override public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama, boolean isPanorama360) { if (mediaObject == mCurrentPhoto) { mHandler.obtainMessage(MSG_UPDATE_PANORAMA_UI, isPanorama360 ? 1 : 0, 0, mediaObject).sendToTarget(); } } }; private final PanoramaSupportCallback mRefreshBottomControlsCallback = new PanoramaSupportCallback() { @Override public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama, boolean isPanorama360) { if (mediaObject == mCurrentPhoto) { mHandler.obtainMessage(MSG_REFRESH_BOTTOM_CONTROLS, isPanorama ? 1 : 0, isPanorama360 ? 1 : 0, mediaObject).sendToTarget(); } } }; private final PanoramaSupportCallback mUpdateShareURICallback = new PanoramaSupportCallback() { @Override public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama, boolean isPanorama360) { if (mediaObject == mCurrentPhoto) { mHandler.obtainMessage(MSG_UPDATE_SHARE_URI, isPanorama360 ? 1 : 0, 0, mediaObject) .sendToTarget(); } } }; public static interface Model extends PhotoView.Model { public void resume(); public void pause(); public boolean isEmpty(); public void setCurrentPhoto(Path path, int indexHint); } private class MyMenuVisibilityListener implements OnMenuVisibilityListener { @Override public void onMenuVisibilityChanged(boolean isVisible) { mIsMenuVisible = isVisible; refreshHidingMessage(); } } private class UpdateProgressListener implements StitchingChangeListener { @Override public void onStitchingResult(Uri uri) { sendUpdate(uri, MSG_REFRESH_IMAGE); } @Override public void onStitchingQueued(Uri uri) { sendUpdate(uri, MSG_UPDATE_PROGRESS); } @Override public void onStitchingProgress(Uri uri, final int progress) { sendUpdate(uri, MSG_UPDATE_PROGRESS); } private void sendUpdate(Uri uri, int message) { MediaObject currentPhoto = mCurrentPhoto; boolean isCurrentPhoto = currentPhoto instanceof LocalImage && currentPhoto.getContentUri().equals(uri); if (isCurrentPhoto) { mHandler.sendEmptyMessage(message); } } }; @Override protected int getBackgroundColorId() { return R.color.photo_background; } private final GLView mRootPane = new GLView() { @Override protected void onLayout( boolean changed, int left, int top, int right, int bottom) { mPhotoView.layout(0, 0, right - left, bottom - top); if (mShowDetails) { mDetailsHelper.layout(left, mActionBar.getHeight(), right, bottom); } } }; @Override public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mActionBar = mActivity.getGalleryActionBar(); mSelectionManager = new SelectionManager(mActivity, false); mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager); mPhotoView = new PhotoView(mActivity); mPhotoView.setListener(this); mRootPane.addComponent(mPhotoView); mApplication = (GalleryApp) ((Activity) mActivity).getApplication(); mOrientationManager = mActivity.getOrientationManager(); mActivity.getGLRoot().setOrientationSource(mOrientationManager); mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_HIDE_BARS: { hideBars(); break; } case MSG_REFRESH_BOTTOM_CONTROLS: { if (mCurrentPhoto == message.obj && mBottomControls != null) { mIsPanorama = message.arg1 == 1; mIsPanorama360 = message.arg2 == 1; mBottomControls.refresh(); } break; } case MSG_ON_FULL_SCREEN_CHANGED: { - mAppBridge.onFullScreenChanged(message.arg1 == 1); + if (mAppBridge != null) { + mAppBridge.onFullScreenChanged(message.arg1 == 1); + } break; } case MSG_UPDATE_ACTION_BAR: { updateBars(); break; } case MSG_WANT_BARS: { wantBars(); break; } case MSG_UNFREEZE_GLROOT: { mActivity.getGLRoot().unfreeze(); break; } case MSG_UPDATE_DEFERRED: { long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis(); if (nextUpdate <= 0) { mDeferredUpdateWaiting = false; updateUIForCurrentPhoto(); } else { mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate); } break; } case MSG_ON_CAMERA_CENTER: { mSkipUpdateCurrentPhoto = false; boolean stayedOnCamera = false; if (!mPhotoView.getFilmMode()) { stayedOnCamera = true; } else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff && mMediaSet.getMediaItemCount() > 1) { mPhotoView.switchToImage(1); } else { if (mAppBridge != null) mPhotoView.setFilmMode(false); stayedOnCamera = true; } if (stayedOnCamera) { if (mAppBridge == null) { launchCamera(); /* We got here by swiping from photo 1 to the placeholder, so make it be the thing that is in focus when the user presses back from the camera app */ mPhotoView.switchToImage(1); } else { updateBars(); updateCurrentPhoto(mModel.getMediaItem(0)); } } break; } case MSG_ON_PICTURE_CENTER: { if (!mPhotoView.getFilmMode() && mCurrentPhoto != null && (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) { mPhotoView.setFilmMode(true); } break; } case MSG_REFRESH_IMAGE: { final MediaItem photo = mCurrentPhoto; mCurrentPhoto = null; updateCurrentPhoto(photo); break; } case MSG_UPDATE_PHOTO_UI: { updateUIForCurrentPhoto(); break; } case MSG_UPDATE_PROGRESS: { updateProgressBar(); break; } case MSG_UPDATE_SHARE_URI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; Uri contentUri = mCurrentPhoto.getContentUri(); Intent panoramaIntent = null; if (isPanorama360) { panoramaIntent = createSharePanoramaIntent(contentUri); } Intent shareIntent = createShareIntent(mCurrentPhoto); mActionBar.setShareIntents(panoramaIntent, shareIntent); setNfcBeamPushUri(contentUri); } break; } case MSG_UPDATE_PANORAMA_UI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; updatePanoramaUI(isPanorama360); } break; } default: throw new AssertionError(message.what); } } }; mSetPathString = data.getString(KEY_MEDIA_SET_PATH); mOriginalSetPathString = mSetPathString; setupNfcBeamPush(); String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH); Path itemPath = itemPathString != null ? Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) : null; mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false); mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false); boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false); mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0); if (mSetPathString != null) { mShowSpinner = true; mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE); if (mAppBridge != null) { mShowBars = false; mHasCameraScreennailOrPlaceholder = true; mAppBridge.setServer(this); // Get the ScreenNail from AppBridge and register it. int id = SnailSource.newId(); Path screenNailSetPath = SnailSource.getSetPath(id); Path screenNailItemPath = SnailSource.getItemPath(id); mScreenNailSet = (SnailAlbum) mActivity.getDataManager() .getMediaObject(screenNailSetPath); mScreenNailItem = (SnailItem) mActivity.getDataManager() .getMediaObject(screenNailItemPath); mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) { // Set the flag to be on top of the lock screen. mFlags |= FLAG_SHOW_WHEN_LOCKED; } // Don't display "empty album" action item for capture intents. if (!mSetPathString.equals("/local/all/0")) { // Check if the path is a secure album. if (SecureSource.isSecurePath(mSetPathString)) { mSecureAlbum = (SecureAlbum) mActivity.getDataManager() .getMediaSet(mSetPathString); mShowSpinner = false; } mSetPathString = "/filter/empty/{"+mSetPathString+"}"; } // Combine the original MediaSet with the one for ScreenNail // from AppBridge. mSetPathString = "/combo/item/{" + screenNailSetPath + "," + mSetPathString + "}"; // Start from the screen nail. itemPath = screenNailItemPath; } else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) { mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT + "," + mSetPathString + "}"; mCurrentIndex++; mHasCameraScreennailOrPlaceholder = true; } MediaSet originalSet = mActivity.getDataManager() .getMediaSet(mSetPathString); if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) { // Use the name of the camera album rather than the default // ComboAlbum behavior ((ComboAlbum) originalSet).useNameOfChild(1); } mSelectionManager.setSourceMediaSet(originalSet); mSetPathString = "/filter/delete/{" + mSetPathString + "}"; mMediaSet = (FilterDeleteSet) mActivity.getDataManager() .getMediaSet(mSetPathString); if (mMediaSet == null) { Log.w(TAG, "failed to restore " + mSetPathString); } if (itemPath == null) { int mediaItemCount = mMediaSet.getMediaItemCount(); if (mediaItemCount > 0) { if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0; itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1) .get(0).getPath(); } else { // Bail out, PhotoPage can't load on an empty album return; } } PhotoDataAdapter pda = new PhotoDataAdapter( mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex, mAppBridge == null ? -1 : 0, mAppBridge == null ? false : mAppBridge.isPanorama(), mAppBridge == null ? false : mAppBridge.isStaticCamera()); mModel = pda; mPhotoView.setModel(mModel); pda.setDataListener(new PhotoDataAdapter.DataListener() { @Override public void onPhotoChanged(int index, Path item) { int oldIndex = mCurrentIndex; mCurrentIndex = index; if (mHasCameraScreennailOrPlaceholder) { if (mCurrentIndex > 0) { mSkipUpdateCurrentPhoto = false; } if (oldIndex == 0 && mCurrentIndex > 0 && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); } else if (oldIndex == 2 && mCurrentIndex == 1) { mCameraSwitchCutoff = SystemClock.uptimeMillis() + CAMERA_SWITCH_CUTOFF_THRESHOLD_MS; mPhotoView.stopScrolling(); } else if (oldIndex >= 1 && mCurrentIndex == 0) { mPhotoView.setWantPictureCenterCallbacks(true); mSkipUpdateCurrentPhoto = true; } } if (!mSkipUpdateCurrentPhoto) { if (item != null) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } updateBars(); } // Reset the timeout for the bars after a swipe refreshHidingMessage(); } @Override public void onLoadingFinished(boolean loadingFailed) { if (!mModel.isEmpty()) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } else if (mIsActive) { // We only want to finish the PhotoPage if there is no // deletion that the user can undo. if (mMediaSet.getNumberOfDeletions() == 0) { mActivity.getStateManager().finishState( PhotoPage.this); } } } @Override public void onLoadingStarted() { } }); } else { // Get default media set by the URI MediaItem mediaItem = (MediaItem) mActivity.getDataManager().getMediaObject(itemPath); mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem); mPhotoView.setModel(mModel); updateCurrentPhoto(mediaItem); mShowSpinner = false; } mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1); RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity) .findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root); if (galleryRoot != null) { if (mSecureAlbum == null) { mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot); } StitchingProgressManager progressManager = mApplication.getStitchingProgressManager(); if (progressManager != null) { mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot); mProgressListener = new UpdateProgressListener(); progressManager.addChangeListener(mProgressListener); if (mSecureAlbum != null) { progressManager.addChangeListener(mSecureAlbum); } } } } @Override public void onPictureCenter(boolean isCamera) { isCamera = isCamera || (mHasCameraScreennailOrPlaceholder && mAppBridge == null); mPhotoView.setWantPictureCenterCallbacks(false); mHandler.removeMessages(MSG_ON_CAMERA_CENTER); mHandler.removeMessages(MSG_ON_PICTURE_CENTER); mHandler.sendEmptyMessage(isCamera ? MSG_ON_CAMERA_CENTER : MSG_ON_PICTURE_CENTER); } @Override public boolean canDisplayBottomControls() { return mIsActive && !mPhotoView.canUndo(); } @Override public boolean canDisplayBottomControl(int control) { if (mCurrentPhoto == null) { return false; } switch(control) { case R.id.photopage_bottom_control_edit: return mHaveImageEditor && mShowBars && !mPhotoView.getFilmMode() && (mCurrentPhoto.getSupportedOperations() & MediaItem.SUPPORT_EDIT) != 0 && mCurrentPhoto.getMediaType() == MediaObject.MEDIA_TYPE_IMAGE; case R.id.photopage_bottom_control_panorama: return mIsPanorama; case R.id.photopage_bottom_control_tiny_planet: return mHaveImageEditor && mShowBars && mIsPanorama360 && !mPhotoView.getFilmMode(); default: return false; } } @Override public void onBottomControlClicked(int control) { switch(control) { case R.id.photopage_bottom_control_edit: launchPhotoEditor(); return; case R.id.photopage_bottom_control_panorama: mActivity.getPanoramaViewHelper() .showPanorama(mCurrentPhoto.getContentUri()); return; case R.id.photopage_bottom_control_tiny_planet: launchTinyPlanet(); return; default: return; } } @TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN) private void setupNfcBeamPush() { if (!ApiHelper.HAS_SET_BEAM_PUSH_URIS) return; NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mActivity); if (adapter != null) { adapter.setBeamPushUris(null, mActivity); adapter.setBeamPushUrisCallback(new CreateBeamUrisCallback() { @Override public Uri[] createBeamUris(NfcEvent event) { return mNfcPushUris; } }, mActivity); } } private void setNfcBeamPushUri(Uri uri) { mNfcPushUris[0] = uri; } private static Intent createShareIntent(MediaObject mediaObject) { int type = mediaObject.getMediaType(); return new Intent(Intent.ACTION_SEND) .setType(MenuExecutor.getMimeType(type)) .putExtra(Intent.EXTRA_STREAM, mediaObject.getContentUri()) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } private static Intent createSharePanoramaIntent(Uri contentUri) { return new Intent(Intent.ACTION_SEND) .setType(GalleryUtils.MIME_TYPE_PANORAMA360) .putExtra(Intent.EXTRA_STREAM, contentUri) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } private void overrideTransitionToEditor() { ((Activity) mActivity).overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.fade_out); } private void launchTinyPlanet() { // Deep link into tiny planet MediaItem current = mModel.getMediaItem(0); Intent intent = new Intent(FilterShowActivity.TINY_PLANET_ACTION); intent.setClass(mActivity, FilterShowActivity.class); intent.setDataAndType(current.getContentUri(), current.getMimeType()) .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN, mActivity.isFullscreen()); mActivity.startActivityForResult(intent, REQUEST_EDIT); overrideTransitionToEditor(); } private void launchCamera() { Intent intent = new Intent(mActivity, CameraActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mRecenterCameraOnResume = false; mActivity.startActivity(intent); } private void launchPhotoEditor() { MediaItem current = mModel.getMediaItem(0); if (current == null || (current.getSupportedOperations() & MediaObject.SUPPORT_EDIT) == 0) { return; } Intent intent = new Intent(ACTION_NEXTGEN_EDIT); intent.setDataAndType(current.getContentUri(), current.getMimeType()) .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (mActivity.getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() == 0) { intent.setAction(Intent.ACTION_EDIT); } intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN, mActivity.isFullscreen()); ((Activity) mActivity).startActivityForResult(Intent.createChooser(intent, null), REQUEST_EDIT); overrideTransitionToEditor(); } private void requestDeferredUpdate() { mDeferUpdateUntil = SystemClock.uptimeMillis() + DEFERRED_UPDATE_MS; if (!mDeferredUpdateWaiting) { mDeferredUpdateWaiting = true; mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, DEFERRED_UPDATE_MS); } } private void updateUIForCurrentPhoto() { if (mCurrentPhoto == null) return; // If by swiping or deletion the user ends up on an action item // and zoomed in, zoom out so that the context of the action is // more clear if ((mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0 && !mPhotoView.getFilmMode()) { mPhotoView.setWantPictureCenterCallbacks(true); } updateMenuOperations(); refreshBottomControlsWhenReady(); if (mShowDetails) { mDetailsHelper.reloadDetails(); } if ((mSecureAlbum == null) && (mCurrentPhoto.getSupportedOperations() & MediaItem.SUPPORT_SHARE) != 0) { mCurrentPhoto.getPanoramaSupport(mUpdateShareURICallback); } updateProgressBar(); } private void updateCurrentPhoto(MediaItem photo) { if (mCurrentPhoto == photo) return; mCurrentPhoto = photo; if (mPhotoView.getFilmMode()) { requestDeferredUpdate(); } else { updateUIForCurrentPhoto(); } } private void updateProgressBar() { if (mProgressBar != null) { mProgressBar.hideProgress(); StitchingProgressManager progressManager = mApplication.getStitchingProgressManager(); if (progressManager != null && mCurrentPhoto instanceof LocalImage) { Integer progress = progressManager.getProgress(mCurrentPhoto.getContentUri()); if (progress != null) { mProgressBar.setProgress(progress); } } } } private void updateMenuOperations() { Menu menu = mActionBar.getMenu(); // it could be null if onCreateActionBar has not been called yet if (menu == null) return; MenuItem item = menu.findItem(R.id.action_slideshow); if (item != null) { item.setVisible((mSecureAlbum == null) && canDoSlideShow()); } if (mCurrentPhoto == null) return; int supportedOperations = mCurrentPhoto.getSupportedOperations(); if (mSecureAlbum != null) { supportedOperations &= MediaObject.SUPPORT_DELETE; } else if (!mHaveImageEditor) { supportedOperations &= ~MediaObject.SUPPORT_EDIT; } MenuExecutor.updateMenuOperation(menu, supportedOperations); mCurrentPhoto.getPanoramaSupport(mUpdatePanoramaMenuItemsCallback); } private boolean canDoSlideShow() { if (mMediaSet == null || mCurrentPhoto == null) { return false; } if (mCurrentPhoto.getMediaType() != MediaObject.MEDIA_TYPE_IMAGE) { return false; } if (MtpSource.isMtpPath(mOriginalSetPathString)) { return false; } return true; } ////////////////////////////////////////////////////////////////////////// // Action Bar show/hide management ////////////////////////////////////////////////////////////////////////// private void showBars() { if (mShowBars) return; mShowBars = true; mOrientationManager.unlockOrientation(); mActionBar.show(); mActivity.getGLRoot().setLightsOutMode(false); refreshHidingMessage(); refreshBottomControlsWhenReady(); } private void hideBars() { if (!mShowBars) return; mShowBars = false; mActionBar.hide(); mActivity.getGLRoot().setLightsOutMode(true); mHandler.removeMessages(MSG_HIDE_BARS); refreshBottomControlsWhenReady(); } private void refreshHidingMessage() { mHandler.removeMessages(MSG_HIDE_BARS); if (!mIsMenuVisible && !mPhotoView.getFilmMode()) { mHandler.sendEmptyMessageDelayed(MSG_HIDE_BARS, HIDE_BARS_TIMEOUT); } } private boolean canShowBars() { // No bars if we are showing camera preview. if (mAppBridge != null && mCurrentIndex == 0 && !mPhotoView.getFilmMode()) return false; // No bars if it's not allowed. if (!mActionBarAllowed) return false; return true; } private void wantBars() { if (canShowBars()) showBars(); } private void toggleBars() { if (mShowBars) { hideBars(); } else { if (canShowBars()) showBars(); } } private void updateBars() { if (!canShowBars()) { hideBars(); } } @Override protected void onBackPressed() { if (mShowDetails) { hideDetails(); } else if (mAppBridge == null || !switchWithCaptureAnimation(-1)) { // We are leaving this page. Set the result now. setResult(); if (mStartInFilmstrip && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); } else if (mTreatBackAsUp) { onUpPressed(); } else { super.onBackPressed(); } } } private void onUpPressed() { if ((mStartInFilmstrip || mAppBridge != null) && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); return; } if (mActivity.getStateManager().getStateCount() > 1) { setResult(); super.onBackPressed(); return; } if (mOriginalSetPathString == null) return; if (mAppBridge == null) { // We're in view mode so set up the stacks on our own. Bundle data = new Bundle(getData()); data.putString(AlbumPage.KEY_MEDIA_PATH, mOriginalSetPathString); data.putString(AlbumPage.KEY_PARENT_MEDIA_PATH, mActivity.getDataManager().getTopSetPath( DataManager.INCLUDE_ALL)); mActivity.getStateManager().switchState(this, AlbumPage.class, data); } else { GalleryUtils.startGalleryActivity(mActivity); } } private void setResult() { Intent result = null; result = new Intent(); result.putExtra(KEY_RETURN_INDEX_HINT, mCurrentIndex); setStateResult(Activity.RESULT_OK, result); } ////////////////////////////////////////////////////////////////////////// // AppBridge.Server interface ////////////////////////////////////////////////////////////////////////// @Override public void setCameraRelativeFrame(Rect frame) { mPhotoView.setCameraRelativeFrame(frame); } @Override public boolean switchWithCaptureAnimation(int offset) { return mPhotoView.switchWithCaptureAnimation(offset); } @Override public void setSwipingEnabled(boolean enabled) { mPhotoView.setSwipingEnabled(enabled); } @Override public void notifyScreenNailChanged() { mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); mScreenNailSet.notifyChange(); } @Override public void addSecureAlbumItem(boolean isVideo, int id) { mSecureAlbum.addMediaItem(isVideo, id); } @Override protected boolean onCreateActionBar(Menu menu) { mActionBar.createActionBarMenu(R.menu.photo, menu); mHaveImageEditor = GalleryUtils.isEditorAvailable(mActivity, "image/*"); updateMenuOperations(); mActionBar.setTitle(mMediaSet != null ? mMediaSet.getName() : ""); return true; } private MenuExecutor.ProgressListener mConfirmDialogListener = new MenuExecutor.ProgressListener() { @Override public void onProgressUpdate(int index) {} @Override public void onProgressComplete(int result) {} @Override public void onConfirmDialogShown() { mHandler.removeMessages(MSG_HIDE_BARS); } @Override public void onConfirmDialogDismissed(boolean confirmed) { refreshHidingMessage(); } @Override public void onProgressStart() {} }; private void switchToGrid() { if (mActivity.getStateManager().hasStateClass(AlbumPage.class)) { onUpPressed(); } else { if (mOriginalSetPathString == null) return; if (mProgressBar != null) { updateCurrentPhoto(null); mProgressBar.hideProgress(); } Bundle data = new Bundle(getData()); data.putString(AlbumPage.KEY_MEDIA_PATH, mOriginalSetPathString); data.putString(AlbumPage.KEY_PARENT_MEDIA_PATH, mActivity.getDataManager().getTopSetPath( DataManager.INCLUDE_ALL)); // We only show cluster menu in the first AlbumPage in stack // TODO: Enable this when running from the camera app boolean inAlbum = mActivity.getStateManager().hasStateClass(AlbumPage.class); data.putBoolean(AlbumPage.KEY_SHOW_CLUSTER_MENU, !inAlbum && mAppBridge == null); data.putBoolean(PhotoPage.KEY_APP_BRIDGE, mAppBridge != null); // Account for live preview being first item mActivity.getTransitionStore().put(KEY_RETURN_INDEX_HINT, mAppBridge != null ? mCurrentIndex - 1 : mCurrentIndex); if (mHasCameraScreennailOrPlaceholder && mAppBridge != null) { mActivity.getStateManager().startState(AlbumPage.class, data); } else { mActivity.getStateManager().switchState(this, AlbumPage.class, data); } } } @Override protected boolean onItemSelected(MenuItem item) { if (mModel == null) return true; refreshHidingMessage(); MediaItem current = mModel.getMediaItem(0); if (current == null) { // item is not ready, ignore return true; } int currentIndex = mModel.getCurrentIndex(); Path path = current.getPath(); DataManager manager = mActivity.getDataManager(); int action = item.getItemId(); String confirmMsg = null; switch (action) { case android.R.id.home: { onUpPressed(); return true; } case R.id.action_slideshow: { Bundle data = new Bundle(); data.putString(SlideshowPage.KEY_SET_PATH, mMediaSet.getPath().toString()); data.putString(SlideshowPage.KEY_ITEM_PATH, path.toString()); data.putInt(SlideshowPage.KEY_PHOTO_INDEX, currentIndex); data.putBoolean(SlideshowPage.KEY_REPEAT, true); mActivity.getStateManager().startStateForResult( SlideshowPage.class, REQUEST_SLIDESHOW, data); return true; } case R.id.action_crop: { Activity activity = mActivity; Intent intent = new Intent(FilterShowActivity.CROP_ACTION); intent.setClass(activity, FilterShowActivity.class); intent.setDataAndType(manager.getContentUri(path), current.getMimeType()) .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); activity.startActivityForResult(intent, PicasaSource.isPicasaImage(current) ? REQUEST_CROP_PICASA : REQUEST_CROP); return true; } case R.id.action_trim: { Intent intent = new Intent(mActivity, TrimVideo.class); intent.setData(manager.getContentUri(path)); // We need the file path to wrap this into a RandomAccessFile. intent.putExtra(KEY_MEDIA_ITEM_PATH, current.getFilePath()); mActivity.startActivityForResult(intent, REQUEST_TRIM); return true; } case R.id.action_edit: { launchPhotoEditor(); return true; } case R.id.action_details: { if (mShowDetails) { hideDetails(); } else { showDetails(); } return true; } case R.id.action_delete: confirmMsg = mActivity.getResources().getQuantityString( R.plurals.delete_selection, 1); case R.id.action_setas: case R.id.action_rotate_ccw: case R.id.action_rotate_cw: case R.id.action_show_on_map: mSelectionManager.deSelectAll(); mSelectionManager.toggle(path); mMenuExecutor.onMenuClicked(item, confirmMsg, mConfirmDialogListener); return true; case R.id.action_import: mSelectionManager.deSelectAll(); mSelectionManager.toggle(path); mMenuExecutor.onMenuClicked(item, confirmMsg, new ImportCompleteListener(mActivity)); return true; default : return false; } } private void hideDetails() { mShowDetails = false; mDetailsHelper.hide(); } private void showDetails() { mShowDetails = true; if (mDetailsHelper == null) { mDetailsHelper = new DetailsHelper(mActivity, mRootPane, new MyDetailsSource()); mDetailsHelper.setCloseListener(new CloseListener() { @Override public void onClose() { hideDetails(); } }); } mDetailsHelper.show(); } //////////////////////////////////////////////////////////////////////////// // Callbacks from PhotoView //////////////////////////////////////////////////////////////////////////// @Override public void onSingleTapUp(int x, int y) { if (mAppBridge != null) { if (mAppBridge.onSingleTapUp(x, y)) return; } MediaItem item = mModel.getMediaItem(0); if (item == null || item == mScreenNailItem) { // item is not ready or it is camera preview, ignore return; } int supported = item.getSupportedOperations(); boolean playVideo = ((supported & MediaItem.SUPPORT_PLAY) != 0); boolean unlock = ((supported & MediaItem.SUPPORT_UNLOCK) != 0); boolean goBack = ((supported & MediaItem.SUPPORT_BACK) != 0); boolean launchCamera = ((supported & MediaItem.SUPPORT_CAMERA_SHORTCUT) != 0); if (playVideo) { // determine if the point is at center (1/6) of the photo view. // (The position of the "play" icon is at center (1/6) of the photo) int w = mPhotoView.getWidth(); int h = mPhotoView.getHeight(); playVideo = (Math.abs(x - w / 2) * 12 <= w) && (Math.abs(y - h / 2) * 12 <= h); } if (playVideo) { if (mSecureAlbum == null) { playVideo(mActivity, item.getPlayUri(), item.getName()); } else { mActivity.getStateManager().finishState(this); } } else if (goBack) { onBackPressed(); } else if (unlock) { Intent intent = new Intent(mActivity, Gallery.class); intent.putExtra(Gallery.KEY_DISMISS_KEYGUARD, true); mActivity.startActivity(intent); } else if (launchCamera) { launchCamera(); } else { toggleBars(); } } @Override public void onActionBarAllowed(boolean allowed) { mActionBarAllowed = allowed; mHandler.sendEmptyMessage(MSG_UPDATE_ACTION_BAR); } @Override public void onActionBarWanted() { mHandler.sendEmptyMessage(MSG_WANT_BARS); } @Override public void onFullScreenChanged(boolean full) { Message m = mHandler.obtainMessage( MSG_ON_FULL_SCREEN_CHANGED, full ? 1 : 0, 0); m.sendToTarget(); } // How we do delete/undo: // // When the user choose to delete a media item, we just tell the // FilterDeleteSet to hide that item. If the user choose to undo it, we // again tell FilterDeleteSet not to hide it. If the user choose to commit // the deletion, we then actually delete the media item. @Override public void onDeleteImage(Path path, int offset) { onCommitDeleteImage(); // commit the previous deletion mDeletePath = path; mDeleteIsFocus = (offset == 0); mMediaSet.addDeletion(path, mCurrentIndex + offset); } @Override public void onUndoDeleteImage() { if (mDeletePath == null) return; // If the deletion was done on the focused item, we want the model to // focus on it when it is undeleted. if (mDeleteIsFocus) mModel.setFocusHintPath(mDeletePath); mMediaSet.removeDeletion(mDeletePath); mDeletePath = null; } @Override public void onCommitDeleteImage() { if (mDeletePath == null) return; mSelectionManager.deSelectAll(); mSelectionManager.toggle(mDeletePath); mMenuExecutor.onMenuClicked(R.id.action_delete, null, true, false); mDeletePath = null; } public void playVideo(Activity activity, Uri uri, String title) { try { Intent intent = new Intent(Intent.ACTION_VIEW) .setDataAndType(uri, "video/*") .putExtra(Intent.EXTRA_TITLE, title) .putExtra(MovieActivity.KEY_TREAT_UP_AS_BACK, true); activity.startActivityForResult(intent, REQUEST_PLAY_VIDEO); } catch (ActivityNotFoundException e) { Toast.makeText(activity, activity.getString(R.string.video_err), Toast.LENGTH_SHORT).show(); } } private void setCurrentPhotoByIntent(Intent intent) { if (intent == null) return; Path path = mApplication.getDataManager() .findPathByUri(intent.getData(), intent.getType()); if (path != null) { Path albumPath = mApplication.getDataManager().getDefaultSetOf(path); if (!albumPath.equalsIgnoreCase(mOriginalSetPathString)) { // If the edited image is stored in a different album, we need // to start a new activity state to show the new image Bundle data = new Bundle(getData()); data.putString(KEY_MEDIA_SET_PATH, albumPath.toString()); data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, path.toString()); mActivity.getStateManager().startState(PhotoPage.class, data); return; } mModel.setCurrentPhoto(path, mCurrentIndex); } } @Override protected void onStateResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_CANCELED) { // This is a reset, not a canceled return; } if (resultCode == ProxyLauncher.RESULT_USER_CANCELED) { // Unmap reset vs. canceled resultCode = Activity.RESULT_CANCELED; } mRecenterCameraOnResume = false; switch (requestCode) { case REQUEST_EDIT: setCurrentPhotoByIntent(data); break; case REQUEST_CROP: if (resultCode == Activity.RESULT_OK) { setCurrentPhotoByIntent(data); } break; case REQUEST_CROP_PICASA: { if (resultCode == Activity.RESULT_OK) { Context context = mActivity.getAndroidContext(); String message = context.getString(R.string.crop_saved, context.getString(R.string.folder_edited_online_photos)); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } break; } case REQUEST_SLIDESHOW: { if (data == null) break; String path = data.getStringExtra(SlideshowPage.KEY_ITEM_PATH); int index = data.getIntExtra(SlideshowPage.KEY_PHOTO_INDEX, 0); if (path != null) { mModel.setCurrentPhoto(Path.fromString(path), index); } } } } @Override public void onPause() { super.onPause(); mIsActive = false; mActivity.getGLRoot().unfreeze(); mHandler.removeMessages(MSG_UNFREEZE_GLROOT); DetailsHelper.pause(); // Hide the detail dialog on exit if (mShowDetails) hideDetails(); if (mModel != null) { mModel.pause(); } mPhotoView.pause(); mHandler.removeMessages(MSG_HIDE_BARS); mHandler.removeMessages(MSG_REFRESH_BOTTOM_CONTROLS); refreshBottomControlsWhenReady(); mActionBar.removeOnMenuVisibilityListener(mMenuVisibilityListener); if (mShowSpinner) { mActionBar.disableAlbumModeMenu(true); } onCommitDeleteImage(); mMenuExecutor.pause(); if (mMediaSet != null) mMediaSet.clearDeletion(); } @Override public void onCurrentImageUpdated() { mActivity.getGLRoot().unfreeze(); } @Override public void onFilmModeChanged(boolean enabled) { refreshBottomControlsWhenReady(); if (mShowSpinner) { if (enabled) { mActionBar.enableAlbumModeMenu( GalleryActionBar.ALBUM_FILMSTRIP_MODE_SELECTED, this); } else { mActionBar.disableAlbumModeMenu(true); } } if (enabled) { mHandler.removeMessages(MSG_HIDE_BARS); } else { refreshHidingMessage(); } } private void transitionFromAlbumPageIfNeeded() { TransitionStore transitions = mActivity.getTransitionStore(); int albumPageTransition = transitions.get( KEY_ALBUMPAGE_TRANSITION, MSG_ALBUMPAGE_NONE); if (albumPageTransition == MSG_ALBUMPAGE_NONE && mAppBridge != null && mRecenterCameraOnResume) { // Generally, resuming the PhotoPage when in Camera should // reset to the capture mode to allow quick photo taking mCurrentIndex = 0; mPhotoView.resetToFirstPicture(); } else { int resumeIndex = transitions.get(KEY_INDEX_HINT, -1); if (resumeIndex >= 0) { if (mHasCameraScreennailOrPlaceholder) { // Account for preview/placeholder being the first item resumeIndex++; } if (resumeIndex < mMediaSet.getMediaItemCount()) { mCurrentIndex = resumeIndex; mModel.moveTo(mCurrentIndex); } } } if (albumPageTransition == MSG_ALBUMPAGE_RESUMED) { mPhotoView.setFilmMode(mStartInFilmstrip || mAppBridge != null); } else if (albumPageTransition == MSG_ALBUMPAGE_PICKED) { mPhotoView.setFilmMode(false); } } @Override protected void onResume() { super.onResume(); if (mModel == null) { mActivity.getStateManager().finishState(this); return; } transitionFromAlbumPageIfNeeded(); mActivity.getGLRoot().freeze(); mIsActive = true; setContentPane(mRootPane); mModel.resume(); mPhotoView.resume(); mActionBar.setDisplayOptions( ((mSecureAlbum == null) && (mSetPathString != null)), false); mActionBar.addOnMenuVisibilityListener(mMenuVisibilityListener); refreshBottomControlsWhenReady(); if (mShowSpinner && mPhotoView.getFilmMode()) { mActionBar.enableAlbumModeMenu( GalleryActionBar.ALBUM_FILMSTRIP_MODE_SELECTED, this); } if (!mShowBars) { mActionBar.hide(); mActivity.getGLRoot().setLightsOutMode(true); } boolean haveImageEditor = GalleryUtils.isEditorAvailable(mActivity, "image/*"); if (haveImageEditor != mHaveImageEditor) { mHaveImageEditor = haveImageEditor; updateMenuOperations(); } mRecenterCameraOnResume = true; mHandler.sendEmptyMessageDelayed(MSG_UNFREEZE_GLROOT, UNFREEZE_GLROOT_TIMEOUT); } @Override protected void onDestroy() { if (mAppBridge != null) { mAppBridge.setServer(null); mScreenNailItem.setScreenNail(null); mAppBridge.detachScreenNail(); mAppBridge = null; mScreenNailSet = null; mScreenNailItem = null; } mActivity.getGLRoot().setOrientationSource(null); if (mBottomControls != null) mBottomControls.cleanup(); // Remove all pending messages. mHandler.removeCallbacksAndMessages(null); super.onDestroy(); } private class MyDetailsSource implements DetailsSource { @Override public MediaDetails getDetails() { return mModel.getMediaItem(0).getDetails(); } @Override public int size() { return mMediaSet != null ? mMediaSet.getMediaItemCount() : 1; } @Override public int setIndex() { return mModel.getCurrentIndex(); } } @Override public void onAlbumModeSelected(int mode) { if (mode == GalleryActionBar.ALBUM_GRID_MODE_SELECTED) { switchToGrid(); } } @Override public void refreshBottomControlsWhenReady() { if (mBottomControls == null) { return; } MediaObject currentPhoto = mCurrentPhoto; if (currentPhoto == null) { mHandler.obtainMessage(MSG_REFRESH_BOTTOM_CONTROLS, 0, 0, currentPhoto).sendToTarget(); } else { currentPhoto.getPanoramaSupport(mRefreshBottomControlsCallback); } } private void updatePanoramaUI(boolean isPanorama360) { Menu menu = mActionBar.getMenu(); // it could be null if onCreateActionBar has not been called yet if (menu == null) { return; } MenuExecutor.updateMenuForPanorama(menu, isPanorama360, isPanorama360); if (isPanorama360) { MenuItem item = menu.findItem(R.id.action_share); if (item != null) { item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); item.setTitle(mActivity.getResources().getString(R.string.share_as_photo)); } } else if ((mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_SHARE) != 0) { MenuItem item = menu.findItem(R.id.action_share); if (item != null) { item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); item.setTitle(mActivity.getResources().getString(R.string.share)); } } } @Override public void onUndoBarVisibilityChanged(boolean visible) { refreshBottomControlsWhenReady(); } }
true
true
public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mActionBar = mActivity.getGalleryActionBar(); mSelectionManager = new SelectionManager(mActivity, false); mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager); mPhotoView = new PhotoView(mActivity); mPhotoView.setListener(this); mRootPane.addComponent(mPhotoView); mApplication = (GalleryApp) ((Activity) mActivity).getApplication(); mOrientationManager = mActivity.getOrientationManager(); mActivity.getGLRoot().setOrientationSource(mOrientationManager); mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_HIDE_BARS: { hideBars(); break; } case MSG_REFRESH_BOTTOM_CONTROLS: { if (mCurrentPhoto == message.obj && mBottomControls != null) { mIsPanorama = message.arg1 == 1; mIsPanorama360 = message.arg2 == 1; mBottomControls.refresh(); } break; } case MSG_ON_FULL_SCREEN_CHANGED: { mAppBridge.onFullScreenChanged(message.arg1 == 1); break; } case MSG_UPDATE_ACTION_BAR: { updateBars(); break; } case MSG_WANT_BARS: { wantBars(); break; } case MSG_UNFREEZE_GLROOT: { mActivity.getGLRoot().unfreeze(); break; } case MSG_UPDATE_DEFERRED: { long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis(); if (nextUpdate <= 0) { mDeferredUpdateWaiting = false; updateUIForCurrentPhoto(); } else { mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate); } break; } case MSG_ON_CAMERA_CENTER: { mSkipUpdateCurrentPhoto = false; boolean stayedOnCamera = false; if (!mPhotoView.getFilmMode()) { stayedOnCamera = true; } else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff && mMediaSet.getMediaItemCount() > 1) { mPhotoView.switchToImage(1); } else { if (mAppBridge != null) mPhotoView.setFilmMode(false); stayedOnCamera = true; } if (stayedOnCamera) { if (mAppBridge == null) { launchCamera(); /* We got here by swiping from photo 1 to the placeholder, so make it be the thing that is in focus when the user presses back from the camera app */ mPhotoView.switchToImage(1); } else { updateBars(); updateCurrentPhoto(mModel.getMediaItem(0)); } } break; } case MSG_ON_PICTURE_CENTER: { if (!mPhotoView.getFilmMode() && mCurrentPhoto != null && (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) { mPhotoView.setFilmMode(true); } break; } case MSG_REFRESH_IMAGE: { final MediaItem photo = mCurrentPhoto; mCurrentPhoto = null; updateCurrentPhoto(photo); break; } case MSG_UPDATE_PHOTO_UI: { updateUIForCurrentPhoto(); break; } case MSG_UPDATE_PROGRESS: { updateProgressBar(); break; } case MSG_UPDATE_SHARE_URI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; Uri contentUri = mCurrentPhoto.getContentUri(); Intent panoramaIntent = null; if (isPanorama360) { panoramaIntent = createSharePanoramaIntent(contentUri); } Intent shareIntent = createShareIntent(mCurrentPhoto); mActionBar.setShareIntents(panoramaIntent, shareIntent); setNfcBeamPushUri(contentUri); } break; } case MSG_UPDATE_PANORAMA_UI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; updatePanoramaUI(isPanorama360); } break; } default: throw new AssertionError(message.what); } } }; mSetPathString = data.getString(KEY_MEDIA_SET_PATH); mOriginalSetPathString = mSetPathString; setupNfcBeamPush(); String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH); Path itemPath = itemPathString != null ? Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) : null; mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false); mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false); boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false); mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0); if (mSetPathString != null) { mShowSpinner = true; mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE); if (mAppBridge != null) { mShowBars = false; mHasCameraScreennailOrPlaceholder = true; mAppBridge.setServer(this); // Get the ScreenNail from AppBridge and register it. int id = SnailSource.newId(); Path screenNailSetPath = SnailSource.getSetPath(id); Path screenNailItemPath = SnailSource.getItemPath(id); mScreenNailSet = (SnailAlbum) mActivity.getDataManager() .getMediaObject(screenNailSetPath); mScreenNailItem = (SnailItem) mActivity.getDataManager() .getMediaObject(screenNailItemPath); mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) { // Set the flag to be on top of the lock screen. mFlags |= FLAG_SHOW_WHEN_LOCKED; } // Don't display "empty album" action item for capture intents. if (!mSetPathString.equals("/local/all/0")) { // Check if the path is a secure album. if (SecureSource.isSecurePath(mSetPathString)) { mSecureAlbum = (SecureAlbum) mActivity.getDataManager() .getMediaSet(mSetPathString); mShowSpinner = false; } mSetPathString = "/filter/empty/{"+mSetPathString+"}"; } // Combine the original MediaSet with the one for ScreenNail // from AppBridge. mSetPathString = "/combo/item/{" + screenNailSetPath + "," + mSetPathString + "}"; // Start from the screen nail. itemPath = screenNailItemPath; } else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) { mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT + "," + mSetPathString + "}"; mCurrentIndex++; mHasCameraScreennailOrPlaceholder = true; } MediaSet originalSet = mActivity.getDataManager() .getMediaSet(mSetPathString); if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) { // Use the name of the camera album rather than the default // ComboAlbum behavior ((ComboAlbum) originalSet).useNameOfChild(1); } mSelectionManager.setSourceMediaSet(originalSet); mSetPathString = "/filter/delete/{" + mSetPathString + "}"; mMediaSet = (FilterDeleteSet) mActivity.getDataManager() .getMediaSet(mSetPathString); if (mMediaSet == null) { Log.w(TAG, "failed to restore " + mSetPathString); } if (itemPath == null) { int mediaItemCount = mMediaSet.getMediaItemCount(); if (mediaItemCount > 0) { if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0; itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1) .get(0).getPath(); } else { // Bail out, PhotoPage can't load on an empty album return; } } PhotoDataAdapter pda = new PhotoDataAdapter( mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex, mAppBridge == null ? -1 : 0, mAppBridge == null ? false : mAppBridge.isPanorama(), mAppBridge == null ? false : mAppBridge.isStaticCamera()); mModel = pda; mPhotoView.setModel(mModel); pda.setDataListener(new PhotoDataAdapter.DataListener() { @Override public void onPhotoChanged(int index, Path item) { int oldIndex = mCurrentIndex; mCurrentIndex = index; if (mHasCameraScreennailOrPlaceholder) { if (mCurrentIndex > 0) { mSkipUpdateCurrentPhoto = false; } if (oldIndex == 0 && mCurrentIndex > 0 && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); } else if (oldIndex == 2 && mCurrentIndex == 1) { mCameraSwitchCutoff = SystemClock.uptimeMillis() + CAMERA_SWITCH_CUTOFF_THRESHOLD_MS; mPhotoView.stopScrolling(); } else if (oldIndex >= 1 && mCurrentIndex == 0) { mPhotoView.setWantPictureCenterCallbacks(true); mSkipUpdateCurrentPhoto = true; } } if (!mSkipUpdateCurrentPhoto) { if (item != null) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } updateBars(); } // Reset the timeout for the bars after a swipe refreshHidingMessage(); } @Override public void onLoadingFinished(boolean loadingFailed) { if (!mModel.isEmpty()) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } else if (mIsActive) { // We only want to finish the PhotoPage if there is no // deletion that the user can undo. if (mMediaSet.getNumberOfDeletions() == 0) { mActivity.getStateManager().finishState( PhotoPage.this); } } } @Override public void onLoadingStarted() { } }); } else { // Get default media set by the URI MediaItem mediaItem = (MediaItem) mActivity.getDataManager().getMediaObject(itemPath); mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem); mPhotoView.setModel(mModel); updateCurrentPhoto(mediaItem); mShowSpinner = false; } mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1); RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity) .findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root); if (galleryRoot != null) { if (mSecureAlbum == null) { mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot); } StitchingProgressManager progressManager = mApplication.getStitchingProgressManager(); if (progressManager != null) { mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot); mProgressListener = new UpdateProgressListener(); progressManager.addChangeListener(mProgressListener); if (mSecureAlbum != null) { progressManager.addChangeListener(mSecureAlbum); } } } }
public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mActionBar = mActivity.getGalleryActionBar(); mSelectionManager = new SelectionManager(mActivity, false); mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager); mPhotoView = new PhotoView(mActivity); mPhotoView.setListener(this); mRootPane.addComponent(mPhotoView); mApplication = (GalleryApp) ((Activity) mActivity).getApplication(); mOrientationManager = mActivity.getOrientationManager(); mActivity.getGLRoot().setOrientationSource(mOrientationManager); mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_HIDE_BARS: { hideBars(); break; } case MSG_REFRESH_BOTTOM_CONTROLS: { if (mCurrentPhoto == message.obj && mBottomControls != null) { mIsPanorama = message.arg1 == 1; mIsPanorama360 = message.arg2 == 1; mBottomControls.refresh(); } break; } case MSG_ON_FULL_SCREEN_CHANGED: { if (mAppBridge != null) { mAppBridge.onFullScreenChanged(message.arg1 == 1); } break; } case MSG_UPDATE_ACTION_BAR: { updateBars(); break; } case MSG_WANT_BARS: { wantBars(); break; } case MSG_UNFREEZE_GLROOT: { mActivity.getGLRoot().unfreeze(); break; } case MSG_UPDATE_DEFERRED: { long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis(); if (nextUpdate <= 0) { mDeferredUpdateWaiting = false; updateUIForCurrentPhoto(); } else { mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate); } break; } case MSG_ON_CAMERA_CENTER: { mSkipUpdateCurrentPhoto = false; boolean stayedOnCamera = false; if (!mPhotoView.getFilmMode()) { stayedOnCamera = true; } else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff && mMediaSet.getMediaItemCount() > 1) { mPhotoView.switchToImage(1); } else { if (mAppBridge != null) mPhotoView.setFilmMode(false); stayedOnCamera = true; } if (stayedOnCamera) { if (mAppBridge == null) { launchCamera(); /* We got here by swiping from photo 1 to the placeholder, so make it be the thing that is in focus when the user presses back from the camera app */ mPhotoView.switchToImage(1); } else { updateBars(); updateCurrentPhoto(mModel.getMediaItem(0)); } } break; } case MSG_ON_PICTURE_CENTER: { if (!mPhotoView.getFilmMode() && mCurrentPhoto != null && (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) { mPhotoView.setFilmMode(true); } break; } case MSG_REFRESH_IMAGE: { final MediaItem photo = mCurrentPhoto; mCurrentPhoto = null; updateCurrentPhoto(photo); break; } case MSG_UPDATE_PHOTO_UI: { updateUIForCurrentPhoto(); break; } case MSG_UPDATE_PROGRESS: { updateProgressBar(); break; } case MSG_UPDATE_SHARE_URI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; Uri contentUri = mCurrentPhoto.getContentUri(); Intent panoramaIntent = null; if (isPanorama360) { panoramaIntent = createSharePanoramaIntent(contentUri); } Intent shareIntent = createShareIntent(mCurrentPhoto); mActionBar.setShareIntents(panoramaIntent, shareIntent); setNfcBeamPushUri(contentUri); } break; } case MSG_UPDATE_PANORAMA_UI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; updatePanoramaUI(isPanorama360); } break; } default: throw new AssertionError(message.what); } } }; mSetPathString = data.getString(KEY_MEDIA_SET_PATH); mOriginalSetPathString = mSetPathString; setupNfcBeamPush(); String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH); Path itemPath = itemPathString != null ? Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) : null; mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false); mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false); boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false); mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0); if (mSetPathString != null) { mShowSpinner = true; mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE); if (mAppBridge != null) { mShowBars = false; mHasCameraScreennailOrPlaceholder = true; mAppBridge.setServer(this); // Get the ScreenNail from AppBridge and register it. int id = SnailSource.newId(); Path screenNailSetPath = SnailSource.getSetPath(id); Path screenNailItemPath = SnailSource.getItemPath(id); mScreenNailSet = (SnailAlbum) mActivity.getDataManager() .getMediaObject(screenNailSetPath); mScreenNailItem = (SnailItem) mActivity.getDataManager() .getMediaObject(screenNailItemPath); mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) { // Set the flag to be on top of the lock screen. mFlags |= FLAG_SHOW_WHEN_LOCKED; } // Don't display "empty album" action item for capture intents. if (!mSetPathString.equals("/local/all/0")) { // Check if the path is a secure album. if (SecureSource.isSecurePath(mSetPathString)) { mSecureAlbum = (SecureAlbum) mActivity.getDataManager() .getMediaSet(mSetPathString); mShowSpinner = false; } mSetPathString = "/filter/empty/{"+mSetPathString+"}"; } // Combine the original MediaSet with the one for ScreenNail // from AppBridge. mSetPathString = "/combo/item/{" + screenNailSetPath + "," + mSetPathString + "}"; // Start from the screen nail. itemPath = screenNailItemPath; } else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) { mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT + "," + mSetPathString + "}"; mCurrentIndex++; mHasCameraScreennailOrPlaceholder = true; } MediaSet originalSet = mActivity.getDataManager() .getMediaSet(mSetPathString); if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) { // Use the name of the camera album rather than the default // ComboAlbum behavior ((ComboAlbum) originalSet).useNameOfChild(1); } mSelectionManager.setSourceMediaSet(originalSet); mSetPathString = "/filter/delete/{" + mSetPathString + "}"; mMediaSet = (FilterDeleteSet) mActivity.getDataManager() .getMediaSet(mSetPathString); if (mMediaSet == null) { Log.w(TAG, "failed to restore " + mSetPathString); } if (itemPath == null) { int mediaItemCount = mMediaSet.getMediaItemCount(); if (mediaItemCount > 0) { if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0; itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1) .get(0).getPath(); } else { // Bail out, PhotoPage can't load on an empty album return; } } PhotoDataAdapter pda = new PhotoDataAdapter( mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex, mAppBridge == null ? -1 : 0, mAppBridge == null ? false : mAppBridge.isPanorama(), mAppBridge == null ? false : mAppBridge.isStaticCamera()); mModel = pda; mPhotoView.setModel(mModel); pda.setDataListener(new PhotoDataAdapter.DataListener() { @Override public void onPhotoChanged(int index, Path item) { int oldIndex = mCurrentIndex; mCurrentIndex = index; if (mHasCameraScreennailOrPlaceholder) { if (mCurrentIndex > 0) { mSkipUpdateCurrentPhoto = false; } if (oldIndex == 0 && mCurrentIndex > 0 && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); } else if (oldIndex == 2 && mCurrentIndex == 1) { mCameraSwitchCutoff = SystemClock.uptimeMillis() + CAMERA_SWITCH_CUTOFF_THRESHOLD_MS; mPhotoView.stopScrolling(); } else if (oldIndex >= 1 && mCurrentIndex == 0) { mPhotoView.setWantPictureCenterCallbacks(true); mSkipUpdateCurrentPhoto = true; } } if (!mSkipUpdateCurrentPhoto) { if (item != null) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } updateBars(); } // Reset the timeout for the bars after a swipe refreshHidingMessage(); } @Override public void onLoadingFinished(boolean loadingFailed) { if (!mModel.isEmpty()) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } else if (mIsActive) { // We only want to finish the PhotoPage if there is no // deletion that the user can undo. if (mMediaSet.getNumberOfDeletions() == 0) { mActivity.getStateManager().finishState( PhotoPage.this); } } } @Override public void onLoadingStarted() { } }); } else { // Get default media set by the URI MediaItem mediaItem = (MediaItem) mActivity.getDataManager().getMediaObject(itemPath); mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem); mPhotoView.setModel(mModel); updateCurrentPhoto(mediaItem); mShowSpinner = false; } mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1); RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity) .findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root); if (galleryRoot != null) { if (mSecureAlbum == null) { mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot); } StitchingProgressManager progressManager = mApplication.getStitchingProgressManager(); if (progressManager != null) { mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot); mProgressListener = new UpdateProgressListener(); progressManager.addChangeListener(mProgressListener); if (mSecureAlbum != null) { progressManager.addChangeListener(mSecureAlbum); } } } }
diff --git a/src/com/shade/lighting/LightMask.java b/src/com/shade/lighting/LightMask.java index 0828cb0..db17042 100644 --- a/src/com/shade/lighting/LightMask.java +++ b/src/com/shade/lighting/LightMask.java @@ -1,164 +1,168 @@ package com.shade.lighting; import java.util.Arrays; import java.util.LinkedList; import org.lwjgl.opengl.GL11; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.state.StateBasedGame; import com.shade.controls.DayPhaseTimer; /** * A view which renders a set of entities, lights, and background images in such * a way as to generate dynamic lighting. * * It's safe to draw things to the screen after calling LightMask.render if you * want them to appear above the gameplay, for instance user controls. * * <em>Note that calling render will update your entities' luminosity. Please * direct any hate mail to JJ Jou.</em> * * @author JJ Jou <[email protected]> * @author Alexander Schearer <[email protected]> */ public class LightMask { protected final static Color SHADE = new Color(0, 0, 0, .3f); public static final float MAX_DARKNESS = 0.4f; private DayPhaseTimer timer; /**======================END CONSTANTS=======================*/ private int threshold; private LinkedList<LightSource> lights; public LightMask(int threshold, DayPhaseTimer time) { this.threshold = threshold; lights = new LinkedList<LightSource>(); timer = time; } public void add(LightSource light) { lights.add(light); } public void render(StateBasedGame game, Graphics g, LuminousEntity[] entities, Image... backgrounds) { renderLights(game, g, entities); renderBackgrounds(game, g, backgrounds); renderEntities(game, g, entities); //RENDER NIGHT! WHEEE renderTimeOfDay(game, g); } public void renderTimeOfDay(StateBasedGame game, Graphics g){ Color c = g.getColor(); if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.DUSK){ g.setColor(new Color(1-timer.timeLeft(),1-timer.timeLeft(),0f,MAX_DARKNESS*timer.timeLeft())); g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight()); } else if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.NIGHT){ g.setColor(new Color(0,0,0,MAX_DARKNESS)); g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight()); } else if(timer.getDaylightStatus()==DayPhaseTimer.DayLightStatus.DAWN){ g.setColor(new Color(timer.timeLeft(),timer.timeLeft(),0,MAX_DARKNESS*(1-timer.timeLeft()))); g.fillRect(0, 0, game.getContainer().getWidth(), game.getContainer().getHeight()); } g.setColor(c); } private void renderLights(StateBasedGame game, Graphics g, LuminousEntity... entities) { enableStencil(); for (LightSource light : lights) { light.render(game, g, entities); } disableStencil(); GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); g.setColor(SHADE); GameContainer c = game.getContainer(); g.fillRect(0, 0, c.getWidth(), c.getHeight()); g.setColor(Color.white); } private void renderBackgrounds(StateBasedGame game, Graphics g, Image... backgrounds) { GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ONE); for (Image background : backgrounds) { background.draw(); } } private void renderEntities(StateBasedGame game, Graphics g, LuminousEntity... entities) { Arrays.sort(entities); int i = 0; - GL11.glEnable(GL11.GL_ALPHA_TEST); + // GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_STENCIL_TEST); + GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 1); + GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_REPLACE); GL11.glAlphaFunc(GL11.GL_GREATER, 0); - GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ZERO); + GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); while (i < entities.length && entities[i].getZIndex() < threshold) { entities[i].render(game, g); entities[i].setLuminosity(getLuminosityFor(entities[i], g)); i++; } GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); while (i < entities.length) { entities[i].render(game, g); entities[i].setLuminosity(getLuminosityFor(entities[i], g)); i++; } + GL11.glDisable(GL11.GL_STENCIL_TEST); GL11.glDisable(GL11.GL_ALPHA_TEST); } private float getLuminosityFor(LuminousEntity entity, Graphics g) { return g.getPixel((int) entity.getXCenter(), (int) entity.getYCenter()).a; } /** * Called before drawing the shadows cast by a light. */ protected static void enableStencil() { // write only to the stencil buffer GL11.glEnable(GL11.GL_STENCIL_TEST); GL11.glColorMask(false, false, false, false); GL11.glDepthMask(false); } protected static void resetStencil(){ GL11.glClearStencil(0); // write a one to the stencil buffer everywhere we are about to draw GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 1); // this is to always pass a one to the stencil buffer where we draw GL11.glStencilOp(GL11.GL_REPLACE, GL11.GL_REPLACE, GL11.GL_REPLACE); } /** * Called after drawing the shadows cast by a light. */ protected static void keepStencil() { // resume drawing to everything GL11.glDepthMask(true); GL11.glColorMask(true, true, true, true); GL11.glStencilFunc(GL11.GL_NOTEQUAL, 1, 1); // don't modify the contents of the stencil buffer GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP); GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); } protected static void disableStencil(){ GL11.glDisable(GL11.GL_STENCIL_TEST); GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); } }
false
true
private void renderEntities(StateBasedGame game, Graphics g, LuminousEntity... entities) { Arrays.sort(entities); int i = 0; GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0); GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ZERO); while (i < entities.length && entities[i].getZIndex() < threshold) { entities[i].render(game, g); entities[i].setLuminosity(getLuminosityFor(entities[i], g)); i++; } GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); while (i < entities.length) { entities[i].render(game, g); entities[i].setLuminosity(getLuminosityFor(entities[i], g)); i++; } GL11.glDisable(GL11.GL_ALPHA_TEST); }
private void renderEntities(StateBasedGame game, Graphics g, LuminousEntity... entities) { Arrays.sort(entities); int i = 0; // GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_STENCIL_TEST); GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 1); GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_REPLACE); GL11.glAlphaFunc(GL11.GL_GREATER, 0); GL11.glBlendFunc(GL11.GL_DST_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); while (i < entities.length && entities[i].getZIndex() < threshold) { entities[i].render(game, g); entities[i].setLuminosity(getLuminosityFor(entities[i], g)); i++; } GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); while (i < entities.length) { entities[i].render(game, g); entities[i].setLuminosity(getLuminosityFor(entities[i], g)); i++; } GL11.glDisable(GL11.GL_STENCIL_TEST); GL11.glDisable(GL11.GL_ALPHA_TEST); }
diff --git a/src/com/android/providers/downloads/DownloadNotifier.java b/src/com/android/providers/downloads/DownloadNotifier.java index df0bf84..0405478 100644 --- a/src/com/android/providers/downloads/DownloadNotifier.java +++ b/src/com/android/providers/downloads/DownloadNotifier.java @@ -1,366 +1,368 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.providers.downloads; import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE; import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED; import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION; import static android.provider.Downloads.Impl.STATUS_RUNNING; import static com.android.providers.downloads.Constants.TAG; import android.app.DownloadManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.SystemClock; import android.provider.Downloads; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.Log; import android.util.LongSparseLongArray; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import javax.annotation.concurrent.GuardedBy; /** * Update {@link NotificationManager} to reflect current {@link DownloadInfo} * states. Collapses similar downloads into a single notification, and builds * {@link PendingIntent} that launch towards {@link DownloadReceiver}. */ public class DownloadNotifier { private static final int TYPE_ACTIVE = 1; private static final int TYPE_WAITING = 2; private static final int TYPE_COMPLETE = 3; private final Context mContext; private final NotificationManager mNotifManager; /** * Currently active notifications, mapped from clustering tag to timestamp * when first shown. * * @see #buildNotificationTag(DownloadInfo) */ @GuardedBy("mActiveNotifs") private final HashMap<String, Long> mActiveNotifs = Maps.newHashMap(); /** * Current speed of active downloads, mapped from {@link DownloadInfo#mId} * to speed in bytes per second. */ @GuardedBy("mDownloadSpeed") private final LongSparseLongArray mDownloadSpeed = new LongSparseLongArray(); /** * Last time speed was reproted, mapped from {@link DownloadInfo#mId} to * {@link SystemClock#elapsedRealtime()}. */ @GuardedBy("mDownloadSpeed") private final LongSparseLongArray mDownloadTouch = new LongSparseLongArray(); public DownloadNotifier(Context context) { mContext = context; mNotifManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE); } public void cancelAll() { mNotifManager.cancelAll(); } /** * Notify the current speed of an active download, used for calculating * estimated remaining time. */ public void notifyDownloadSpeed(long id, long bytesPerSecond) { synchronized (mDownloadSpeed) { if (bytesPerSecond != 0) { mDownloadSpeed.put(id, bytesPerSecond); mDownloadTouch.put(id, SystemClock.elapsedRealtime()); } else { mDownloadSpeed.delete(id); mDownloadTouch.delete(id); } } } /** * Update {@link NotificationManager} to reflect the given set of * {@link DownloadInfo}, adding, collapsing, and removing as needed. */ public void updateWith(Collection<DownloadInfo> downloads) { synchronized (mActiveNotifs) { updateWithLocked(downloads); } } private void updateWithLocked(Collection<DownloadInfo> downloads) { final Resources res = mContext.getResources(); // Cluster downloads together final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create(); for (DownloadInfo info : downloads) { final String tag = buildNotificationTag(info); if (tag != null) { clustered.put(tag, info); } } // Build notification for each cluster for (String tag : clustered.keySet()) { final int type = getNotificationTagType(tag); final Collection<DownloadInfo> cluster = clustered.get(tag); final Notification.Builder builder = new Notification.Builder(mContext); // Use time when cluster was first shown to avoid shuffling final long firstShown; if (mActiveNotifs.containsKey(tag)) { firstShown = mActiveNotifs.get(tag); } else { firstShown = System.currentTimeMillis(); mActiveNotifs.put(tag, firstShown); } builder.setWhen(firstShown); // Show relevant icon if (type == TYPE_ACTIVE) { builder.setSmallIcon(android.R.drawable.stat_sys_download); } else if (type == TYPE_WAITING) { builder.setSmallIcon(android.R.drawable.stat_sys_warning); } else if (type == TYPE_COMPLETE) { builder.setSmallIcon(android.R.drawable.stat_sys_download_done); } // Build action intents if (type == TYPE_ACTIVE || type == TYPE_WAITING) { + // build a synthetic uri for intent identification purposes + final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build(); final Intent intent = new Intent(Constants.ACTION_LIST, - null, mContext, DownloadReceiver.class); + uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); - builder.setContentIntent(PendingIntent.getBroadcast( - mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); + builder.setContentIntent(PendingIntent.getBroadcast(mContext, + 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); builder.setOngoing(true); } else if (type == TYPE_COMPLETE) { final DownloadInfo info = cluster.iterator().next(); final Uri uri = ContentUris.withAppendedId( Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId); final String action; if (Downloads.Impl.isStatusError(info.mStatus)) { action = Constants.ACTION_LIST; } else { if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) { action = Constants.ACTION_OPEN; } else { action = Constants.ACTION_LIST; } } final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); - builder.setContentIntent(PendingIntent.getBroadcast( - mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); + builder.setContentIntent(PendingIntent.getBroadcast(mContext, + 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class); builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0)); } // Calculate and show progress String remainingText = null; String percentText = null; if (type == TYPE_ACTIVE) { long current = 0; long total = 0; long speed = 0; synchronized (mDownloadSpeed) { for (DownloadInfo info : cluster) { if (info.mTotalBytes != -1) { current += info.mCurrentBytes; total += info.mTotalBytes; speed += mDownloadSpeed.get(info.mId); } } } if (total > 0) { final int percent = (int) ((current * 100) / total); percentText = res.getString(R.string.download_percent, percent); if (speed > 0) { final long remainingMillis = ((total - current) * 1000) / speed; remainingText = res.getString(R.string.download_remaining, DateUtils.formatDuration(remainingMillis)); } builder.setProgress(100, percent, false); } else { builder.setProgress(100, 0, true); } } // Build titles and description final Notification notif; if (cluster.size() == 1) { final DownloadInfo info = cluster.iterator().next(); builder.setContentTitle(getDownloadTitle(res, info)); if (type == TYPE_ACTIVE) { if (!TextUtils.isEmpty(info.mDescription)) { builder.setContentText(info.mDescription); } else { builder.setContentText(remainingText); } builder.setContentInfo(percentText); } else if (type == TYPE_WAITING) { builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); } else if (type == TYPE_COMPLETE) { if (Downloads.Impl.isStatusError(info.mStatus)) { builder.setContentText(res.getText(R.string.notification_download_failed)); } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) { builder.setContentText( res.getText(R.string.notification_download_complete)); } } notif = builder.build(); } else { final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder); for (DownloadInfo info : cluster) { inboxStyle.addLine(getDownloadTitle(res, info)); } if (type == TYPE_ACTIVE) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_active, cluster.size(), cluster.size())); builder.setContentText(remainingText); builder.setContentInfo(percentText); inboxStyle.setSummaryText(remainingText); } else if (type == TYPE_WAITING) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_waiting, cluster.size(), cluster.size())); builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); inboxStyle.setSummaryText( res.getString(R.string.notification_need_wifi_for_size)); } notif = inboxStyle.build(); } mNotifManager.notify(tag, 0, notif); } // Remove stale tags that weren't renewed final Iterator<String> it = mActiveNotifs.keySet().iterator(); while (it.hasNext()) { final String tag = it.next(); if (!clustered.containsKey(tag)) { mNotifManager.cancel(tag, 0); it.remove(); } } } private static CharSequence getDownloadTitle(Resources res, DownloadInfo info) { if (!TextUtils.isEmpty(info.mTitle)) { return info.mTitle; } else { return res.getString(R.string.download_unknown_title); } } private long[] getDownloadIds(Collection<DownloadInfo> infos) { final long[] ids = new long[infos.size()]; int i = 0; for (DownloadInfo info : infos) { ids[i++] = info.mId; } return ids; } public void dumpSpeeds() { synchronized (mDownloadSpeed) { for (int i = 0; i < mDownloadSpeed.size(); i++) { final long id = mDownloadSpeed.keyAt(i); final long delta = SystemClock.elapsedRealtime() - mDownloadTouch.get(id); Log.d(TAG, "Download " + id + " speed " + mDownloadSpeed.valueAt(i) + "bps, " + delta + "ms ago"); } } } /** * Build tag used for collapsing several {@link DownloadInfo} into a single * {@link Notification}. */ private static String buildNotificationTag(DownloadInfo info) { if (info.mStatus == Downloads.Impl.STATUS_QUEUED_FOR_WIFI) { return TYPE_WAITING + ":" + info.mPackage; } else if (isActiveAndVisible(info)) { return TYPE_ACTIVE + ":" + info.mPackage; } else if (isCompleteAndVisible(info)) { // Complete downloads always have unique notifs return TYPE_COMPLETE + ":" + info.mId; } else { return null; } } /** * Return the cluster type of the given tag, as created by * {@link #buildNotificationTag(DownloadInfo)}. */ private static int getNotificationTagType(String tag) { return Integer.parseInt(tag.substring(0, tag.indexOf(':'))); } private static boolean isActiveAndVisible(DownloadInfo download) { return download.mStatus == STATUS_RUNNING && (download.mVisibility == VISIBILITY_VISIBLE || download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } private static boolean isCompleteAndVisible(DownloadInfo download) { return Downloads.Impl.isStatusCompleted(download.mStatus) && (download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED || download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION); } }
false
true
private void updateWithLocked(Collection<DownloadInfo> downloads) { final Resources res = mContext.getResources(); // Cluster downloads together final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create(); for (DownloadInfo info : downloads) { final String tag = buildNotificationTag(info); if (tag != null) { clustered.put(tag, info); } } // Build notification for each cluster for (String tag : clustered.keySet()) { final int type = getNotificationTagType(tag); final Collection<DownloadInfo> cluster = clustered.get(tag); final Notification.Builder builder = new Notification.Builder(mContext); // Use time when cluster was first shown to avoid shuffling final long firstShown; if (mActiveNotifs.containsKey(tag)) { firstShown = mActiveNotifs.get(tag); } else { firstShown = System.currentTimeMillis(); mActiveNotifs.put(tag, firstShown); } builder.setWhen(firstShown); // Show relevant icon if (type == TYPE_ACTIVE) { builder.setSmallIcon(android.R.drawable.stat_sys_download); } else if (type == TYPE_WAITING) { builder.setSmallIcon(android.R.drawable.stat_sys_warning); } else if (type == TYPE_COMPLETE) { builder.setSmallIcon(android.R.drawable.stat_sys_download_done); } // Build action intents if (type == TYPE_ACTIVE || type == TYPE_WAITING) { final Intent intent = new Intent(Constants.ACTION_LIST, null, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent(PendingIntent.getBroadcast( mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); builder.setOngoing(true); } else if (type == TYPE_COMPLETE) { final DownloadInfo info = cluster.iterator().next(); final Uri uri = ContentUris.withAppendedId( Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId); final String action; if (Downloads.Impl.isStatusError(info.mStatus)) { action = Constants.ACTION_LIST; } else { if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) { action = Constants.ACTION_OPEN; } else { action = Constants.ACTION_LIST; } } final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent(PendingIntent.getBroadcast( mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class); builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0)); } // Calculate and show progress String remainingText = null; String percentText = null; if (type == TYPE_ACTIVE) { long current = 0; long total = 0; long speed = 0; synchronized (mDownloadSpeed) { for (DownloadInfo info : cluster) { if (info.mTotalBytes != -1) { current += info.mCurrentBytes; total += info.mTotalBytes; speed += mDownloadSpeed.get(info.mId); } } } if (total > 0) { final int percent = (int) ((current * 100) / total); percentText = res.getString(R.string.download_percent, percent); if (speed > 0) { final long remainingMillis = ((total - current) * 1000) / speed; remainingText = res.getString(R.string.download_remaining, DateUtils.formatDuration(remainingMillis)); } builder.setProgress(100, percent, false); } else { builder.setProgress(100, 0, true); } } // Build titles and description final Notification notif; if (cluster.size() == 1) { final DownloadInfo info = cluster.iterator().next(); builder.setContentTitle(getDownloadTitle(res, info)); if (type == TYPE_ACTIVE) { if (!TextUtils.isEmpty(info.mDescription)) { builder.setContentText(info.mDescription); } else { builder.setContentText(remainingText); } builder.setContentInfo(percentText); } else if (type == TYPE_WAITING) { builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); } else if (type == TYPE_COMPLETE) { if (Downloads.Impl.isStatusError(info.mStatus)) { builder.setContentText(res.getText(R.string.notification_download_failed)); } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) { builder.setContentText( res.getText(R.string.notification_download_complete)); } } notif = builder.build(); } else { final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder); for (DownloadInfo info : cluster) { inboxStyle.addLine(getDownloadTitle(res, info)); } if (type == TYPE_ACTIVE) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_active, cluster.size(), cluster.size())); builder.setContentText(remainingText); builder.setContentInfo(percentText); inboxStyle.setSummaryText(remainingText); } else if (type == TYPE_WAITING) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_waiting, cluster.size(), cluster.size())); builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); inboxStyle.setSummaryText( res.getString(R.string.notification_need_wifi_for_size)); } notif = inboxStyle.build(); } mNotifManager.notify(tag, 0, notif); } // Remove stale tags that weren't renewed final Iterator<String> it = mActiveNotifs.keySet().iterator(); while (it.hasNext()) { final String tag = it.next(); if (!clustered.containsKey(tag)) { mNotifManager.cancel(tag, 0); it.remove(); } } }
private void updateWithLocked(Collection<DownloadInfo> downloads) { final Resources res = mContext.getResources(); // Cluster downloads together final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create(); for (DownloadInfo info : downloads) { final String tag = buildNotificationTag(info); if (tag != null) { clustered.put(tag, info); } } // Build notification for each cluster for (String tag : clustered.keySet()) { final int type = getNotificationTagType(tag); final Collection<DownloadInfo> cluster = clustered.get(tag); final Notification.Builder builder = new Notification.Builder(mContext); // Use time when cluster was first shown to avoid shuffling final long firstShown; if (mActiveNotifs.containsKey(tag)) { firstShown = mActiveNotifs.get(tag); } else { firstShown = System.currentTimeMillis(); mActiveNotifs.put(tag, firstShown); } builder.setWhen(firstShown); // Show relevant icon if (type == TYPE_ACTIVE) { builder.setSmallIcon(android.R.drawable.stat_sys_download); } else if (type == TYPE_WAITING) { builder.setSmallIcon(android.R.drawable.stat_sys_warning); } else if (type == TYPE_COMPLETE) { builder.setSmallIcon(android.R.drawable.stat_sys_download_done); } // Build action intents if (type == TYPE_ACTIVE || type == TYPE_WAITING) { // build a synthetic uri for intent identification purposes final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build(); final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); builder.setOngoing(true); } else if (type == TYPE_COMPLETE) { final DownloadInfo info = cluster.iterator().next(); final Uri uri = ContentUris.withAppendedId( Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId); final String action; if (Downloads.Impl.isStatusError(info.mStatus)) { action = Constants.ACTION_LIST; } else { if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) { action = Constants.ACTION_OPEN; } else { action = Constants.ACTION_LIST; } } final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class); builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0)); } // Calculate and show progress String remainingText = null; String percentText = null; if (type == TYPE_ACTIVE) { long current = 0; long total = 0; long speed = 0; synchronized (mDownloadSpeed) { for (DownloadInfo info : cluster) { if (info.mTotalBytes != -1) { current += info.mCurrentBytes; total += info.mTotalBytes; speed += mDownloadSpeed.get(info.mId); } } } if (total > 0) { final int percent = (int) ((current * 100) / total); percentText = res.getString(R.string.download_percent, percent); if (speed > 0) { final long remainingMillis = ((total - current) * 1000) / speed; remainingText = res.getString(R.string.download_remaining, DateUtils.formatDuration(remainingMillis)); } builder.setProgress(100, percent, false); } else { builder.setProgress(100, 0, true); } } // Build titles and description final Notification notif; if (cluster.size() == 1) { final DownloadInfo info = cluster.iterator().next(); builder.setContentTitle(getDownloadTitle(res, info)); if (type == TYPE_ACTIVE) { if (!TextUtils.isEmpty(info.mDescription)) { builder.setContentText(info.mDescription); } else { builder.setContentText(remainingText); } builder.setContentInfo(percentText); } else if (type == TYPE_WAITING) { builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); } else if (type == TYPE_COMPLETE) { if (Downloads.Impl.isStatusError(info.mStatus)) { builder.setContentText(res.getText(R.string.notification_download_failed)); } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) { builder.setContentText( res.getText(R.string.notification_download_complete)); } } notif = builder.build(); } else { final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder); for (DownloadInfo info : cluster) { inboxStyle.addLine(getDownloadTitle(res, info)); } if (type == TYPE_ACTIVE) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_active, cluster.size(), cluster.size())); builder.setContentText(remainingText); builder.setContentInfo(percentText); inboxStyle.setSummaryText(remainingText); } else if (type == TYPE_WAITING) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_waiting, cluster.size(), cluster.size())); builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); inboxStyle.setSummaryText( res.getString(R.string.notification_need_wifi_for_size)); } notif = inboxStyle.build(); } mNotifManager.notify(tag, 0, notif); } // Remove stale tags that weren't renewed final Iterator<String> it = mActiveNotifs.keySet().iterator(); while (it.hasNext()) { final String tag = it.next(); if (!clustered.containsKey(tag)) { mNotifManager.cancel(tag, 0); it.remove(); } } }
diff --git a/src/me/ThaH3lper/com/SkillsCollection/SkillSwarm.java b/src/me/ThaH3lper/com/SkillsCollection/SkillSwarm.java index 2b78242..754b07a 100644 --- a/src/me/ThaH3lper/com/SkillsCollection/SkillSwarm.java +++ b/src/me/ThaH3lper/com/SkillsCollection/SkillSwarm.java @@ -1,67 +1,67 @@ package me.ThaH3lper.com.SkillsCollection; import me.ThaH3lper.com.EpicBoss; import me.ThaH3lper.com.API.BossSkillEvent; import me.ThaH3lper.com.Mobs.AllMobs; import me.ThaH3lper.com.Mobs.EpicMobs; import me.ThaH3lper.com.Mobs.MobCommon; import me.ThaH3lper.com.Mobs.MobHandler; import me.ThaH3lper.com.Skills.SkillHandler; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; public class SkillSwarm { //- swarm type:amount:radious =HP chance // $boss public static void ExecuteSwarm(LivingEntity l, String skill, Player player) { String[] base = skill.split(" "); String[] data = base[1].split(":"); float chance = Float.parseFloat(base[base.length-1]); if(EpicBoss.r.nextFloat() < chance) { if(SkillHandler.CheckHealth(base[base.length-2], l, skill)) { BossSkillEvent event = new BossSkillEvent(l, skill, player, false); Bukkit.getServer().getPluginManager().callEvent(event); if(event.isChanceled()) return; int amount = Integer.parseInt(data[1]); int radious = Integer.parseInt(data[2]); if(data[0].contains("$")) { String s = data[0].replace("$", ""); EpicMobs em = MobCommon.getEpicMob(s); if(em != null) { - for(int i = 0; i <= amount; i++) + for(int i = 1; i <= amount; i++) { double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2)); double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2)); Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z); MobHandler.SpawnMob(s, loc); } } } else { for(int i = 0; i <= amount; i++) { double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2)); double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2)); Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z); AllMobs.spawnMob(data[0], loc); } } } } } }
true
true
public static void ExecuteSwarm(LivingEntity l, String skill, Player player) { String[] base = skill.split(" "); String[] data = base[1].split(":"); float chance = Float.parseFloat(base[base.length-1]); if(EpicBoss.r.nextFloat() < chance) { if(SkillHandler.CheckHealth(base[base.length-2], l, skill)) { BossSkillEvent event = new BossSkillEvent(l, skill, player, false); Bukkit.getServer().getPluginManager().callEvent(event); if(event.isChanceled()) return; int amount = Integer.parseInt(data[1]); int radious = Integer.parseInt(data[2]); if(data[0].contains("$")) { String s = data[0].replace("$", ""); EpicMobs em = MobCommon.getEpicMob(s); if(em != null) { for(int i = 0; i <= amount; i++) { double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2)); double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2)); Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z); MobHandler.SpawnMob(s, loc); } } } else { for(int i = 0; i <= amount; i++) { double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2)); double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2)); Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z); AllMobs.spawnMob(data[0], loc); } } } } }
public static void ExecuteSwarm(LivingEntity l, String skill, Player player) { String[] base = skill.split(" "); String[] data = base[1].split(":"); float chance = Float.parseFloat(base[base.length-1]); if(EpicBoss.r.nextFloat() < chance) { if(SkillHandler.CheckHealth(base[base.length-2], l, skill)) { BossSkillEvent event = new BossSkillEvent(l, skill, player, false); Bukkit.getServer().getPluginManager().callEvent(event); if(event.isChanceled()) return; int amount = Integer.parseInt(data[1]); int radious = Integer.parseInt(data[2]); if(data[0].contains("$")) { String s = data[0].replace("$", ""); EpicMobs em = MobCommon.getEpicMob(s); if(em != null) { for(int i = 1; i <= amount; i++) { double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2)); double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2)); Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z); MobHandler.SpawnMob(s, loc); } } } else { for(int i = 0; i <= amount; i++) { double x = (l.getLocation().getX() - radious) + (EpicBoss.r.nextInt(radious * 2)); double z = (l.getLocation().getZ() - radious) + (EpicBoss.r.nextInt(radious * 2)); Location loc = new Location(l.getWorld(), x, l.getLocation().getY(), z); AllMobs.spawnMob(data[0], loc); } } } } }
diff --git a/src/sai_cas/servlet/CrossMatchServlet.java b/src/sai_cas/servlet/CrossMatchServlet.java index fe2401e..e6c20a3 100644 --- a/src/sai_cas/servlet/CrossMatchServlet.java +++ b/src/sai_cas/servlet/CrossMatchServlet.java @@ -1,211 +1,211 @@ package sai_cas.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.File; import java.util.List; import java.util.Calendar; import java.util.logging.Logger; import java.sql.Connection; import java.sql.SQLException; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.fileupload.*; import org.apache.commons.fileupload.servlet.*; import org.apache.commons.fileupload.disk.*; import sai_cas.db.*; import sai_cas.output.VOTableQueryResultsOutputter; import sai_cas.vo.*; import sai_cas.Votable; import sai_cas.VotableException; public class CrossMatchServlet extends HttpServlet { static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("sai_cas.CrossMatchServlet"); public class CrossMatchServletException extends Exception { CrossMatchServletException() { super(); } CrossMatchServletException(String s) { super(s); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); response.setContentType("text/xml"); String cat = null, tab = null, radString = null; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; VOTableQueryResultsOutputter voqro = new VOTableQueryResultsOutputter(); try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new ServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String tempUser = "cas_user_tmp"; String tempPasswd = "aspen"; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = new Votable (uploadedFile); String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { voqro.printError(out, "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } else { response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); voqro.setResource(cat + "_" + fi.getName() ); - voqro.setResourceDescription("This is the table obtained by"+ - "crossmatching the table "+cat+"."+tab + "with the " + - "user supplied table from the file" + fi.getName()+"\n"+ + voqro.setResourceDescription("This is the table obtained by "+ + "crossmatching the table "+cat+"."+tab + " with the " + + "user supplied table from the file " + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); voqro.print(out,dbi); } } catch (VotableException e) { voqro.printError(out, "Error occured: " + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { voqro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { voqro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { uploadedFile.delete(); } catch (Exception e) { } } } }
true
true
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); response.setContentType("text/xml"); String cat = null, tab = null, radString = null; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; VOTableQueryResultsOutputter voqro = new VOTableQueryResultsOutputter(); try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new ServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String tempUser = "cas_user_tmp"; String tempPasswd = "aspen"; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = new Votable (uploadedFile); String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { voqro.printError(out, "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } else { response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); voqro.setResource(cat + "_" + fi.getName() ); voqro.setResourceDescription("This is the table obtained by"+ "crossmatching the table "+cat+"."+tab + "with the " + "user supplied table from the file" + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); voqro.print(out,dbi); } } catch (VotableException e) { voqro.printError(out, "Error occured: " + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { voqro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { voqro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { uploadedFile.delete(); } catch (Exception e) { } } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); response.setContentType("text/xml"); String cat = null, tab = null, radString = null; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; VOTableQueryResultsOutputter voqro = new VOTableQueryResultsOutputter(); try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new ServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String tempUser = "cas_user_tmp"; String tempPasswd = "aspen"; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = new Votable (uploadedFile); String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { voqro.printError(out, "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } else { response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); voqro.setResource(cat + "_" + fi.getName() ); voqro.setResourceDescription("This is the table obtained by "+ "crossmatching the table "+cat+"."+tab + " with the " + "user supplied table from the file " + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); voqro.print(out,dbi); } } catch (VotableException e) { voqro.printError(out, "Error occured: " + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { voqro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { voqro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); voqro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { uploadedFile.delete(); } catch (Exception e) { } } }
diff --git a/runtime/android/java/src/org/xwalk/core/XWalkContent.java b/runtime/android/java/src/org/xwalk/core/XWalkContent.java index 79003184..7b8f143e 100644 --- a/runtime/android/java/src/org/xwalk/core/XWalkContent.java +++ b/runtime/android/java/src/org/xwalk/core/XWalkContent.java @@ -1,202 +1,204 @@ // Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.core; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Rect; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.FrameLayout; import org.chromium.base.JNINamespace; import org.chromium.content.browser.ContentVideoView; import org.chromium.content.browser.ContentView; import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.ContentViewRenderView; import org.chromium.content.browser.LoadUrlParams; import org.chromium.content.browser.NavigationHistory; import org.chromium.ui.WindowAndroid; @JNINamespace("xwalk") /** * This class is the implementation class for XWalkView by calling internal * various classes. */ public class XWalkContent extends FrameLayout { private ContentViewCore mContentViewCore; private ContentView mContentView; private ContentViewRenderView mContentViewRenderView; private WindowAndroid mWindow; private XWalkView mXWalkView; private XWalkContentsClientBridge mContentsClientBridge; private XWalkWebContentsDelegateAdapter mXWalkContentsDelegateAdapter; private XWalkSettings mSettings; int mXWalkContent; int mWebContents; boolean mReadyToLoad = false; String mPendingUrl = null; public XWalkContent(Context context, AttributeSet attrs, XWalkView xwView) { super(context, attrs); // Initialize the WebContensDelegate. mXWalkView = xwView; mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView); mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter( mContentsClientBridge); // Initialize ContentViewRenderView mContentViewRenderView = new ContentViewRenderView(context) { protected void onReadyToRender() { - if (mPendingUrl != null) + if (mPendingUrl != null) { doLoadUrl(mPendingUrl); + mPendingUrl = null; + } mReadyToLoad = true; } }; addView(mContentViewRenderView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mXWalkContent = nativeInit(mXWalkContentsDelegateAdapter, mContentsClientBridge); mWebContents = nativeGetWebContents(mXWalkContent); // Initialize mWindow which is needed by content mWindow = new WindowAndroid(xwView.getActivity()); // Initialize ContentView. mContentView = ContentView.newInstance(getContext(), mWebContents, mWindow); addView(mContentView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mContentView.setContentViewClient(mContentsClientBridge); mContentViewRenderView.setCurrentContentView(mContentView); // For addJavascriptInterface mContentViewCore = mContentView.getContentViewCore(); mContentsClientBridge.installWebContentsObserver(mContentViewCore); mSettings = new XWalkSettings(getContext(), mWebContents, true); } void doLoadUrl(String url) { //TODO(Xingnan): Configure appropriate parameters here. // Handle the same url loading by parameters. if (TextUtils.equals(url, mContentView.getUrl())) { mContentView.reload(); } else { mContentView.loadUrl(new LoadUrlParams(url)); } mContentView.clearFocus(); mContentView.requestFocus(); } public void loadUrl(String url) { if (url == null) return; if (mReadyToLoad) doLoadUrl(url); else mPendingUrl = url; } public String getUrl() { String url = mContentView.getUrl(); if (url == null || url.trim().isEmpty()) return null; return url; } public void addJavascriptInterface(Object object, String name) { mContentViewCore.addJavascriptInterface(object, name); } public void setXWalkWebChromeClient(XWalkWebChromeClient client) { mContentsClientBridge.setXWalkWebChromeClient(client); } public void setXWalkClient(XWalkClient client) { mContentsClientBridge.setXWalkClient(client); } public void onPause() { mContentViewCore.onActivityPause(); } public void onResume() { mContentViewCore.onActivityResume(); } public void onActivityResult(int requestCode, int resultCode, Intent data) { mWindow.onActivityResult(requestCode, resultCode, data); } public void clearCache(boolean includeDiskFiles) { if (mXWalkContent == 0) return; nativeClearCache(mXWalkContent, includeDiskFiles); } public boolean canGoBack() { return mContentView.canGoBack(); } public void goBack() { mContentView.goBack(); } public boolean canGoForward() { return mContentView.canGoForward(); } public void goForward() { mContentView.goForward(); } public void stopLoading() { mContentView.stopLoading(); } public String getOriginalUrl() { NavigationHistory history = mContentViewCore.getNavigationHistory(); int currentIndex = history.getCurrentEntryIndex(); if (currentIndex >= 0 && currentIndex < history.getEntryCount()) { return history.getEntryAtIndex(currentIndex).getOriginalUrl(); } return null; } // For instrumentation test. public ContentViewCore getContentViewCoreForTest() { return mContentViewCore; } // For instrumentation test. public void installWebContentsObserverForTest(XWalkContentsClient contentClient) { contentClient.installWebContentsObserver(mContentViewCore); } public String devToolsAgentId() { return nativeDevToolsAgentId(mXWalkContent); } public XWalkSettings getSettings() { return mSettings; } private native int nativeInit(XWalkWebContentsDelegate webViewContentsDelegate, XWalkContentsClientBridge bridge); private native int nativeGetWebContents(int nativeXWalkContent); private native void nativeClearCache(int nativeXWalkContent, boolean includeDiskFiles); private native String nativeDevToolsAgentId(int nativeXWalkContent); }
false
true
public XWalkContent(Context context, AttributeSet attrs, XWalkView xwView) { super(context, attrs); // Initialize the WebContensDelegate. mXWalkView = xwView; mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView); mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter( mContentsClientBridge); // Initialize ContentViewRenderView mContentViewRenderView = new ContentViewRenderView(context) { protected void onReadyToRender() { if (mPendingUrl != null) doLoadUrl(mPendingUrl); mReadyToLoad = true; } }; addView(mContentViewRenderView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mXWalkContent = nativeInit(mXWalkContentsDelegateAdapter, mContentsClientBridge); mWebContents = nativeGetWebContents(mXWalkContent); // Initialize mWindow which is needed by content mWindow = new WindowAndroid(xwView.getActivity()); // Initialize ContentView. mContentView = ContentView.newInstance(getContext(), mWebContents, mWindow); addView(mContentView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mContentView.setContentViewClient(mContentsClientBridge); mContentViewRenderView.setCurrentContentView(mContentView); // For addJavascriptInterface mContentViewCore = mContentView.getContentViewCore(); mContentsClientBridge.installWebContentsObserver(mContentViewCore); mSettings = new XWalkSettings(getContext(), mWebContents, true); }
public XWalkContent(Context context, AttributeSet attrs, XWalkView xwView) { super(context, attrs); // Initialize the WebContensDelegate. mXWalkView = xwView; mContentsClientBridge = new XWalkContentsClientBridge(mXWalkView); mXWalkContentsDelegateAdapter = new XWalkWebContentsDelegateAdapter( mContentsClientBridge); // Initialize ContentViewRenderView mContentViewRenderView = new ContentViewRenderView(context) { protected void onReadyToRender() { if (mPendingUrl != null) { doLoadUrl(mPendingUrl); mPendingUrl = null; } mReadyToLoad = true; } }; addView(mContentViewRenderView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mXWalkContent = nativeInit(mXWalkContentsDelegateAdapter, mContentsClientBridge); mWebContents = nativeGetWebContents(mXWalkContent); // Initialize mWindow which is needed by content mWindow = new WindowAndroid(xwView.getActivity()); // Initialize ContentView. mContentView = ContentView.newInstance(getContext(), mWebContents, mWindow); addView(mContentView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); mContentView.setContentViewClient(mContentsClientBridge); mContentViewRenderView.setCurrentContentView(mContentView); // For addJavascriptInterface mContentViewCore = mContentView.getContentViewCore(); mContentsClientBridge.installWebContentsObserver(mContentViewCore); mSettings = new XWalkSettings(getContext(), mWebContents, true); }
diff --git a/cli/src/main/java/com/vmware/bdd/cli/commands/NetworkCommands.java b/cli/src/main/java/com/vmware/bdd/cli/commands/NetworkCommands.java index 218472b6..e2d321d1 100644 --- a/cli/src/main/java/com/vmware/bdd/cli/commands/NetworkCommands.java +++ b/cli/src/main/java/com/vmware/bdd/cli/commands/NetworkCommands.java @@ -1,506 +1,506 @@ /***************************************************************************** * Copyright (c) 2012-2013 VMware, Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.vmware.bdd.cli.commands; /** * <p>This class is the realization of Network command.</p> */ import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.regex.Pattern; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliAvailabilityIndicator; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.stereotype.Component; import com.vmware.bdd.apitypes.IpAllocEntryRead; import com.vmware.bdd.apitypes.IpBlock; import com.vmware.bdd.apitypes.NetworkAdd; import com.vmware.bdd.apitypes.NetworkRead; import com.vmware.bdd.cli.rest.CliRestException; import com.vmware.bdd.cli.rest.NetworkRestClient; @Component public class NetworkCommands implements CommandMarker { @Autowired private NetworkRestClient networkRestClient; private String networkName; // Define network type private enum NetworkType { DHCP, IP } // Define the pattern type. private interface PatternType { // Match a single IP format,eg. 192.168.0.2 . final String IP = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b"; // Match a IP section format,eg. 192.168.0.2-100 . final String IPSEG = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\-((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b"; } @CliAvailabilityIndicator({ "network help" }) public boolean isCommandAvailable() { return true; } /** * <p> * Add function of network command. * </p> * * @param name * Customize the network's name. * @param portGroup * The port group name. * @param dhcp * The dhcp flag. * @param dns * The frist dns information. * @param sedDNS * The second dns information. * @param ip * The ip range information. * @param gateway * The gateway information. * @param mask * The network mask information. */ @CliCommand(value = "network add", help = "Add a network to Serengeti") public void addNetwork( @CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name, @CliOption(key = { "portGroup" }, mandatory = true, help = "The port group name") final String portGroup, @CliOption(key = { "dhcp" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "The dhcp information") final boolean dhcp, @CliOption(key = { "dns" }, mandatory = false, help = "The first dns information") final String dns, @CliOption(key = { "secondDNS" }, mandatory = false, help = "The second dns information") final String sedDNS, @CliOption(key = { "ip" }, mandatory = false, help = "The ip information") final String ip, @CliOption(key = { "gateway" }, mandatory = false, help = "The gateway information") final String gateway, @CliOption(key = { "mask" }, mandatory = false, help = "The mask information") final String mask) { NetworkType operType = null; if (!CommandsUtils.isBlank(ip) && dhcp) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_EXCLUSION_PAIR_NETWORK_ADD_IP_DHCP + Constants.PARAMS_EXCLUSION); return; } else if (dhcp) { operType = NetworkType.DHCP; } else if (!CommandsUtils.isBlank(ip)) { operType = NetworkType.IP; } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_IP_DHCP_NOT_NULL); return; } addNetwork(operType, name, portGroup, ip, dhcp, dns, sedDNS, gateway, mask); } /** * <p> * Delete a network from Serengeti by name * </p> * * @param name * Customize the network's name */ @CliCommand(value = "network delete", help = "Delete a network from Serengeti by name") public void deleteNetwork( @CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name) { //rest invocation try { networkRestClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_DELETE); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } /** * <p> * get network information from Serengeti * </p> * * @param name * Customize the network's name * @param detail * The detail flag * */ @CliCommand(value = "network list", help = "Get network information from Serengeti") public void getNetwork( @CliOption(key = { "name" }, mandatory = false, help = "Customize the network's name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { NetworkRead[] networks = networkRestClient.getAll(detail); prettyOutputNetworksInfo(networks, detail); } else { NetworkRead network = networkRestClient.get(name, detail); prettyOutputNetworkInfo(network, detail); } }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void addNetwork(NetworkType operType, final String name, final String portGroup, final String ip, final boolean dhcp, final String dns, final String sedDNS, final String gateway, final String mask) { switch (operType) { case IP: try { addNetworkByIPModel(operType, name, portGroup, ip, dns, sedDNS, gateway, mask); } catch (UnknownHostException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.OUTPUT_UNKNOWN_HOST); } break; case DHCP: addNetworkByDHCPModel(operType, name, portGroup, dhcp); } } private void addNetworkByDHCPModel(NetworkType operType, final String name, final String portGroup, final boolean dhcp) { NetworkAdd networkAdd = new NetworkAdd(); networkAdd.setName(name); networkAdd.setPortGroup(portGroup); networkAdd.setDhcp(true); //rest invocation try { networkRestClient.add(networkAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void addNetworkByIPModel(NetworkType operType, final String name, final String portGroup, final String ip, final String dns, final String sedDNS, final String gateway, final String mask) throws UnknownHostException { // validate the network add command option. networkName = name; if (validateAddNetworkOptionByIP(ip, dns, sedDNS, gateway, mask)) { NetworkAdd networkAdd = new NetworkAdd(); networkAdd.setName(name); networkAdd.setPortGroup(portGroup); networkAdd.setIp(transferIpInfo(ip)); networkAdd.setDns1(dns); networkAdd.setDns2(sedDNS); networkAdd.setGateway(gateway); networkAdd.setNetmask(mask); //rest invocation try { networkRestClient.add(networkAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private List<IpBlock> transferIpInfo(final String ip) throws UnknownHostException { List<IpBlock> ipBlockList = new ArrayList<IpBlock>(); List<String> ipList = CommandsUtils.inputsConvert(ip); Pattern ipPattern = Pattern.compile(PatternType.IP); Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG); if (ipList == null) { throw new RuntimeException( "[NetworkCommands:transferIpInfo]ipList is null ."); } else if (ipList.size() == 0) { return ipBlockList; } else { IpBlock ipBlock = null; for (Iterator<String> iterator = ipList.iterator(); iterator.hasNext();) { String ipRangeStr = (String) iterator.next(); if (ipPattern.matcher(ipRangeStr).matches()) { ipBlock = new IpBlock(); ipBlock.setBeginIp(ipRangeStr); ipBlock.setEndIp(ipRangeStr); ipBlockList.add(ipBlock); } else if (ipSegPattern.matcher(ipRangeStr).matches()) { ipBlock = new IpBlock(); String[] ips = ipRangeStr.split("-"); ipBlock.setBeginIp(ips[0]); ipBlock.setEndIp(new StringBuilder() .append(ips[0].substring(0, ips[0].lastIndexOf(".") + 1)) .append(ips[1]).toString()); ipBlockList.add(ipBlock); } } } return ipBlockList; } private boolean validateAddNetworkOptionByIP(final String ip, final String dns, final String sedDNS, final String gateway, final String mask) { if (!validateIP(ip)) { return false; } if (!validateDNS(dns)) { return false; } if (!validateDNS(sedDNS)) { return false; } if (!validateGateway(gateway)) { return false; } if (!validateMask(mask)) { return false; } return true; } private boolean validateIP(final String ip) { Pattern ipPattern = Pattern.compile(PatternType.IP); Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG); List<String> ipPrarams = CommandsUtils.inputsConvert(ip); if (ipPrarams.size() == 0) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString()); return false; } for (Iterator<String> iterator = ipPrarams.iterator(); iterator.hasNext();) { String ipParam = (String) iterator.next(); if (!ipPattern.matcher(ipParam).matches() && !ipSegPattern.matcher(ipParam).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString()); return false; } } return true; } private boolean validateDNS(final String dns) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (!CommandsUtils.isBlank(dns) && !ipPattern.matcher(dns).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "dns=" + dns + errorMessage.toString()); return false; } else return true; } private boolean validateGateway(final String gateway) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (CommandsUtils.isBlank(gateway)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_GATEWAY + Constants.MULTI_INPUTS_CHECK); return false; } else if (!ipPattern.matcher(gateway).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "gateway=" + gateway + errorMessage.toString()); return false; } else return true; } private boolean validateMask(final String mask) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (CommandsUtils.isBlank(mask)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_MASK + Constants.MULTI_INPUTS_CHECK); return false; } else if (!ipPattern.matcher(mask).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, - Constants.INVALID_VALUE + " " + "maks=" + mask + errorMessage.toString()); + Constants.INVALID_VALUE + " " + "mask=" + mask + errorMessage.toString()); return false; } else return true; } private void prettyOutputNetworksInfo(NetworkRead[] networks, boolean detail) { if (networks != null) { LinkedHashMap<String, List<String>> networkIpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PORT_GROUP, Arrays.asList("getPortGroup")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("findDhcpOrIp")); if (detail) { networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_FREE_IPS, Arrays.asList("getFreeIpBlocks")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ASSIGNED_IPS, Arrays.asList("getAssignedIpBlocks")); } else { networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP_RANGES, Arrays.asList("getAllIpBlocks")); } networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_DNS1, Arrays.asList("getDns1")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_DNS2, Arrays.asList("getDns2")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_GATEWAY, Arrays.asList("getGateway")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_MASK, Arrays.asList("getNetmask")); try { if (detail) { LinkedHashMap<String, List<String>> networkDhcpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PORT_GROUP, Arrays.asList("getPortGroup")); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("findDhcpOrIp")); for (NetworkRead network : networks) { if (network.isDhcp()) CommandsUtils.printInTableFormat( networkDhcpColumnNamesWithGetMethodNames, new NetworkRead[] { network }, Constants.OUTPUT_INDENT); else CommandsUtils.printInTableFormat( networkIpColumnNamesWithGetMethodNames, new NetworkRead[] { network }, Constants.OUTPUT_INDENT); System.out.println(); prettyOutputNetworkDetailInfo(network); System.out.println(); } } else { CommandsUtils.printInTableFormat( networkIpColumnNamesWithGetMethodNames, networks, Constants.OUTPUT_INDENT); } } catch (Exception e) { System.err.println(e.getMessage()); } } } private void prettyOutputNetworkInfo(NetworkRead network, boolean detail) { if (network != null) prettyOutputNetworksInfo(new NetworkRead[] {network}, detail); } private void prettyOutputNetworkDetailInfo(NetworkRead network) throws Exception { List<IpAllocEntryRead> ipAllocEntrys = network.getIpAllocEntries(); LinkedHashMap<String, List<String>> networkDetailColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIpAddress")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE, Arrays.asList("getNodeName")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE_GROUP_NAME, Arrays.asList("getNodeGroupName")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_CLUSTER_NAME, Arrays.asList("getClusterName")); CommandsUtils.printInTableFormat( networkDetailColumnNamesWithGetMethodNames, ipAllocEntrys.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } }
true
true
public void addNetwork( @CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name, @CliOption(key = { "portGroup" }, mandatory = true, help = "The port group name") final String portGroup, @CliOption(key = { "dhcp" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "The dhcp information") final boolean dhcp, @CliOption(key = { "dns" }, mandatory = false, help = "The first dns information") final String dns, @CliOption(key = { "secondDNS" }, mandatory = false, help = "The second dns information") final String sedDNS, @CliOption(key = { "ip" }, mandatory = false, help = "The ip information") final String ip, @CliOption(key = { "gateway" }, mandatory = false, help = "The gateway information") final String gateway, @CliOption(key = { "mask" }, mandatory = false, help = "The mask information") final String mask) { NetworkType operType = null; if (!CommandsUtils.isBlank(ip) && dhcp) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_EXCLUSION_PAIR_NETWORK_ADD_IP_DHCP + Constants.PARAMS_EXCLUSION); return; } else if (dhcp) { operType = NetworkType.DHCP; } else if (!CommandsUtils.isBlank(ip)) { operType = NetworkType.IP; } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_IP_DHCP_NOT_NULL); return; } addNetwork(operType, name, portGroup, ip, dhcp, dns, sedDNS, gateway, mask); } /** * <p> * Delete a network from Serengeti by name * </p> * * @param name * Customize the network's name */ @CliCommand(value = "network delete", help = "Delete a network from Serengeti by name") public void deleteNetwork( @CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name) { //rest invocation try { networkRestClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_DELETE); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } /** * <p> * get network information from Serengeti * </p> * * @param name * Customize the network's name * @param detail * The detail flag * */ @CliCommand(value = "network list", help = "Get network information from Serengeti") public void getNetwork( @CliOption(key = { "name" }, mandatory = false, help = "Customize the network's name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { NetworkRead[] networks = networkRestClient.getAll(detail); prettyOutputNetworksInfo(networks, detail); } else { NetworkRead network = networkRestClient.get(name, detail); prettyOutputNetworkInfo(network, detail); } }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void addNetwork(NetworkType operType, final String name, final String portGroup, final String ip, final boolean dhcp, final String dns, final String sedDNS, final String gateway, final String mask) { switch (operType) { case IP: try { addNetworkByIPModel(operType, name, portGroup, ip, dns, sedDNS, gateway, mask); } catch (UnknownHostException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.OUTPUT_UNKNOWN_HOST); } break; case DHCP: addNetworkByDHCPModel(operType, name, portGroup, dhcp); } } private void addNetworkByDHCPModel(NetworkType operType, final String name, final String portGroup, final boolean dhcp) { NetworkAdd networkAdd = new NetworkAdd(); networkAdd.setName(name); networkAdd.setPortGroup(portGroup); networkAdd.setDhcp(true); //rest invocation try { networkRestClient.add(networkAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void addNetworkByIPModel(NetworkType operType, final String name, final String portGroup, final String ip, final String dns, final String sedDNS, final String gateway, final String mask) throws UnknownHostException { // validate the network add command option. networkName = name; if (validateAddNetworkOptionByIP(ip, dns, sedDNS, gateway, mask)) { NetworkAdd networkAdd = new NetworkAdd(); networkAdd.setName(name); networkAdd.setPortGroup(portGroup); networkAdd.setIp(transferIpInfo(ip)); networkAdd.setDns1(dns); networkAdd.setDns2(sedDNS); networkAdd.setGateway(gateway); networkAdd.setNetmask(mask); //rest invocation try { networkRestClient.add(networkAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private List<IpBlock> transferIpInfo(final String ip) throws UnknownHostException { List<IpBlock> ipBlockList = new ArrayList<IpBlock>(); List<String> ipList = CommandsUtils.inputsConvert(ip); Pattern ipPattern = Pattern.compile(PatternType.IP); Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG); if (ipList == null) { throw new RuntimeException( "[NetworkCommands:transferIpInfo]ipList is null ."); } else if (ipList.size() == 0) { return ipBlockList; } else { IpBlock ipBlock = null; for (Iterator<String> iterator = ipList.iterator(); iterator.hasNext();) { String ipRangeStr = (String) iterator.next(); if (ipPattern.matcher(ipRangeStr).matches()) { ipBlock = new IpBlock(); ipBlock.setBeginIp(ipRangeStr); ipBlock.setEndIp(ipRangeStr); ipBlockList.add(ipBlock); } else if (ipSegPattern.matcher(ipRangeStr).matches()) { ipBlock = new IpBlock(); String[] ips = ipRangeStr.split("-"); ipBlock.setBeginIp(ips[0]); ipBlock.setEndIp(new StringBuilder() .append(ips[0].substring(0, ips[0].lastIndexOf(".") + 1)) .append(ips[1]).toString()); ipBlockList.add(ipBlock); } } } return ipBlockList; } private boolean validateAddNetworkOptionByIP(final String ip, final String dns, final String sedDNS, final String gateway, final String mask) { if (!validateIP(ip)) { return false; } if (!validateDNS(dns)) { return false; } if (!validateDNS(sedDNS)) { return false; } if (!validateGateway(gateway)) { return false; } if (!validateMask(mask)) { return false; } return true; } private boolean validateIP(final String ip) { Pattern ipPattern = Pattern.compile(PatternType.IP); Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG); List<String> ipPrarams = CommandsUtils.inputsConvert(ip); if (ipPrarams.size() == 0) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString()); return false; } for (Iterator<String> iterator = ipPrarams.iterator(); iterator.hasNext();) { String ipParam = (String) iterator.next(); if (!ipPattern.matcher(ipParam).matches() && !ipSegPattern.matcher(ipParam).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString()); return false; } } return true; } private boolean validateDNS(final String dns) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (!CommandsUtils.isBlank(dns) && !ipPattern.matcher(dns).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "dns=" + dns + errorMessage.toString()); return false; } else return true; } private boolean validateGateway(final String gateway) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (CommandsUtils.isBlank(gateway)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_GATEWAY + Constants.MULTI_INPUTS_CHECK); return false; } else if (!ipPattern.matcher(gateway).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "gateway=" + gateway + errorMessage.toString()); return false; } else return true; } private boolean validateMask(final String mask) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (CommandsUtils.isBlank(mask)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_MASK + Constants.MULTI_INPUTS_CHECK); return false; } else if (!ipPattern.matcher(mask).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "maks=" + mask + errorMessage.toString()); return false; } else return true; } private void prettyOutputNetworksInfo(NetworkRead[] networks, boolean detail) { if (networks != null) { LinkedHashMap<String, List<String>> networkIpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PORT_GROUP, Arrays.asList("getPortGroup")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("findDhcpOrIp")); if (detail) { networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_FREE_IPS, Arrays.asList("getFreeIpBlocks")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ASSIGNED_IPS, Arrays.asList("getAssignedIpBlocks")); } else { networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP_RANGES, Arrays.asList("getAllIpBlocks")); } networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_DNS1, Arrays.asList("getDns1")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_DNS2, Arrays.asList("getDns2")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_GATEWAY, Arrays.asList("getGateway")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_MASK, Arrays.asList("getNetmask")); try { if (detail) { LinkedHashMap<String, List<String>> networkDhcpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PORT_GROUP, Arrays.asList("getPortGroup")); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("findDhcpOrIp")); for (NetworkRead network : networks) { if (network.isDhcp()) CommandsUtils.printInTableFormat( networkDhcpColumnNamesWithGetMethodNames, new NetworkRead[] { network }, Constants.OUTPUT_INDENT); else CommandsUtils.printInTableFormat( networkIpColumnNamesWithGetMethodNames, new NetworkRead[] { network }, Constants.OUTPUT_INDENT); System.out.println(); prettyOutputNetworkDetailInfo(network); System.out.println(); } } else { CommandsUtils.printInTableFormat( networkIpColumnNamesWithGetMethodNames, networks, Constants.OUTPUT_INDENT); } } catch (Exception e) { System.err.println(e.getMessage()); } } } private void prettyOutputNetworkInfo(NetworkRead network, boolean detail) { if (network != null) prettyOutputNetworksInfo(new NetworkRead[] {network}, detail); } private void prettyOutputNetworkDetailInfo(NetworkRead network) throws Exception { List<IpAllocEntryRead> ipAllocEntrys = network.getIpAllocEntries(); LinkedHashMap<String, List<String>> networkDetailColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIpAddress")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE, Arrays.asList("getNodeName")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE_GROUP_NAME, Arrays.asList("getNodeGroupName")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_CLUSTER_NAME, Arrays.asList("getClusterName")); CommandsUtils.printInTableFormat( networkDetailColumnNamesWithGetMethodNames, ipAllocEntrys.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } }
public void addNetwork( @CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name, @CliOption(key = { "portGroup" }, mandatory = true, help = "The port group name") final String portGroup, @CliOption(key = { "dhcp" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "The dhcp information") final boolean dhcp, @CliOption(key = { "dns" }, mandatory = false, help = "The first dns information") final String dns, @CliOption(key = { "secondDNS" }, mandatory = false, help = "The second dns information") final String sedDNS, @CliOption(key = { "ip" }, mandatory = false, help = "The ip information") final String ip, @CliOption(key = { "gateway" }, mandatory = false, help = "The gateway information") final String gateway, @CliOption(key = { "mask" }, mandatory = false, help = "The mask information") final String mask) { NetworkType operType = null; if (!CommandsUtils.isBlank(ip) && dhcp) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_EXCLUSION_PAIR_NETWORK_ADD_IP_DHCP + Constants.PARAMS_EXCLUSION); return; } else if (dhcp) { operType = NetworkType.DHCP; } else if (!CommandsUtils.isBlank(ip)) { operType = NetworkType.IP; } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_IP_DHCP_NOT_NULL); return; } addNetwork(operType, name, portGroup, ip, dhcp, dns, sedDNS, gateway, mask); } /** * <p> * Delete a network from Serengeti by name * </p> * * @param name * Customize the network's name */ @CliCommand(value = "network delete", help = "Delete a network from Serengeti by name") public void deleteNetwork( @CliOption(key = { "name" }, mandatory = true, help = "Customize the network's name") final String name) { //rest invocation try { networkRestClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_DELETE); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } /** * <p> * get network information from Serengeti * </p> * * @param name * Customize the network's name * @param detail * The detail flag * */ @CliCommand(value = "network list", help = "Get network information from Serengeti") public void getNetwork( @CliOption(key = { "name" }, mandatory = false, help = "Customize the network's name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { NetworkRead[] networks = networkRestClient.getAll(detail); prettyOutputNetworksInfo(networks, detail); } else { NetworkRead network = networkRestClient.get(name, detail); prettyOutputNetworkInfo(network, detail); } }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void addNetwork(NetworkType operType, final String name, final String portGroup, final String ip, final boolean dhcp, final String dns, final String sedDNS, final String gateway, final String mask) { switch (operType) { case IP: try { addNetworkByIPModel(operType, name, portGroup, ip, dns, sedDNS, gateway, mask); } catch (UnknownHostException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.OUTPUT_UNKNOWN_HOST); } break; case DHCP: addNetworkByDHCPModel(operType, name, portGroup, dhcp); } } private void addNetworkByDHCPModel(NetworkType operType, final String name, final String portGroup, final boolean dhcp) { NetworkAdd networkAdd = new NetworkAdd(); networkAdd.setName(name); networkAdd.setPortGroup(portGroup); networkAdd.setDhcp(true); //rest invocation try { networkRestClient.add(networkAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void addNetworkByIPModel(NetworkType operType, final String name, final String portGroup, final String ip, final String dns, final String sedDNS, final String gateway, final String mask) throws UnknownHostException { // validate the network add command option. networkName = name; if (validateAddNetworkOptionByIP(ip, dns, sedDNS, gateway, mask)) { NetworkAdd networkAdd = new NetworkAdd(); networkAdd.setName(name); networkAdd.setPortGroup(portGroup); networkAdd.setIp(transferIpInfo(ip)); networkAdd.setDns1(dns); networkAdd.setDns2(sedDNS); networkAdd.setGateway(gateway); networkAdd.setNetmask(mask); //rest invocation try { networkRestClient.add(networkAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private List<IpBlock> transferIpInfo(final String ip) throws UnknownHostException { List<IpBlock> ipBlockList = new ArrayList<IpBlock>(); List<String> ipList = CommandsUtils.inputsConvert(ip); Pattern ipPattern = Pattern.compile(PatternType.IP); Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG); if (ipList == null) { throw new RuntimeException( "[NetworkCommands:transferIpInfo]ipList is null ."); } else if (ipList.size() == 0) { return ipBlockList; } else { IpBlock ipBlock = null; for (Iterator<String> iterator = ipList.iterator(); iterator.hasNext();) { String ipRangeStr = (String) iterator.next(); if (ipPattern.matcher(ipRangeStr).matches()) { ipBlock = new IpBlock(); ipBlock.setBeginIp(ipRangeStr); ipBlock.setEndIp(ipRangeStr); ipBlockList.add(ipBlock); } else if (ipSegPattern.matcher(ipRangeStr).matches()) { ipBlock = new IpBlock(); String[] ips = ipRangeStr.split("-"); ipBlock.setBeginIp(ips[0]); ipBlock.setEndIp(new StringBuilder() .append(ips[0].substring(0, ips[0].lastIndexOf(".") + 1)) .append(ips[1]).toString()); ipBlockList.add(ipBlock); } } } return ipBlockList; } private boolean validateAddNetworkOptionByIP(final String ip, final String dns, final String sedDNS, final String gateway, final String mask) { if (!validateIP(ip)) { return false; } if (!validateDNS(dns)) { return false; } if (!validateDNS(sedDNS)) { return false; } if (!validateGateway(gateway)) { return false; } if (!validateMask(mask)) { return false; } return true; } private boolean validateIP(final String ip) { Pattern ipPattern = Pattern.compile(PatternType.IP); Pattern ipSegPattern = Pattern.compile(PatternType.IPSEG); List<String> ipPrarams = CommandsUtils.inputsConvert(ip); if (ipPrarams.size() == 0) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString()); return false; } for (Iterator<String> iterator = ipPrarams.iterator(); iterator.hasNext();) { String ipParam = (String) iterator.next(); if (!ipPattern.matcher(ipParam).matches() && !ipSegPattern.matcher(ipParam).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_FORMAT_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "ip=" + ipPrarams + errorMessage.toString()); return false; } } return true; } private boolean validateDNS(final String dns) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (!CommandsUtils.isBlank(dns) && !ipPattern.matcher(dns).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "dns=" + dns + errorMessage.toString()); return false; } else return true; } private boolean validateGateway(final String gateway) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (CommandsUtils.isBlank(gateway)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_GATEWAY + Constants.MULTI_INPUTS_CHECK); return false; } else if (!ipPattern.matcher(gateway).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "gateway=" + gateway + errorMessage.toString()); return false; } else return true; } private boolean validateMask(final String mask) { Pattern ipPattern = Pattern.compile(PatternType.IP); if (CommandsUtils.isBlank(mask)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAMS_NETWORK_ADD_MASK + Constants.MULTI_INPUTS_CHECK); return false; } else if (!ipPattern.matcher(mask).matches()) { StringBuilder errorMessage = new StringBuilder().append(Constants.PARAMS_NETWORK_ADD_IP_ERROR); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NETWORK, networkName, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "mask=" + mask + errorMessage.toString()); return false; } else return true; } private void prettyOutputNetworksInfo(NetworkRead[] networks, boolean detail) { if (networks != null) { LinkedHashMap<String, List<String>> networkIpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PORT_GROUP, Arrays.asList("getPortGroup")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("findDhcpOrIp")); if (detail) { networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_FREE_IPS, Arrays.asList("getFreeIpBlocks")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ASSIGNED_IPS, Arrays.asList("getAssignedIpBlocks")); } else { networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP_RANGES, Arrays.asList("getAllIpBlocks")); } networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_DNS1, Arrays.asList("getDns1")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_DNS2, Arrays.asList("getDns2")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_GATEWAY, Arrays.asList("getGateway")); networkIpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_MASK, Arrays.asList("getNetmask")); try { if (detail) { LinkedHashMap<String, List<String>> networkDhcpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PORT_GROUP, Arrays.asList("getPortGroup")); networkDhcpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("findDhcpOrIp")); for (NetworkRead network : networks) { if (network.isDhcp()) CommandsUtils.printInTableFormat( networkDhcpColumnNamesWithGetMethodNames, new NetworkRead[] { network }, Constants.OUTPUT_INDENT); else CommandsUtils.printInTableFormat( networkIpColumnNamesWithGetMethodNames, new NetworkRead[] { network }, Constants.OUTPUT_INDENT); System.out.println(); prettyOutputNetworkDetailInfo(network); System.out.println(); } } else { CommandsUtils.printInTableFormat( networkIpColumnNamesWithGetMethodNames, networks, Constants.OUTPUT_INDENT); } } catch (Exception e) { System.err.println(e.getMessage()); } } } private void prettyOutputNetworkInfo(NetworkRead network, boolean detail) { if (network != null) prettyOutputNetworksInfo(new NetworkRead[] {network}, detail); } private void prettyOutputNetworkDetailInfo(NetworkRead network) throws Exception { List<IpAllocEntryRead> ipAllocEntrys = network.getIpAllocEntries(); LinkedHashMap<String, List<String>> networkDetailColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIpAddress")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE, Arrays.asList("getNodeName")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE_GROUP_NAME, Arrays.asList("getNodeGroupName")); networkDetailColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_CLUSTER_NAME, Arrays.asList("getClusterName")); CommandsUtils.printInTableFormat( networkDetailColumnNamesWithGetMethodNames, ipAllocEntrys.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } }
diff --git a/ext/java/base32/Base32Encoder.java b/ext/java/base32/Base32Encoder.java index 159afd1..e94d7e5 100644 --- a/ext/java/base32/Base32Encoder.java +++ b/ext/java/base32/Base32Encoder.java @@ -1,90 +1,89 @@ /* Copyright (c) 2011 The Skunkworx Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package base32; /** * Static class to perform base32 encoding * * @author Chris Umbel */ public class Base32Encoder { private static final String charTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; public static int getDigit(byte[] buff, int i) { return buff[i] >= 0 ? buff[i] : buff[i] + 256; } public static String encode(String plainText) { return encode(plainText.getBytes()); } public static int quintetCount(byte[] buff) { int quintets = buff.length / 5; return buff.length % 5 == 0 ? quintets: quintets + 1; } public static String encode(byte[] buff) { int next; int current; int iBase = 0; int digit = 0; int i = 0; int outputLength = quintetCount(buff) * 8; StringBuilder builder = new StringBuilder(outputLength); while(i < buff.length) { current = getDigit(buff, i); if(iBase > 3) { if((i + 1) < buff.length) next = getDigit(buff, i + 1); else next = 0; digit = current & (0xff >> iBase); iBase = (iBase + 5) % 8; digit <<= iBase; digit |= next >> (8 - iBase); i++; } else { digit = (current >> (8 - (iBase + 5))) & 0x1f; iBase = (iBase + 5) % 8; if(iBase == 0) i++; } builder.append(charTable.charAt(digit)); } int padding = builder.capacity() - builder.length(); - for(i = 0; i < padding; i++) { + for(i = 0; i < padding; i++) builder.append("="); - } return builder.toString(); } }
false
true
public static String encode(byte[] buff) { int next; int current; int iBase = 0; int digit = 0; int i = 0; int outputLength = quintetCount(buff) * 8; StringBuilder builder = new StringBuilder(outputLength); while(i < buff.length) { current = getDigit(buff, i); if(iBase > 3) { if((i + 1) < buff.length) next = getDigit(buff, i + 1); else next = 0; digit = current & (0xff >> iBase); iBase = (iBase + 5) % 8; digit <<= iBase; digit |= next >> (8 - iBase); i++; } else { digit = (current >> (8 - (iBase + 5))) & 0x1f; iBase = (iBase + 5) % 8; if(iBase == 0) i++; } builder.append(charTable.charAt(digit)); } int padding = builder.capacity() - builder.length(); for(i = 0; i < padding; i++) { builder.append("="); } return builder.toString(); }
public static String encode(byte[] buff) { int next; int current; int iBase = 0; int digit = 0; int i = 0; int outputLength = quintetCount(buff) * 8; StringBuilder builder = new StringBuilder(outputLength); while(i < buff.length) { current = getDigit(buff, i); if(iBase > 3) { if((i + 1) < buff.length) next = getDigit(buff, i + 1); else next = 0; digit = current & (0xff >> iBase); iBase = (iBase + 5) % 8; digit <<= iBase; digit |= next >> (8 - iBase); i++; } else { digit = (current >> (8 - (iBase + 5))) & 0x1f; iBase = (iBase + 5) % 8; if(iBase == 0) i++; } builder.append(charTable.charAt(digit)); } int padding = builder.capacity() - builder.length(); for(i = 0; i < padding; i++) builder.append("="); return builder.toString(); }
diff --git a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/timer/SingleActionTimerData.java b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/timer/SingleActionTimerData.java index a9444ee9c..b56c4dba4 100644 --- a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/timer/SingleActionTimerData.java +++ b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/core/timer/SingleActionTimerData.java @@ -1,64 +1,61 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.core.timer; import java.lang.reflect.Method; import java.text.DateFormat; import java.util.Date; import javax.ejb.TimerConfig; import org.quartz.SimpleTrigger; import org.quartz.Trigger; /** * @version $Rev$ $Date$ */ public class SingleActionTimerData extends TimerData { private final Date expiration; public SingleActionTimerData(long id, EjbTimerServiceImpl timerService, String deploymentId, Object primaryKey, Method timeoutMethod, TimerConfig timerConfig, Date expiration) { super(id, timerService, deploymentId, primaryKey, timeoutMethod, timerConfig); this.expiration = expiration; } @Override public TimerType getType() { return TimerType.SingleAction; } public Date getExpiration() { return expiration; } @Override public Trigger initializeTrigger() { - SimpleTrigger simpleTrigger = new SimpleTrigger(); - Date startTime = new Date(); - simpleTrigger.setStartTime(startTime); - simpleTrigger.setRepeatInterval(expiration.getTime() - startTime.getTime()); - simpleTrigger.setRepeatCount(1); + final SimpleTrigger simpleTrigger = new SimpleTrigger(); + simpleTrigger.setStartTime(expiration); return simpleTrigger; } @Override public String toString() { return TimerType.SingleAction.name() + " expiration = [" + DateFormat.getDateTimeInstance().format(expiration) + "]"; } }
true
true
public Trigger initializeTrigger() { SimpleTrigger simpleTrigger = new SimpleTrigger(); Date startTime = new Date(); simpleTrigger.setStartTime(startTime); simpleTrigger.setRepeatInterval(expiration.getTime() - startTime.getTime()); simpleTrigger.setRepeatCount(1); return simpleTrigger; }
public Trigger initializeTrigger() { final SimpleTrigger simpleTrigger = new SimpleTrigger(); simpleTrigger.setStartTime(expiration); return simpleTrigger; }
diff --git a/framework/src/com/phonegap/CameraLauncher.java b/framework/src/com/phonegap/CameraLauncher.java index 0fdb08a4..9dd5d0c1 100755 --- a/framework/src/com/phonegap/CameraLauncher.java +++ b/framework/src/com/phonegap/CameraLauncher.java @@ -1,500 +1,502 @@ /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.phonegap; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.codec.binary.Base64; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.phonegap.api.Plugin; import com.phonegap.api.PluginResult; import com.phonegap.api.LOG; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.net.Uri; import android.provider.MediaStore; /** * This class launches the camera view, allows the user to take a picture, closes the camera view, * and returns the captured image. When the camera view is closed, the screen displayed before * the camera view was shown is redisplayed. */ public class CameraLauncher extends Plugin { private static final int DATA_URL = 0; // Return base64 encoded string private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android) private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android) private static final int CAMERA = 1; // Take picture from camera private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android) private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL private static final int ALLMEDIA = 2; // allow selection from all media types private static final int JPEG = 0; // Take a picture of type JPEG private static final int PNG = 1; // Take a picture of type PNG private static final String GET_PICTURE = "Get Picture"; private static final String GET_VIDEO = "Get Video"; private static final String GET_All = "Get All"; private static final String LOG_TAG = "CameraLauncher"; private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) private int targetWidth; // desired width of the image private int targetHeight; // desired height of the image private Uri imageUri; // Uri of captured image private int encodingType; // Type of encoding to use private int mediaType; // What type of media to retrieve public String callbackId; private int numPics; /** * Constructor. */ public CameraLauncher() { } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackId The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; this.callbackId = callbackId; try { if (action.equals("takePicture")) { int srcType = CAMERA; int destType = DATA_URL; this.targetHeight = 0; this.targetWidth = 0; this.encodingType = JPEG; this.mediaType = PICTURE; this.mQuality = 80; JSONObject options = args.optJSONObject(0); if (options != null) { srcType = options.getInt("sourceType"); destType = options.getInt("destinationType"); this.targetHeight = options.getInt("targetHeight"); this.targetWidth = options.getInt("targetWidth"); this.encodingType = options.getInt("encodingType"); this.mediaType = options.getInt("mediaType"); this.mQuality = options.getInt("quality"); } if (srcType == CAMERA) { this.takePicture(destType, encodingType); } else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { this.getImage(srcType, destType); } PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); r.setKeepCallback(true); return r; } return new PluginResult(status, result); } catch (JSONException e) { e.printStackTrace(); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } } //-------------------------------------------------------------------------- // LOCAL METHODS //-------------------------------------------------------------------------- /** * Take a picture with the camera. * When an image is captured or the camera view is cancelled, the result is returned * in PhonegapActivity.onActivityResult, which forwards the result to this.onActivityResult. * * The image can either be returned as a base64 string or a URI that points to the file. * To display base64 string in an img tag, set the source to: * img.src="data:image/jpeg;base64,"+result; * or to display URI in an img tag * img.src=result; * * @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) * @param returnType Set the type of image to return. */ public void takePicture(int returnType, int encodingType) { // Save the number of images currently on disk for later this.numPics = queryImgDB().getCount(); // Display camera Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); // Specify file so that large image is captured and returned // TODO: What if there isn't any external storage? File photo = createCaptureFile(encodingType); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); this.imageUri = Uri.fromFile(photo); this.ctx.startActivityForResult((Plugin) this, intent, (CAMERA+1)*16 + returnType+1); } /** * Create a file in the applications temporary directory based upon the supplied encoding. * * @param encodingType of the image to be taken * @return a File object pointing to the temporary picture */ private File createCaptureFile(int encodingType) { File photo = null; if (encodingType == JPEG) { photo = new File(DirectoryManager.getTempDirectoryPath(ctx), "Pic.jpg"); } else { photo = new File(DirectoryManager.getTempDirectoryPath(ctx), "Pic.png"); } return photo; } /** * Get image from photo library. * * @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) * @param srcType The album to get image from. * @param returnType Set the type of image to return. */ // TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do! public void getImage(int srcType, int returnType) { Intent intent = new Intent(); String title = GET_PICTURE; if (this.mediaType == PICTURE) { intent.setType("image/*"); } else if (this.mediaType == VIDEO) { intent.setType("video/*"); title = GET_VIDEO; } else if (this.mediaType == ALLMEDIA) { // I wanted to make the type 'image/*, video/*' but this does not work on all versions // of android so I had to go with the wildcard search. intent.setType("*/*"); title = GET_All; } intent.setAction(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent, new String(title)), (srcType+1)*16 + returnType + 1); } /** * Scales the bitmap according to the requested size. * * @param bitmap The bitmap to scale. * @return Bitmap A new Bitmap object of the same bitmap after scaling. */ public Bitmap scaleBitmap(Bitmap bitmap) { int newWidth = this.targetWidth; int newHeight = this.targetHeight; int origWidth = bitmap.getWidth(); int origHeight = bitmap.getHeight(); // If no new width or height were specified return the original bitmap if (newWidth <= 0 && newHeight <= 0) { return bitmap; } // Only the width was specified else if (newWidth > 0 && newHeight <= 0) { newHeight = (newWidth * origHeight) / origWidth; } // only the height was specified else if (newWidth <= 0 && newHeight > 0) { newWidth = (newHeight * origWidth) / origHeight; } // If the user specified both a positive width and height // (potentially different aspect ratio) then the width or height is // scaled so that the image fits while maintaining aspect ratio. // Alternatively, the specified width and height could have been // kept and Bitmap.SCALE_TO_FIT specified when scaling, but this // would result in whitespace in the new image. else { double newRatio = newWidth / (double)newHeight; double origRatio = origWidth / (double)origHeight; if (origRatio > newRatio) { newHeight = (newWidth * origHeight) / origWidth; } else if (origRatio < newRatio) { newWidth = (newHeight * origWidth) / origHeight; } } return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); } /** * Called when the camera view exits. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // Get src and dest types from request code int srcType = (requestCode/16) - 1; int destType = (requestCode % 16) - 1; // If CAMERA if (srcType == CAMERA) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Create an ExifHelper to save the exif data that is lost during compression ExifHelper exif = new ExifHelper(); if (this.encodingType == JPEG) { exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Pic.jpg"); exif.readExifData(); } // Read in bitmap of captured image Bitmap bitmap; try { bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri); } catch (FileNotFoundException e) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); } bitmap = scaleBitmap(bitmap); // If sending base64 image back if (destType == DATA_URL) { this.processPicture(bitmap); checkForDuplicateImage(DATA_URL); } // If sending filename back else if (destType == FILE_URI){ // Create entry in media store for image // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } // Add compressed version of captured image to returned media store Uri OutputStream os = this.ctx.getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Restore exif data to file if (this.encodingType == JPEG) { exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx)); exif.writeExifData(); } // Send Uri back to JavaScript for viewing image this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } bitmap.recycle(); bitmap = null; System.gc(); checkForDuplicateImage(FILE_URI); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } } // If retrieving photo from library else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { if (resultCode == Activity.RESULT_OK) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); // If you ask for video or all media type you will automatically get back a file URI // and there will be no attempt to resize any returned data if (this.mediaType != PICTURE) { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } else { // If sending base64 image back if (destType == DATA_URL) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); bitmap = scaleBitmap(bitmap); this.processPicture(bitmap); bitmap.recycle(); bitmap = null; System.gc(); } catch (FileNotFoundException e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } // If sending filename back else if (destType == FILE_URI) { // Do we need to scale the returned file if (this.targetHeight > 0 && this.targetWidth > 0) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); bitmap = scaleBitmap(bitmap); String fileName = DirectoryManager.getTempDirectoryPath(ctx) + "/resize.jpg"; OutputStream os = new FileOutputStream(fileName); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); bitmap.recycle(); bitmap = null; - this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName)), this.callbackId); + // The resized image is cached by the app in order to get around this and not have to delete you + // application cache I'm adding the current system time to the end of the file url. + this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName + "?" + System.currentTimeMillis())), this.callbackId); System.gc(); } catch (Exception e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } else { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } } } } else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Selection cancelled."); } else { this.failPicture("Selection did not complete!"); } } } /** * Creates a cursor that can be used to determine how many images we have. * * @return a cursor */ private Cursor queryImgDB() { return this.ctx.getContentResolver().query( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.Media._ID }, null, null, null); } /** * Used to find out if we are in a situation where the Camera Intent adds to images * to the content store. If we are using a FILE_URI and the number of images in the DB * increases by 2 we have a duplicate, when using a DATA_URL the number is 1. * * @param type FILE_URI or DATA_URL */ private void checkForDuplicateImage(int type) { int diff = 1; Cursor cursor = queryImgDB(); int currentNumOfImages = cursor.getCount(); if (type == FILE_URI) { diff = 2; } // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL if ((currentNumOfImages - numPics) == diff) { cursor.moveToLast(); int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1; Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id); this.ctx.getContentResolver().delete(uri, null, null); } } /** * Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript. * * @param bitmap */ public void processPicture(Bitmap bitmap) { ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); try { if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) { byte[] code = jpeg_data.toByteArray(); byte[] output = Base64.encodeBase64(code); String js_out = new String(output); this.success(new PluginResult(PluginResult.Status.OK, js_out), this.callbackId); js_out = null; output = null; code = null; } } catch(Exception e) { this.failPicture("Error compressing image."); } jpeg_data = null; } /** * Send error message to JavaScript. * * @param err */ public void failPicture(String err) { this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId); } }
true
true
public void onActivityResult(int requestCode, int resultCode, Intent intent) { // Get src and dest types from request code int srcType = (requestCode/16) - 1; int destType = (requestCode % 16) - 1; // If CAMERA if (srcType == CAMERA) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Create an ExifHelper to save the exif data that is lost during compression ExifHelper exif = new ExifHelper(); if (this.encodingType == JPEG) { exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Pic.jpg"); exif.readExifData(); } // Read in bitmap of captured image Bitmap bitmap; try { bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri); } catch (FileNotFoundException e) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); } bitmap = scaleBitmap(bitmap); // If sending base64 image back if (destType == DATA_URL) { this.processPicture(bitmap); checkForDuplicateImage(DATA_URL); } // If sending filename back else if (destType == FILE_URI){ // Create entry in media store for image // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } // Add compressed version of captured image to returned media store Uri OutputStream os = this.ctx.getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Restore exif data to file if (this.encodingType == JPEG) { exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx)); exif.writeExifData(); } // Send Uri back to JavaScript for viewing image this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } bitmap.recycle(); bitmap = null; System.gc(); checkForDuplicateImage(FILE_URI); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } } // If retrieving photo from library else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { if (resultCode == Activity.RESULT_OK) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); // If you ask for video or all media type you will automatically get back a file URI // and there will be no attempt to resize any returned data if (this.mediaType != PICTURE) { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } else { // If sending base64 image back if (destType == DATA_URL) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); bitmap = scaleBitmap(bitmap); this.processPicture(bitmap); bitmap.recycle(); bitmap = null; System.gc(); } catch (FileNotFoundException e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } // If sending filename back else if (destType == FILE_URI) { // Do we need to scale the returned file if (this.targetHeight > 0 && this.targetWidth > 0) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); bitmap = scaleBitmap(bitmap); String fileName = DirectoryManager.getTempDirectoryPath(ctx) + "/resize.jpg"; OutputStream os = new FileOutputStream(fileName); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); bitmap.recycle(); bitmap = null; this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName)), this.callbackId); System.gc(); } catch (Exception e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } else { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } } } } else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Selection cancelled."); } else { this.failPicture("Selection did not complete!"); } } }
public void onActivityResult(int requestCode, int resultCode, Intent intent) { // Get src and dest types from request code int srcType = (requestCode/16) - 1; int destType = (requestCode % 16) - 1; // If CAMERA if (srcType == CAMERA) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Create an ExifHelper to save the exif data that is lost during compression ExifHelper exif = new ExifHelper(); if (this.encodingType == JPEG) { exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Pic.jpg"); exif.readExifData(); } // Read in bitmap of captured image Bitmap bitmap; try { bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri); } catch (FileNotFoundException e) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); } bitmap = scaleBitmap(bitmap); // If sending base64 image back if (destType == DATA_URL) { this.processPicture(bitmap); checkForDuplicateImage(DATA_URL); } // If sending filename back else if (destType == FILE_URI){ // Create entry in media store for image // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } // Add compressed version of captured image to returned media store Uri OutputStream os = this.ctx.getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Restore exif data to file if (this.encodingType == JPEG) { exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx)); exif.writeExifData(); } // Send Uri back to JavaScript for viewing image this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } bitmap.recycle(); bitmap = null; System.gc(); checkForDuplicateImage(FILE_URI); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } } // If retrieving photo from library else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { if (resultCode == Activity.RESULT_OK) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); // If you ask for video or all media type you will automatically get back a file URI // and there will be no attempt to resize any returned data if (this.mediaType != PICTURE) { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } else { // If sending base64 image back if (destType == DATA_URL) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); bitmap = scaleBitmap(bitmap); this.processPicture(bitmap); bitmap.recycle(); bitmap = null; System.gc(); } catch (FileNotFoundException e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } // If sending filename back else if (destType == FILE_URI) { // Do we need to scale the returned file if (this.targetHeight > 0 && this.targetWidth > 0) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); bitmap = scaleBitmap(bitmap); String fileName = DirectoryManager.getTempDirectoryPath(ctx) + "/resize.jpg"; OutputStream os = new FileOutputStream(fileName); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); bitmap.recycle(); bitmap = null; // The resized image is cached by the app in order to get around this and not have to delete you // application cache I'm adding the current system time to the end of the file url. this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName + "?" + System.currentTimeMillis())), this.callbackId); System.gc(); } catch (Exception e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } else { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } } } } else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Selection cancelled."); } else { this.failPicture("Selection did not complete!"); } } }
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/ClickListener.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/ClickListener.java index 34c1d9770..b7e50744b 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/ClickListener.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/utils/ClickListener.java @@ -1,192 +1,193 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.scenes.scene2d.utils; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.utils.TimeUtils; /** Detects mouse over, mouse or finger touch presses, and clicks on an actor. A touch must go down over the actor and is * considered pressed as long as it is over the actor or within the {@link #setTapSquareSize(float) tap square}. This behavior * makes it easier to press buttons on a touch interface when the initial touch happens near the edge of the actor. Double clicks * can be detected using {@link #getTapCount()}. Any touch (not just the first) will trigger this listener. While pressed, other * touch downs are ignored. * @author Nathan Sweet */ public class ClickListener extends InputListener { private float tapSquareSize = 14, touchDownX = -1, touchDownY = -1; private int pressedPointer = -1; private int pressedButton = -1; private int button; private boolean pressed, over, cancelled; private long tapCountInterval = (long)(0.4f * 1000000000l); private int tapCount; private long lastTapTime; public ClickListener () { } /** @see #setButton(int) */ public ClickListener (int button) { this.button = button; } public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { if (pressed) return false; if (pointer == 0 && this.button != -1 && button != this.button) return false; pressed = true; pressedPointer = pointer; pressedButton = button; touchDownX = x; touchDownY = y; return true; } public void touchDragged (InputEvent event, float x, float y, int pointer) { if (pointer != pressedPointer || cancelled) return; pressed = isOver(event.getListenerActor(), x, y); if (pressed && pointer == 0 && button != -1 && !Gdx.input.isButtonPressed(button)) pressed = false; if (!pressed) { // Once outside the tap square, don't use the tap square anymore. invalidateTapSquare(); } } public void touchUp (InputEvent event, float x, float y, int pointer, int button) { if (pointer == pressedPointer) { if (!cancelled) { - over = isOver(event.getListenerActor(), x, y); - if (over && pointer == 0 && this.button != -1 && button != this.button) over = false; - if (over) { + boolean touchUpOver = isOver(event.getListenerActor(), x, y); + // Ignore touch up if the wrong mouse button. + if (touchUpOver && pointer == 0 && this.button != -1 && button != this.button) touchUpOver = false; + if (touchUpOver) { long time = TimeUtils.nanoTime(); if (time - lastTapTime > tapCountInterval) tapCount = 0; tapCount++; lastTapTime = time; clicked(event, x, y); } } pressed = false; pressedPointer = -1; pressedButton = -1; cancelled = false; } } public void enter (InputEvent event, float x, float y, int pointer, Actor fromActor) { if (pointer == -1 && !cancelled) over = true; } public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) { if (pointer == -1 && !cancelled) over = false; } /** If a touch down is being monitored, the drag and touch up events are ignored until the next touch up. */ public void cancel () { if (pressedPointer == -1) return; cancelled = true; over = false; pressed = false; } public void clicked (InputEvent event, float x, float y) { } public void dragStart (InputEvent event, float x, float y, int pointer) { } public void drag (InputEvent event, float x, float y, int pointer) { } public void dragStop (InputEvent event, float x, float y, int pointer) { } /** Returns true if the specified position is over the specified actor or within the tap square. */ public boolean isOver (Actor actor, float x, float y) { Actor hit = actor.hit(x, y, true); if (hit == null || !hit.isDescendantOf(actor)) return inTapSquare(x, y); return true; } public boolean inTapSquare (float x, float y) { if (touchDownX == -1 && touchDownY == -1) return false; return Math.abs(x - touchDownX) < tapSquareSize && Math.abs(y - touchDownY) < tapSquareSize; } /** The tap square will not longer be used for the current touch. */ public void invalidateTapSquare () { touchDownX = -1; touchDownY = -1; } /** Returns true if a touch is over the actor or within the tap square. */ public boolean isPressed () { return pressed; } /** Returns true if the mouse or touch is over the actor or pressed and within the tap square. */ public boolean isOver () { return over || pressed; } public void setTapSquareSize (float halfTapSquareSize) { tapSquareSize = halfTapSquareSize; } public float getTapSquareSize () { return tapSquareSize; } /** @param tapCountInterval time in seconds that must pass for two touch down/up sequences to be detected as consecutive taps. */ public void setTapCountInterval (float tapCountInterval) { this.tapCountInterval = (long)(tapCountInterval * 1000000000l); } /** Returns the number of taps within the tap count interval for the most recent click event. */ public int getTapCount () { return tapCount; } public float getTouchDownX () { return touchDownX; } public float getTouchDownY () { return touchDownY; } /** The button that initially pressed this button or -1 if the button is not pressed. */ public int getPressedButton () { return pressedButton; } /** The pointer that initially pressed this button or -1 if the button is not pressed. */ public int getPressedPointer () { return pressedPointer; } /** @see #setButton(int) */ public int getButton () { return button; } /** Sets the button to listen for, all other buttons are ignored. Default is {@link Buttons#LEFT}. Use -1 for any button. */ public void setButton (int button) { this.button = button; } }
true
true
public void touchUp (InputEvent event, float x, float y, int pointer, int button) { if (pointer == pressedPointer) { if (!cancelled) { over = isOver(event.getListenerActor(), x, y); if (over && pointer == 0 && this.button != -1 && button != this.button) over = false; if (over) { long time = TimeUtils.nanoTime(); if (time - lastTapTime > tapCountInterval) tapCount = 0; tapCount++; lastTapTime = time; clicked(event, x, y); } } pressed = false; pressedPointer = -1; pressedButton = -1; cancelled = false; } }
public void touchUp (InputEvent event, float x, float y, int pointer, int button) { if (pointer == pressedPointer) { if (!cancelled) { boolean touchUpOver = isOver(event.getListenerActor(), x, y); // Ignore touch up if the wrong mouse button. if (touchUpOver && pointer == 0 && this.button != -1 && button != this.button) touchUpOver = false; if (touchUpOver) { long time = TimeUtils.nanoTime(); if (time - lastTapTime > tapCountInterval) tapCount = 0; tapCount++; lastTapTime = time; clicked(event, x, y); } } pressed = false; pressedPointer = -1; pressedButton = -1; cancelled = false; } }
diff --git a/api/src/main/java/org/openmrs/PersonAddress.java b/api/src/main/java/org/openmrs/PersonAddress.java index 73c5b2b3..bb3a190f 100644 --- a/api/src/main/java/org/openmrs/PersonAddress.java +++ b/api/src/main/java/org/openmrs/PersonAddress.java @@ -1,641 +1,641 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.util.OpenmrsUtil; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; /** * This class is the representation of a person's address. This class is many-to-one to the Person * class, so a Person/Patient/User can have zero to n addresses */ @Root(strict = false) public class PersonAddress extends BaseOpenmrsData implements java.io.Serializable, Cloneable, Comparable<PersonAddress> { public static final long serialVersionUID = 343333L; private static final Log log = LogFactory.getLog(PersonAddress.class); // Fields private Integer personAddressId; private Person person; private Boolean preferred = false; private String address1; private String address2; private String cityVillage; private String address3; private String countyDistrict; private String address4; private String address6; private String address5; private String stateProvince; private String country; private String postalCode; private String latitude; private String longitude; private Date startDate; private Date endDate; // Constructors /** default constructor */ public PersonAddress() { } /** constructor with id */ public PersonAddress(Integer personAddressId) { this.personAddressId = personAddressId; } /** * @see java.lang.Object#toString() */ public String toString() { return "a1:" + getAddress1() + ", a2:" + getAddress2() + ", cv:" + getCityVillage() + ", sp:" + getStateProvince() + ", c:" + getCountry() + ", cd:" + getCountyDistrict() + ", nc:" + getNeighborhoodCell() + ", pc:" + getPostalCode() + ", lat:" + getLatitude() + ", long:" + getLongitude(); } /** * Compares this address to the given object/address for similarity. Uses the very basic * comparison of just the PersonAddress.personAddressId * * @param obj Object (Usually PersonAddress) with which to compare * @return boolean true/false whether or not they are the same objects * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof PersonAddress) { PersonAddress p = (PersonAddress) obj; if (this.getPersonAddressId() != null && p.getPersonAddressId() != null) return (this.getPersonAddressId().equals(p.getPersonAddressId())); } return false; } /** * Compares this PersonAddress object to the given otherAddress. This method differs from * {@link #equals(Object)} in that this method compares the inner fields of each address for * equality. Note: Null/empty fields on <code>otherAddress</code> /will not/ cause a false value * to be returned * * @param otherAddress PersonAddress with which to compare * @return boolean true/false whether or not they are the same addresses */ @SuppressWarnings("unchecked") public boolean equalsContent(PersonAddress otherAddress) { boolean returnValue = true; // these are the methods to compare. All are expected to be Strings - String[] methods = { "getAddress1", "getAddress2", "getAddress3", "getAddress4", "getAddress5", "getCityVillage", - "getNeighborhoodCell", "getCountyDistrict", "getStateProvince", "getCountry", "getPostalCode", - "getLatitude", "getLongitude" }; + String[] methods = { "getAddress1", "getAddress2", "getAddress3", "getAddress4", "getAddress5", "getAddress6", + "getCityVillage", "getCountyDistrict", "getStateProvince", "getCountry", "getPostalCode", "getLatitude", + "getLongitude" }; Class addressClass = this.getClass(); // loop over all of the selected methods and compare this and other for (String methodName : methods) { try { Method method = addressClass.getMethod(methodName, new Class[] {}); String thisValue = (String) method.invoke(this); String otherValue = (String) method.invoke(otherAddress); if (otherValue != null && otherValue.length() > 0) returnValue &= otherValue.equals(thisValue); } catch (NoSuchMethodException e) { log.warn("No such method for comparison " + methodName, e); } catch (IllegalAccessException e) { log.error("Error while comparing addresses", e); } catch (InvocationTargetException e) { log.error("Error while comparing addresses", e); } } return returnValue; } /** * @see java.lang.Object#hashCode() */ public int hashCode() { if (this.getPersonAddressId() == null) return super.hashCode(); return this.getPersonAddressId().hashCode(); } /** * bitwise copy of the personAddress object. NOTICE: THIS WILL NOT COPY THE PATIENT OBJECT. The * PersonAddress.person object in this object AND the cloned object will point at the same * person * * @return New PersonAddress object */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError("PersonAddress should be cloneable"); } } /** * @return Returns the address1. */ @Element(data = true, required = false) public String getAddress1() { return address1; } /** * @param address1 The address1 to set. */ @Element(data = true, required = false) public void setAddress1(String address1) { this.address1 = address1; } /** * @return Returns the address2. */ @Element(data = true, required = false) public String getAddress2() { return address2; } /** * @param address2 The address2 to set. */ @Element(data = true, required = false) public void setAddress2(String address2) { this.address2 = address2; } /** * @return Returns the cityVillage. */ @Element(data = true, required = false) public String getCityVillage() { return cityVillage; } /** * @param cityVillage The cityVillage to set. */ @Element(data = true, required = false) public void setCityVillage(String cityVillage) { this.cityVillage = cityVillage; } /** * @return Returns the country. */ @Element(data = true, required = false) public String getCountry() { return country; } /** * @param country The country to set. */ @Element(data = true, required = false) public void setCountry(String country) { this.country = country; } /** * @return Returns the preferred. */ public Boolean isPreferred() { if (preferred == null) return new Boolean(false); return preferred; } @Attribute(required = true) public Boolean getPreferred() { return isPreferred(); } /** * @param preferred The preferred to set. */ @Attribute(required = true) public void setPreferred(Boolean preferred) { this.preferred = preferred; } /** * @return Returns the latitude. */ @Attribute(required = false) public String getLatitude() { return latitude; } /** * @param latitude The latitude to set. */ @Attribute(required = false) public void setLatitude(String latitude) { this.latitude = latitude; } /** * @return Returns the longitude. */ @Attribute(required = false) public String getLongitude() { return longitude; } /** * @param longitude The longitude to set. */ @Attribute(required = false) public void setLongitude(String longitude) { this.longitude = longitude; } /** * @return Returns the person. */ @Element(required = true) public Person getPerson() { return person; } /** * @param person The person to set. */ @Element(required = true) public void setPerson(Person person) { this.person = person; } /** * @return Returns the personAddressId. */ @Attribute(required = true) public Integer getPersonAddressId() { return personAddressId; } /** * @param personAddressId The personAddressId to set. */ @Attribute(required = true) public void setPersonAddressId(Integer personAddressId) { this.personAddressId = personAddressId; } /** * @return Returns the postalCode. */ @Element(data = true, required = false) public String getPostalCode() { return postalCode; } /** * @param postalCode The postalCode to set. */ @Element(data = true, required = false) public void setPostalCode(String postalCode) { this.postalCode = postalCode; } /** * @return Returns the stateProvince. */ @Element(data = true, required = false) public String getStateProvince() { return stateProvince; } /** * @param stateProvince The stateProvince to set. */ @Element(data = true, required = false) public void setStateProvince(String stateProvince) { this.stateProvince = stateProvince; } /** * @return Returns the countyDistrict. */ @Element(data = true, required = false) public String getCountyDistrict() { return countyDistrict; } /** * @param countyDistrict The countyDistrict to set. */ @Element(data = true, required = false) public void setCountyDistrict(String countyDistrict) { this.countyDistrict = countyDistrict; } /** * @deprecated As of 1.8, replaced by {@link #getAddress3()} * @return Returns the neighborhoodCell. */ @Deprecated @Element(data = true, required = false) public String getNeighborhoodCell() { return getAddress3(); } /** * @deprecated As of 1.8, replaced by {@link #setAddress3(String)} * @param address3 The neighborhoodCell to set. */ @Deprecated @Element(data = true, required = false) public void setNeighborhoodCell(String address3) { this.setAddress3(address3); } /** * Convenience method to test whether any of the fields in this address are set * * @return whether any of the address fields (address1, address2, cityVillage, stateProvince, * country, countyDistrict, neighborhoodCell, postalCode, latitude, longitude) are * non-null */ public boolean isBlank() { return getAddress1() == null && getAddress2() == null && getCityVillage() == null && getStateProvince() == null && getCountry() == null && getCountyDistrict() == null && getNeighborhoodCell() == null && getPostalCode() == null && getLatitude() == null && getLongitude() == null; } /** * @deprecated As of 1.8, replaced by {@link #getAddress6()} * @return the region */ @Deprecated @Element(data = true, required = false) public String getRegion() { return getAddress6(); } /** * @deprecated As of 1.8, replaced by {@link #setAddress6(String)} * @param address6 the region to set */ @Deprecated @Element(data = true, required = false) public void setRegion(String address6) { this.setAddress6(address6); } /** * @deprecated As of 1.8, replaced by {@link #getAddress5()} * @return the subregion */ @Deprecated @Element(data = true, required = false) public String getSubregion() { return getAddress5(); } /** * @deprecated As of 1.8, replaced by {@link #setAddress5(String)} * @param address5 the subregion to set */ @Deprecated @Element(data = true, required = false) public void setSubregion(String address5) { this.setAddress5(address5); } /** * @deprecated As of 1.8, replaced by {@link #getAddress4()} * @return the townshipDivision */ @Deprecated @Element(data = true, required = false) public String getTownshipDivision() { return getAddress4(); } /** * @deprecated As of 1.8, replaced by {@link #setAddress4(String)} * @param address4 the address4 to set */ @Deprecated @Element(data = true, required = false) public void setTownshipDivision(String address4) { this.setAddress4(address4); } /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(PersonAddress other) { int retValue = 0; if (other != null) { retValue = isVoided().compareTo(other.isVoided()); if (retValue == 0) retValue = other.isPreferred().compareTo(isPreferred()); if (retValue == 0 && getDateCreated() != null) retValue = OpenmrsUtil.compareWithNullAsLatest(getDateCreated(), other.getDateCreated()); if (retValue == 0) retValue = OpenmrsUtil.compareWithNullAsGreatest(getPersonAddressId(), other.getPersonAddressId()); // if we've gotten this far, just check all address values. If they are // equal, leave the objects at 0. If not, arbitrarily pick retValue=1 // and return that (they are not equal). if (retValue == 0 && !equalsContent(other)) retValue = 1; } return retValue; } /** * @since 1.8 * @return the address3 */ public String getAddress3() { return address3; } /** * @since 1.8 * @param address3 the address3 to set */ public void setAddress3(String address3) { this.address3 = address3; } /** * @since 1.8 * @return the address4 */ public String getAddress4() { return address4; } /** * @since 1.8 * @param address4 the address4 to set */ public void setAddress4(String address4) { this.address4 = address4; } /** * @since 1.8 * @return the address6 */ public String getAddress6() { return address6; } /** * @since 1.8 * @param address6 the address6 to set */ public void setAddress6(String address6) { this.address6 = address6; } /** * @since 1.8 * @return the address5 */ public String getAddress5() { return address5; } /** * @since 1.8 * @param address5 the address5 to set */ public void setAddress5(String address5) { this.address5 = address5; } /** * @since 1.5 * @see org.openmrs.OpenmrsObject#getId() */ public Integer getId() { return getPersonAddressId(); } /** * @since 1.5 * @see org.openmrs.OpenmrsObject#setId(java.lang.Integer) */ public void setId(Integer id) { setPersonAddressId(id); } /** * @return the startDate * @since 1.9 */ public Date getStartDate() { return startDate; } /** * @param startDate to set to * @since 1.9 */ public void setStartDate(Date startDate) { this.startDate = startDate; } /** * @return the endDate * @since 1.9 */ public Date getEndDate() { return this.endDate; } /** * @param endDate to set to * @since 1.9 */ public void setEndDate(Date endDate) { this.endDate = endDate; } /** * Returns true if the address' endDate is null * * @return true or false * @since 1.9 */ public Boolean isActive() { return (this.endDate == null); } /** * Makes an address inactive by setting its endDate to the current time * * @since 1.9 */ public void inactivate() { setEndDate(Calendar.getInstance().getTime()); } /** * Makes an address active by setting its endDate to null * * @since 1.9 */ public void activate() { setEndDate(null); } }
true
true
public boolean equalsContent(PersonAddress otherAddress) { boolean returnValue = true; // these are the methods to compare. All are expected to be Strings String[] methods = { "getAddress1", "getAddress2", "getAddress3", "getAddress4", "getAddress5", "getCityVillage", "getNeighborhoodCell", "getCountyDistrict", "getStateProvince", "getCountry", "getPostalCode", "getLatitude", "getLongitude" }; Class addressClass = this.getClass(); // loop over all of the selected methods and compare this and other for (String methodName : methods) { try { Method method = addressClass.getMethod(methodName, new Class[] {}); String thisValue = (String) method.invoke(this); String otherValue = (String) method.invoke(otherAddress); if (otherValue != null && otherValue.length() > 0) returnValue &= otherValue.equals(thisValue); } catch (NoSuchMethodException e) { log.warn("No such method for comparison " + methodName, e); } catch (IllegalAccessException e) { log.error("Error while comparing addresses", e); } catch (InvocationTargetException e) { log.error("Error while comparing addresses", e); } } return returnValue; }
public boolean equalsContent(PersonAddress otherAddress) { boolean returnValue = true; // these are the methods to compare. All are expected to be Strings String[] methods = { "getAddress1", "getAddress2", "getAddress3", "getAddress4", "getAddress5", "getAddress6", "getCityVillage", "getCountyDistrict", "getStateProvince", "getCountry", "getPostalCode", "getLatitude", "getLongitude" }; Class addressClass = this.getClass(); // loop over all of the selected methods and compare this and other for (String methodName : methods) { try { Method method = addressClass.getMethod(methodName, new Class[] {}); String thisValue = (String) method.invoke(this); String otherValue = (String) method.invoke(otherAddress); if (otherValue != null && otherValue.length() > 0) returnValue &= otherValue.equals(thisValue); } catch (NoSuchMethodException e) { log.warn("No such method for comparison " + methodName, e); } catch (IllegalAccessException e) { log.error("Error while comparing addresses", e); } catch (InvocationTargetException e) { log.error("Error while comparing addresses", e); } } return returnValue; }
diff --git a/utils/src/org/jackie/utils/Assert.java b/utils/src/org/jackie/utils/Assert.java index d6feeea..fc25ca0 100755 --- a/utils/src/org/jackie/utils/Assert.java +++ b/utils/src/org/jackie/utils/Assert.java @@ -1,119 +1,119 @@ package org.jackie.utils; /** * @author Patrik Beno */ @SuppressWarnings({"ThrowableInstanceNeverThrown", "unchecked"}) public class Assert { static public void doAssert(boolean condition, String msg, Object... args) { if (!condition) { throw new AssertionError(msg, args); } } static public AssertionError assertFailed(Throwable thrown) { return new AssertionError(thrown); } static public AssertionError assertFailed(final Throwable thrown, String msg, Object... args) { return new AssertionError(thrown, msg, args); } // todo optimize; make this effectivelly inlinable static public <T> T typecast(Object o, Class<T> expected) { if (o == null) { return null; } if (!expected.isAssignableFrom(o.getClass())) { throw new ClassCastException(String.format( - "Incompatible types: Expected %s, found: %s", + "Incompatible types. Expected: %s, found: %s", expected.getName(), o.getClass().getName())); } return (T) o; } static public AssertionError notYetImplemented() { StackTraceElement ste = Thread.currentThread().getStackTrace()[2]; return new AssertionError("Not Yet Implemented! %s", ste); } static public UnsupportedOperationException unsupported() { StackTraceElement ste = Thread.currentThread().getStackTrace()[2]; return new UnsupportedOperationException(ste.toString()); } static public AssertionError unexpected(Throwable thrown) { return new AssertionError(thrown, "Unexpected: %s", thrown.getClass()); } static public AssertionError notYetHandled(Throwable t) { return new AssertionError(t, "Not Yet Handled: %s", t.getClass().getName()); } static public void logNotYetHandled(Throwable thrown) { Log.warn("Not Yet Handled: at %s", thrown); } static public AssertionError invariantFailed(Throwable thrown, String msg, Object ... args) { return new AssertionError(thrown, msg, args); } static public AssertionError invariantFailed(String msg, Object ... args) { return new AssertionError(String.format(msg, args)); } static public AssertionError invariantFailed(Enum e) { return new AssertionError("Unexpected enum value: %s.%s", e.getClass().getName(), e.name()); } static public void notNull(Object obj) { if (obj == null) { throw new AssertionError("Unexpected NULL"); } } static public <T> T NOTNULL(T t, String message, Object ... args) { if (t == null) { throw new AssertionError("Unexpected NULL: %s", String.format(message, args)); } return t; } static public <T> T NOTNULL(T t) { if (t == null) { throw new AssertionError("Unexpected NULL"); } return t; } static public void logNotYetImplemented() { StackTraceElement ste = Thread.currentThread().getStackTrace()[2]; Log.warn("Not Yet Implemented: at %s", ste); } static public void expected(Object expected, Object found, String msg, Object ... args) { if (expected != null && expected.equals(found) || expected == null && found == null) { return; } throw assertFailed(null, "Expected [%s], found [%s]. %s", expected, found, String.format(msg, args)); } static public boolean NOT(boolean expression) { return !expression; } static class AssertionError extends java.lang.AssertionError { AssertionError(String message, Object ... args) { this(null, message, args); } AssertionError(Throwable thrown) { this(thrown, thrown.getClass().getSimpleName()); } AssertionError(Throwable cause, String message, Object ... args) { super(String.format(message, args)); initCause(cause); } } }
true
true
static public <T> T typecast(Object o, Class<T> expected) { if (o == null) { return null; } if (!expected.isAssignableFrom(o.getClass())) { throw new ClassCastException(String.format( "Incompatible types: Expected %s, found: %s", expected.getName(), o.getClass().getName())); } return (T) o; }
static public <T> T typecast(Object o, Class<T> expected) { if (o == null) { return null; } if (!expected.isAssignableFrom(o.getClass())) { throw new ClassCastException(String.format( "Incompatible types. Expected: %s, found: %s", expected.getName(), o.getClass().getName())); } return (T) o; }
diff --git a/src/main/java/ch/ethz/bsse/indelfixer/minimal/Start.java b/src/main/java/ch/ethz/bsse/indelfixer/minimal/Start.java index 7e727fd..f8f4bbd 100644 --- a/src/main/java/ch/ethz/bsse/indelfixer/minimal/Start.java +++ b/src/main/java/ch/ethz/bsse/indelfixer/minimal/Start.java @@ -1,467 +1,467 @@ /** * Copyright (c) 2011-2013 Armin Töpfer * * This file is part of InDelFixer. * * InDelFixer 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 any later version. * * InDelFixer 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 * InDelFixer. If not, see <http://www.gnu.org/licenses/>. */ package ch.ethz.bsse.indelfixer.minimal; import ch.ethz.bsse.indelfixer.minimal.processing.ProcessingFastaSingle; import ch.ethz.bsse.indelfixer.minimal.processing.ProcessingIlluminaPaired; import ch.ethz.bsse.indelfixer.minimal.processing.ProcessingIlluminaSingle; import ch.ethz.bsse.indelfixer.minimal.processing.ProcessingSFFSingle; import ch.ethz.bsse.indelfixer.sffParser.SFFParsing; import ch.ethz.bsse.indelfixer.stored.Genome; import ch.ethz.bsse.indelfixer.stored.Globals; import ch.ethz.bsse.indelfixer.utils.FastaParser; import ch.ethz.bsse.indelfixer.utils.StatusUpdate; import ch.ethz.bsse.indelfixer.utils.Utils; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Handler; import java.util.logging.Logger; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; /** * Entry point. * * @author Armin Töpfer (armin.toepfer [at] gmail.com) */ public class Start { @Option(name = "-i") private String input; @Option(name = "-ir") private String inputReverse; @Option(name = "-g") private String genome; @Option(name = "-o", usage = "Path to the output directory (default: current directory)", metaVar = "PATH") private String output; @Option(name = "-v") private int overlap = 2; @Option(name = "-k") private int kmerLength = 10; @Option(name = "-adjust") private boolean adjust; @Option(name = "-t") private int threshold = 30; @Option(name = "-step") private int step = 10; @Option(name = "-r") private String regions; @Option(name = "-flat") private boolean flat; @Option(name = "-l") private int minlength = 0; @Option(name = "-la") private int minlengthAligned = 0; @Option(name = "-sub") private double sub = 1; @Option(name = "-del") private double del = 1; @Option(name = "-ins") private double ins = 1; @Option(name = "-gop") private float gop = 30; @Option(name = "-gex") private float gex = 3; // @Option(name = "-pacbio") // private boolean pacbio; // @Option(name = "-illumina") // private boolean illumina; // @Option(name = "-454") // private boolean roche; @Option(name = "-cut") private int cut; @Option(name = "-header") private String header; @Option(name = "--filter") private boolean filter; @Option(name = "--freq") private boolean freq; @Option(name = "-refine") private int refine; @Option(name = "--version") private boolean version; @Option(name = "-rmDel") private boolean rmDel; @Option(name = "-consensus") private boolean consensus; @Option(name = "-N") private int N = 3; @Option(name = "-sensitive") private boolean sensitive; @Option(name = "-maxDel") private int maxDel = -1; @Option(name = "-noHashing") private boolean noHashing; @Option(name = "-fix") private boolean fix; /** * Remove logging of jaligner. */ { Logger rootLogger = Logger.getLogger(""); Handler[] handlers = rootLogger.getHandlers(); if (handlers.length > 0) { rootLogger.removeHandler(handlers[0]); } } /** * Forwards command-line parameters. * * @param args command-line parameters * @throws IOException If parameters are wrong */ public static void main(String[] args) throws IOException { new Start().doMain(args); System.exit(0); } /** * Main. * * @param args command-line parameters */ public void doMain(String[] args) { try { CmdLineParser parser = new CmdLineParser(this); parser.setUsageWidth(80); try { parser.parseArgument(args); if (this.version) { System.out.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion()); return; } this.checkOutput(); if (this.input == null && this.genome == null) { throw new CmdLineException(""); } if (this.fix) { if (this.refine == 0) { refine = 1; } } this.setGlobals(); Genome[] genomes = parseGenome(this.genome); if (this.regions != null) { Globals.RS = this.splitRegion(); genomes = parseGenome(this.cutGenomes(genomes)); } compute(genomes); if (this.fix) { Globals.ADJUST = true; } if (this.refine > 0) { this.genome = this.output + "consensus.fasta"; genomes = parseGenome(this.genome); for (int i = 0; i < this.refine; i++) { StatusUpdate.readCount = 0; StatusUpdate.unmappedCount = 0; StatusUpdate.tooSmallCount = 0; StatusUpdate.alignCount1 = 0; StatusUpdate.alignCount2 = 0; StatusUpdate.alignCount3 = 0; compute(genomes); } } } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion()); System.err.println("Get latest version from http://bit.ly/indelfixer"); System.err.println(""); System.err.println("USAGE: java -jar InDelFixer.jar options...\n"); System.err.println(" ------------------------"); System.err.println(" === GENERAL options ==="); System.err.println(" -o PATH\t\t: Path to the output directory (default: current directory)"); System.err.println(" -i PATH\t\t: Path to the NGS input file (FASTA, FASTQ or SFF format) [REQUIRED]"); System.err.println(" -ir PATH\t\t: Path to the second paired end file (FASTQ) [ONLY REQUIRED if first file is also fastq]"); System.err.println(" -g PATH\t\t: Path to the reference genomes file (FASTA format) [REQUIRED]"); System.err.println(" -r interval\t\t: Region on the reference genome (i.e. 342-944)"); System.err.println(" -k INT\t\t: Kmer size (default 10)"); System.err.println(" -v INT\t\t: Kmer offset (default 2)"); System.err.println(" -cut INT\t\t: Cut given number of bases (primer) from beginning of the read (default 0)"); System.err.println(" -refine INT\t\t: Computes a consensus sequence from alignment and re-aligns against that."); System.err.println("\t\t\t Refinement is repeated as many times as specified."); System.err.println(" -rmDel\t\t: Removes conserved gaps from consensus sequence during refinement"); System.err.println(" -sensitive\t\t: More sensitive but slower alignment"); System.err.println(" -fix\t\t\t: Fill frame-shift causing deletions with consensus sequence."); System.err.println(" -noHashing\t\t: No fast kmer-matching to find approximate mapping region. Please use with PacBio data!"); System.err.println(""); System.err.println(" === FILTER ==="); System.err.println(" -l INT\t\t: Minimal read-length prior alignment (default 0)"); System.err.println(" -la INT\t\t: Minimal read-length after alignment (default 0)"); - System.err.println(" -ins DOUBLE\t\t: The maximum precentage of insertions allowed [range 0.0 - 1.0] (default 1.0)"); - System.err.println(" -del DOUBLE\t\t: The maximum precentage of deletions allowed [range 0.0 - 1.0] (default 1.0)"); - System.err.println(" -sub DOUBLE\t\t: The maximum precentage of substitutions allowed [range 0.0 - 1.0] (default 1.0)"); + System.err.println(" -ins DOUBLE\t\t: The maximum percentage of insertions allowed [range 0.0 - 1.0] (default 1.0)"); + System.err.println(" -del DOUBLE\t\t: The maximum percentage of deletions allowed [range 0.0 - 1.0] (default 1.0)"); + System.err.println(" -sub DOUBLE\t\t: The maximum percentage of substitutions allowed [range 0.0 - 1.0] (default 1.0)"); System.err.println(" -maxDel INT\t\t: The maximum number of consecutive deletions allowed (default no filtering)"); System.err.println(""); System.err.println(" === GAP costs ==="); System.err.println(" -gop\t\t\t: Gap opening costs for Smith-Waterman (default 30)"); System.err.println(" -gex\t\t\t: Gap extension costs for Smith-Waterman (default 3)"); // System.err.println(""); // System.err.println(" === GAP costs predefined ==="); // System.err.println(" -454\t\t\t: 10 open / 1 extend"); // System.err.println(" -illumina\t\t: 30 open / 3 extend"); // System.err.println(" -pacbio\t\t: 10 open / 10 extend"); System.err.println(""); System.err.println(" ------------------------"); System.err.println(" === EXAMPLES ==="); System.err.println(" 454/Roche\t\t: java -jar InDelFixer.jar -i libCase102.fastq -g referenceGenomes.fasta"); System.err.println(" PacBio\t\t: java -jar InDelFixer.jar -i libCase102.ccs.fastq -g referenceGenomes.fasta"); System.err.println(" Illumina\t\t: java -jar InDelFixer.jar -i libCase102_R1.fastq -ir libCase102_R2.fastq -g referenceGenomes.fasta"); System.err.println(" ------------------------"); } } catch (OutOfMemoryError e) { Utils.error(); System.err.println("Please increase the heap space."); } } /** * Creates output directory if not existing. */ private void checkOutput() { if (this.output == null) { this.output = System.getProperty("user.dir") + File.separator; } else { Globals.output = this.output; } if (!new File(this.output).exists()) { new File(this.output).mkdirs(); } } /** * Splits input region in format x-y * * @return */ private int[] splitRegion() { String[] split = regions.split("-"); return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1])}; } /** * Cuts genomes into defined region. * * @param genomes of type Genome */ private String cutGenomes(Genome[] genomes) { int[] rs = Globals.RS; StringBuilder sb = new StringBuilder(); for (Genome g : genomes) { try { sb.append(">").append(g.getHeader()).append("\n"); sb.append(g.getSequence().substring(rs[0] - 1, rs[1] - 1)).append("\n"); } catch (Exception e) { System.err.println(e); Utils.error(); } } String output = Globals.output + "ref_" + (rs[0]) + "-" + (rs[1] - 1) + ".fasta"; Utils.saveFile(output, sb.toString()); return output; } /** * Parses genomes from multiple fasta file. * * @param genomePath multiple fasta file path * @return Genome sequences wrapped into Genome class */ private Genome[] parseGenome(String genomePath) { Map<String, String> haps = FastaParser.parseHaplotypeFile(genomePath); List<Genome> genomeList = new LinkedList<>(); for (Map.Entry<String, String> hap : haps.entrySet()) { if (header == null || hap.getValue().startsWith(this.header)) { genomeList.add(new Genome(hap)); } } Genome[] gs = genomeList.toArray(new Genome[genomeList.size()]); Globals.GENOMES = gs; Globals.GENOME_COUNT = gs.length; Globals.GENOME_SEQUENCES = haps.keySet().toArray(new String[gs.length]); Globals.GENOME_LENGTH = Globals.GENOME_SEQUENCES[0].length(); return gs; } /** * Set global variables from command-line parameters */ private void setGlobals() { // if (this.pacbio) { // Globals.GOP = 10; // Globals.GEX = 10; // } else if (this.illumina) { // Globals.GOP = 30; // Globals.GEX = 3; // } else if (this.roche) { // Globals.GOP = 10; // Globals.GEX = 1; // } else { Globals.GOP = this.gop; Globals.GEX = this.gex; // } Globals.MIN_LENGTH_ALIGNED = minlengthAligned; Globals.MIN_LENGTH = minlength; Globals.ADJUST = this.adjust; Globals.STEPS = this.step; Globals.THRESHOLD = this.threshold; Globals.KMER_OVERLAP = this.overlap; Globals.KMER_LENGTH = this.kmerLength; Globals.MAX_DEL = this.del; Globals.MAX_INS = this.ins; Globals.MAX_SUB = this.sub; Globals.FLAT = this.flat; Globals.CUT = this.cut; Globals.FILTER = this.filter; Globals.REFINE = this.refine > 0; Globals.RM_DEL = this.rmDel; Globals.maxN = this.N; Globals.CONSENSUS = this.consensus; Globals.SENSITIVE = this.sensitive; Globals.MAX_CONSECUTIVE_DEL = this.maxDel; Globals.NO_HASHING = this.noHashing; } /** * Flats multiple fasta file and splits it files with 100 sequences. */ private void flatAndSave() { Map<String, String> far = FastaParser.parseHaplotypeFile(input); StringBuilder sb = new StringBuilder(); int x = 0; int i = 0; for (Map.Entry<String, String> entry : far.entrySet()) { sb.append(entry.getValue()).append("\n").append(entry.getKey()).append("\n"); if (i++ % 1000 == 0) { Utils.saveFile(output + "flat-" + x++ + ".fasta", sb.toString()); sb.setLength(0); } } if (sb.length() > 0) { Utils.saveFile(output + "flat-" + x + ".fasta", sb.toString()); } } public static byte[] splitReadIntoByteArray(String read) { byte[] Rs = new byte[read.length()]; char[] readSplit = read.toCharArray(); int length = readSplit.length; for (int i = 0; i < length; i++) { switch ((short) readSplit[i]) { case 65: Rs[i] = 0; break; case 67: Rs[i] = 1; break; case 71: Rs[i] = 2; break; case 84: Rs[i] = 3; break; case 45: Rs[i] = 4; break; default: break; } } return Rs; } public static String shortenSmall(double value) { String s; if (value < 1e-16) { s = "0 "; } else if (value == 1.0) { s = "1 "; } else { String t = "" + value; String r; if (t.length() > 7) { r = t.substring(0, 7); if (t.contains("E")) { r = r.substring(0, 4); r += "E" + t.split("E")[1]; } s = r; } else { s = String.valueOf(value); } } return s; } private boolean compute(Genome[] genomes) throws CmdLineException, IllegalStateException { if (this.freq) { double[][] allels = new double[genomes[0].getSequence().length()][5]; for (Genome g : genomes) { byte[] a = splitReadIntoByteArray(g.getSequence()); for (int j = 0; j < g.getSequence().length(); j++) { allels[j][a[j]] += 1d / genomes.length; } } StringBuilder sb = new StringBuilder(); sb.append("\tA\tC\tG\tT\t-\n"); for (int j = 0; j < allels.length; j++) { sb.append(j); double sum = 0d; for (int v = 0; v < 5; v++) { sum += allels[j][v] > 1e-5 ? allels[j][v] : 0;; } for (int v = 0; v < 5; v++) { sb.append("\t").append(shortenSmall(allels[j][v] / sum)); } sb.append("\n"); } Utils.saveFile("Genome_allels.txt", sb.toString()); return true; } for (Genome g : genomes) { g.split(); } if (!new File(this.input).exists()) { throw new CmdLineException("Input file does not exist"); } File readsSam = new File(this.output + "reads.sam"); if (readsSam.exists()) { readsSam.delete(); } if (this.inputReverse != null) { if (!new File(this.inputReverse).exists()) { throw new CmdLineException("Input reverse file does not exist"); } new ProcessingIlluminaPaired(this.input, this.inputReverse); } else if (Utils.isFastaGlobalMatePairFormat(this.input)) { new ProcessingIlluminaSingle(this.input); } else if (Utils.isFastaFormat(this.input)) { new ProcessingFastaSingle(this.input); } else { new ProcessingSFFSingle(SFFParsing.parse(this.input)); } return false; } }
true
true
public void doMain(String[] args) { try { CmdLineParser parser = new CmdLineParser(this); parser.setUsageWidth(80); try { parser.parseArgument(args); if (this.version) { System.out.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion()); return; } this.checkOutput(); if (this.input == null && this.genome == null) { throw new CmdLineException(""); } if (this.fix) { if (this.refine == 0) { refine = 1; } } this.setGlobals(); Genome[] genomes = parseGenome(this.genome); if (this.regions != null) { Globals.RS = this.splitRegion(); genomes = parseGenome(this.cutGenomes(genomes)); } compute(genomes); if (this.fix) { Globals.ADJUST = true; } if (this.refine > 0) { this.genome = this.output + "consensus.fasta"; genomes = parseGenome(this.genome); for (int i = 0; i < this.refine; i++) { StatusUpdate.readCount = 0; StatusUpdate.unmappedCount = 0; StatusUpdate.tooSmallCount = 0; StatusUpdate.alignCount1 = 0; StatusUpdate.alignCount2 = 0; StatusUpdate.alignCount3 = 0; compute(genomes); } } } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion()); System.err.println("Get latest version from http://bit.ly/indelfixer"); System.err.println(""); System.err.println("USAGE: java -jar InDelFixer.jar options...\n"); System.err.println(" ------------------------"); System.err.println(" === GENERAL options ==="); System.err.println(" -o PATH\t\t: Path to the output directory (default: current directory)"); System.err.println(" -i PATH\t\t: Path to the NGS input file (FASTA, FASTQ or SFF format) [REQUIRED]"); System.err.println(" -ir PATH\t\t: Path to the second paired end file (FASTQ) [ONLY REQUIRED if first file is also fastq]"); System.err.println(" -g PATH\t\t: Path to the reference genomes file (FASTA format) [REQUIRED]"); System.err.println(" -r interval\t\t: Region on the reference genome (i.e. 342-944)"); System.err.println(" -k INT\t\t: Kmer size (default 10)"); System.err.println(" -v INT\t\t: Kmer offset (default 2)"); System.err.println(" -cut INT\t\t: Cut given number of bases (primer) from beginning of the read (default 0)"); System.err.println(" -refine INT\t\t: Computes a consensus sequence from alignment and re-aligns against that."); System.err.println("\t\t\t Refinement is repeated as many times as specified."); System.err.println(" -rmDel\t\t: Removes conserved gaps from consensus sequence during refinement"); System.err.println(" -sensitive\t\t: More sensitive but slower alignment"); System.err.println(" -fix\t\t\t: Fill frame-shift causing deletions with consensus sequence."); System.err.println(" -noHashing\t\t: No fast kmer-matching to find approximate mapping region. Please use with PacBio data!"); System.err.println(""); System.err.println(" === FILTER ==="); System.err.println(" -l INT\t\t: Minimal read-length prior alignment (default 0)"); System.err.println(" -la INT\t\t: Minimal read-length after alignment (default 0)"); System.err.println(" -ins DOUBLE\t\t: The maximum precentage of insertions allowed [range 0.0 - 1.0] (default 1.0)"); System.err.println(" -del DOUBLE\t\t: The maximum precentage of deletions allowed [range 0.0 - 1.0] (default 1.0)"); System.err.println(" -sub DOUBLE\t\t: The maximum precentage of substitutions allowed [range 0.0 - 1.0] (default 1.0)"); System.err.println(" -maxDel INT\t\t: The maximum number of consecutive deletions allowed (default no filtering)"); System.err.println(""); System.err.println(" === GAP costs ==="); System.err.println(" -gop\t\t\t: Gap opening costs for Smith-Waterman (default 30)"); System.err.println(" -gex\t\t\t: Gap extension costs for Smith-Waterman (default 3)"); // System.err.println(""); // System.err.println(" === GAP costs predefined ==="); // System.err.println(" -454\t\t\t: 10 open / 1 extend"); // System.err.println(" -illumina\t\t: 30 open / 3 extend"); // System.err.println(" -pacbio\t\t: 10 open / 10 extend"); System.err.println(""); System.err.println(" ------------------------"); System.err.println(" === EXAMPLES ==="); System.err.println(" 454/Roche\t\t: java -jar InDelFixer.jar -i libCase102.fastq -g referenceGenomes.fasta"); System.err.println(" PacBio\t\t: java -jar InDelFixer.jar -i libCase102.ccs.fastq -g referenceGenomes.fasta"); System.err.println(" Illumina\t\t: java -jar InDelFixer.jar -i libCase102_R1.fastq -ir libCase102_R2.fastq -g referenceGenomes.fasta"); System.err.println(" ------------------------"); } } catch (OutOfMemoryError e) { Utils.error(); System.err.println("Please increase the heap space."); } }
public void doMain(String[] args) { try { CmdLineParser parser = new CmdLineParser(this); parser.setUsageWidth(80); try { parser.parseArgument(args); if (this.version) { System.out.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion()); return; } this.checkOutput(); if (this.input == null && this.genome == null) { throw new CmdLineException(""); } if (this.fix) { if (this.refine == 0) { refine = 1; } } this.setGlobals(); Genome[] genomes = parseGenome(this.genome); if (this.regions != null) { Globals.RS = this.splitRegion(); genomes = parseGenome(this.cutGenomes(genomes)); } compute(genomes); if (this.fix) { Globals.ADJUST = true; } if (this.refine > 0) { this.genome = this.output + "consensus.fasta"; genomes = parseGenome(this.genome); for (int i = 0; i < this.refine; i++) { StatusUpdate.readCount = 0; StatusUpdate.unmappedCount = 0; StatusUpdate.tooSmallCount = 0; StatusUpdate.alignCount1 = 0; StatusUpdate.alignCount2 = 0; StatusUpdate.alignCount3 = 0; compute(genomes); } } } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("InDelFixer version: " + Start.class.getPackage().getImplementationVersion()); System.err.println("Get latest version from http://bit.ly/indelfixer"); System.err.println(""); System.err.println("USAGE: java -jar InDelFixer.jar options...\n"); System.err.println(" ------------------------"); System.err.println(" === GENERAL options ==="); System.err.println(" -o PATH\t\t: Path to the output directory (default: current directory)"); System.err.println(" -i PATH\t\t: Path to the NGS input file (FASTA, FASTQ or SFF format) [REQUIRED]"); System.err.println(" -ir PATH\t\t: Path to the second paired end file (FASTQ) [ONLY REQUIRED if first file is also fastq]"); System.err.println(" -g PATH\t\t: Path to the reference genomes file (FASTA format) [REQUIRED]"); System.err.println(" -r interval\t\t: Region on the reference genome (i.e. 342-944)"); System.err.println(" -k INT\t\t: Kmer size (default 10)"); System.err.println(" -v INT\t\t: Kmer offset (default 2)"); System.err.println(" -cut INT\t\t: Cut given number of bases (primer) from beginning of the read (default 0)"); System.err.println(" -refine INT\t\t: Computes a consensus sequence from alignment and re-aligns against that."); System.err.println("\t\t\t Refinement is repeated as many times as specified."); System.err.println(" -rmDel\t\t: Removes conserved gaps from consensus sequence during refinement"); System.err.println(" -sensitive\t\t: More sensitive but slower alignment"); System.err.println(" -fix\t\t\t: Fill frame-shift causing deletions with consensus sequence."); System.err.println(" -noHashing\t\t: No fast kmer-matching to find approximate mapping region. Please use with PacBio data!"); System.err.println(""); System.err.println(" === FILTER ==="); System.err.println(" -l INT\t\t: Minimal read-length prior alignment (default 0)"); System.err.println(" -la INT\t\t: Minimal read-length after alignment (default 0)"); System.err.println(" -ins DOUBLE\t\t: The maximum percentage of insertions allowed [range 0.0 - 1.0] (default 1.0)"); System.err.println(" -del DOUBLE\t\t: The maximum percentage of deletions allowed [range 0.0 - 1.0] (default 1.0)"); System.err.println(" -sub DOUBLE\t\t: The maximum percentage of substitutions allowed [range 0.0 - 1.0] (default 1.0)"); System.err.println(" -maxDel INT\t\t: The maximum number of consecutive deletions allowed (default no filtering)"); System.err.println(""); System.err.println(" === GAP costs ==="); System.err.println(" -gop\t\t\t: Gap opening costs for Smith-Waterman (default 30)"); System.err.println(" -gex\t\t\t: Gap extension costs for Smith-Waterman (default 3)"); // System.err.println(""); // System.err.println(" === GAP costs predefined ==="); // System.err.println(" -454\t\t\t: 10 open / 1 extend"); // System.err.println(" -illumina\t\t: 30 open / 3 extend"); // System.err.println(" -pacbio\t\t: 10 open / 10 extend"); System.err.println(""); System.err.println(" ------------------------"); System.err.println(" === EXAMPLES ==="); System.err.println(" 454/Roche\t\t: java -jar InDelFixer.jar -i libCase102.fastq -g referenceGenomes.fasta"); System.err.println(" PacBio\t\t: java -jar InDelFixer.jar -i libCase102.ccs.fastq -g referenceGenomes.fasta"); System.err.println(" Illumina\t\t: java -jar InDelFixer.jar -i libCase102_R1.fastq -ir libCase102_R2.fastq -g referenceGenomes.fasta"); System.err.println(" ------------------------"); } } catch (OutOfMemoryError e) { Utils.error(); System.err.println("Please increase the heap space."); } }
diff --git a/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java b/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java index 0ac087781..eab63cb58 100644 --- a/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java +++ b/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java @@ -1,270 +1,270 @@ /** * Copyright (c) 2011 Metropolitan Transportation Authority * * 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.onebusaway.nyc.webapp.actions; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.onebusaway.nyc.webapp.actions.OneBusAwayNYCActionSupport; /** * Adapted from Google Analytics' ga.jsp code, which was: Copyright 2009 Google Inc. All Rights Reserved. **/ @Results( {@Result(type = "stream", name = "pixel", params = {"contentType", "image/gif"})} ) public class GaAction extends OneBusAwayNYCActionSupport { private static final long serialVersionUID = 1L; // Download stream to write 1x1 px. GIF back to user. private InputStream inputStream; // Tracker version. private static final String version = "4.4sj"; private static final String COOKIE_NAME = "__utmmobile"; // The path the cookie will be available to, edit this to use a different // cookie path. private static final String COOKIE_PATH = "/"; // Two years in seconds. private static final int COOKIE_USER_PERSISTENCE = 63072000; // 1x1 transparent GIF private static final byte[] GIF_DATA = new byte[] { (byte)0x47, (byte)0x49, (byte)0x46, (byte)0x38, (byte)0x39, (byte)0x61, (byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x80, (byte)0xff, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x2c, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x02, (byte)0x44, (byte)0x01, (byte)0x00, (byte)0x3b }; // this is the download streamed to the user public InputStream getInputStream() { return inputStream; } // A string is empty in our terms, if it is null, empty or a dash. private static boolean isEmpty(String in) { return in == null || "-".equals(in) || "".equals(in); } // The last octect of the IP address is removed to anonymize the user. private static String getIP(String remoteAddress) { if (isEmpty(remoteAddress)) { return ""; } // Capture the first three octects of the IP address and replace the forth // with 0, e.g. 124.455.3.123 becomes 124.455.3.0 String regex = "^([^.]+\\.[^.]+\\.[^.]+\\.).*"; Pattern getFirstBitOfIPAddress = Pattern.compile(regex); Matcher m = getFirstBitOfIPAddress.matcher(remoteAddress); if (m.matches()) { return m.group(1) + "0"; } else { return ""; } } // Generate a visitor id for this hit. // If there is a visitor id in the cookie, use that, otherwise // use the guid if we have one, otherwise use a random number. private static String getVisitorId( String guid, String account, String userAgent, Cookie cookie) throws NoSuchAlgorithmException, UnsupportedEncodingException { // If there is a value in the cookie, don't change it. if (cookie != null && cookie.getValue() != null) { return cookie.getValue(); } String message; if (!isEmpty(guid)) { // Create the visitor id using the guid. message = guid + account; } else { // otherwise this is a new user, create a new random id. message = userAgent + getRandomNumber() + UUID.randomUUID().toString(); } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(message.getBytes("UTF-8"), 0, message.length()); byte[] sum = m.digest(); BigInteger messageAsNumber = new BigInteger(1, sum); String md5String = messageAsNumber.toString(16); // Pad to make sure id is 32 characters long. while (md5String.length() < 32) { md5String = "0" + md5String; } return "0x" + md5String.substring(0, 16); } // Get a random number string. private static String getRandomNumber() { return Integer.toString((int) (Math.random() * 0x7fffffff)); } // Make a tracking request to Google Analytics from this server. // Copies the headers from the original request to the new one. // If request containg utmdebug parameter, exceptions encountered // communicating with Google Analytics are thown. private void sendRequestToGoogleAnalytics( String utmUrl, HttpServletRequest request) throws Exception { try { URL url = new URL(utmUrl); URLConnection connection = url.openConnection(); connection.setUseCaches(false); connection.addRequestProperty("User-Agent", request.getHeader("User-Agent")); connection.addRequestProperty("Accepts-Language", request.getHeader("Accepts-Language")); connection.getContent(); } catch (Exception e) { if (request.getParameter("utmdebug") != null) { throw new Exception(e); } } } // Track a page view, updates all the cookies and campaign tracker, // makes a server side request to Google Analytics and writes the transparent // gif byte data to the response. @Override public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String domainName = request.getServerName(); if (isEmpty(domainName)) { domainName = ""; } // Get the referrer from the utmr parameter, this is the referrer to the // page that contains the tracking pixel, not the referrer for tracking // pixel. String documentReferer = request.getParameter("utmr"); if (isEmpty(documentReferer)) { documentReferer = "-"; } else { documentReferer = URLDecoder.decode(documentReferer, "UTF-8"); } String documentPath = request.getParameter("utmp"); if (isEmpty(documentPath)) { documentPath = ""; } else { documentPath = URLDecoder.decode(documentPath, "UTF-8"); } String account = request.getParameter("utmac"); String userAgent = request.getHeader("User-Agent"); if (isEmpty(userAgent)) { userAgent = ""; } // Try and get visitor cookie from the request. Cookie[] cookies = request.getCookies(); Cookie cookie = null; if (cookies != null) { for(int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(COOKIE_NAME)) { cookie = cookies[i]; } } } String visitorId = getVisitorId( request.getHeader("X-DCMGUID"), account, userAgent, cookie); // Always try and add the cookie to the response. Cookie newCookie = new Cookie(COOKIE_NAME, visitorId); newCookie.setMaxAge(COOKIE_USER_PERSISTENCE); newCookie.setPath(COOKIE_PATH); response.addCookie(newCookie); // Construct the gif hit url. String utmUrl = "utmwv=" + version + "&utmn=" + getRandomNumber() + "&utmhn=" + domainName + "&utmr=" + documentReferer + "&utmp=" + documentPath + "&utmac=" + account + "&utmcc=__utma%3D999.999.999.999.999.1%3B" + "&utmvid=" + visitorId + "&utmip=" + getIP(request.getRemoteAddr()); // event tracking String type = request.getParameter("utmt"); String event = request.getParameter("utme"); if (!isEmpty(type) && !isEmpty(event)) { utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8"); utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8"); } URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null); - sendRequestToGoogleAnalytics(utfGifLocationUri.toASCIIString(), request); + sendRequestToGoogleAnalytics(utfGifLocationUri.toString(), request); // If the debug parameter is on, add a header to the response that contains // the url that was used to contact Google Analytics. if (request.getParameter("utmdebug") != null) { - response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toASCIIString()); + response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toString()); } // write 1x1 pixel tracking gif to output stream final PipedInputStream pipedInputStream = new PipedInputStream(); final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); response.addHeader( "Cache-Control", "private, no-cache, no-cache=Set-Cookie, proxy-revalidate"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT"); pipedOutputStream.write(GIF_DATA); pipedOutputStream.flush(); pipedOutputStream.close(); // the input stream will get populated by the piped output stream inputStream = pipedInputStream; return "pixel"; } }
false
true
public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String domainName = request.getServerName(); if (isEmpty(domainName)) { domainName = ""; } // Get the referrer from the utmr parameter, this is the referrer to the // page that contains the tracking pixel, not the referrer for tracking // pixel. String documentReferer = request.getParameter("utmr"); if (isEmpty(documentReferer)) { documentReferer = "-"; } else { documentReferer = URLDecoder.decode(documentReferer, "UTF-8"); } String documentPath = request.getParameter("utmp"); if (isEmpty(documentPath)) { documentPath = ""; } else { documentPath = URLDecoder.decode(documentPath, "UTF-8"); } String account = request.getParameter("utmac"); String userAgent = request.getHeader("User-Agent"); if (isEmpty(userAgent)) { userAgent = ""; } // Try and get visitor cookie from the request. Cookie[] cookies = request.getCookies(); Cookie cookie = null; if (cookies != null) { for(int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(COOKIE_NAME)) { cookie = cookies[i]; } } } String visitorId = getVisitorId( request.getHeader("X-DCMGUID"), account, userAgent, cookie); // Always try and add the cookie to the response. Cookie newCookie = new Cookie(COOKIE_NAME, visitorId); newCookie.setMaxAge(COOKIE_USER_PERSISTENCE); newCookie.setPath(COOKIE_PATH); response.addCookie(newCookie); // Construct the gif hit url. String utmUrl = "utmwv=" + version + "&utmn=" + getRandomNumber() + "&utmhn=" + domainName + "&utmr=" + documentReferer + "&utmp=" + documentPath + "&utmac=" + account + "&utmcc=__utma%3D999.999.999.999.999.1%3B" + "&utmvid=" + visitorId + "&utmip=" + getIP(request.getRemoteAddr()); // event tracking String type = request.getParameter("utmt"); String event = request.getParameter("utme"); if (!isEmpty(type) && !isEmpty(event)) { utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8"); utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8"); } URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null); sendRequestToGoogleAnalytics(utfGifLocationUri.toASCIIString(), request); // If the debug parameter is on, add a header to the response that contains // the url that was used to contact Google Analytics. if (request.getParameter("utmdebug") != null) { response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toASCIIString()); } // write 1x1 pixel tracking gif to output stream final PipedInputStream pipedInputStream = new PipedInputStream(); final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); response.addHeader( "Cache-Control", "private, no-cache, no-cache=Set-Cookie, proxy-revalidate"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT"); pipedOutputStream.write(GIF_DATA); pipedOutputStream.flush(); pipedOutputStream.close(); // the input stream will get populated by the piped output stream inputStream = pipedInputStream; return "pixel"; }
public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String domainName = request.getServerName(); if (isEmpty(domainName)) { domainName = ""; } // Get the referrer from the utmr parameter, this is the referrer to the // page that contains the tracking pixel, not the referrer for tracking // pixel. String documentReferer = request.getParameter("utmr"); if (isEmpty(documentReferer)) { documentReferer = "-"; } else { documentReferer = URLDecoder.decode(documentReferer, "UTF-8"); } String documentPath = request.getParameter("utmp"); if (isEmpty(documentPath)) { documentPath = ""; } else { documentPath = URLDecoder.decode(documentPath, "UTF-8"); } String account = request.getParameter("utmac"); String userAgent = request.getHeader("User-Agent"); if (isEmpty(userAgent)) { userAgent = ""; } // Try and get visitor cookie from the request. Cookie[] cookies = request.getCookies(); Cookie cookie = null; if (cookies != null) { for(int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(COOKIE_NAME)) { cookie = cookies[i]; } } } String visitorId = getVisitorId( request.getHeader("X-DCMGUID"), account, userAgent, cookie); // Always try and add the cookie to the response. Cookie newCookie = new Cookie(COOKIE_NAME, visitorId); newCookie.setMaxAge(COOKIE_USER_PERSISTENCE); newCookie.setPath(COOKIE_PATH); response.addCookie(newCookie); // Construct the gif hit url. String utmUrl = "utmwv=" + version + "&utmn=" + getRandomNumber() + "&utmhn=" + domainName + "&utmr=" + documentReferer + "&utmp=" + documentPath + "&utmac=" + account + "&utmcc=__utma%3D999.999.999.999.999.1%3B" + "&utmvid=" + visitorId + "&utmip=" + getIP(request.getRemoteAddr()); // event tracking String type = request.getParameter("utmt"); String event = request.getParameter("utme"); if (!isEmpty(type) && !isEmpty(event)) { utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8"); utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8"); } URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null); sendRequestToGoogleAnalytics(utfGifLocationUri.toString(), request); // If the debug parameter is on, add a header to the response that contains // the url that was used to contact Google Analytics. if (request.getParameter("utmdebug") != null) { response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toString()); } // write 1x1 pixel tracking gif to output stream final PipedInputStream pipedInputStream = new PipedInputStream(); final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); response.addHeader( "Cache-Control", "private, no-cache, no-cache=Set-Cookie, proxy-revalidate"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT"); pipedOutputStream.write(GIF_DATA); pipedOutputStream.flush(); pipedOutputStream.close(); // the input stream will get populated by the piped output stream inputStream = pipedInputStream; return "pixel"; }
diff --git a/src/directtalkserver/MainClass.java b/src/directtalkserver/MainClass.java index fb3915c..5c0efad 100644 --- a/src/directtalkserver/MainClass.java +++ b/src/directtalkserver/MainClass.java @@ -1,58 +1,57 @@ package directtalkserver; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class MainClass { public static void main(String[] args) { ServerSocket ssocket = null; Socket connection = null; OutputStream client = null; int ch = 0; if (args.length != 1) { System.out.println("Wrong number of args (takes 1)."); return; } try { ssocket = new ServerSocket(Integer.parseInt(args[0])); } catch (IOException | NumberFormatException e) { e.printStackTrace(); return; } try { System.out.println("Listening on port 4444 (single connection)."); connection = ssocket.accept(); client = connection.getOutputStream(); System.out.println("Got Connection: " + connection.getInetAddress().getHostName()); while (true) { ch = (int) (Math.random() * 255); System.out.println("Sending random byte " + ch); client.write(ch); - client.flush(); Thread.sleep(1000); } } catch (IOException e) { - e.printStackTrace(); + System.out.println("Error: " + e.getMessage()); } catch (InterruptedException e) { - e.printStackTrace(); + System.out.println("Error: " + e.getMessage()); } } }
false
true
public static void main(String[] args) { ServerSocket ssocket = null; Socket connection = null; OutputStream client = null; int ch = 0; if (args.length != 1) { System.out.println("Wrong number of args (takes 1)."); return; } try { ssocket = new ServerSocket(Integer.parseInt(args[0])); } catch (IOException | NumberFormatException e) { e.printStackTrace(); return; } try { System.out.println("Listening on port 4444 (single connection)."); connection = ssocket.accept(); client = connection.getOutputStream(); System.out.println("Got Connection: " + connection.getInetAddress().getHostName()); while (true) { ch = (int) (Math.random() * 255); System.out.println("Sending random byte " + ch); client.write(ch); client.flush(); Thread.sleep(1000); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
public static void main(String[] args) { ServerSocket ssocket = null; Socket connection = null; OutputStream client = null; int ch = 0; if (args.length != 1) { System.out.println("Wrong number of args (takes 1)."); return; } try { ssocket = new ServerSocket(Integer.parseInt(args[0])); } catch (IOException | NumberFormatException e) { e.printStackTrace(); return; } try { System.out.println("Listening on port 4444 (single connection)."); connection = ssocket.accept(); client = connection.getOutputStream(); System.out.println("Got Connection: " + connection.getInetAddress().getHostName()); while (true) { ch = (int) (Math.random() * 255); System.out.println("Sending random byte " + ch); client.write(ch); Thread.sleep(1000); } } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } catch (InterruptedException e) { System.out.println("Error: " + e.getMessage()); } }
diff --git a/maven-amps-plugin/src/test/java/com/atlassian/maven/plugins/amps/TestMavenGoalsHomeZip.java b/maven-amps-plugin/src/test/java/com/atlassian/maven/plugins/amps/TestMavenGoalsHomeZip.java index b29a9070..14104151 100644 --- a/maven-amps-plugin/src/test/java/com/atlassian/maven/plugins/amps/TestMavenGoalsHomeZip.java +++ b/maven-amps-plugin/src/test/java/com/atlassian/maven/plugins/amps/TestMavenGoalsHomeZip.java @@ -1,220 +1,220 @@ package com.atlassian.maven.plugins.amps; import org.apache.commons.io.FileUtils; import org.apache.maven.model.Build; import org.apache.maven.plugin.PluginManager; import org.apache.maven.plugin.logging.SystemStreamLog; import org.apache.maven.project.MavenProject; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.UUID; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class TestMavenGoalsHomeZip { public static final String PROJECT_ID = "noplacelike"; public static final String TMP_RESOURCES = "tmp-resources"; public static final String GENERATED_HOME = "generated-home"; public static final String PLUGINS = "plugins"; public static final String BUNDLED_PLUGINS = "bundled-plugins"; public static final String ZIP_PREFIX = "generated-resources/" + PROJECT_ID + "-home"; private MavenContext ctx; private MavenGoals goals; private File tempDir; private File productDir; private File tempResourcesDir; private File generatedHomeDir; private File pluginsDir; private File bundledPluginsDir; private ZipFile zip; @Before public void setup(){ //Create the temp dir - final File sysTempDir = new File(System.getProperty("java.io.tmpdir")); + final File sysTempDir = new File("target"); String dirName = UUID.randomUUID().toString(); tempDir = new File(sysTempDir, dirName); productDir = new File(tempDir,PROJECT_ID); tempResourcesDir = new File(productDir,TMP_RESOURCES); generatedHomeDir = new File(tempResourcesDir,GENERATED_HOME); pluginsDir = new File(generatedHomeDir,PLUGINS); bundledPluginsDir = new File(generatedHomeDir,BUNDLED_PLUGINS); //setup maven mocks MavenProject project = mock(MavenProject.class); Build build = mock(Build.class); //Mockito throws NoClassDefFoundError: org/apache/maven/project/ProjectBuilderConfiguration //when mocking the session //MavenSession session = mock(MavenSession.class); PluginManager pluginManager = mock(PluginManager.class); List<MavenProject> reactor = Collections.<MavenProject>emptyList(); ctx = mock(MavenContext.class); when(build.getDirectory()).thenReturn(tempDir.getAbsolutePath()); when(project.getBuild()).thenReturn(build); when(ctx.getProject()).thenReturn(project); when(ctx.getLog()).thenReturn(new SystemStreamLog()); when(ctx.getReactor()).thenReturn(reactor); when(ctx.getSession()).thenReturn(null); when(ctx.getPluginManager()).thenReturn(pluginManager); goals = new MavenGoals(ctx); } @After public void removeTempDir() throws IOException { //make sure zip is closed, else delete fails on windows if (zip != null) { try { zip.close(); } catch (IOException e) { //ignore } zip = null; } FileUtils.deleteDirectory(tempDir); } @Test public void skipNullHomeDir(){ File zip = new File(tempDir,"nullHomeZip.zip"); goals.createHomeResourcesZip(null,zip,PROJECT_ID); assertFalse("zip for null home should not exist", zip.exists()); } @Test public void skipNonExistentHomeDir(){ File zip = new File(tempDir,"noExistHomeZip.zip"); File fakeHomeDir = new File(tempDir,"this-folder-does-not-exist"); goals.createHomeResourcesZip(fakeHomeDir,zip,PROJECT_ID); assertFalse("zip for non-existent home should not exist", zip.exists()); } @Test public void existingGeneratedDirGetsDeleted() throws IOException { generatedHomeDir.mkdirs(); File deletedFile = new File(generatedHomeDir,"should-be-deleted.txt"); FileUtils.writeStringToFile(deletedFile,"This file should have been deleted!"); File zip = new File(tempDir,"deleteGenHomeZip.zip"); File homeDir = new File(tempDir,"deleteGenHomeDir"); homeDir.mkdirs(); goals.createHomeResourcesZip(homeDir,zip,PROJECT_ID); assertFalse("generated text file should have been deleted",deletedFile.exists()); } @Test public void pluginsNotIncluded() throws IOException { pluginsDir.mkdirs(); File pluginFile = new File(pluginsDir,"plugin.txt"); FileUtils.writeStringToFile(pluginFile,"This file should have been deleted!"); File zip = new File(tempDir,"deletePluginsHomeZip.zip"); File homeDir = new File(tempDir,"deletePluginsHomeDir"); homeDir.mkdirs(); goals.createHomeResourcesZip(homeDir,zip,PROJECT_ID); assertFalse("plugins file should have been deleted",pluginFile.exists()); } @Test public void bundledPluginsNotIncluded() throws IOException { bundledPluginsDir.mkdirs(); File pluginFile = new File(bundledPluginsDir,"bundled-plugin.txt"); FileUtils.writeStringToFile(pluginFile,"This file should have been deleted!"); File zip = new File(tempDir,"deleteBundledPluginsHomeZip.zip"); File homeDir = new File(tempDir,"deleteBundledPluginsHomeDir"); homeDir.mkdirs(); goals.createHomeResourcesZip(homeDir,zip,PROJECT_ID); assertFalse("bundled-plugins file should have been deleted",pluginFile.exists()); } @Test public void zipContainsProperPrefix() throws IOException { File zipFile = new File(tempDir,"prefixedHomeZip.zip"); File homeDir = new File(tempDir,"prefixedHomeDir"); File dataDir = new File(homeDir,"data"); dataDir.mkdirs(); goals.createHomeResourcesZip(homeDir,zipFile,PROJECT_ID); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); String zipPath = zipEntry.getName(); String[] segments = zipPath.split("/"); if(segments.length > 1) { String testPrefix = segments[0] + "/" + segments[1]; assertEquals(ZIP_PREFIX,testPrefix); } } } @Test public void zipContainsTestFile() throws IOException { File zipFile = new File(tempDir,"fileHomeZip.zip"); File homeDir = new File(tempDir,"fileHomeDir"); File dataDir = new File(homeDir,"data"); File dataFile = new File(dataDir,"data.txt"); dataDir.mkdirs(); FileUtils.writeStringToFile(dataFile,"This is some data."); goals.createHomeResourcesZip(homeDir,zipFile,PROJECT_ID); boolean dataFileFound = false; zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); String zipPath = zipEntry.getName(); String fileName = zipPath.substring(zipPath.lastIndexOf("/") + 1); if(fileName.equals(dataFile.getName())) { dataFileFound = true; break; } } assertTrue("data file not found in zip.",dataFileFound); } }
true
true
public void setup(){ //Create the temp dir final File sysTempDir = new File(System.getProperty("java.io.tmpdir")); String dirName = UUID.randomUUID().toString(); tempDir = new File(sysTempDir, dirName); productDir = new File(tempDir,PROJECT_ID); tempResourcesDir = new File(productDir,TMP_RESOURCES); generatedHomeDir = new File(tempResourcesDir,GENERATED_HOME); pluginsDir = new File(generatedHomeDir,PLUGINS); bundledPluginsDir = new File(generatedHomeDir,BUNDLED_PLUGINS); //setup maven mocks MavenProject project = mock(MavenProject.class); Build build = mock(Build.class); //Mockito throws NoClassDefFoundError: org/apache/maven/project/ProjectBuilderConfiguration //when mocking the session //MavenSession session = mock(MavenSession.class); PluginManager pluginManager = mock(PluginManager.class); List<MavenProject> reactor = Collections.<MavenProject>emptyList(); ctx = mock(MavenContext.class); when(build.getDirectory()).thenReturn(tempDir.getAbsolutePath()); when(project.getBuild()).thenReturn(build); when(ctx.getProject()).thenReturn(project); when(ctx.getLog()).thenReturn(new SystemStreamLog()); when(ctx.getReactor()).thenReturn(reactor); when(ctx.getSession()).thenReturn(null); when(ctx.getPluginManager()).thenReturn(pluginManager); goals = new MavenGoals(ctx); }
public void setup(){ //Create the temp dir final File sysTempDir = new File("target"); String dirName = UUID.randomUUID().toString(); tempDir = new File(sysTempDir, dirName); productDir = new File(tempDir,PROJECT_ID); tempResourcesDir = new File(productDir,TMP_RESOURCES); generatedHomeDir = new File(tempResourcesDir,GENERATED_HOME); pluginsDir = new File(generatedHomeDir,PLUGINS); bundledPluginsDir = new File(generatedHomeDir,BUNDLED_PLUGINS); //setup maven mocks MavenProject project = mock(MavenProject.class); Build build = mock(Build.class); //Mockito throws NoClassDefFoundError: org/apache/maven/project/ProjectBuilderConfiguration //when mocking the session //MavenSession session = mock(MavenSession.class); PluginManager pluginManager = mock(PluginManager.class); List<MavenProject> reactor = Collections.<MavenProject>emptyList(); ctx = mock(MavenContext.class); when(build.getDirectory()).thenReturn(tempDir.getAbsolutePath()); when(project.getBuild()).thenReturn(build); when(ctx.getProject()).thenReturn(project); when(ctx.getLog()).thenReturn(new SystemStreamLog()); when(ctx.getReactor()).thenReturn(reactor); when(ctx.getSession()).thenReturn(null); when(ctx.getPluginManager()).thenReturn(pluginManager); goals = new MavenGoals(ctx); }
diff --git a/src/test/java/org/pingles/cascading/protobuf/ProtobufFlowTest.java b/src/test/java/org/pingles/cascading/protobuf/ProtobufFlowTest.java index 371818e..ab28c50 100644 --- a/src/test/java/org/pingles/cascading/protobuf/ProtobufFlowTest.java +++ b/src/test/java/org/pingles/cascading/protobuf/ProtobufFlowTest.java @@ -1,143 +1,143 @@ package org.pingles.cascading.protobuf; import cascading.flow.Flow; import cascading.flow.FlowConnector; import cascading.operation.Identity; import cascading.pipe.Each; import cascading.pipe.Pipe; import cascading.scheme.TextLine; import cascading.tap.Lfs; import cascading.tap.SinkMode; import cascading.tap.Tap; import cascading.tuple.Fields; import cascading.tuple.Tuple; import cascading.tuple.TupleEntry; import cascading.tuple.TupleEntryIterator; import org.apache.commons.io.FileUtils; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.mapred.JobConf; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import static junit.framework.Assert.*; public class ProtobufFlowTest { private static final String TEST_DATA_ROOT = "./tmp/test"; private static Map<Object, Object> properties = new HashMap<Object, Object>(); private final JobConf conf = new JobConf(); @Before public void setup() throws IOException { File outputDir = new File(TEST_DATA_ROOT); if (outputDir.exists()) { outputDir.delete(); } FileUtils.forceMkdir(new File(TEST_DATA_ROOT)); } @Test public void shouldKeepOnlyNames() throws IOException { String inputFile = "./tmp/test/data/small.seq"; String outputDir = "./tmp/test/output/names-out"; writePersonToSequenceFile(personBuilder().setId(123).setName("Paul").setEmail("[email protected]").build(), inputFile); Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email")), inputFile); Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE); Pipe pipe = new Each("Extract names", new Fields("name"), new Identity()); Flow flow = new FlowConnector(properties).connect(source, sink, pipe); flow.complete(); List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000")); assertEquals(1, lines.size()); assertEquals("Paul", lines.get(0)); } @Test public void shouldKeepNamesAndEmail() throws IOException { String inputFile = "./tmp/test/data/small.seq"; String outputDir = "./tmp/test/output/names-out"; writePersonToSequenceFile(personBuilder().setId(123).setName("Paul").setEmail("[email protected]").build(), inputFile); Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email")), inputFile); Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE); Pipe pipe = new Each("Extract names", new Fields("name", "email"), new Identity()); Flow flow = new FlowConnector(properties).connect(source, sink, pipe); flow.complete(); List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000")); assertEquals(1, lines.size()); assertEquals("Paul\[email protected]", lines.get(0)); } @Test public void shouldSetEmailFieldToEmptyStringWhenNotSetOnMessage() throws IOException { String inputFile = "./tmp/test/data/small.seq"; String outputDir = "./tmp/test/output/names-out"; writePersonToSequenceFile(personBuilder().setId(123).setName("Paul").build(), inputFile); Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email")), inputFile); Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE); Pipe pipe = new Each("Extract names", new Fields("name", "email"), new Identity()); Flow flow = new FlowConnector(properties).connect(source, sink, pipe); flow.complete(); List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000")); assertEquals(1, lines.size()); assertEquals("Paul\t", lines.get(0)); } @Test public void shouldHandleRepeatedFields() throws IOException { String inputFile = "./tmp/test/data/small.seq"; String outputDir = "./tmp/test/output/names-out"; Messages.Person strongbad = personBuilder().setId(456).setName("strongbad").build(); Messages.Person homestar = personBuilder().setId(789).setName("homestar").build(); Messages.Person paul = personBuilder().setId(123).setName("Paul").addFriends(strongbad).addFriends(homestar).build(); writePersonToSequenceFile(paul, inputFile); Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email", "friends")), inputFile); Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE); - Pipe pipe = new Each("Extract friends names", new Fields("friends"), new Identity()); + Pipe pipe = new Each("Extract friends", new Fields("friends"), new Identity()); Flow flow = new FlowConnector(properties).connect(source, sink, pipe); flow.complete(); List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000")); assertEquals(1, lines.size()); assertEquals("456\tstrongbad\t\t\t789\thomestar\t\t", lines.get(0)); } private Messages.Person.Builder personBuilder() { return Messages.Person.newBuilder(); } private void writePersonToSequenceFile(Messages.Person person, String path) throws IOException { SequenceFile.Writer writer = SequenceFile.createWriter(FileSystem.getLocal(conf), conf, new Path(path), LongWritable.class, BytesWritable.class); try { writer.append(new LongWritable(1), new BytesWritable(person.toByteArray())); } finally { writer.close(); } } }
true
true
public void shouldHandleRepeatedFields() throws IOException { String inputFile = "./tmp/test/data/small.seq"; String outputDir = "./tmp/test/output/names-out"; Messages.Person strongbad = personBuilder().setId(456).setName("strongbad").build(); Messages.Person homestar = personBuilder().setId(789).setName("homestar").build(); Messages.Person paul = personBuilder().setId(123).setName("Paul").addFriends(strongbad).addFriends(homestar).build(); writePersonToSequenceFile(paul, inputFile); Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email", "friends")), inputFile); Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE); Pipe pipe = new Each("Extract friends names", new Fields("friends"), new Identity()); Flow flow = new FlowConnector(properties).connect(source, sink, pipe); flow.complete(); List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000")); assertEquals(1, lines.size()); assertEquals("456\tstrongbad\t\t\t789\thomestar\t\t", lines.get(0)); }
public void shouldHandleRepeatedFields() throws IOException { String inputFile = "./tmp/test/data/small.seq"; String outputDir = "./tmp/test/output/names-out"; Messages.Person strongbad = personBuilder().setId(456).setName("strongbad").build(); Messages.Person homestar = personBuilder().setId(789).setName("homestar").build(); Messages.Person paul = personBuilder().setId(123).setName("Paul").addFriends(strongbad).addFriends(homestar).build(); writePersonToSequenceFile(paul, inputFile); Tap source = new Lfs(new ProtobufSequenceFileScheme(Messages.Person.class, new Fields("id", "name", "email", "friends")), inputFile); Tap sink = new Lfs(new TextLine(), outputDir, SinkMode.REPLACE); Pipe pipe = new Each("Extract friends", new Fields("friends"), new Identity()); Flow flow = new FlowConnector(properties).connect(source, sink, pipe); flow.complete(); List<String> lines = FileUtils.readLines(new File(outputDir + "/part-00000")); assertEquals(1, lines.size()); assertEquals("456\tstrongbad\t\t\t789\thomestar\t\t", lines.get(0)); }
diff --git a/src/main/java/servlet/TestLampServlet.java b/src/main/java/servlet/TestLampServlet.java index e001986..ded6297 100644 --- a/src/main/java/servlet/TestLampServlet.java +++ b/src/main/java/servlet/TestLampServlet.java @@ -1,104 +1,104 @@ package main.java.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.net.URI; import java.net.URISyntaxException; import java.sql.*; public class TestLampServlet extends HttpServlet { // Database Connection private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; // Hardcoded dbUrl: // String dbUrl = "jdbc:postgres://ixhixpfgeanclh:p1uyfk5c9yLh1VEWoCOGb4FIEX@ec2-54-225-112-205.compute-1.amazonaws.com:5432/d3lbshfcpi0soa"; // Heroku dbUrl: String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } private static String convertIntToStatus(int data_value_int) { // Convert int to string String status_str = "on"; if (data_value_int == 0) { status_str = "off"; } return status_str; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Connection connection = getConnection(); // Return the latest status of the test lamp Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1"); rs.next(); request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1))); request.setAttribute("lampStatusTime", rs.getString(2)); } catch (SQLException e) { request.setAttribute("SQLException", e.getMessage()); } catch (URISyntaxException e) { request.setAttribute("URISyntaxException", e.getMessage()); } request.getRequestDispatcher("/testlamp-get.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data_value_str = request.getParameter("data_value"); // data_value_str = data_value_str.toLowerCase(); // Convert string to corresponding int 0-off 1-on int data_value_int; - if (data_value_str == "off") { + if (data_value_str.contains("off")) { data_value_int = 0; } - else if (data_value_str == "on") { + else if (data_value_str.contains("on")) { data_value_int = 1; } else { data_value_int = 2; } try { Connection connection = getConnection(); // Insert latest test lamp change Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())"); stmt.executeUpdate("INSERT INTO testing VALUES ('" + data_value_str + "')"); // Return the latest status of the test lamp ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1"); rs.next(); request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1))); request.setAttribute("lampStatusTime", rs.getString(2)); } catch (SQLException e) { request.setAttribute("SQLException", e.getMessage()); } catch (URISyntaxException e) { request.setAttribute("URISyntaxException", e.getMessage()); } request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response); } };
false
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data_value_str = request.getParameter("data_value"); // data_value_str = data_value_str.toLowerCase(); // Convert string to corresponding int 0-off 1-on int data_value_int; if (data_value_str == "off") { data_value_int = 0; } else if (data_value_str == "on") { data_value_int = 1; } else { data_value_int = 2; } try { Connection connection = getConnection(); // Insert latest test lamp change Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())"); stmt.executeUpdate("INSERT INTO testing VALUES ('" + data_value_str + "')"); // Return the latest status of the test lamp ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1"); rs.next(); request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1))); request.setAttribute("lampStatusTime", rs.getString(2)); } catch (SQLException e) { request.setAttribute("SQLException", e.getMessage()); } catch (URISyntaxException e) { request.setAttribute("URISyntaxException", e.getMessage()); } request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data_value_str = request.getParameter("data_value"); // data_value_str = data_value_str.toLowerCase(); // Convert string to corresponding int 0-off 1-on int data_value_int; if (data_value_str.contains("off")) { data_value_int = 0; } else if (data_value_str.contains("on")) { data_value_int = 1; } else { data_value_int = 2; } try { Connection connection = getConnection(); // Insert latest test lamp change Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO test_lamp VALUES (" + data_value_int + ", now())"); stmt.executeUpdate("INSERT INTO testing VALUES ('" + data_value_str + "')"); // Return the latest status of the test lamp ResultSet rs = stmt.executeQuery("SELECT * FROM test_lamp ORDER BY time DESC LIMIT 1"); rs.next(); request.setAttribute("lampStatus", convertIntToStatus(rs.getInt(1))); request.setAttribute("lampStatusTime", rs.getString(2)); } catch (SQLException e) { request.setAttribute("SQLException", e.getMessage()); } catch (URISyntaxException e) { request.setAttribute("URISyntaxException", e.getMessage()); } request.getRequestDispatcher("/testlamp-post.jsp").forward(request, response); }
diff --git a/src/java/org/apache/hadoop/mapred/JobTrackerInfoServer.java b/src/java/org/apache/hadoop/mapred/JobTrackerInfoServer.java index 9cb2128d1..fdd37e291 100644 --- a/src/java/org/apache/hadoop/mapred/JobTrackerInfoServer.java +++ b/src/java/org/apache/hadoop/mapred/JobTrackerInfoServer.java @@ -1,117 +1,117 @@ /** * 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. */ package org.apache.hadoop.mapred; import org.mortbay.http.*; import org.mortbay.http.handler.*; import org.mortbay.jetty.servlet.*; import java.io.*; import java.net.*; /******************************************************* * JobTrackerInfoServer provides stats about the JobTracker * via HTTP. It's useful for clients that want to track * their jobs' progress. * * @author Mike Cafarella *******************************************************/ class JobTrackerInfoServer { public static class RedirectHandler extends AbstractHttpHandler { public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { response.sendRedirect("/jobtracker"); request.setHandled(true); } } ///////////////////////////////////// // The actual JobTrackerInfoServer ///////////////////////////////////// static JobTracker jobTracker; org.mortbay.jetty.Server server; /** * We need the jobTracker to grab stats, and the port to * know where to listen. */ private static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows"); public JobTrackerInfoServer(JobTracker jobTracker, int port) throws IOException { this.jobTracker = jobTracker; this.server = new org.mortbay.jetty.Server(); URL url = JobTrackerInfoServer.class.getClassLoader().getResource("webapps"); String path = url.getPath(); if (WINDOWS && path.startsWith("/")) { path = path.substring(1); try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { } } - File jobtracker = new File(path, "jobtracker"); - WebApplicationContext context = server.addWebApplication(null, "/", jobtracker.getCanonicalPath()); + WebApplicationContext context = + server.addWebApplication(null,"/",new File(path).getCanonicalPath()); SocketListener socketListener = new SocketListener(); socketListener.setPort(port); this.server.addListener(socketListener); // // REMIND - mjc - I can't figure out how to get request redirect to work. // I've tried adding an additional default handler to the context, but // it doesn't seem to work. The handler has its handle() function called // even when the JSP is processed correctly! I just want to add a redirect // page, when the URL is incorrectly typed. // // context.addHandler(new LocalNotFoundHandler()); } /** * The thread class we need to kick off the HTTP server async-style. */ class HTTPStarter implements Runnable { public void run() { try { server.start(); } catch (Exception me) { me.printStackTrace(); } } } /** * Launch the HTTP server */ public void start() throws IOException { new Thread(new HTTPStarter()).start(); try { Thread.sleep(1000); } catch (InterruptedException ie) { } if (! server.isStarted()) { throw new IOException("Could not start HTTP server"); } } /** * Stop the HTTP server */ public void stop() { try { this.server.stop(); } catch (InterruptedException ie) { } } }
true
true
public JobTrackerInfoServer(JobTracker jobTracker, int port) throws IOException { this.jobTracker = jobTracker; this.server = new org.mortbay.jetty.Server(); URL url = JobTrackerInfoServer.class.getClassLoader().getResource("webapps"); String path = url.getPath(); if (WINDOWS && path.startsWith("/")) { path = path.substring(1); try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { } } File jobtracker = new File(path, "jobtracker"); WebApplicationContext context = server.addWebApplication(null, "/", jobtracker.getCanonicalPath()); SocketListener socketListener = new SocketListener(); socketListener.setPort(port); this.server.addListener(socketListener); // // REMIND - mjc - I can't figure out how to get request redirect to work. // I've tried adding an additional default handler to the context, but // it doesn't seem to work. The handler has its handle() function called // even when the JSP is processed correctly! I just want to add a redirect // page, when the URL is incorrectly typed. // // context.addHandler(new LocalNotFoundHandler()); }
public JobTrackerInfoServer(JobTracker jobTracker, int port) throws IOException { this.jobTracker = jobTracker; this.server = new org.mortbay.jetty.Server(); URL url = JobTrackerInfoServer.class.getClassLoader().getResource("webapps"); String path = url.getPath(); if (WINDOWS && path.startsWith("/")) { path = path.substring(1); try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { } } WebApplicationContext context = server.addWebApplication(null,"/",new File(path).getCanonicalPath()); SocketListener socketListener = new SocketListener(); socketListener.setPort(port); this.server.addListener(socketListener); // // REMIND - mjc - I can't figure out how to get request redirect to work. // I've tried adding an additional default handler to the context, but // it doesn't seem to work. The handler has its handle() function called // even when the JSP is processed correctly! I just want to add a redirect // page, when the URL is incorrectly typed. // // context.addHandler(new LocalNotFoundHandler()); }
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/MetadataWriter.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/MetadataWriter.java index 12cb7e23..6c96ebff 100644 --- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/MetadataWriter.java +++ b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/MetadataWriter.java @@ -1,276 +1,276 @@ /** * 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.cxf.fediz.service.idp.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.crypto.dsig.CanonicalizationMethod; import javax.xml.crypto.dsig.DigestMethod; import javax.xml.crypto.dsig.Reference; import javax.xml.crypto.dsig.SignatureMethod; import javax.xml.crypto.dsig.SignedInfo; import javax.xml.crypto.dsig.Transform; import javax.xml.crypto.dsig.XMLSignature; import javax.xml.crypto.dsig.XMLSignatureFactory; import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; import javax.xml.crypto.dsig.keyinfo.X509Data; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.apache.cxf.fediz.core.util.DOMUtils; import org.apache.cxf.fediz.service.idp.model.IDPConfig; import org.apache.ws.security.components.crypto.Crypto; import org.apache.ws.security.util.Base64; import org.apache.ws.security.util.UUIDGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.cxf.fediz.core.FederationConstants.SAML2_METADATA_NS; import static org.apache.cxf.fediz.core.FederationConstants.SCHEMA_INSTANCE_NS; import static org.apache.cxf.fediz.core.FederationConstants.WS_ADDRESSING_NS; import static org.apache.cxf.fediz.core.FederationConstants.WS_FEDERATION_NS; public class MetadataWriter { private static final Logger LOG = LoggerFactory.getLogger(MetadataWriter.class); private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance(); private static final XMLSignatureFactory XML_SIGNATURE_FACTORY = XMLSignatureFactory.getInstance("DOM"); private static final DocumentBuilderFactory DOC_BUILDER_FACTORY = DocumentBuilderFactory.newInstance(); private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance(); static { DOC_BUILDER_FACTORY.setNamespaceAware(true); } //CHECKSTYLE:OFF public Document getMetaData(IDPConfig config) throws RuntimeException { //Return as text/xml try { Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); - Writer streamWriter = new OutputStreamWriter(bout); + Writer streamWriter = new OutputStreamWriter(bout, "UTF-8"); XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter); - writer.writeStartDocument(); + writer.writeStartDocument("UTF-8", "1.0"); String referenceID = "_" + UUIDGenerator.getUUID(); writer.writeStartElement("", "EntityDescriptor", SAML2_METADATA_NS); writer.writeAttribute("ID", referenceID); writer.writeAttribute("entityID", config.getIdpUrl()); writer.writeNamespace("fed", WS_FEDERATION_NS); writer.writeNamespace("wsa", WS_ADDRESSING_NS); writer.writeNamespace("auth", WS_FEDERATION_NS); writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS); writer.writeStartElement("fed", "RoleDescriptor", WS_FEDERATION_NS); writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType"); writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS); if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) { writer.writeAttribute("ServiceDescription", config.getServiceDescription()); } if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) { writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName()); } //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd //missing organization, contactperson //KeyDescriptor writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS); writer.writeAttribute("use", "signing"); writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#"); writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#"); writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#"); try { X509Certificate cert = CertsUtils.getX509Certificate(crypto, null); writer.writeCharacters(Base64.encode(cert.getEncoded())); } catch (Exception ex) { LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex); } writer.writeEndElement(); // X509Certificate writer.writeEndElement(); // X509Data writer.writeEndElement(); // KeyInfo writer.writeEndElement(); // KeyDescriptor // SecurityTokenServiceEndpoint writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS); writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS); writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS); writer.writeCharacters(config.getStsUrl()); writer.writeEndElement(); // Address writer.writeEndElement(); // EndpointReference writer.writeEndElement(); // SecurityTokenServiceEndpoint // PassiveRequestorEndpoint writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS); writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS); writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS); writer.writeCharacters(config.getIdpUrl()); writer.writeEndElement(); // Address writer.writeEndElement(); // EndpointReference writer.writeEndElement(); // PassiveRequestorEndpoint // create ClaimsType section if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) { writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS); for (String claim : config.getClaimTypesOffered()) { writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS); writer.writeAttribute("Uri", claim); writer.writeAttribute("Optional", "true"); writer.writeEndElement(); // ClaimType } writer.writeEndElement(); // ClaimTypesOffered } writer.writeEndElement(); // RoleDescriptor writer.writeEndElement(); // EntityDescriptor writer.writeEndDocument(); streamWriter.flush(); bout.flush(); // if (LOG.isDebugEnabled()) { String out = new String(bout.toByteArray()); LOG.debug("***************** unsigned ****************"); LOG.debug(out); LOG.debug("***************** unsigned ****************"); } InputStream is = new ByteArrayInputStream(bout.toByteArray()); ByteArrayOutputStream result = signMetaInfo(crypto, config.getCertificatePassword(), is, referenceID); if (result != null) { is = new ByteArrayInputStream(result.toByteArray()); } else { throw new RuntimeException("Failed to sign the metadata document: result=null"); } return DOMUtils.readXml(is); } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.error("Error creating service metadata information ", e); throw new RuntimeException("Error creating service metadata information: " + e.getMessage()); } } private ByteArrayOutputStream signMetaInfo(Crypto crypto, String keyPassword, InputStream metaInfo, String referenceID) throws Exception { String keyAlias = crypto.getDefaultX509Identifier(); //only one key supported in JKS X509Certificate cert = CertsUtils.getX509Certificate(crypto, keyAlias); // Create a Reference to the enveloped document (in this case, // you are signing the whole document, so a URI of "" signifies // that, and also specify the SHA1 digest algorithm and // the ENVELOPED Transform. Reference ref = XML_SIGNATURE_FACTORY.newReference("#" + referenceID, XML_SIGNATURE_FACTORY.newDigestMethod(DigestMethod.SHA1, null), Collections .singletonList(XML_SIGNATURE_FACTORY.newTransform(Transform.ENVELOPED, (TransformParameterSpec)null)), null, null); String signatureMethod = null; if ("SHA1withDSA".equals(cert.getSigAlgName())) { signatureMethod = SignatureMethod.DSA_SHA1; } else if ("SHA1withRSA".equals(cert.getSigAlgName())) { signatureMethod = SignatureMethod.RSA_SHA1; } else if ("SHA256withRSA".equals(cert.getSigAlgName())) { signatureMethod = SignatureMethod.RSA_SHA1; } else { LOG.error("Unsupported signature method: " + cert.getSigAlgName()); throw new RuntimeException("Unsupported signature method: " + cert.getSigAlgName()); } // Create the SignedInfo. SignedInfo si = XML_SIGNATURE_FACTORY.newSignedInfo(XML_SIGNATURE_FACTORY.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null), XML_SIGNATURE_FACTORY .newSignatureMethod(signatureMethod, null), Collections.singletonList(ref)); // .newSignatureMethod(cert.getSigAlgOID(), null), Collections.singletonList(ref)); PrivateKey keyEntry = crypto.getPrivateKey(keyAlias, keyPassword); // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = XML_SIGNATURE_FACTORY.getKeyInfoFactory(); List<Object> x509Content = new ArrayList<Object>(); x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert); X509Data xd = kif.newX509Data(x509Content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); // Instantiate the document to be signed. Document doc = DOC_BUILDER_FACTORY.newDocumentBuilder().parse(metaInfo); // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(keyEntry, doc.getDocumentElement()); dsc.setIdAttributeNS(doc.getDocumentElement(), null, "ID"); dsc.setNextSibling(doc.getDocumentElement().getFirstChild()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = XML_SIGNATURE_FACTORY.newXMLSignature(si, ki); // Marshal, generate, and sign the enveloped signature. signature.sign(dsc); // Output the resulting document. ByteArrayOutputStream os = new ByteArrayOutputStream(8192); Transformer trans = TRANSFORMER_FACTORY.newTransformer(); trans.transform(new DOMSource(doc), new StreamResult(os)); os.flush(); return os; } }
false
true
public Document getMetaData(IDPConfig config) throws RuntimeException { //Return as text/xml try { Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); Writer streamWriter = new OutputStreamWriter(bout); XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter); writer.writeStartDocument(); String referenceID = "_" + UUIDGenerator.getUUID(); writer.writeStartElement("", "EntityDescriptor", SAML2_METADATA_NS); writer.writeAttribute("ID", referenceID); writer.writeAttribute("entityID", config.getIdpUrl()); writer.writeNamespace("fed", WS_FEDERATION_NS); writer.writeNamespace("wsa", WS_ADDRESSING_NS); writer.writeNamespace("auth", WS_FEDERATION_NS); writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS); writer.writeStartElement("fed", "RoleDescriptor", WS_FEDERATION_NS); writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType"); writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS); if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) { writer.writeAttribute("ServiceDescription", config.getServiceDescription()); } if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) { writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName()); } //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd //missing organization, contactperson //KeyDescriptor writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS); writer.writeAttribute("use", "signing"); writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#"); writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#"); writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#"); try { X509Certificate cert = CertsUtils.getX509Certificate(crypto, null); writer.writeCharacters(Base64.encode(cert.getEncoded())); } catch (Exception ex) { LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex); } writer.writeEndElement(); // X509Certificate writer.writeEndElement(); // X509Data writer.writeEndElement(); // KeyInfo writer.writeEndElement(); // KeyDescriptor // SecurityTokenServiceEndpoint writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS); writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS); writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS); writer.writeCharacters(config.getStsUrl()); writer.writeEndElement(); // Address writer.writeEndElement(); // EndpointReference writer.writeEndElement(); // SecurityTokenServiceEndpoint // PassiveRequestorEndpoint writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS); writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS); writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS); writer.writeCharacters(config.getIdpUrl()); writer.writeEndElement(); // Address writer.writeEndElement(); // EndpointReference writer.writeEndElement(); // PassiveRequestorEndpoint // create ClaimsType section if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) { writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS); for (String claim : config.getClaimTypesOffered()) { writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS); writer.writeAttribute("Uri", claim); writer.writeAttribute("Optional", "true"); writer.writeEndElement(); // ClaimType } writer.writeEndElement(); // ClaimTypesOffered } writer.writeEndElement(); // RoleDescriptor writer.writeEndElement(); // EntityDescriptor writer.writeEndDocument(); streamWriter.flush(); bout.flush(); // if (LOG.isDebugEnabled()) { String out = new String(bout.toByteArray()); LOG.debug("***************** unsigned ****************"); LOG.debug(out); LOG.debug("***************** unsigned ****************"); } InputStream is = new ByteArrayInputStream(bout.toByteArray()); ByteArrayOutputStream result = signMetaInfo(crypto, config.getCertificatePassword(), is, referenceID); if (result != null) { is = new ByteArrayInputStream(result.toByteArray()); } else { throw new RuntimeException("Failed to sign the metadata document: result=null"); } return DOMUtils.readXml(is); } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.error("Error creating service metadata information ", e); throw new RuntimeException("Error creating service metadata information: " + e.getMessage()); } }
public Document getMetaData(IDPConfig config) throws RuntimeException { //Return as text/xml try { Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); Writer streamWriter = new OutputStreamWriter(bout, "UTF-8"); XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter); writer.writeStartDocument("UTF-8", "1.0"); String referenceID = "_" + UUIDGenerator.getUUID(); writer.writeStartElement("", "EntityDescriptor", SAML2_METADATA_NS); writer.writeAttribute("ID", referenceID); writer.writeAttribute("entityID", config.getIdpUrl()); writer.writeNamespace("fed", WS_FEDERATION_NS); writer.writeNamespace("wsa", WS_ADDRESSING_NS); writer.writeNamespace("auth", WS_FEDERATION_NS); writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS); writer.writeStartElement("fed", "RoleDescriptor", WS_FEDERATION_NS); writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType"); writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS); if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) { writer.writeAttribute("ServiceDescription", config.getServiceDescription()); } if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) { writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName()); } //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd //missing organization, contactperson //KeyDescriptor writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS); writer.writeAttribute("use", "signing"); writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#"); writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#"); writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#"); try { X509Certificate cert = CertsUtils.getX509Certificate(crypto, null); writer.writeCharacters(Base64.encode(cert.getEncoded())); } catch (Exception ex) { LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex); } writer.writeEndElement(); // X509Certificate writer.writeEndElement(); // X509Data writer.writeEndElement(); // KeyInfo writer.writeEndElement(); // KeyDescriptor // SecurityTokenServiceEndpoint writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS); writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS); writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS); writer.writeCharacters(config.getStsUrl()); writer.writeEndElement(); // Address writer.writeEndElement(); // EndpointReference writer.writeEndElement(); // SecurityTokenServiceEndpoint // PassiveRequestorEndpoint writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS); writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS); writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS); writer.writeCharacters(config.getIdpUrl()); writer.writeEndElement(); // Address writer.writeEndElement(); // EndpointReference writer.writeEndElement(); // PassiveRequestorEndpoint // create ClaimsType section if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) { writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS); for (String claim : config.getClaimTypesOffered()) { writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS); writer.writeAttribute("Uri", claim); writer.writeAttribute("Optional", "true"); writer.writeEndElement(); // ClaimType } writer.writeEndElement(); // ClaimTypesOffered } writer.writeEndElement(); // RoleDescriptor writer.writeEndElement(); // EntityDescriptor writer.writeEndDocument(); streamWriter.flush(); bout.flush(); // if (LOG.isDebugEnabled()) { String out = new String(bout.toByteArray()); LOG.debug("***************** unsigned ****************"); LOG.debug(out); LOG.debug("***************** unsigned ****************"); } InputStream is = new ByteArrayInputStream(bout.toByteArray()); ByteArrayOutputStream result = signMetaInfo(crypto, config.getCertificatePassword(), is, referenceID); if (result != null) { is = new ByteArrayInputStream(result.toByteArray()); } else { throw new RuntimeException("Failed to sign the metadata document: result=null"); } return DOMUtils.readXml(is); } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.error("Error creating service metadata information ", e); throw new RuntimeException("Error creating service metadata information: " + e.getMessage()); } }
diff --git a/PopulateNext/Solution.java b/PopulateNext/Solution.java index bbb4333..b7b9f6a 100644 --- a/PopulateNext/Solution.java +++ b/PopulateNext/Solution.java @@ -1,58 +1,64 @@ /** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ public class Solution { private TreeLinkNode findNextParentWithChild(TreeLinkNode node) { while(node.next != null) { node = node.next; if (node.left != null || node.right != null) return node; } return null; } public void connect(TreeLinkNode root) { // Start typing your Java solution below // DO NOT write main() function TreeLinkNode parent = root; TreeLinkNode nextParent = null; - while(parent != null && nextParent != null) { + while(parent != null || nextParent != null) { while(parent != null) { if(parent.left != null){ + if(nextParent == null){ + nextParent = parent.left; + } if(parent.right != null){ parent.left.next = parent.right; } else { TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.left.next = null; } else{ parent.left.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } } if(parent.right != null) { - TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); - if(nextParentWithChild == null) { - parent.right.next = null; - } - else{ - parent.right.next = (nextParentWithChild.left != null)? - (nextParentWithChild.left):(nextParentWithChild.right); - } + if(nextParent == null) { + nextParent = parent.right; + } + TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); + if(nextParentWithChild == null) { + parent.right.next = null; + } + else{ + parent.right.next = (nextParentWithChild.left != null)? + (nextParentWithChild.left):(nextParentWithChild.right); + } } parent = parent.next; } if(nextParent != null) { parent = nextParent; nextParent = null; } } } }
false
true
public void connect(TreeLinkNode root) { // Start typing your Java solution below // DO NOT write main() function TreeLinkNode parent = root; TreeLinkNode nextParent = null; while(parent != null && nextParent != null) { while(parent != null) { if(parent.left != null){ if(parent.right != null){ parent.left.next = parent.right; } else { TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.left.next = null; } else{ parent.left.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } } if(parent.right != null) { TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.right.next = null; } else{ parent.right.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } parent = parent.next; } if(nextParent != null) { parent = nextParent; nextParent = null; } } }
public void connect(TreeLinkNode root) { // Start typing your Java solution below // DO NOT write main() function TreeLinkNode parent = root; TreeLinkNode nextParent = null; while(parent != null || nextParent != null) { while(parent != null) { if(parent.left != null){ if(nextParent == null){ nextParent = parent.left; } if(parent.right != null){ parent.left.next = parent.right; } else { TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.left.next = null; } else{ parent.left.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } } if(parent.right != null) { if(nextParent == null) { nextParent = parent.right; } TreeLinkNode nextParentWithChild = findNextParentWithChild(parent); if(nextParentWithChild == null) { parent.right.next = null; } else{ parent.right.next = (nextParentWithChild.left != null)? (nextParentWithChild.left):(nextParentWithChild.right); } } parent = parent.next; } if(nextParent != null) { parent = nextParent; nextParent = null; } } }
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java index 8a20205..eb2f29c 100644 --- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java +++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java @@ -1,186 +1,187 @@ package uk.ac.gla.dcs.tp3.w.algorithm; import java.util.LinkedList; import uk.ac.gla.dcs.tp3.w.league.League; import uk.ac.gla.dcs.tp3.w.league.Match; import uk.ac.gla.dcs.tp3.w.league.Team; public class Graph { private Vertex[] vertices; private int[][] matrix; private Vertex source; private Vertex sink; public Graph() { this(null, null); } public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; + // TODO limit this to something more sensible int infinity = Integer.MAX_VALUE; - for (int i = 0; i < teamTotal + 1; i++) { - for (int j = 1; j < teamTotal; j++) { + for (int i = 0; i < teams.length; i++) { + for (int j = 1; j < teams.length; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. } public Vertex[] getV() { return vertices; } public void setV(Vertex[] v) { this.vertices = v; } public int[][] getMatrix() { return matrix; } public int getSize() { return vertices.length; } public void setMatrix(int[][] matrix) { this.matrix = matrix; } public Vertex getSource() { return source; } public void setSource(Vertex source) { this.source = source; } public Vertex getSink() { return sink; } public void setSink(Vertex sink) { this.sink = sink; } private static int fact(int s) { // For s < 2, the factorial is 1. Otherwise, multiply s by fact(s-1) return (s < 2) ? 1 : s * fact(s - 1); } private static int comb(int n, int r) { // r-combination of size n is n!/r!(n-r)! return (fact(n) / (fact(r) * fact(n - r))); } /** * carry out a breadth first search/traversal of the graph */ public void bfs() { // TODO Read over this code, I (GR) just dropped this in here from // bfs-example. for (Vertex v : vertices) v.setVisited(false); LinkedList<Vertex> queue = new LinkedList<Vertex>(); for (Vertex v : vertices) { if (!v.getVisited()) { v.setVisited(true); v.setPredecessor(v.getIndex()); queue.add(v); while (!queue.isEmpty()) { Vertex u = queue.removeFirst(); LinkedList<AdjListNode> list = u.getAdjList(); for (AdjListNode node : list) { Vertex w = node.getVertex(); if (!w.getVisited()) { w.setVisited(true); w.setPredecessor(u.getIndex()); queue.add(w); } } } } } } }
false
true
public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; int infinity = Integer.MAX_VALUE; for (int i = 0; i < teamTotal + 1; i++) { for (int j = 1; j < teamTotal; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. }
public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; // TODO limit this to something more sensible int infinity = Integer.MAX_VALUE; for (int i = 0; i < teams.length; i++) { for (int j = 1; j < teams.length; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. }
diff --git a/omod/src/main/java/org/openmrs/module/appointment/web/DWRAppointmentService.java b/omod/src/main/java/org/openmrs/module/appointment/web/DWRAppointmentService.java index e8d2864..4fa0843 100644 --- a/omod/src/main/java/org/openmrs/module/appointment/web/DWRAppointmentService.java +++ b/omod/src/main/java/org/openmrs/module/appointment/web/DWRAppointmentService.java @@ -1,171 +1,172 @@ package org.openmrs.module.appointment.web; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.http.HttpSession; import org.directwebremoting.WebContext; import org.directwebremoting.WebContextFactory; import org.openmrs.Location; import org.openmrs.Patient; import org.openmrs.PersonAttribute; import org.openmrs.api.PatientService; import org.openmrs.api.context.Context; import org.openmrs.module.appointment.Appointment; import org.openmrs.module.appointment.Appointment.AppointmentStatus; import org.openmrs.module.appointment.AppointmentBlock; import org.openmrs.module.appointment.AppointmentType; import org.openmrs.module.appointment.TimeSlot; import org.openmrs.module.appointment.api.AppointmentService; /** * DWR patient methods. The methods in here are used in the webapp to get data from the database via * javascript calls. * * @see PatientService */ public class DWRAppointmentService { public PatientData getPatientDescription(Integer patientId) { Patient patient = Context.getPatientService().getPatient(patientId); if (patient == null) return null; PatientData patientData = new PatientData(); patientData .setIdentifiers(Context.getService(AppointmentService.class).getPatientIdentifiersRepresentation(patient)); //Get Patient's phone Integer phonePropertyId = Integer.parseInt(Context.getAdministrationService().getGlobalProperty( "appointment.phoneNumberPersonAttributeTypeId")); PersonAttribute phoneAttribute = patient.getAttribute(phonePropertyId); if (phoneAttribute != null) patientData.setPhoneNumber(phoneAttribute.getValue()); //Checks if patient missed his/her last appointment. Appointment lastAppointment = Context.getService(AppointmentService.class).getLastAppointment(patient); if (lastAppointment != null && lastAppointment.getStatus() == AppointmentStatus.MISSED) patientData.setDateMissedLastAppointment(Context.getDateFormat().format( lastAppointment.getTimeSlot().getStartDate())); return patientData; } public List<AppointmentBlockData> getAppointmentBlocks(String fromDate, String toDate, Integer locationId) throws ParseException { List<AppointmentBlock> appointmentBlockList = new ArrayList<AppointmentBlock>(); List<AppointmentBlockData> appointmentBlockDatalist = new ArrayList<AppointmentBlockData>(); Date fromAsDate = null; Date toAsDate = null; //location needs authentication if (Context.isAuthenticated()) { AppointmentService appointmentService = Context.getService(AppointmentService.class); Location location = null; if (locationId != null) { location = Context.getLocationService().getLocation(locationId); } //In case the user selected a date. if (!fromDate.isEmpty()) { fromAsDate = Context.getDateTimeFormat().parse(fromDate); } if (!toDate.isEmpty()) { toAsDate = Context.getDateTimeFormat().parse(toDate); } appointmentBlockList = appointmentService .getAppointmentBlocks(fromAsDate, toAsDate, buildLocationList(location)); for (AppointmentBlock appointmentBlock : appointmentBlockList) { //don't include voided appointment blocks if (!appointmentBlock.isVoided()) { - Set<String> typesDescription = new HashSet<String>(); + Set<String> typesNames = new HashSet<String>(); Set<AppointmentType> appointmentTypes = appointmentBlock.getTypes(); for (AppointmentType appointmentType : appointmentTypes) { - typesDescription.add(appointmentType.getDescription()); + typesNames.add(appointmentType.getName()); } - appointmentBlockDatalist.add(new AppointmentBlockData(appointmentBlock.getId(), appointmentBlock - .getLocation().getName(), appointmentBlock.getProvider().getName(), typesDescription, - appointmentBlock.getStartDate(), appointmentBlock.getEndDate(), this - .getTimeSlotLength(appointmentBlock.getId()))); + appointmentBlockDatalist + .add(new AppointmentBlockData(appointmentBlock.getId(), + appointmentBlock.getLocation().getName(), appointmentBlock.getProvider().getName(), + typesNames, appointmentBlock.getStartDate(), appointmentBlock.getEndDate(), this + .getTimeSlotLength(appointmentBlock.getId()))); } } } return appointmentBlockDatalist; } public Integer[] getNumberOfAppointmentsInAppointmentBlock(Integer appointmentBlockId) { Integer[] appointmentsCount = null; if (Context.isAuthenticated()) { AppointmentService as = Context.getService(AppointmentService.class); if (appointmentBlockId != null) { appointmentsCount = new Integer[3]; appointmentsCount[0] = 0; appointmentsCount[1] = 0; appointmentsCount[2] = 0; //Assumption - Exists such an appointment block in the data base with the given Id AppointmentBlock appointmentBlock = as.getAppointmentBlock(appointmentBlockId); //Getting the timeslots of the given appointment block List<TimeSlot> timeSlots = as.getTimeSlotsInAppointmentBlock(appointmentBlock); for (TimeSlot timeSlot : timeSlots) { List<Appointment> appointmentsInTimeSlot = as.getAppointmentsInTimeSlot(timeSlot); for (Appointment appointment : appointmentsInTimeSlot) { if (appointment.getStatus().toString().equalsIgnoreCase(AppointmentStatus.INCONSULTATION.toString()) || appointment.getStatus().toString().equalsIgnoreCase(AppointmentStatus.WAITING.toString())) { //Active appointments appointmentsCount[0]++; } else if (appointment.getStatus().toString().equalsIgnoreCase( AppointmentStatus.SCHEDULED.toString())) { appointmentsCount[1]++; //Scheduled appointments } else { appointmentsCount[2]++; //Missed/Cancelled/Completed appointments } } } } } return appointmentsCount; } public boolean validateDates(String fromDate, String toDate) throws ParseException { boolean error = false; WebContext webContext = WebContextFactory.get(); HttpSession httpSession = webContext.getHttpServletRequest().getSession(); //date validation if (!Context.getDateTimeFormat().parse(fromDate).before(Context.getDateTimeFormat().parse(toDate))) { error = true; } return error; } private String buildLocationList(Location location) { String ans = ""; if (location != null) { ans = location.getId() + ""; if (location.getChildLocations().size() == 0) return ans; else { for (Location locationChild : location.getChildLocations()) { ans += "," + buildLocationList(locationChild); } } } return ans; } private String getTimeSlotLength(Integer appointmentBlockId) { if (appointmentBlockId == null) return ""; else { if (Context.isAuthenticated()) { AppointmentService as = Context.getService(AppointmentService.class); AppointmentBlock appointmentBlock = as.getAppointmentBlock(appointmentBlockId); TimeSlot timeSlot = Context.getService(AppointmentService.class).getTimeSlotsInAppointmentBlock( appointmentBlock).get(0); return (timeSlot.getEndDate().getTime() - timeSlot.getStartDate().getTime()) / 60000 + ""; } } return ""; } }
false
true
public List<AppointmentBlockData> getAppointmentBlocks(String fromDate, String toDate, Integer locationId) throws ParseException { List<AppointmentBlock> appointmentBlockList = new ArrayList<AppointmentBlock>(); List<AppointmentBlockData> appointmentBlockDatalist = new ArrayList<AppointmentBlockData>(); Date fromAsDate = null; Date toAsDate = null; //location needs authentication if (Context.isAuthenticated()) { AppointmentService appointmentService = Context.getService(AppointmentService.class); Location location = null; if (locationId != null) { location = Context.getLocationService().getLocation(locationId); } //In case the user selected a date. if (!fromDate.isEmpty()) { fromAsDate = Context.getDateTimeFormat().parse(fromDate); } if (!toDate.isEmpty()) { toAsDate = Context.getDateTimeFormat().parse(toDate); } appointmentBlockList = appointmentService .getAppointmentBlocks(fromAsDate, toAsDate, buildLocationList(location)); for (AppointmentBlock appointmentBlock : appointmentBlockList) { //don't include voided appointment blocks if (!appointmentBlock.isVoided()) { Set<String> typesDescription = new HashSet<String>(); Set<AppointmentType> appointmentTypes = appointmentBlock.getTypes(); for (AppointmentType appointmentType : appointmentTypes) { typesDescription.add(appointmentType.getDescription()); } appointmentBlockDatalist.add(new AppointmentBlockData(appointmentBlock.getId(), appointmentBlock .getLocation().getName(), appointmentBlock.getProvider().getName(), typesDescription, appointmentBlock.getStartDate(), appointmentBlock.getEndDate(), this .getTimeSlotLength(appointmentBlock.getId()))); } } } return appointmentBlockDatalist; }
public List<AppointmentBlockData> getAppointmentBlocks(String fromDate, String toDate, Integer locationId) throws ParseException { List<AppointmentBlock> appointmentBlockList = new ArrayList<AppointmentBlock>(); List<AppointmentBlockData> appointmentBlockDatalist = new ArrayList<AppointmentBlockData>(); Date fromAsDate = null; Date toAsDate = null; //location needs authentication if (Context.isAuthenticated()) { AppointmentService appointmentService = Context.getService(AppointmentService.class); Location location = null; if (locationId != null) { location = Context.getLocationService().getLocation(locationId); } //In case the user selected a date. if (!fromDate.isEmpty()) { fromAsDate = Context.getDateTimeFormat().parse(fromDate); } if (!toDate.isEmpty()) { toAsDate = Context.getDateTimeFormat().parse(toDate); } appointmentBlockList = appointmentService .getAppointmentBlocks(fromAsDate, toAsDate, buildLocationList(location)); for (AppointmentBlock appointmentBlock : appointmentBlockList) { //don't include voided appointment blocks if (!appointmentBlock.isVoided()) { Set<String> typesNames = new HashSet<String>(); Set<AppointmentType> appointmentTypes = appointmentBlock.getTypes(); for (AppointmentType appointmentType : appointmentTypes) { typesNames.add(appointmentType.getName()); } appointmentBlockDatalist .add(new AppointmentBlockData(appointmentBlock.getId(), appointmentBlock.getLocation().getName(), appointmentBlock.getProvider().getName(), typesNames, appointmentBlock.getStartDate(), appointmentBlock.getEndDate(), this .getTimeSlotLength(appointmentBlock.getId()))); } } } return appointmentBlockDatalist; }
diff --git a/src/com/possebom/mypharmacy/GetMedicine.java b/src/com/possebom/mypharmacy/GetMedicine.java index 4d23521..640e5d1 100644 --- a/src/com/possebom/mypharmacy/GetMedicine.java +++ b/src/com/possebom/mypharmacy/GetMedicine.java @@ -1,83 +1,83 @@ package com.possebom.mypharmacy; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; import com.possebom.mypharmacy.model.Medicine; public class GetMedicine extends AsyncTask<Void, Void, Void> { private static final String TAG = "MEDICINE"; private String barcode; private ProgressDialog progressDialog; private JSONObject json; private String country; private GetMedicineListener listener; public GetMedicine(ProgressDialog progressDialog,GetMedicineListener listener, String barcode, String country) { this.barcode = barcode; this.country = country; this.listener = listener; this.progressDialog = progressDialog; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); Medicine medicine = new Medicine(); try { medicine.setBrandName(json.getString("brandName")); medicine.setDrug(json.getString("drug")); medicine.setConcentration(json.getString("concentration")); medicine.setForm(json.getString("form")); medicine.setLaboratory(json.getString("laboratory")); - } catch (JSONException e) { + } catch (Exception e) { Log.e(TAG, "Error on json : " + e.toString()); } listener.onRemoteCallComplete(medicine); - if (progressDialog.isShowing()) { + if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } @Override protected Void doInBackground(Void... arg0) { HttpClient httpclient = new DefaultHttpClient(); ResponseHandler<String> handler = new BasicResponseHandler(); HttpGet request = new HttpGet("http://possebom.com/android/mypharmacy/getMedicine.php?country="+country+"&barcode="+barcode); try { String result = new String(httpclient.execute(request, handler).getBytes("ISO-8859-1"),"UTF-8"); JSONArray jsonArray = new JSONArray(result); json = jsonArray.getJSONObject(0); httpclient.getConnectionManager().shutdown(); } catch (Exception e) { json = null; Log.e(TAG, "Error converting result " + e.toString()); } return null; } public interface GetMedicineListener { public void onRemoteCallComplete(Medicine medicine); } }
false
true
protected void onPostExecute(Void result) { super.onPostExecute(result); Medicine medicine = new Medicine(); try { medicine.setBrandName(json.getString("brandName")); medicine.setDrug(json.getString("drug")); medicine.setConcentration(json.getString("concentration")); medicine.setForm(json.getString("form")); medicine.setLaboratory(json.getString("laboratory")); } catch (JSONException e) { Log.e(TAG, "Error on json : " + e.toString()); } listener.onRemoteCallComplete(medicine); if (progressDialog.isShowing()) { progressDialog.dismiss(); } }
protected void onPostExecute(Void result) { super.onPostExecute(result); Medicine medicine = new Medicine(); try { medicine.setBrandName(json.getString("brandName")); medicine.setDrug(json.getString("drug")); medicine.setConcentration(json.getString("concentration")); medicine.setForm(json.getString("form")); medicine.setLaboratory(json.getString("laboratory")); } catch (Exception e) { Log.e(TAG, "Error on json : " + e.toString()); } listener.onRemoteCallComplete(medicine); if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } }
diff --git a/src/com/dmdirc/addons/dcc/DCCSendWindow.java b/src/com/dmdirc/addons/dcc/DCCSendWindow.java index 99f354ed..b3248841 100644 --- a/src/com/dmdirc/addons/dcc/DCCSendWindow.java +++ b/src/com/dmdirc/addons/dcc/DCCSendWindow.java @@ -1,383 +1,383 @@ /* * Copyright (c) 2006-2010 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.addons.dcc; import com.dmdirc.Server; import com.dmdirc.ServerState; import com.dmdirc.actions.ActionManager; import com.dmdirc.addons.dcc.actions.DCCActions; import com.dmdirc.config.IdentityManager; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.interfaces.Parser; import com.dmdirc.parser.interfaces.callbacks.SocketCloseListener; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import net.miginfocom.swing.MigLayout; /** * This class links DCC Send objects to a window. * * @author Shane 'Dataforce' McCormack */ public class DCCSendWindow extends DCCFrame implements DCCSendInterface, ActionListener, SocketCloseListener { /** The DCCSend object we are a window for */ private final DCCSend dcc; /** Other Nickname */ private final String otherNickname; /** Total data transfered */ private volatile long transferCount = 0; /** Time Started */ private long timeStarted = 0; /** Progress Bar */ private final JProgressBar progress = new JProgressBar(); /** Status Label */ private final JLabel status = new JLabel("Status: Waiting"); /** Speed Label */ private final JLabel speed = new JLabel("Speed: Unknown"); /** Time Label */ private final JLabel remaining = new JLabel("Time Remaining: Unknown"); /** Time Taken */ private final JLabel taken = new JLabel("Time Taken: 00:00"); /** Button */ private final JButton button = new JButton("Cancel"); /** Open Button */ private final JButton openButton = new JButton("Open"); /** Plugin that this send belongs to. */ private final DCCPlugin myPlugin; /** IRC Parser that caused this send */ private Parser parser = null; /** Server that caused this send */ private Server server = null; /** Show open button. */ private boolean showOpen = Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN); /** * Creates a new instance of DCCSendWindow with a given DCCSend object. * * @param plugin the DCC Plugin responsible for this window * @param dcc The DCCSend object this window wraps around * @param title The title of this window * @param targetNick Nickname of target * @param server The server that initiated this send */ public DCCSendWindow(final DCCPlugin plugin, final DCCSend dcc, final String title, final String targetNick, final Server server) { super(plugin, title, dcc.getType() == DCCSend.TransferType.SEND ? "dcc-send-inactive" : "dcc-receive-inactive"); this.dcc = dcc; this.server = server; this.parser = server == null ? null : server.getParser(); this.myPlugin = plugin; if (parser != null) { parser.getCallbackManager().addNonCriticalCallback(SocketCloseListener.class, this); } dcc.setHandler(this); otherNickname = targetNick; getContentPane().setLayout(new MigLayout("hidemode 0")); progress.setMinimum(0); progress.setMaximum(100); progress.setStringPainted(true); progress.setValue(0); if (dcc.getType() == DCCSend.TransferType.SEND) { getContentPane().add(new JLabel("Sending: " + dcc.getShortFileName()), "wrap"); getContentPane().add(new JLabel("To: " + targetNick), "wrap"); } else { getContentPane().add(new JLabel("Recieving: " + dcc.getShortFileName()), "wrap"); getContentPane().add(new JLabel("From: " + targetNick), "wrap"); } getContentPane().add(status, "wrap"); getContentPane().add(speed, "wrap"); getContentPane().add(remaining, "wrap"); getContentPane().add(taken, "wrap"); getContentPane().add(progress, "growx, wrap"); button.addActionListener(this); openButton.addActionListener(this); openButton.setVisible(false); getContentPane().add(openButton, "split 2, align right"); getContentPane().add(button, "align right"); plugin.addWindow(this); } /** {@inheritDoc} */ @Override public void onSocketClosed(final Parser tParser) { // Remove our reference to the parser (and its reference to us) parser.getCallbackManager().delAllCallback(this); parser = null; // Can't resend without the parser. if ("Resend".equals(button.getText())) { button.setText("Close Window"); } } /** * Get the DCCSend Object associated with this window * * @return The DCCSend Object associated with this window */ public DCCSend getDCC() { return dcc; } /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("Cancel")) { if (dcc.getType() == DCCSend.TransferType.SEND) { button.setText("Resend"); } else { button.setText("Close Window"); } status.setText("Status: Cancelled"); dcc.close(); } else if (e.getActionCommand().equals("Resend")) { button.setText("Cancel"); status.setText("Status: Resending..."); synchronized (this) { transferCount = 0; } dcc.reset(); if (parser != null && server.getState() == ServerState.CONNECTED) { final String myNickname = parser.getLocalClient().getNickname(); // Check again incase we have changed nickname to the same nickname that // this send is for. if (parser.getStringConverter().equalsIgnoreCase(otherNickname, myNickname)) { final Thread errorThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { JOptionPane.showMessageDialog(null, "You can't DCC yourself.", "DCC Error", JOptionPane.ERROR_MESSAGE); } }); errorThread.start(); return; } else { if (IdentityManager.getGlobalConfig().getOptionBool(plugin.getDomain(), "send.reverse")) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " 0 " + dcc.getFileSize() + " " + dcc.makeToken() + ((dcc.isTurbo()) ? " T" : "")); return; } else if (plugin.listen(dcc)) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " " + dcc.getPort() + " " + dcc.getFileSize() + ((dcc.isTurbo()) ? " T" : "")); return; } } } else { status.setText("Status: Resend failed."); button.setText("Close Window"); } } else if (e.getActionCommand().equals("Close Window")) { close(); } else if (e.getSource() == openButton) { final File file = new File(dcc.getFileName()); try { Desktop.getDesktop().open(file); } catch (IllegalArgumentException ex) { Logger.userError(ErrorLevel.LOW, "Unable to open file: " + - file + ex); + file, ex); openButton.setEnabled(false); } catch (IOException ex) { try { Desktop.getDesktop().open(file.getParentFile()); } catch (IllegalArgumentException ex1) { Logger.userError(ErrorLevel.LOW, "Unable to open folder: " + - file.getParentFile() + ex1); + file.getParentFile(), ex1); openButton.setEnabled(false); } catch (IOException ex1) { Logger.userError(ErrorLevel.LOW, "No associated handler " + - "to open file or directory." + ex1); + "to open file or directory.", ex1); openButton.setEnabled(false); } } } } /** * Called when data is sent/recieved * * @param dcc The DCCSend that this message is from * @param bytes The number of new bytes that were transfered */ @Override public void dataTransfered(final DCCSend dcc, final int bytes) { final double percent; synchronized (this) { transferCount += bytes; percent = (100.00 / dcc.getFileSize()) * (transferCount + dcc.getFileStart()); } if (dcc.getType() == DCCSend.TransferType.SEND) { status.setText("Status: Sending"); } else { status.setText("Status: Recieving"); } updateSpeedAndTime(); progress.setValue((int) Math.floor(percent)); ActionManager.processEvent(DCCActions.DCC_SEND_DATATRANSFERED, null, this, bytes); } /** * Update the transfer speed, time remaining and time taken labels. */ public void updateSpeedAndTime() { final long time = (System.currentTimeMillis() - timeStarted) / 1000; final double bytesPerSecond; synchronized (this) { bytesPerSecond = (time > 0) ? (transferCount / time) : transferCount; } if (bytesPerSecond > 1048576) { speed.setText(String.format("Speed: %.2f MB/s", (bytesPerSecond / 1048576))); } else if (bytesPerSecond > 1024) { speed.setText(String.format("Speed: %.2f KB/s", (bytesPerSecond / 1024))); } else { speed.setText(String.format("Speed: %.2f B/s", bytesPerSecond)); } final long remaningBytes; synchronized (this) { remaningBytes = dcc.getFileSize() - dcc.getFileStart() - transferCount; } final double remainingSeconds = (bytesPerSecond > 0) ? (remaningBytes / bytesPerSecond) : 1; remaining.setText(String.format("Time Remaining: %s", duration((int) Math.floor(remainingSeconds)))); taken.setText(String.format("Time Taken: %s", timeStarted == 0 ? "N/A" : duration(time))); } /** * Get the duration in seconds as a string. * * @param secondsInput to get duration for * @return Duration as a string */ private String duration(final long secondsInput) { final StringBuilder result = new StringBuilder(); final long hours = (secondsInput / 3600); final long minutes = (secondsInput / 60 % 60); final long seconds = (secondsInput % 60); if (hours > 0) { result.append(hours + ":"); } result.append(String.format("%0,2d:%0,2d", minutes, seconds)); return result.toString(); } /** * Called when the socket is closed * * @param dcc The DCCSend that this message is from */ @Override public void socketClosed(final DCCSend dcc) { ActionManager.processEvent(DCCActions.DCC_SEND_SOCKETCLOSED, null, this); if (!isWindowClosing()) { synchronized (this) { if (transferCount == dcc.getFileSize()) { status.setText("Status: Transfer Compelete."); if (showOpen && dcc.getType() == DCCSend.TransferType.RECEIVE) { openButton.setVisible(true); } progress.setValue(100); setIcon(dcc.getType() == DCCSend.TransferType.SEND ? "dcc-send-done" : "dcc-receive-done"); button.setText("Close Window"); } else { status.setText("Status: Transfer Failed."); setIcon(dcc.getType() == DCCSend.TransferType.SEND ? "dcc-send-failed" : "dcc-receive-failed"); if (dcc.getType() == DCCSend.TransferType.SEND) { button.setText("Resend"); } else { button.setText("Close Window"); } } } updateSpeedAndTime(); } } /** * Called when the socket is opened * * @param dcc The DCCSend that this message is from */ @Override public void socketOpened(final DCCSend dcc) { ActionManager.processEvent(DCCActions.DCC_SEND_SOCKETOPENED, null, this); status.setText("Status: Socket Opened"); timeStarted = System.currentTimeMillis(); setIcon(dcc.getType() == DCCSend.TransferType.SEND ? "dcc-send-active" : "dcc-receive-active"); } /** * Closes this container (and it's associated frame). */ @Override public void windowClosing() { super.windowClosing(); dcc.removeFromSends(); dcc.close(); } }
false
true
public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("Cancel")) { if (dcc.getType() == DCCSend.TransferType.SEND) { button.setText("Resend"); } else { button.setText("Close Window"); } status.setText("Status: Cancelled"); dcc.close(); } else if (e.getActionCommand().equals("Resend")) { button.setText("Cancel"); status.setText("Status: Resending..."); synchronized (this) { transferCount = 0; } dcc.reset(); if (parser != null && server.getState() == ServerState.CONNECTED) { final String myNickname = parser.getLocalClient().getNickname(); // Check again incase we have changed nickname to the same nickname that // this send is for. if (parser.getStringConverter().equalsIgnoreCase(otherNickname, myNickname)) { final Thread errorThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { JOptionPane.showMessageDialog(null, "You can't DCC yourself.", "DCC Error", JOptionPane.ERROR_MESSAGE); } }); errorThread.start(); return; } else { if (IdentityManager.getGlobalConfig().getOptionBool(plugin.getDomain(), "send.reverse")) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " 0 " + dcc.getFileSize() + " " + dcc.makeToken() + ((dcc.isTurbo()) ? " T" : "")); return; } else if (plugin.listen(dcc)) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " " + dcc.getPort() + " " + dcc.getFileSize() + ((dcc.isTurbo()) ? " T" : "")); return; } } } else { status.setText("Status: Resend failed."); button.setText("Close Window"); } } else if (e.getActionCommand().equals("Close Window")) { close(); } else if (e.getSource() == openButton) { final File file = new File(dcc.getFileName()); try { Desktop.getDesktop().open(file); } catch (IllegalArgumentException ex) { Logger.userError(ErrorLevel.LOW, "Unable to open file: " + file + ex); openButton.setEnabled(false); } catch (IOException ex) { try { Desktop.getDesktop().open(file.getParentFile()); } catch (IllegalArgumentException ex1) { Logger.userError(ErrorLevel.LOW, "Unable to open folder: " + file.getParentFile() + ex1); openButton.setEnabled(false); } catch (IOException ex1) { Logger.userError(ErrorLevel.LOW, "No associated handler " + "to open file or directory." + ex1); openButton.setEnabled(false); } } } }
public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("Cancel")) { if (dcc.getType() == DCCSend.TransferType.SEND) { button.setText("Resend"); } else { button.setText("Close Window"); } status.setText("Status: Cancelled"); dcc.close(); } else if (e.getActionCommand().equals("Resend")) { button.setText("Cancel"); status.setText("Status: Resending..."); synchronized (this) { transferCount = 0; } dcc.reset(); if (parser != null && server.getState() == ServerState.CONNECTED) { final String myNickname = parser.getLocalClient().getNickname(); // Check again incase we have changed nickname to the same nickname that // this send is for. if (parser.getStringConverter().equalsIgnoreCase(otherNickname, myNickname)) { final Thread errorThread = new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { JOptionPane.showMessageDialog(null, "You can't DCC yourself.", "DCC Error", JOptionPane.ERROR_MESSAGE); } }); errorThread.start(); return; } else { if (IdentityManager.getGlobalConfig().getOptionBool(plugin.getDomain(), "send.reverse")) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " 0 " + dcc.getFileSize() + " " + dcc.makeToken() + ((dcc.isTurbo()) ? " T" : "")); return; } else if (plugin.listen(dcc)) { parser.sendCTCP(otherNickname, "DCC", "SEND \"" + (new File(dcc.getFileName())).getName() + "\" " + DCC.ipToLong(myPlugin.getListenIP(parser)) + " " + dcc.getPort() + " " + dcc.getFileSize() + ((dcc.isTurbo()) ? " T" : "")); return; } } } else { status.setText("Status: Resend failed."); button.setText("Close Window"); } } else if (e.getActionCommand().equals("Close Window")) { close(); } else if (e.getSource() == openButton) { final File file = new File(dcc.getFileName()); try { Desktop.getDesktop().open(file); } catch (IllegalArgumentException ex) { Logger.userError(ErrorLevel.LOW, "Unable to open file: " + file, ex); openButton.setEnabled(false); } catch (IOException ex) { try { Desktop.getDesktop().open(file.getParentFile()); } catch (IllegalArgumentException ex1) { Logger.userError(ErrorLevel.LOW, "Unable to open folder: " + file.getParentFile(), ex1); openButton.setEnabled(false); } catch (IOException ex1) { Logger.userError(ErrorLevel.LOW, "No associated handler " + "to open file or directory.", ex1); openButton.setEnabled(false); } } } }
diff --git a/helloworld-mbean/helloworld-mbean-webapp/src/main/java/org/jboss/as/quickstarts/mbeanhelloworld/util/CDIExtension.java b/helloworld-mbean/helloworld-mbean-webapp/src/main/java/org/jboss/as/quickstarts/mbeanhelloworld/util/CDIExtension.java index ec7b86bf1..1786ddc48 100644 --- a/helloworld-mbean/helloworld-mbean-webapp/src/main/java/org/jboss/as/quickstarts/mbeanhelloworld/util/CDIExtension.java +++ b/helloworld-mbean/helloworld-mbean-webapp/src/main/java/org/jboss/as/quickstarts/mbeanhelloworld/util/CDIExtension.java @@ -1,50 +1,50 @@ /* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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.jboss.as.quickstarts.mbeanhelloworld.util; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.BeforeBeanDiscovery; import javax.enterprise.inject.spi.Extension; /** * A CDI Extension to retrieve bean in a non-CDI context. * * @author Jeremie Lagarde * */ public class CDIExtension implements Extension { private static BeanManager beanManager; void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscovery, BeanManager beanManager) { setBeanManager(beanManager); } @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> beanType) { final Bean<T> bean = (Bean<T>) beanManager.getBeans(beanType).iterator().next(); final CreationalContext<T> ctx = beanManager.createCreationalContext(bean); - return (T) beanManager.getReference(bean, bean.getClass(), ctx); + return (T) beanManager.getReference(bean, beanType, ctx); } private static void setBeanManager(BeanManager beanManager) { CDIExtension.beanManager = beanManager; } }
true
true
public static <T> T getBean(Class<T> beanType) { final Bean<T> bean = (Bean<T>) beanManager.getBeans(beanType).iterator().next(); final CreationalContext<T> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, bean.getClass(), ctx); }
public static <T> T getBean(Class<T> beanType) { final Bean<T> bean = (Bean<T>) beanManager.getBeans(beanType).iterator().next(); final CreationalContext<T> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, beanType, ctx); }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java index 39ca61d56..15019c6d6 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java @@ -1,1152 +1,1162 @@ /******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui.actions; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IBreakpointManager; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeParameter; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.debug.core.IJavaBreakpoint; import org.eclipse.jdt.debug.core.IJavaClassPrepareBreakpoint; import org.eclipse.jdt.debug.core.IJavaFieldVariable; import org.eclipse.jdt.debug.core.IJavaLineBreakpoint; import org.eclipse.jdt.debug.core.IJavaMethodBreakpoint; import org.eclipse.jdt.debug.core.IJavaType; import org.eclipse.jdt.debug.core.IJavaWatchpoint; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.debug.core.JavaDebugUtils; import org.eclipse.jdt.internal.debug.ui.BreakpointUtils; import org.eclipse.jdt.internal.debug.ui.DebugWorkingCopyManager; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.IEditorStatusLine; import org.eclipse.ui.texteditor.ITextEditor; /** * Toggles a line breakpoint in a Java editor. * * @since 3.0 */ public class ToggleBreakpointAdapter implements IToggleBreakpointsTargetExtension { private static final String EMPTY_STRING = ""; //$NON-NLS-1$ /** * Constructor */ public ToggleBreakpointAdapter() { // initialize helper in UI thread ActionDelegateHelper.getDefault(); } /** * Convenience method for printing messages to the status line * @param message the message to be displayed * @param part the currently active workbench part */ protected void report(final String message, final IWorkbenchPart part) { JDIDebugUIPlugin.getStandardDisplay().asyncExec(new Runnable() { public void run() { IEditorStatusLine statusLine = (IEditorStatusLine) part.getAdapter(IEditorStatusLine.class); if (statusLine != null) { if (message != null) { statusLine.setMessage(true, message, null); } else { statusLine.setMessage(true, null, null); } } if (message != null && JDIDebugUIPlugin.getActiveWorkbenchShell() != null) { JDIDebugUIPlugin.getActiveWorkbenchShell().getDisplay().beep(); } } }); } /** * Returns the <code>IType</code> for the given selection * @param selection the current text selection * @return the <code>IType</code> for the text selection or <code>null</code> */ protected IType getType(ITextSelection selection) { IMember member = ActionDelegateHelper.getDefault().getCurrentMember(selection); IType type = null; if (member instanceof IType) { type = (IType) member; } else if (member != null) { type = member.getDeclaringType(); } // bug 52385: we don't want local and anonymous types from compilation // unit, // we are getting 'not-always-correct' names for them. try { while (type != null && !type.isBinary() && type.isLocal()) { type = type.getDeclaringType(); } } catch (JavaModelException e) { JDIDebugUIPlugin.log(e); } return type; } /** * Returns the IType associated with the <code>IJavaElement</code> passed in * @param element the <code>IJavaElement</code> to get the type from * @return the corresponding <code>IType</code> for the <code>IJavaElement</code>, or <code>null</code> if there is not one. * @since 3.3 */ protected IType getType(IJavaElement element) { switch(element.getElementType()) { case IJavaElement.FIELD: { return ((IField)element).getDeclaringType(); } case IJavaElement.METHOD: { return ((IMethod)element).getDeclaringType(); } case IJavaElement.TYPE: { return (IType)element; } default: { return null; } } } /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleLineBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) */ public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { toggleLineBreakpoints(part, selection, false); } /** * Toggles a line breakpoint. * @param part the currently active workbench part * @param selection the current selection * @param bestMatch if we should make a best match or not */ public void toggleLineBreakpoints(final IWorkbenchPart part, final ISelection selection, final boolean bestMatch) { Job job = new Job("Toggle Line Breakpoint") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { ITextEditor editor = getTextEditor(part); if (editor != null && selection instanceof ITextSelection) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection sel = selection; if(!(selection instanceof IStructuredSelection)) { sel = translateToMembers(part, selection); } if(isInterface(sel, part)) { report(ActionMessages.ToggleBreakpointAdapter_6, part); return Status.OK_STATUS; } if(sel instanceof IStructuredSelection) { IMember member = (IMember) ((IStructuredSelection)sel).getFirstElement(); IType type = null; if(member.getElementType() == IJavaElement.TYPE) { type = (IType) member; } else { type = member.getDeclaringType(); } String tname = createQualifiedTypeName(type); IResource resource = BreakpointUtils.getBreakpointResource(type); int lnumber = ((ITextSelection) selection).getStartLine() + 1; IJavaLineBreakpoint existingBreakpoint = JDIDebugModel.lineBreakpointExists(resource, tname, lnumber); if (existingBreakpoint != null) { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(existingBreakpoint, true); return Status.OK_STATUS; } Map attributes = new HashMap(10); IDocumentProvider documentProvider = editor.getDocumentProvider(); if (documentProvider == null) { return Status.CANCEL_STATUS; } IDocument document = documentProvider.getDocument(editor.getEditorInput()); try { IRegion line = document.getLineInformation(lnumber - 1); int start = line.getOffset(); int end = start + line.getLength() - 1; BreakpointUtils.addJavaBreakpointAttributesWithMemberDetails(attributes, type, start, end); } catch (BadLocationException ble) {JDIDebugUIPlugin.log(ble);} IJavaLineBreakpoint breakpoint = JDIDebugModel.createLineBreakpoint(resource, tname, lnumber, -1, -1, 0, true, attributes); new BreakpointLocationVerifierJob(document, breakpoint, lnumber, bestMatch, tname, type, resource, editor).schedule(); } else { report(ActionMessages.ToggleBreakpointAdapter_3, part); return Status.OK_STATUS; } } catch (CoreException ce) {return ce.getStatus();} } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleLineBreakpoints(IWorkbenchPart, * ISelection) */ public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) { if (isRemote(part, selection)) { return false; } return selection instanceof ITextSelection; } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public void toggleMethodBreakpoints(final IWorkbenchPart part, final ISelection finalSelection) { Job job = new Job("Toggle Method Breakpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection selection = finalSelection; if(!(selection instanceof IStructuredSelection)) { selection = translateToMembers(part, selection); } if(isInterface(selection, part)) { report(ActionMessages.ToggleBreakpointAdapter_7, part); return Status.OK_STATUS; } if (selection instanceof IStructuredSelection) { IMethod[] members = getMethods((IStructuredSelection) selection); if (members.length == 0) { report(ActionMessages.ToggleBreakpointAdapter_9, part); return Status.OK_STATUS; } IJavaBreakpoint breakpoint = null; ISourceRange range = null; Map attributes = null; IType type = null; String signature = null; String mname = null; for (int i = 0, length = members.length; i < length; i++) { breakpoint = getMethodBreakpoint(members[i]); if (breakpoint == null) { int start = -1; int end = -1; range = members[i].getNameRange(); if (range != null) { start = range.getOffset(); end = start + range.getLength(); } attributes = new HashMap(10); BreakpointUtils.addJavaBreakpointAttributes(attributes, members[i]); type = members[i].getDeclaringType(); signature = members[i].getSignature(); mname = members[i].getElementName(); if (members[i].isConstructor()) { mname = "<init>"; //$NON-NLS-1$ if (type.isEnum()) { signature = "(Ljava.lang.String;I" + signature.substring(1); //$NON-NLS-1$ } } if (!type.isBinary()) { signature = resolveMethodSignature(type, signature); if (signature == null) { report(ActionMessages.ManageMethodBreakpointActionDelegate_methodNonAvailable, part); return Status.OK_STATUS; } } JDIDebugModel.createMethodBreakpoint(BreakpointUtils.getBreakpointResource(members[i]), createQualifiedTypeName(type), mname, signature, true, false, false, -1, start, end, 0, true, attributes); } else { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); } } } else { report(ActionMessages.ToggleBreakpointAdapter_4, part); return Status.OK_STATUS; } } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /** * Toggles a class load breakpoint * @param part the part * @param selection the current selection * @since 3.3 */ public void toggleClassBreakpoints(final IWorkbenchPart part, final ISelection selection) { Job job = new Job("Toggle Class Load Breakpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection sel = selection; if(!(selection instanceof IStructuredSelection)) { sel = translateToMembers(part, selection); } if(isInterface(sel, part)) { report(ActionMessages.ToggleBreakpointAdapter_1, part); return Status.OK_STATUS; } if(sel instanceof IStructuredSelection) { IMember member = (IMember)((IStructuredSelection)sel).getFirstElement(); IType type = (IType) member; IBreakpoint existing = getClassLoadBreakpoint(type); if (existing != null) { existing.delete(); } else { HashMap map = new HashMap(10); BreakpointUtils.addJavaBreakpointAttributes(map, type); ISourceRange range= type.getNameRange(); int start = -1; int end = -1; if (range != null) { start = range.getOffset(); end = start + range.getLength(); } JDIDebugModel.createClassPrepareBreakpoint(BreakpointUtils.getBreakpointResource(member), createQualifiedTypeName(type), IJavaClassPrepareBreakpoint.TYPE_CLASS, start, end, true, map); } } else { report(ActionMessages.ToggleBreakpointAdapter_0, part); return Status.OK_STATUS; } } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /** * Returns the class load breakpoint for the specified type or null if none found * @param type the type to search for a class load breakpoint for * @return the existing class load breakpoint, or null if none * @throws CoreException * @since 3.3 */ protected IBreakpoint getClassLoadBreakpoint(IType type) throws CoreException { IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(JDIDebugModel.getPluginIdentifier()); IBreakpoint existing = null; IJavaBreakpoint breakpoint = null; for (int i = 0; i < breakpoints.length; i++) { breakpoint = (IJavaBreakpoint) breakpoints[i]; if (breakpoint instanceof IJavaClassPrepareBreakpoint && createQualifiedTypeName(type).equals(breakpoint.getTypeName())) { existing = breakpoint; break; } } return existing; } /** * Returns the package qualified name, while accounting for the fact that a source file might * not have a project * @param type the type to ensure the package qualified name is created for * @return the package qualified name * @since 3.3 */ private String createQualifiedTypeName(IType type) { String tname = type.getFullyQualifiedName(); try { if(!type.getJavaProject().exists()) { String packName = null; if (type.isBinary()) { packName = type.getPackageFragment().getElementName(); } else { IPackageDeclaration[] pd = type.getCompilationUnit().getPackageDeclarations(); if(pd.length > 0) { packName = pd[0].getElementName(); } } if(packName != null && !packName.equals(EMPTY_STRING)) { tname = packName+"."+tname; //$NON-NLS-1$ } } if(type.isAnonymous()) { //prune the $# from the name int idx = tname.indexOf('$'); if(idx > -1) { tname = tname.substring(0, idx); } } } catch (JavaModelException e) {} return tname; } /** * gets the <code>IJavaElement</code> from the editor input * @param input the current editor input * @return the corresponding <code>IJavaElement</code> * @since 3.3 */ private IJavaElement getJavaElement(IEditorInput input) { IJavaElement je = JavaUI.getEditorInputJavaElement(input); if(je != null) { return je; } //try to get from the working copy manager return DebugWorkingCopyManager.getWorkingCopy(input, false); } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) { if (isRemote(part, selection)) { return false; } if (selection instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) selection; return getMethods(ss).length > 0; } return (selection instanceof ITextSelection) && isMethod((ITextSelection) selection, part); } /** * Returns whether the given part/selection is remote (viewing a repository) * * @param part * @param selection * @return */ protected boolean isRemote(IWorkbenchPart part, ISelection selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) selection; Object element = ss.getFirstElement(); if(element instanceof IMember) { IMember member = (IMember) element; return !member.getJavaProject().getProject().exists(); } } ITextEditor editor = getTextEditor(part); if (editor != null) { IEditorInput input = editor.getEditorInput(); Object adapter = Platform.getAdapterManager().getAdapter(input, "org.eclipse.team.core.history.IFileRevision"); //$NON-NLS-1$ return adapter != null; } return false; } /** * Returns the text editor associated with the given part or <code>null</code> * if none. In case of a multi-page editor, this method should be used to retrieve * the correct editor to perform the breakpoint operation on. * * @param part workbench part * @return text editor part or <code>null</code> */ protected ITextEditor getTextEditor(IWorkbenchPart part) { if (part instanceof ITextEditor) { return (ITextEditor) part; } return (ITextEditor) part.getAdapter(ITextEditor.class); } /** * Returns the methods from the selection, or an empty array * @param selection the selection to get the methods from * @return an array of the methods from the selection or an empty array */ protected IMethod[] getMethods(IStructuredSelection selection) { if (selection.isEmpty()) { return new IMethod[0]; } List methods = new ArrayList(selection.size()); Iterator iterator = selection.iterator(); while (iterator.hasNext()) { Object thing = iterator.next(); try { if (thing instanceof IMethod) { IMethod method = (IMethod) thing; if (!Flags.isAbstract(method.getFlags())) { methods.add(method); } } } catch (JavaModelException e) {} } return (IMethod[]) methods.toArray(new IMethod[methods.size()]); } /** * Returns if the text selection is a valid method or not * @param selection the text selection * @param part the associated workbench part * @return true if the selection is a valid method, false otherwise */ private boolean isMethod(ITextSelection selection, IWorkbenchPart part) { ITextEditor editor = getTextEditor(part); if(editor != null) { IJavaElement element = getJavaElement(editor.getEditorInput()); if(element != null) { try { if(element instanceof ICompilationUnit) { element = ((ICompilationUnit) element).getElementAt(selection.getOffset()); } else if(element instanceof IClassFile) { element = ((IClassFile) element).getElementAt(selection.getOffset()); } return element != null && element.getElementType() == IJavaElement.METHOD; } catch (JavaModelException e) {return false;} } } return false; } /** * Returns a list of <code>IField</code> and <code>IJavaFieldVariable</code> in the given selection. * When an <code>IField</code> can be resolved for an <code>IJavaFieldVariable</code>, it is * returned in favour of the variable. * * @param selection * @return list of <code>IField</code> and <code>IJavaFieldVariable</code>, possibly empty * @throws CoreException */ protected List getFields(IStructuredSelection selection) throws CoreException { if (selection.isEmpty()) { return Collections.EMPTY_LIST; } List fields = new ArrayList(selection.size()); Iterator iterator = selection.iterator(); while (iterator.hasNext()) { Object thing = iterator.next(); if (thing instanceof IField) { fields.add(thing); } else if (thing instanceof IJavaFieldVariable) { IField field = getField((IJavaFieldVariable) thing); if (field == null) { fields.add(thing); } else { fields.add(field); } } } return fields; } /** * Returns if the structured selection is itself or is part of an interface * @param selection the current selection * @return true if the selection is part of an interface, false otherwise * @since 3.2 */ private boolean isInterface(ISelection selection, IWorkbenchPart part) { try { ISelection sel = selection; if(!(sel instanceof IStructuredSelection)) { sel = translateToMembers(part, selection); } if(sel instanceof IStructuredSelection) { Object obj = ((IStructuredSelection)sel).getFirstElement(); if(obj instanceof IMember) { IMember member = (IMember) ((IStructuredSelection)sel).getFirstElement(); if(member.getElementType() == IJavaElement.TYPE) { return ((IType)member).isInterface(); } return member.getDeclaringType().isInterface(); } else if(obj instanceof IJavaFieldVariable) { IJavaFieldVariable var = (IJavaFieldVariable) obj; IType type = JavaDebugUtils.resolveType(var.getDeclaringType()); return type != null && type.isInterface(); } } } catch (CoreException e1) {} return false; } /** * Returns if the text selection is a field selection or not * @param selection the text selection * @param part the associated workbench part * @return true if the text selection is a valid field for a watchpoint, false otherwise * @since 3.3 */ private boolean isField(ITextSelection selection, IWorkbenchPart part) { ITextEditor editor = getTextEditor(part); if(editor != null) { IJavaElement element = getJavaElement(editor.getEditorInput()); if(element != null) { try { if(element instanceof ICompilationUnit) { element = ((ICompilationUnit) element).getElementAt(selection.getOffset()); } else if(element instanceof IClassFile) { element = ((IClassFile) element).getElementAt(selection.getOffset()); } return element != null && element.getElementType() == IJavaElement.FIELD; } catch (JavaModelException e) {return false;} } } return false; } /** * Determines if the selection is a field or not * @param selection the current selection * @return true if the selection is a field false otherwise */ private boolean isFields(IStructuredSelection selection) { if (!selection.isEmpty()) { try { Iterator iterator = selection.iterator(); while (iterator.hasNext()) { Object thing = iterator.next(); if (thing instanceof IField) { int flags = ((IField)thing).getFlags(); return !Flags.isFinal(flags) & !(Flags.isFinal(flags) & Flags.isStatic(flags)); } else if(thing instanceof IJavaFieldVariable) { IJavaFieldVariable fv = (IJavaFieldVariable)thing; return !fv.isFinal() & !(fv.isFinal() & fv.isStatic()); } } } catch(JavaModelException e) {return false;} catch(DebugException de) {return false;} } return false; } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleWatchpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public void toggleWatchpoints(final IWorkbenchPart part, final ISelection finalSelection) { Job job = new Job("Toggle Watchpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection selection = finalSelection; if(!(selection instanceof IStructuredSelection)) { selection = translateToMembers(part, finalSelection); } if(isInterface(selection, part)) { report(ActionMessages.ToggleBreakpointAdapter_5, part); return Status.OK_STATUS; } boolean allowed = false; if (selection instanceof IStructuredSelection) { List fields = getFields((IStructuredSelection) selection); if (fields.isEmpty()) { report(ActionMessages.ToggleBreakpointAdapter_10, part); return Status.OK_STATUS; } Iterator theFields = fields.iterator(); IField javaField = null; IResource resource = null; String typeName = null; String fieldName = null; Object element = null; Map attributes = null; IJavaBreakpoint breakpoint = null; while (theFields.hasNext()) { element = theFields.next(); if (element instanceof IField) { javaField = (IField) element; IType type = javaField.getDeclaringType(); typeName = createQualifiedTypeName(type); fieldName = javaField.getElementName(); int f = javaField.getFlags(); boolean fin = Flags.isFinal(f); allowed = !(fin) & !(Flags.isStatic(f) & fin); + } else if (element instanceof IJavaFieldVariable) { + IJavaFieldVariable var = (IJavaFieldVariable) element; + typeName = var.getDeclaringType().getName(); + fieldName = var.getName(); + boolean fin = var.isFinal(); + allowed = !(fin) & !(var.isStatic() & fin); } breakpoint = getWatchpoint(typeName, fieldName); if (breakpoint == null) { if(!allowed) { toggleLineBreakpoints(part, finalSelection); return Status.OK_STATUS; } int start = -1; int end = -1; attributes = new HashMap(10); - IType type = javaField.getDeclaringType(); - ISourceRange range = javaField.getNameRange(); - if (range != null) { - start = range.getOffset(); - end = start + range.getLength(); - } - BreakpointUtils.addJavaBreakpointAttributes(attributes, javaField); - resource = BreakpointUtils.getBreakpointResource(type); + if (javaField == null) { + resource = ResourcesPlugin.getWorkspace().getRoot(); + } else { + IType type = javaField.getDeclaringType(); + ISourceRange range = javaField.getNameRange(); + if (range != null) { + start = range.getOffset(); + end = start + range.getLength(); + } + BreakpointUtils.addJavaBreakpointAttributes(attributes, javaField); + resource = BreakpointUtils.getBreakpointResource(type); + } JDIDebugModel.createWatchpoint(resource, typeName, fieldName, -1, start, end, 0, true, attributes); } else { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); } } } else { report(ActionMessages.ToggleBreakpointAdapter_2, part); return Status.OK_STATUS; } } catch (CoreException e) {return e.getStatus();} return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } /** * Returns any existing watchpoint for the given field, or <code>null</code> if none. * * @param typeName fully qualified type name on which watchpoint may exist * @param fieldName field name * @return any existing watchpoint for the given field, or <code>null</code> if none * @throws CoreException */ private IJavaWatchpoint getWatchpoint(String typeName, String fieldName) throws CoreException { IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); IBreakpoint[] breakpoints = breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint = breakpoints[i]; if (breakpoint instanceof IJavaWatchpoint) { IJavaWatchpoint watchpoint = (IJavaWatchpoint) breakpoint; if (typeName.equals(watchpoint.getTypeName()) && fieldName.equals(watchpoint.getFieldName())) { return watchpoint; } } } return null; } /** * Returns the resolved method signature for the specified type * @param type the declaring type the method is contained in * @param methodSignature the method signature to resolve * @return the resolved method signature * @throws JavaModelException */ public static String resolveMethodSignature(IType type, String methodSignature) throws JavaModelException { String[] parameterTypes = Signature.getParameterTypes(methodSignature); int length = parameterTypes.length; String[] resolvedParameterTypes = new String[length]; for (int i = 0; i < length; i++) { resolvedParameterTypes[i] = resolveType(type, parameterTypes[i]); if (resolvedParameterTypes[i] == null) { return null; } } String resolvedReturnType = resolveType(type, Signature.getReturnType(methodSignature)); if (resolvedReturnType == null) { return null; } return Signature.createMethodSignature(resolvedParameterTypes, resolvedReturnType); } /** * Resolves the the type for its given signature * @param type the type * @param typeSignature the types signature * @return the resolved type name * @throws JavaModelException */ private static String resolveType(IType type, String typeSignature) throws JavaModelException { int count = Signature.getArrayCount(typeSignature); String elementTypeSignature = Signature.getElementType(typeSignature); if (elementTypeSignature.length() == 1) { // no need to resolve primitive types return typeSignature; } String elementTypeName = Signature.toString(elementTypeSignature); String[][] resolvedElementTypeNames = type.resolveType(elementTypeName); if (resolvedElementTypeNames == null || resolvedElementTypeNames.length != 1) { // check if type parameter ITypeParameter[] typeParameters = type.getTypeParameters(); for (int i = 0; i < typeParameters.length; i++) { ITypeParameter parameter = typeParameters[i]; if (parameter.getElementName().equals(elementTypeName)) { String[] bounds = parameter.getBounds(); if (bounds.length == 0) { return "Ljava/lang/Object;"; //$NON-NLS-1$ } else { String bound = Signature.createTypeSignature(bounds[0], false); return resolveType(type, bound); } } } // the type name cannot be resolved return null; } String[] types = resolvedElementTypeNames[0]; types[1] = types[1].replace('.', '$'); String resolvedElementTypeName = Signature.toQualifiedName(types); String resolvedElementTypeSignature = EMPTY_STRING; if(types[0].equals(EMPTY_STRING)) { resolvedElementTypeName = resolvedElementTypeName.substring(1); resolvedElementTypeSignature = Signature.createTypeSignature(resolvedElementTypeName, true); } else { resolvedElementTypeSignature = Signature.createTypeSignature(resolvedElementTypeName, true).replace('.', '/'); } return Signature.createArraySignature(resolvedElementTypeSignature, count); } /** * Returns the resource associated with the specified editor part * @param editor the currently active editor part * @return the corresponding <code>IResource</code> from the editor part */ protected static IResource getResource(IEditorPart editor) { IEditorInput editorInput = editor.getEditorInput(); IResource resource = (IResource) editorInput.getAdapter(IFile.class); if (resource == null) { resource = ResourcesPlugin.getWorkspace().getRoot(); } return resource; } /** * Returns a handle to the specified method or <code>null</code> if none. * * @param editorPart * the editor containing the method * @param typeName * @param methodName * @param signature * @return handle or <code>null</code> */ protected IMethod getMethodHandle(IEditorPart editorPart, String typeName, String methodName, String signature) throws CoreException { IJavaElement element = (IJavaElement) editorPart.getEditorInput().getAdapter(IJavaElement.class); IType type = null; if (element instanceof ICompilationUnit) { IType[] types = ((ICompilationUnit) element).getAllTypes(); for (int i = 0; i < types.length; i++) { if (types[i].getFullyQualifiedName().equals(typeName)) { type = types[i]; break; } } } else if (element instanceof IClassFile) { type = ((IClassFile) element).getType(); } if (type != null) { String[] sigs = Signature.getParameterTypes(signature); return type.getMethod(methodName, sigs); } return null; } /** * Returns the <code>IJavaBreakpoint</code> from the specified <code>IMember</code> * @param element the element to get the breakpoint from * @return the current breakpoint from the element or <code>null</code> */ protected IJavaBreakpoint getMethodBreakpoint(IMember element) { IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); IBreakpoint[] breakpoints = breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); if (element instanceof IMethod) { IMethod method = (IMethod) element; for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint = breakpoints[i]; if (breakpoint instanceof IJavaMethodBreakpoint) { IJavaMethodBreakpoint methodBreakpoint = (IJavaMethodBreakpoint) breakpoint; IMember container = null; try { container = BreakpointUtils.getMember(methodBreakpoint); } catch (CoreException e) { JDIDebugUIPlugin.log(e); return null; } if (container == null) { try { if (method.getDeclaringType().getFullyQualifiedName().equals(methodBreakpoint.getTypeName()) && method.getElementName().equals(methodBreakpoint.getMethodName()) && methodBreakpoint.getMethodSignature().equals(resolveMethodSignature(method.getDeclaringType(), method.getSignature()))) { return methodBreakpoint; } } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } else { if (container instanceof IMethod) { if(method.getDeclaringType().equals(container.getDeclaringType())) { if (method.getDeclaringType().getFullyQualifiedName().equals(container.getDeclaringType().getFullyQualifiedName())) { if (method.isSimilar((IMethod) container)) { return methodBreakpoint; } } } } } } } } return null; } /** * Returns the compilation unit from the editor * @param editor the editor to get the compilation unit from * @return the compilation unit or <code>null</code> * @throws CoreException */ protected CompilationUnit parseCompilationUnit(ITextEditor editor) throws CoreException { IEditorInput editorInput = editor.getEditorInput(); IDocumentProvider documentProvider = editor.getDocumentProvider(); if (documentProvider == null) { throw new CoreException(Status.CANCEL_STATUS); } IDocument document = documentProvider.getDocument(editorInput); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(document.get().toCharArray()); return (CompilationUnit) parser.createAST(null); } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleWatchpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) { if (isRemote(part, selection)) { return false; } if (selection instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) selection; return isFields(ss); } return (selection instanceof ITextSelection) && isField((ITextSelection) selection, part); } /** * Returns a selection of the member in the given text selection, or the * original selection if none. * * @param part * @param selection * @return a structured selection of the member in the given text selection, * or the original selection if none * @exception CoreException * if an exception occurs */ protected ISelection translateToMembers(IWorkbenchPart part, ISelection selection) throws CoreException { ITextEditor textEditor = getTextEditor(part); if (textEditor != null && selection instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) selection; IEditorInput editorInput = textEditor.getEditorInput(); IDocumentProvider documentProvider = textEditor.getDocumentProvider(); if (documentProvider == null) { throw new CoreException(Status.CANCEL_STATUS); } IDocument document = documentProvider.getDocument(editorInput); int offset = textSelection.getOffset(); if (document != null) { try { IRegion region = document.getLineInformationOfOffset(offset); int end = region.getOffset() + region.getLength(); while (Character.isWhitespace(document.getChar(offset)) && offset < end) { offset++; } } catch (BadLocationException e) {} } IMember m = null; IClassFile classFile = (IClassFile) editorInput.getAdapter(IClassFile.class); if (classFile != null) { IJavaElement e = classFile.getElementAt(offset); if (e instanceof IMember) { m = (IMember) e; } } else { IWorkingCopyManager manager = JavaUI.getWorkingCopyManager(); ICompilationUnit unit = manager.getWorkingCopy(editorInput); if (unit != null) { synchronized (unit) { unit.reconcile(ICompilationUnit.NO_AST , false, null, null); } } else { unit = DebugWorkingCopyManager.getWorkingCopy(editorInput, false); if(unit != null) { synchronized (unit) { unit.reconcile(ICompilationUnit.NO_AST, false, null, null); } } } IJavaElement e = unit.getElementAt(offset); if (e instanceof IMember) { m = (IMember) e; } } if (m != null) { return new StructuredSelection(m); } } return selection; } /** * Return the associated IField (Java model) for the given * IJavaFieldVariable (JDI model) */ private IField getField(IJavaFieldVariable variable) throws CoreException { String varName = null; try { varName = variable.getName(); } catch (DebugException x) { JDIDebugUIPlugin.log(x); return null; } IField field; IJavaType declaringType = variable.getDeclaringType(); IType type = JavaDebugUtils.resolveType(declaringType); if (type != null) { field = type.getField(varName); if (field.exists()) { return field; } } return null; } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension#toggleBreakpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public void toggleBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { ISelection sel = translateToMembers(part, selection); if(sel instanceof IStructuredSelection) { IMember member = (IMember) ((IStructuredSelection)sel).getFirstElement(); int mtype = member.getElementType(); if(mtype == IJavaElement.FIELD || mtype == IJavaElement.METHOD) { // remove line breakpoint if present first if (selection instanceof ITextSelection) { ITextSelection ts = (ITextSelection) selection; IType declaringType = member.getDeclaringType(); IResource resource = BreakpointUtils.getBreakpointResource(declaringType); IJavaLineBreakpoint breakpoint = JDIDebugModel.lineBreakpointExists(resource, createQualifiedTypeName(declaringType), ts.getStartLine() + 1); if (breakpoint != null) { breakpoint.delete(); return; } CompilationUnit unit = parseCompilationUnit(getTextEditor(part)); ValidBreakpointLocationLocator loc = new ValidBreakpointLocationLocator(unit, ts.getStartLine()+1, true, true); unit.accept(loc); if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_METHOD) { toggleMethodBreakpoints(part, sel); } else if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_FIELD) { toggleWatchpoints(part, ts); } else if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_LINE) { toggleLineBreakpoints(part, ts); } } } else if(member.getElementType() == IJavaElement.TYPE) { toggleClassBreakpoints(part, sel); } else { //fall back to old behavior, always create a line breakpoint toggleLineBreakpoints(part, selection, true); } } } /* * (non-Javadoc) * * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTargetExtension#canToggleBreakpoints(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public boolean canToggleBreakpoints(IWorkbenchPart part, ISelection selection) { if (isRemote(part, selection)) { return false; } return canToggleLineBreakpoints(part, selection); } }
false
true
public void toggleWatchpoints(final IWorkbenchPart part, final ISelection finalSelection) { Job job = new Job("Toggle Watchpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection selection = finalSelection; if(!(selection instanceof IStructuredSelection)) { selection = translateToMembers(part, finalSelection); } if(isInterface(selection, part)) { report(ActionMessages.ToggleBreakpointAdapter_5, part); return Status.OK_STATUS; } boolean allowed = false; if (selection instanceof IStructuredSelection) { List fields = getFields((IStructuredSelection) selection); if (fields.isEmpty()) { report(ActionMessages.ToggleBreakpointAdapter_10, part); return Status.OK_STATUS; } Iterator theFields = fields.iterator(); IField javaField = null; IResource resource = null; String typeName = null; String fieldName = null; Object element = null; Map attributes = null; IJavaBreakpoint breakpoint = null; while (theFields.hasNext()) { element = theFields.next(); if (element instanceof IField) { javaField = (IField) element; IType type = javaField.getDeclaringType(); typeName = createQualifiedTypeName(type); fieldName = javaField.getElementName(); int f = javaField.getFlags(); boolean fin = Flags.isFinal(f); allowed = !(fin) & !(Flags.isStatic(f) & fin); } breakpoint = getWatchpoint(typeName, fieldName); if (breakpoint == null) { if(!allowed) { toggleLineBreakpoints(part, finalSelection); return Status.OK_STATUS; } int start = -1; int end = -1; attributes = new HashMap(10); IType type = javaField.getDeclaringType(); ISourceRange range = javaField.getNameRange(); if (range != null) { start = range.getOffset(); end = start + range.getLength(); } BreakpointUtils.addJavaBreakpointAttributes(attributes, javaField); resource = BreakpointUtils.getBreakpointResource(type); JDIDebugModel.createWatchpoint(resource, typeName, fieldName, -1, start, end, 0, true, attributes); } else { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); } } } else { report(ActionMessages.ToggleBreakpointAdapter_2, part); return Status.OK_STATUS; } } catch (CoreException e) {return e.getStatus();} return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); }
public void toggleWatchpoints(final IWorkbenchPart part, final ISelection finalSelection) { Job job = new Job("Toggle Watchpoints") { //$NON-NLS-1$ protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } try { report(null, part); ISelection selection = finalSelection; if(!(selection instanceof IStructuredSelection)) { selection = translateToMembers(part, finalSelection); } if(isInterface(selection, part)) { report(ActionMessages.ToggleBreakpointAdapter_5, part); return Status.OK_STATUS; } boolean allowed = false; if (selection instanceof IStructuredSelection) { List fields = getFields((IStructuredSelection) selection); if (fields.isEmpty()) { report(ActionMessages.ToggleBreakpointAdapter_10, part); return Status.OK_STATUS; } Iterator theFields = fields.iterator(); IField javaField = null; IResource resource = null; String typeName = null; String fieldName = null; Object element = null; Map attributes = null; IJavaBreakpoint breakpoint = null; while (theFields.hasNext()) { element = theFields.next(); if (element instanceof IField) { javaField = (IField) element; IType type = javaField.getDeclaringType(); typeName = createQualifiedTypeName(type); fieldName = javaField.getElementName(); int f = javaField.getFlags(); boolean fin = Flags.isFinal(f); allowed = !(fin) & !(Flags.isStatic(f) & fin); } else if (element instanceof IJavaFieldVariable) { IJavaFieldVariable var = (IJavaFieldVariable) element; typeName = var.getDeclaringType().getName(); fieldName = var.getName(); boolean fin = var.isFinal(); allowed = !(fin) & !(var.isStatic() & fin); } breakpoint = getWatchpoint(typeName, fieldName); if (breakpoint == null) { if(!allowed) { toggleLineBreakpoints(part, finalSelection); return Status.OK_STATUS; } int start = -1; int end = -1; attributes = new HashMap(10); if (javaField == null) { resource = ResourcesPlugin.getWorkspace().getRoot(); } else { IType type = javaField.getDeclaringType(); ISourceRange range = javaField.getNameRange(); if (range != null) { start = range.getOffset(); end = start + range.getLength(); } BreakpointUtils.addJavaBreakpointAttributes(attributes, javaField); resource = BreakpointUtils.getBreakpointResource(type); } JDIDebugModel.createWatchpoint(resource, typeName, fieldName, -1, start, end, 0, true, attributes); } else { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(breakpoint, true); } } } else { report(ActionMessages.ToggleBreakpointAdapter_2, part); return Status.OK_STATUS; } } catch (CoreException e) {return e.getStatus();} return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); }
diff --git a/source/ictrobot/gems/magnetic/item/ItemRing.java b/source/ictrobot/gems/magnetic/item/ItemRing.java index 108ac8e..5581d8f 100644 --- a/source/ictrobot/gems/magnetic/item/ItemRing.java +++ b/source/ictrobot/gems/magnetic/item/ItemRing.java @@ -1,128 +1,142 @@ package ictrobot.gems.magnetic.item; import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import ictrobot.core.Core; public class ItemRing extends Item { int Level; public ItemRing(int id) { super(id); setTextureName(Core.ModID + ":" + "ItemRing"); setUnlocalizedName("ItemRing"); setCreativeTab(CreativeTabs.tabTools); setMaxStackSize(1); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void onUpdate(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { if (Core.isServer()) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( )); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); EntityPlayer player; if (tag.getBoolean("Enabled") && ((entity instanceof EntityPlayer))) { float radius = 10; player = (EntityPlayer)entity; final List<EntityItem> list = (List<EntityItem>)world.getEntitiesWithinAABB((Class)EntityItem.class, player.boundingBox.expand(radius, radius, radius)); for (final EntityItem e : list) { if (e.age >= tag.getInteger("Delay")) { if (Core.isServer() && player.inventory.addItemStackToInventory(e.getEntityItem())) { world.removeEntity(e); tag.setInteger("Pnum", tag.getInteger("Pnum")+1); tag.setDouble("P" + tag.getInteger("Pnum")+"x", e.posX); tag.setDouble("P" + tag.getInteger("Pnum")+"y", e.posY); tag.setDouble("P" + tag.getInteger("Pnum")+"z", e.posZ); tag.setInteger("P" + tag.getInteger("Pnum") + "t", 1); + tag.setBoolean("P" + tag.getInteger("Pnum") + "e", true); } } } - //System.out.println(tag.getInteger("Pnum")); - for(int i=1; i<=tag.getInteger("Pnum"); i++){ - int time = tag.getInteger("P" + i + "t"); - time++; - //System.out.println("t " + tag.getInteger("P" + 1 + "t") + "x " + tag.getDouble("P" + 1 + "x") + "y " + tag.getDouble("P" + 1 + "y") + "z " + tag.getDouble("P" + 1 + "z")); - if (time>20) { - tag.removeTag("P" + i + "t"); - tag.removeTag("P" + i + "x"); - tag.removeTag("P" + i + "y"); - tag.removeTag("P" + i + "z"); - } else { - tag.setInteger("P" + i + "t", time); + if (tag.getInteger("Pnum")>0) { + boolean shouldReset = true; + for(int i=1; i<=tag.getInteger("Pnum"); i++){ + if (tag.getInteger("P" + i + "t")!=0) { + int time = tag.getInteger("P" + i + "t"); + time++; + if (time>20) { + tag.removeTag("P" + i + "t"); + tag.removeTag("P" + i + "x"); + tag.removeTag("P" + i + "y"); + tag.removeTag("P" + i + "z"); + tag.setBoolean("P" + i + "e", false); + } else { + tag.setInteger("P" + i + "t", time); + } + } + if (tag.getBoolean("P" + i + "e")) { + shouldReset=false; + } + } + if (shouldReset) { + for(int i=1; i<=tag.getInteger("Pnum"); i++){ + tag.removeTag("P" + i + "e"); + } + tag.setInteger("Pnum", 0); } } } } else { NBTTagCompound tag = itemStack.getTagCompound(); if (tag!=null) { if (tag.getInteger("Pnum")>0) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ world.spawnParticle("largesmoke", tag.getDouble("P" + i + "x"), tag.getDouble("P" + i + "y"), tag.getDouble("P" + i + "z"), 0, 0.1, 0); } } } } } public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { if (Core.isServer()) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( ) ); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); if (player.isSneaking()) { if (!tag.getBoolean("Enabled")) { tag.setBoolean("Enabled", true); player.addChatMessage("\u00A73\u00A7lFlight Ring:\u00A7r\u00A77 Enabled"); } double time = tag.getInteger("Delay"); time = time / 20; time = time + 0.5; if (time>5) { time=0.5; } double ticks = time*20; int t = (int)ticks; tag.setInteger("Delay", t); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Delay " + time); } else { if (tag.getBoolean("Enabled")) { tag.setBoolean("Enabled", false); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Disabled"); } else { tag.setBoolean("Enabled", true); player.addChatMessage("\u00A73\u00A7lItem Ring:\u00A7r\u00A77 Enabled"); } } } return itemStack; } @SuppressWarnings({ "rawtypes", "unchecked" }) public void addInformation(ItemStack itemStack, EntityPlayer player, List par3List, boolean par4) { if( itemStack.getTagCompound() != null ) { NBTTagCompound tag = itemStack.getTagCompound(); if (tag.getBoolean("Enabled")) { par3List.add("\u00A77Enabled"); double time = tag.getInteger("Delay"); double delay = time/20; par3List.add("\u00A77Delay - " + delay + " seconds"); } else { par3List.add("\u00A77Disabled"); } } } }
false
true
public void onUpdate(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { if (Core.isServer()) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( )); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); EntityPlayer player; if (tag.getBoolean("Enabled") && ((entity instanceof EntityPlayer))) { float radius = 10; player = (EntityPlayer)entity; final List<EntityItem> list = (List<EntityItem>)world.getEntitiesWithinAABB((Class)EntityItem.class, player.boundingBox.expand(radius, radius, radius)); for (final EntityItem e : list) { if (e.age >= tag.getInteger("Delay")) { if (Core.isServer() && player.inventory.addItemStackToInventory(e.getEntityItem())) { world.removeEntity(e); tag.setInteger("Pnum", tag.getInteger("Pnum")+1); tag.setDouble("P" + tag.getInteger("Pnum")+"x", e.posX); tag.setDouble("P" + tag.getInteger("Pnum")+"y", e.posY); tag.setDouble("P" + tag.getInteger("Pnum")+"z", e.posZ); tag.setInteger("P" + tag.getInteger("Pnum") + "t", 1); } } } //System.out.println(tag.getInteger("Pnum")); for(int i=1; i<=tag.getInteger("Pnum"); i++){ int time = tag.getInteger("P" + i + "t"); time++; //System.out.println("t " + tag.getInteger("P" + 1 + "t") + "x " + tag.getDouble("P" + 1 + "x") + "y " + tag.getDouble("P" + 1 + "y") + "z " + tag.getDouble("P" + 1 + "z")); if (time>20) { tag.removeTag("P" + i + "t"); tag.removeTag("P" + i + "x"); tag.removeTag("P" + i + "y"); tag.removeTag("P" + i + "z"); } else { tag.setInteger("P" + i + "t", time); } } } } else { NBTTagCompound tag = itemStack.getTagCompound(); if (tag!=null) { if (tag.getInteger("Pnum")>0) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ world.spawnParticle("largesmoke", tag.getDouble("P" + i + "x"), tag.getDouble("P" + i + "y"), tag.getDouble("P" + i + "z"), 0, 0.1, 0); } } } } }
public void onUpdate(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { if (Core.isServer()) { if( itemStack.getTagCompound() == null ) { itemStack.setTagCompound( new NBTTagCompound( )); itemStack.getTagCompound().setInteger("Delay", 10); } NBTTagCompound tag = itemStack.getTagCompound(); EntityPlayer player; if (tag.getBoolean("Enabled") && ((entity instanceof EntityPlayer))) { float radius = 10; player = (EntityPlayer)entity; final List<EntityItem> list = (List<EntityItem>)world.getEntitiesWithinAABB((Class)EntityItem.class, player.boundingBox.expand(radius, radius, radius)); for (final EntityItem e : list) { if (e.age >= tag.getInteger("Delay")) { if (Core.isServer() && player.inventory.addItemStackToInventory(e.getEntityItem())) { world.removeEntity(e); tag.setInteger("Pnum", tag.getInteger("Pnum")+1); tag.setDouble("P" + tag.getInteger("Pnum")+"x", e.posX); tag.setDouble("P" + tag.getInteger("Pnum")+"y", e.posY); tag.setDouble("P" + tag.getInteger("Pnum")+"z", e.posZ); tag.setInteger("P" + tag.getInteger("Pnum") + "t", 1); tag.setBoolean("P" + tag.getInteger("Pnum") + "e", true); } } } if (tag.getInteger("Pnum")>0) { boolean shouldReset = true; for(int i=1; i<=tag.getInteger("Pnum"); i++){ if (tag.getInteger("P" + i + "t")!=0) { int time = tag.getInteger("P" + i + "t"); time++; if (time>20) { tag.removeTag("P" + i + "t"); tag.removeTag("P" + i + "x"); tag.removeTag("P" + i + "y"); tag.removeTag("P" + i + "z"); tag.setBoolean("P" + i + "e", false); } else { tag.setInteger("P" + i + "t", time); } } if (tag.getBoolean("P" + i + "e")) { shouldReset=false; } } if (shouldReset) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ tag.removeTag("P" + i + "e"); } tag.setInteger("Pnum", 0); } } } } else { NBTTagCompound tag = itemStack.getTagCompound(); if (tag!=null) { if (tag.getInteger("Pnum")>0) { for(int i=1; i<=tag.getInteger("Pnum"); i++){ world.spawnParticle("largesmoke", tag.getDouble("P" + i + "x"), tag.getDouble("P" + i + "y"), tag.getDouble("P" + i + "z"), 0, 0.1, 0); } } } } }
diff --git a/common/logisticspipes/proxy/ic2/ElectricItemProxy.java b/common/logisticspipes/proxy/ic2/ElectricItemProxy.java index 9bb4c431..a6f7f512 100644 --- a/common/logisticspipes/proxy/ic2/ElectricItemProxy.java +++ b/common/logisticspipes/proxy/ic2/ElectricItemProxy.java @@ -1,94 +1,120 @@ package logisticspipes.proxy.ic2; import ic2.api.IElectricItem; import ic2.api.Ic2Recipes; import ic2.api.Items; import logisticspipes.LogisticsPipes; import logisticspipes.items.ItemModule; import logisticspipes.proxy.interfaces.IElectricItemProxy; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import buildcraft.BuildCraftCore; import buildcraft.BuildCraftSilicon; public class ElectricItemProxy implements IElectricItemProxy { public boolean isElectricItem(ItemStack stack) { return stack != null && stack.getItem() instanceof IElectricItem; } public int getCharge(ItemStack stack) { if (stack.getItem() instanceof IElectricItem && stack.hasTagCompound()) return stack.getTagCompound().getInteger("charge"); else return 0; } public int getMaxCharge(ItemStack stack) { if (stack.getItem() instanceof IElectricItem) return ((IElectricItem) stack.getItem()).getMaxCharge(); else return 0; } public boolean isDischarged(ItemStack stack, boolean partial) { return isDischarged(stack, partial, stack.getItem()); } public boolean isCharged(ItemStack stack, boolean partial) { return isCharged(stack, partial, stack.getItem()); } public boolean isDischarged(ItemStack stack, boolean partial, Item electricItem) { if (electricItem instanceof IElectricItem && (((IElectricItem)electricItem).getChargedItemId() == stack.itemID || ((IElectricItem)electricItem).getEmptyItemId() == stack.itemID)) { if (partial) return getCharge(stack) < getMaxCharge(stack); else return getCharge(stack) == 0; } return false; } public boolean isCharged(ItemStack stack, boolean partial, Item electricItem) { if (electricItem instanceof IElectricItem && ((IElectricItem)electricItem).getChargedItemId() == stack.itemID) { if (partial) return getCharge(stack) > 0; else return getCharge(stack) == getMaxCharge(stack); } return false; } public void addCraftingRecipes() { Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); + Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", + Character.valueOf('C'), Items.getItem("electronicCircuit"), + Character.valueOf('D'), Items.getItem("chargedReBattery"), + Character.valueOf('G'), BuildCraftCore.goldGearItem, + Character.valueOf('r'), Item.redstone, + Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); + Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGc", "rBr", "DrC", + Character.valueOf('C'), Items.getItem("electronicCircuit"), + Character.valueOf('c'), Items.getItem("reBattery"), + Character.valueOf('D'), Items.getItem("chargedReBattery"), + Character.valueOf('G'), BuildCraftCore.goldGearItem, + Character.valueOf('r'), Item.redstone, + Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); + Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGc", "rBr", "DrC", + Character.valueOf('C'), Items.getItem("electronicCircuit"), + Character.valueOf('c'), Items.getItem("chargedReBattery"), + Character.valueOf('D'), Items.getItem("reBattery"), + Character.valueOf('G'), BuildCraftCore.goldGearItem, + Character.valueOf('r'), Item.redstone, + Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); + Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", + Character.valueOf('C'), Items.getItem("electronicCircuit"), + Character.valueOf('D'), Items.getItem("chargedReBattery"), + Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), + Character.valueOf('r'), Item.redstone, + Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); } @Override public boolean hasIC2() { return true; } }
false
true
public void addCraftingRecipes() { Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); }
public void addCraftingRecipes() { Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGD", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("chargedReBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGc", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('c'), Items.getItem("reBattery"), Character.valueOf('D'), Items.getItem("chargedReBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { "CGc", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('c'), Items.getItem("chargedReBattery"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), BuildCraftCore.goldGearItem, Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("reBattery"), Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); Ic2Recipes.addCraftingRecipe(new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.ELECTRICMANAGER), new Object[] { " G ", "rBr", "DrC", Character.valueOf('C'), Items.getItem("electronicCircuit"), Character.valueOf('D'), Items.getItem("chargedReBattery"), Character.valueOf('G'), new ItemStack(BuildCraftSilicon.redstoneChipset, 1, 2), Character.valueOf('r'), Item.redstone, Character.valueOf('B'), new ItemStack(LogisticsPipes.ModuleItem, 1, ItemModule.BLANK)}); }
diff --git a/src/org/reader/Instruction.java b/src/org/reader/Instruction.java index 76e1006..83b3ef6 100644 --- a/src/org/reader/Instruction.java +++ b/src/org/reader/Instruction.java @@ -1,83 +1,83 @@ package org.reader; import org.reader.blocks.ForLoop; import org.reader.blocks.IfStatement; import org.reader.blocks.WhileLoop; import org.reader.instruction.Declaration; import org.reader.instruction.Method; /** * Basic statement that does something when used. * * @author joel */ public abstract class Instruction extends Statement { /** * Hide this method to use the class. <i><b>This method is meant to be * hidden by it's subclasses. It is called in a tree-like structure down the * children of {@link Statement}.</i></b> * * @param statement the statement to analyze * @return whether it is a valid instruction */ public static boolean isValid(String statement) { return statement.endsWith(";") || statement.endsWith("{") || statement.equals("}"); } /** * Hide this method to use the class. <i><b>This method is meant to be * hidden by it's subclasses. It is called in a tree-like structure down the * children of {@link Statement}.</i></b> * * <p> It is very important to verify that the statement is valid before * using this method. If it is not valid, it will throw * {@link InvalidStatementException}. </p> * * @param statement the statement to analyze * @return a {@link Statement} object of the type * @throws org.reader.Statement.InvalidStatementException */ public static Statement getStatementFrom(String statement) throws InvalidStatementException { if (Method.isValid(statement)) { return Method.getStatementFrom(statement); - } else if (Declaration.isValid(statement)) { - return Declaration.getStatementFrom(statement); } else if (IfStatement.isValid(statement)) { return IfStatement.getStatementFrom(statement); } else if (ForLoop.isValid(statement)) { return ForLoop.getStatementFrom(statement); } else if (WhileLoop.isValid(statement)) { return WhileLoop.getStatementFrom(statement); + } else if (Declaration.isValid(statement)) { + return Declaration.getStatementFrom(statement); } else if (statement.equals("}")) { // Does nothing return new Statement(); } else { - throw new InvalidStatementException(statement + " is not a statement type."); + throw new InvalidStatementException(Method.getMethodName(statement) + " is not a recognized method."); } } private final String instruction; /** * Creates instruction by a string. * * @param instruction full code snippet */ public Instruction(String instruction) { this.instruction = instruction; } /** * The instruction in the text file. * * @return instruction as a string */ public String getInstruction() { return instruction; } /** * Method to run the instruction. */ public abstract void run(); }
false
true
public static Statement getStatementFrom(String statement) throws InvalidStatementException { if (Method.isValid(statement)) { return Method.getStatementFrom(statement); } else if (Declaration.isValid(statement)) { return Declaration.getStatementFrom(statement); } else if (IfStatement.isValid(statement)) { return IfStatement.getStatementFrom(statement); } else if (ForLoop.isValid(statement)) { return ForLoop.getStatementFrom(statement); } else if (WhileLoop.isValid(statement)) { return WhileLoop.getStatementFrom(statement); } else if (statement.equals("}")) { // Does nothing return new Statement(); } else { throw new InvalidStatementException(statement + " is not a statement type."); } }
public static Statement getStatementFrom(String statement) throws InvalidStatementException { if (Method.isValid(statement)) { return Method.getStatementFrom(statement); } else if (IfStatement.isValid(statement)) { return IfStatement.getStatementFrom(statement); } else if (ForLoop.isValid(statement)) { return ForLoop.getStatementFrom(statement); } else if (WhileLoop.isValid(statement)) { return WhileLoop.getStatementFrom(statement); } else if (Declaration.isValid(statement)) { return Declaration.getStatementFrom(statement); } else if (statement.equals("}")) { // Does nothing return new Statement(); } else { throw new InvalidStatementException(Method.getMethodName(statement) + " is not a recognized method."); } }
diff --git a/app/models/events/AddCauseEvent.java b/app/models/events/AddCauseEvent.java index 6aafdca..b7e3bdd 100644 --- a/app/models/events/AddCauseEvent.java +++ b/app/models/events/AddCauseEvent.java @@ -1,47 +1,47 @@ /* * Copyright (C) 2011 by Eero Laukkanen, Risto Virtanen, Jussi Patana, Juha Viljanen, * Joona Koistinen, Pekka Rihtniemi, Mika Kekäle, Roope Hovi, Mikko Valjus, * Timo Lehtinen, Jaakko Harjuhahto * * 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 models.events; import models.Cause; public class AddCauseEvent extends Event { public final String text; public final String causeFrom; public final String causeTo; public final String creatorId; public AddCauseEvent(Cause cause, String causeFrom) { super("addcauseevent"); this.causeTo = Long.toString(cause.id); - this.text = cause.name.replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("&", "&amp;"); + this.text = cause.name.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;"); this.causeFrom = causeFrom; this.creatorId = cause.creatorId == null ? null : Long.toString(cause.creatorId); } }
true
true
public AddCauseEvent(Cause cause, String causeFrom) { super("addcauseevent"); this.causeTo = Long.toString(cause.id); this.text = cause.name.replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("&", "&amp;"); this.causeFrom = causeFrom; this.creatorId = cause.creatorId == null ? null : Long.toString(cause.creatorId); }
public AddCauseEvent(Cause cause, String causeFrom) { super("addcauseevent"); this.causeTo = Long.toString(cause.id); this.text = cause.name.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;"); this.causeFrom = causeFrom; this.creatorId = cause.creatorId == null ? null : Long.toString(cause.creatorId); }
diff --git a/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java index 02508508d..ca13748b4 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/LinkActionExposer.java @@ -1,130 +1,130 @@ /** * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.core; import java.util.ArrayList; import java.util.List; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.text.Spannable; import android.text.TextUtils; import android.text.style.URLSpan; import android.text.util.Linkify; import com.timsu.astrid.R; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.api.TaskAction; import com.todoroo.astrid.api.TaskDecoration; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.files.FileMetadata; import com.todoroo.astrid.files.FilesAction; import com.todoroo.astrid.notes.NotesAction; /** * Exposes {@link TaskDecoration} for phone numbers, emails, urls, etc * * @author Tim Su <[email protected]> * */ public class LinkActionExposer { private PackageManager pm; public List<TaskAction> getActionsForTask(Context context, long taskId) { List<TaskAction> result = new ArrayList<TaskAction>(); if(taskId == -1) return result; Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.TITLE, Task.NOTES); if (task == null) return result; String notes = task.getValue(Task.NOTES); Spannable titleSpan = Spannable.Factory.getInstance().newSpannable(task.getValue(Task.TITLE)); Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); - boolean hasAttachments = false; + boolean hasAttachments = FileMetadata.taskHasAttachments(taskId); if(urlSpans.length == 0 && TextUtils.isEmpty(notes) && - !(hasAttachments = FileMetadata.taskHasAttachments(taskId))) + !hasAttachments) return result; pm = context.getPackageManager(); for(URLSpan urlSpan : urlSpans) { String url = urlSpan.getURL(); int start = titleSpan.getSpanStart(urlSpan); int end = titleSpan.getSpanEnd(urlSpan); String text = titleSpan.subSequence(start, end).toString(); TaskAction taskAction = createLinkAction(context, taskId, url, text); if (taskAction != null) result.add(taskAction); } Resources r = context.getResources(); if (hasAttachments) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_attachments)).getBitmap(); FilesAction filesAction = new FilesAction("", null, icon); //$NON-NLS-1$ result.add(filesAction); } if (!TextUtils.isEmpty(notes) && !Preferences.getBoolean(R.string.p_showNotes, false)) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_notes)).getBitmap(); NotesAction notesAction = new NotesAction("", null, icon); //$NON-NLS-1$ result.add(notesAction); } return result; } @SuppressWarnings("nls") private TaskAction createLinkAction(Context context, long id, String url, String text) { Intent itemIntent = new Intent(Intent.ACTION_VIEW); itemIntent.setData(Uri.parse(url)); List<ResolveInfo> resolveInfoList = pm.queryIntentActivities(itemIntent, 0); Intent actionIntent; // if options > 1, display open with... if(resolveInfoList.size() > 1) { actionIntent = Intent.createChooser(itemIntent, text); } // else show app that gets opened else if(resolveInfoList.size() == 1) { actionIntent = itemIntent; } // no intents -> no item else return null; Resources r = context.getResources(); Drawable icon; if (url.startsWith("mailto")) { icon = r.getDrawable(R.drawable.action_mail); } else if (url.startsWith("tel")) { icon = r.getDrawable(R.drawable.action_tel); } else { icon = r.getDrawable(R.drawable.action_web); } Bitmap bitmap = ((BitmapDrawable)icon).getBitmap(); if(text.length() > 15) text = text.substring(0, 12) + "..."; //$NON-NLS-1$ TaskAction action = new TaskAction(text, PendingIntent.getActivity(context, (int)id, actionIntent, 0), bitmap); return action; } }
false
true
public List<TaskAction> getActionsForTask(Context context, long taskId) { List<TaskAction> result = new ArrayList<TaskAction>(); if(taskId == -1) return result; Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.TITLE, Task.NOTES); if (task == null) return result; String notes = task.getValue(Task.NOTES); Spannable titleSpan = Spannable.Factory.getInstance().newSpannable(task.getValue(Task.TITLE)); Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); boolean hasAttachments = false; if(urlSpans.length == 0 && TextUtils.isEmpty(notes) && !(hasAttachments = FileMetadata.taskHasAttachments(taskId))) return result; pm = context.getPackageManager(); for(URLSpan urlSpan : urlSpans) { String url = urlSpan.getURL(); int start = titleSpan.getSpanStart(urlSpan); int end = titleSpan.getSpanEnd(urlSpan); String text = titleSpan.subSequence(start, end).toString(); TaskAction taskAction = createLinkAction(context, taskId, url, text); if (taskAction != null) result.add(taskAction); } Resources r = context.getResources(); if (hasAttachments) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_attachments)).getBitmap(); FilesAction filesAction = new FilesAction("", null, icon); //$NON-NLS-1$ result.add(filesAction); } if (!TextUtils.isEmpty(notes) && !Preferences.getBoolean(R.string.p_showNotes, false)) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_notes)).getBitmap(); NotesAction notesAction = new NotesAction("", null, icon); //$NON-NLS-1$ result.add(notesAction); } return result; }
public List<TaskAction> getActionsForTask(Context context, long taskId) { List<TaskAction> result = new ArrayList<TaskAction>(); if(taskId == -1) return result; Task task = PluginServices.getTaskService().fetchById(taskId, Task.ID, Task.TITLE, Task.NOTES); if (task == null) return result; String notes = task.getValue(Task.NOTES); Spannable titleSpan = Spannable.Factory.getInstance().newSpannable(task.getValue(Task.TITLE)); Linkify.addLinks(titleSpan, Linkify.ALL); URLSpan[] urlSpans = titleSpan.getSpans(0, titleSpan.length(), URLSpan.class); boolean hasAttachments = FileMetadata.taskHasAttachments(taskId); if(urlSpans.length == 0 && TextUtils.isEmpty(notes) && !hasAttachments) return result; pm = context.getPackageManager(); for(URLSpan urlSpan : urlSpans) { String url = urlSpan.getURL(); int start = titleSpan.getSpanStart(urlSpan); int end = titleSpan.getSpanEnd(urlSpan); String text = titleSpan.subSequence(start, end).toString(); TaskAction taskAction = createLinkAction(context, taskId, url, text); if (taskAction != null) result.add(taskAction); } Resources r = context.getResources(); if (hasAttachments) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_attachments)).getBitmap(); FilesAction filesAction = new FilesAction("", null, icon); //$NON-NLS-1$ result.add(filesAction); } if (!TextUtils.isEmpty(notes) && !Preferences.getBoolean(R.string.p_showNotes, false)) { Bitmap icon = ((BitmapDrawable) r.getDrawable(R.drawable.action_notes)).getBitmap(); NotesAction notesAction = new NotesAction("", null, icon); //$NON-NLS-1$ result.add(notesAction); } return result; }
diff --git a/src/main/java/de/cismet/cids/custom/treeicons/wunda_blau/Alb_baulastIconFactory.java b/src/main/java/de/cismet/cids/custom/treeicons/wunda_blau/Alb_baulastIconFactory.java index 2336c86c..75240631 100644 --- a/src/main/java/de/cismet/cids/custom/treeicons/wunda_blau/Alb_baulastIconFactory.java +++ b/src/main/java/de/cismet/cids/custom/treeicons/wunda_blau/Alb_baulastIconFactory.java @@ -1,210 +1,227 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.cismet.cids.custom.treeicons.wunda_blau; import Sirius.navigator.types.treenode.ClassTreeNode; import Sirius.navigator.types.treenode.ObjectTreeNode; import Sirius.navigator.types.treenode.PureTreeNode; import Sirius.navigator.ui.ComponentRegistry; import Sirius.navigator.ui.tree.CidsTreeObjectIconFactory; import Sirius.server.middleware.types.MetaObject; import java.util.HashSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.tree.DefaultTreeModel; import de.cismet.cids.dynamics.CidsBean; import de.cismet.tools.gui.Static2DTools; /** * DOCUMENT ME! * * @author srichter * @version $Revision$, $Date$ */ public class Alb_baulastIconFactory implements CidsTreeObjectIconFactory { //~ Static fields/initializers --------------------------------------------- private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Alb_baulastIconFactory.class); private static ImageIcon fallback = new ImageIcon(Alb_baulastIconFactory.class.getResource( "/res/16/BaulastGrau.png")); //~ Instance fields -------------------------------------------------------- volatile javax.swing.SwingWorker<Void, Void> objectRetrievingWorker = null; final HashSet<ObjectTreeNode> listOfRetrievingObjectWorkers = new HashSet<ObjectTreeNode>(); private ExecutorService objectRetrievalExecutor = Executors.newFixedThreadPool(15); private final ImageIcon DELETED_ICON; private final ImageIcon CLOSED_ICON; private final ImageIcon WARNING_ICON; private final Object objectRetrievingLock = new Object(); //~ Constructors ----------------------------------------------------------- /** * Creates a new Alb_baulastIconFactory object. */ public Alb_baulastIconFactory() { DELETED_ICON = new ImageIcon(getClass().getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/edit-delete.png")); CLOSED_ICON = new ImageIcon(getClass().getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/encrypted.png")); WARNING_ICON = new ImageIcon(getClass().getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/dialog-warning.png")); } //~ Methods ---------------------------------------------------------------- @Override public Icon getClosedPureNodeIcon(final PureTreeNode ptn) { return null; } @Override public Icon getOpenPureNodeIcon(final PureTreeNode ptn) { return null; } @Override public Icon getLeafPureNodeIcon(final PureTreeNode ptn) { return null; } @Override public Icon getOpenObjectNodeIcon(final ObjectTreeNode otn) { return generateIconFromState(otn); } @Override public Icon getClosedObjectNodeIcon(final ObjectTreeNode otn) { return generateIconFromState(otn); } @Override public Icon getLeafObjectNodeIcon(final ObjectTreeNode otn) { return generateIconFromState(otn); } @Override public Icon getClassNodeIcon(final ClassTreeNode dmtn) { return null; } /** * DOCUMENT ME! * * @param node DOCUMENT ME! * * @return DOCUMENT ME! */ private Icon generateIconFromState(final ObjectTreeNode node) { Icon result = null; if (node != null) { final MetaObject baulastMO = node.getMetaObject(false); if (baulastMO != null) { final CidsBean baulastBean = baulastMO.getBean(); result = node.getLeafIcon(); if (!checkIfBaulastBeansIsComplete(baulastBean)) { final Icon overlay = Static2DTools.createOverlayIcon( WARNING_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(WARNING_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, WARNING_ICON}); } else { if (baulastBean.getProperty("loeschungsdatum") != null) { final Icon overlay = Static2DTools.createOverlayIcon( DELETED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(DELETED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, DELETED_ICON}); } else if (baulastBean.getProperty("geschlossen_am") != null) { final Icon overlay = Static2DTools.createOverlayIcon( CLOSED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(CLOSED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, CLOSED_ICON}); } } return result; } else { if (!listOfRetrievingObjectWorkers.contains(node)) { synchronized (listOfRetrievingObjectWorkers) { if (!listOfRetrievingObjectWorkers.contains(node)) { listOfRetrievingObjectWorkers.add(node); objectRetrievalExecutor.execute(new javax.swing.SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { - if (!(node == null) - && ComponentRegistry.getRegistry().getSearchResultsTree() - .containsNode( - node.getNode())) { - node.getMetaObject(true); + if (!(node == null)) { + if (node.getPath()[0].equals( + ComponentRegistry.getRegistry().getSearchResultsTree() + .getModel().getRoot())) { + // Searchtree + if (ComponentRegistry.getRegistry().getSearchResultsTree().containsNode( + node.getNode())) { + node.getMetaObject(true); + } + } else { + // normaler Baum + node.getMetaObject(true); + } } return null; } @Override protected void done() { try { synchronized (listOfRetrievingObjectWorkers) { listOfRetrievingObjectWorkers.remove(node); } final Void result = get(); - ((DefaultTreeModel)ComponentRegistry.getRegistry().getSearchResultsTree() - .getModel()).nodeChanged(node); + if (node.getPath()[0].equals( + ComponentRegistry.getRegistry().getSearchResultsTree() + .getModel().getRoot())) { + // Searchtree + ((DefaultTreeModel)ComponentRegistry.getRegistry() + .getSearchResultsTree().getModel()).nodeChanged(node); + } else { + // normaler Baum + ((DefaultTreeModel)ComponentRegistry.getRegistry().getCatalogueTree() + .getModel()).nodeChanged(node); + } } catch (Exception e) { log.error("Fehler beim Laden des MetaObjects", e); } } }); } } } else { // evtl log meldungen } } return fallback; } return null; } /** * Checks whether or not all important attributes of a baulast are filled. * * @param baulastBean DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean checkIfBaulastBeansIsComplete(final CidsBean baulastBean) { return (baulastBean.getProperty("laufende_nummer") != null) && (baulastBean.getProperty("lageplan") != null) && (baulastBean.getProperty("textblatt") != null); } }
false
true
private Icon generateIconFromState(final ObjectTreeNode node) { Icon result = null; if (node != null) { final MetaObject baulastMO = node.getMetaObject(false); if (baulastMO != null) { final CidsBean baulastBean = baulastMO.getBean(); result = node.getLeafIcon(); if (!checkIfBaulastBeansIsComplete(baulastBean)) { final Icon overlay = Static2DTools.createOverlayIcon( WARNING_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(WARNING_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, WARNING_ICON}); } else { if (baulastBean.getProperty("loeschungsdatum") != null) { final Icon overlay = Static2DTools.createOverlayIcon( DELETED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(DELETED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, DELETED_ICON}); } else if (baulastBean.getProperty("geschlossen_am") != null) { final Icon overlay = Static2DTools.createOverlayIcon( CLOSED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(CLOSED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, CLOSED_ICON}); } } return result; } else { if (!listOfRetrievingObjectWorkers.contains(node)) { synchronized (listOfRetrievingObjectWorkers) { if (!listOfRetrievingObjectWorkers.contains(node)) { listOfRetrievingObjectWorkers.add(node); objectRetrievalExecutor.execute(new javax.swing.SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (!(node == null) && ComponentRegistry.getRegistry().getSearchResultsTree() .containsNode( node.getNode())) { node.getMetaObject(true); } return null; } @Override protected void done() { try { synchronized (listOfRetrievingObjectWorkers) { listOfRetrievingObjectWorkers.remove(node); } final Void result = get(); ((DefaultTreeModel)ComponentRegistry.getRegistry().getSearchResultsTree() .getModel()).nodeChanged(node); } catch (Exception e) { log.error("Fehler beim Laden des MetaObjects", e); } } }); } } } else { // evtl log meldungen } } return fallback; } return null; }
private Icon generateIconFromState(final ObjectTreeNode node) { Icon result = null; if (node != null) { final MetaObject baulastMO = node.getMetaObject(false); if (baulastMO != null) { final CidsBean baulastBean = baulastMO.getBean(); result = node.getLeafIcon(); if (!checkIfBaulastBeansIsComplete(baulastBean)) { final Icon overlay = Static2DTools.createOverlayIcon( WARNING_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(WARNING_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, WARNING_ICON}); } else { if (baulastBean.getProperty("loeschungsdatum") != null) { final Icon overlay = Static2DTools.createOverlayIcon( DELETED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(DELETED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, DELETED_ICON}); } else if (baulastBean.getProperty("geschlossen_am") != null) { final Icon overlay = Static2DTools.createOverlayIcon( CLOSED_ICON, result.getIconWidth(), result.getIconHeight()); result = Static2DTools.mergeIcons(result, overlay); // result = overlay; // result = Static2DTools.mergeIcons(result, Static2DTools.createOverlayIcon(CLOSED_ICON, result.getIconWidth(), result.getIconHeight())); // result = Static2DTools.mergeIcons(new Icon[]{result, CLOSED_ICON}); } } return result; } else { if (!listOfRetrievingObjectWorkers.contains(node)) { synchronized (listOfRetrievingObjectWorkers) { if (!listOfRetrievingObjectWorkers.contains(node)) { listOfRetrievingObjectWorkers.add(node); objectRetrievalExecutor.execute(new javax.swing.SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (!(node == null)) { if (node.getPath()[0].equals( ComponentRegistry.getRegistry().getSearchResultsTree() .getModel().getRoot())) { // Searchtree if (ComponentRegistry.getRegistry().getSearchResultsTree().containsNode( node.getNode())) { node.getMetaObject(true); } } else { // normaler Baum node.getMetaObject(true); } } return null; } @Override protected void done() { try { synchronized (listOfRetrievingObjectWorkers) { listOfRetrievingObjectWorkers.remove(node); } final Void result = get(); if (node.getPath()[0].equals( ComponentRegistry.getRegistry().getSearchResultsTree() .getModel().getRoot())) { // Searchtree ((DefaultTreeModel)ComponentRegistry.getRegistry() .getSearchResultsTree().getModel()).nodeChanged(node); } else { // normaler Baum ((DefaultTreeModel)ComponentRegistry.getRegistry().getCatalogueTree() .getModel()).nodeChanged(node); } } catch (Exception e) { log.error("Fehler beim Laden des MetaObjects", e); } } }); } } } else { // evtl log meldungen } } return fallback; } return null; }
diff --git a/src/net/xemnias/client/AnimationList.java b/src/net/xemnias/client/AnimationList.java index f5f2a4a..b29afdc 100644 --- a/src/net/xemnias/client/AnimationList.java +++ b/src/net/xemnias/client/AnimationList.java @@ -1,33 +1,33 @@ package net.xemnias.client; import org.newdawn.slick.Image; public class AnimationList { public static Animation playerStandingRight; public static Animation playerStandingLeft; public static Animation playerRunningRight; public static void init() { playerStandingRight = new Animation(new org.newdawn.slick.SpriteSheet(CommunityGame.loader.getAnimationByName("playerStandingRight.png"), 32,64), 150); playerStandingLeft = new Animation(new org.newdawn.slick.SpriteSheet(CommunityGame.loader.getAnimationByName("playerStandingLeft.png"), 32,64), 150); playerRunningRight = new Animation(playerRrunningRightSprite(), 150); } private static Image[] playerRrunningRightSprite() { Image[] img = new Image[8]; - img[0] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(0, 0, 32, 64); - img[1] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(32, 0, 32, 64); - img[2] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(64, 0, 46, 64); - img[3] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(110, 0, 40, 64); - img[4] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(150, 0, 32, 64); - img[5] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(182, 0, 32, 64); - img[6] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(214, 0, 38, 64); - img[7] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(252, 0, 44, 64); + img[0] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(0, 0, 32, 64); + img[1] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(32, 0, 32, 64); + img[2] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(64, 0, 46, 64); + img[3] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(110, 0, 40, 64); + img[4] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(150, 0, 32, 64); + img[5] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(182, 0, 32, 64); + img[6] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(214, 0, 38, 64); + img[7] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(252, 0, 44, 64); return img; } }
true
true
private static Image[] playerRrunningRightSprite() { Image[] img = new Image[8]; img[0] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(0, 0, 32, 64); img[1] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(32, 0, 32, 64); img[2] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(64, 0, 46, 64); img[3] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(110, 0, 40, 64); img[4] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(150, 0, 32, 64); img[5] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(182, 0, 32, 64); img[6] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(214, 0, 38, 64); img[7] = CommunityGame.loader.getImageByName("playerAnimationRun.png").getSubImage(252, 0, 44, 64); return img; }
private static Image[] playerRrunningRightSprite() { Image[] img = new Image[8]; img[0] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(0, 0, 32, 64); img[1] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(32, 0, 32, 64); img[2] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(64, 0, 46, 64); img[3] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(110, 0, 40, 64); img[4] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(150, 0, 32, 64); img[5] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(182, 0, 32, 64); img[6] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(214, 0, 38, 64); img[7] = CommunityGame.loader.getAnimationByName("playerRunningRight.png").getSubImage(252, 0, 44, 64); return img; }
diff --git a/src/org/jetbrains/plugins/clojure/psi/util/ClojurePsiUtil.java b/src/org/jetbrains/plugins/clojure/psi/util/ClojurePsiUtil.java index 6288f88..b597447 100644 --- a/src/org/jetbrains/plugins/clojure/psi/util/ClojurePsiUtil.java +++ b/src/org/jetbrains/plugins/clojure/psi/util/ClojurePsiUtil.java @@ -1,256 +1,257 @@ /* * Copyright 2009 JetBrains s.r.o. * * 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.jetbrains.plugins.clojure.psi.util; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import org.jetbrains.plugins.clojure.psi.api.ClBraced; import org.jetbrains.plugins.clojure.psi.api.ClList; import org.jetbrains.plugins.clojure.psi.api.ClojureFile; import org.jetbrains.plugins.clojure.psi.api.symbols.ClSymbol; import org.jetbrains.plugins.clojure.psi.ClojurePsiElement; import org.jetbrains.plugins.clojure.psi.impl.ClKeywordImpl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.intellij.openapi.util.Trinity; import com.intellij.util.containers.HashSet; import java.util.ArrayList; import java.util.Set; import java.util.Arrays; /** * @author ilyas * @author <a href="mailto:[email protected]">Ian Phillips</a> */ public class ClojurePsiUtil { public static final String JAVA_LANG = "java.lang"; public static final String CLOJURE_LANG = "clojure.lang"; public static final Set<String> DEFINITION_FROM_NAMES = new HashSet<String>(); static { DEFINITION_FROM_NAMES.addAll(Arrays.asList("fn")); } @Nullable public static ClList findFormByName(ClojurePsiElement container, @NotNull String name) { for (PsiElement element : container.getChildren()) { if (element instanceof ClList) { ClList list = (ClList) element; final ClSymbol first = list.getFirstSymbol(); if (first != null && name.equals(first.getNameString())) { return list; } } } return null; } @Nullable public static ClList findFormByNameSet(ClojurePsiElement container, @NotNull Set<String> names) { for (PsiElement element : container.getChildren()) { if (element instanceof ClList) { ClList list = (ClList) element; final ClSymbol first = list.getFirstSymbol(); if (first != null && names.contains(first.getNameString())) { return list; } } } return null; } public static ClKeywordImpl findNamespaceKeyByName(ClList ns, String keyName) { final ClList list = ns.findFirstChildByClass(ClList.class); if (list == null) return null; for (PsiElement element : list.getChildren()) { if (element instanceof ClKeywordImpl) { ClKeywordImpl key = (ClKeywordImpl) element; if (keyName.equals(key.getText())) { return key; } } } return null; } @Nullable public static PsiElement getNextNonWhiteSpace(PsiElement element) { PsiElement next = element.getNextSibling(); while (next != null && (next instanceof PsiWhiteSpace)) { next = next.getNextSibling(); } return next; } @NotNull public static Trinity<PsiElement, PsiElement, PsiElement> findCommonParentAndLastChildren(@NotNull PsiElement element1, @NotNull PsiElement element2) { if (element1 == element2) return new Trinity<PsiElement, PsiElement, PsiElement>(element1, element1, element1); final PsiFile containingFile = element1.getContainingFile(); final PsiElement topLevel = containingFile == element2.getContainingFile() ? containingFile : null; ArrayList<PsiElement> parents1 = getParents(element1, topLevel); ArrayList<PsiElement> parents2 = getParents(element2, topLevel); int size = Math.min(parents1.size(), parents2.size()); PsiElement parent = topLevel; for (int i = 1; i <= size; i++) { PsiElement parent1 = parents1.get(parents1.size() - i); PsiElement parent2 = parents2.get(parents2.size() - i); if (!parent1.equals(parent2)) { return new Trinity<PsiElement, PsiElement, PsiElement>(parent, parent1, parent2); } parent = parent1; } return new Trinity<PsiElement, PsiElement, PsiElement>(parent, parent, parent); } public static boolean lessThan(PsiElement elem1, PsiElement elem2) { if (elem1.getParent() != elem2.getParent() || elem1 == elem2) { return false; } PsiElement next = elem1; while (next != null && next != elem2) { next = next.getNextSibling(); } return next != null; } @NotNull public static ArrayList<PsiElement> getParents(@NotNull PsiElement element, @Nullable PsiElement topLevel) { ArrayList<PsiElement> parents = new ArrayList<PsiElement>(); PsiElement parent = element; while (parent != topLevel && parent != null) { parents.add(parent); parent = parent.getParent(); } return parents; } private static boolean isParameterSymbol(ClSymbol symbol) { //todo implement me! return false; } private static boolean anyOf(char c, String s) { return s.indexOf(c) != -1; } /** * Find the s-expression at the caret in a given editor. * * @param editor the editor to search in. * @param previous should the s-exp <i>behind</i> the caret be returned (rather than <i>around</i> the caret). * @return the s-expression, or {@code null} if none could be found. */ public static @Nullable ClBraced findSexpAtCaret(@NotNull Editor editor, boolean previous) { Project project = editor.getProject(); if (project == null) { return null; } VirtualFile vfile = FileDocumentManager.getInstance().getFile(editor.getDocument()); if (vfile == null) return null; PsiFile file = PsiManager.getInstance(project).findFile(vfile); if (file == null) { return null; } CharSequence chars = editor.getDocument().getCharsSequence(); int offset = editor.getCaretModel().getOffset(); if (previous) { + if (offset == chars.length()) --offset; // we want the offset positioned at the last character, not at EOF while (offset != 0 && offset < chars.length() && !anyOf(chars.charAt(offset), "]})")) { --offset; } } if (offset == 0) { return null; } PsiElement element = file.findElementAt(offset); while (element != null && !(element instanceof ClBraced)) { element = element.getParent(); } return (ClBraced) element; } /** * Find the top most s-expression around the caret. * * @param editor the editor to search in. * @return the s-expression, or {@code null} if not currently inside one. */ public static @Nullable ClList findTopSexpAroundCaret(@NotNull Editor editor) { Project project = editor.getProject(); if (project == null) { return null; } Document document = editor.getDocument(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) { return null; } PsiElement element = file.findElementAt(editor.getCaretModel().getOffset()); ClList sexp = null; while (element != null) { if (element instanceof ClList) { sexp = (ClList) element; } element = element.getParent(); } return sexp; } public static PsiElement firstChildSexp(PsiElement element) { PsiElement[] children = element.getChildren(); return children.length != 0 ? children[0] : null; } public static PsiElement lastChildSexp(PsiElement element) { PsiElement[] children = element.getChildren(); return children[children.length - 1]; } public static boolean isValidClojureExpression(String text, @NotNull Project project) { if (text == null) return false; text = text.trim(); final ClojurePsiFactory factory = ClojurePsiFactory.getInstance(project); final ClojureFile file = factory.createClojureFileFromText(text); final PsiElement[] children = file.getChildren(); if (children.length == 0) return false; for (PsiElement child : children) { if (containsSyntaxErrors(child)) { return false; } } return true; } private static boolean containsSyntaxErrors(PsiElement elem) { if (elem instanceof PsiErrorElement) { return true; } for (PsiElement child : elem.getChildren()) { if (containsSyntaxErrors(child)) return true; } return false; } public static boolean isStrictlyBefore(PsiElement e1, PsiElement e2) { final Trinity<PsiElement, PsiElement, PsiElement> result = findCommonParentAndLastChildren(e1, e2); return result.second.getTextRange().getStartOffset() < result.third.getTextRange().getStartOffset(); } }
true
true
public static @Nullable ClBraced findSexpAtCaret(@NotNull Editor editor, boolean previous) { Project project = editor.getProject(); if (project == null) { return null; } VirtualFile vfile = FileDocumentManager.getInstance().getFile(editor.getDocument()); if (vfile == null) return null; PsiFile file = PsiManager.getInstance(project).findFile(vfile); if (file == null) { return null; } CharSequence chars = editor.getDocument().getCharsSequence(); int offset = editor.getCaretModel().getOffset(); if (previous) { while (offset != 0 && offset < chars.length() && !anyOf(chars.charAt(offset), "]})")) { --offset; } } if (offset == 0) { return null; } PsiElement element = file.findElementAt(offset); while (element != null && !(element instanceof ClBraced)) { element = element.getParent(); } return (ClBraced) element; }
public static @Nullable ClBraced findSexpAtCaret(@NotNull Editor editor, boolean previous) { Project project = editor.getProject(); if (project == null) { return null; } VirtualFile vfile = FileDocumentManager.getInstance().getFile(editor.getDocument()); if (vfile == null) return null; PsiFile file = PsiManager.getInstance(project).findFile(vfile); if (file == null) { return null; } CharSequence chars = editor.getDocument().getCharsSequence(); int offset = editor.getCaretModel().getOffset(); if (previous) { if (offset == chars.length()) --offset; // we want the offset positioned at the last character, not at EOF while (offset != 0 && offset < chars.length() && !anyOf(chars.charAt(offset), "]})")) { --offset; } } if (offset == 0) { return null; } PsiElement element = file.findElementAt(offset); while (element != null && !(element instanceof ClBraced)) { element = element.getParent(); } return (ClBraced) element; }
diff --git a/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/TargetPage.java b/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/TargetPage.java index 2e3cfe856..b0fa710b0 100644 --- a/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/TargetPage.java +++ b/update/org.eclipse.update.ui/src/org/eclipse/update/internal/ui/wizards/TargetPage.java @@ -1,559 +1,559 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.update.internal.ui.wizards; import java.io.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.resource.*; import org.eclipse.jface.viewers.*; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.help.*; import org.eclipse.update.configuration.*; import org.eclipse.update.core.*; import org.eclipse.update.internal.operations.*; import org.eclipse.update.internal.ui.*; import org.eclipse.update.internal.ui.parts.*; import org.eclipse.update.operations.*; public class TargetPage extends BannerPage implements IDynamicPage { private TableViewer jobViewer; private TableViewer siteViewer; private IInstallConfiguration config; private ConfigListener configListener; private Label requiredSpaceLabel; private Label availableSpaceLabel; private IInstallFeatureOperation[] jobs; private Button addButton; private Button deleteButton; private HashSet added; class JobsContentProvider extends DefaultContentProvider implements IStructuredContentProvider { public Object[] getElements(Object parent) { return jobs; } } class SitesContentProvider extends DefaultContentProvider implements IStructuredContentProvider { public Object[] getElements(Object parent) { return config.getConfiguredSites(); } } class JobsLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object obj, int col) { UpdateLabelProvider provider = UpdateUI.getDefault().getLabelProvider(); IInstallFeatureOperation job = (IInstallFeatureOperation) obj; ImageDescriptor base = job.getFeature().isPatch() ? UpdateUIImages.DESC_EFIX_OBJ : UpdateUIImages.DESC_FEATURE_OBJ; int flags = 0; if (job.getTargetSite() == null) flags = UpdateLabelProvider.F_ERROR; return provider.get(base, flags); } public String getColumnText(Object obj, int col) { if (col == 0) { IFeature feature = ((IInstallFeatureOperation) obj).getFeature(); return feature.getLabel() + " " //$NON-NLS-1$ + feature.getVersionedIdentifier().getVersion().toString(); } return null; } } class SitesLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object obj, int col) { UpdateLabelProvider provider = UpdateUI.getDefault().getLabelProvider(); return provider.getLocalSiteImage((IConfiguredSite) obj); } public String getColumnText(Object obj, int col) { if (col == 0) { ISite site = ((IConfiguredSite) obj).getSite(); return new File(site.getURL().getFile()).toString(); } return null; } } class ConfigListener implements IInstallConfigurationChangedListener { public void installSiteAdded(IConfiguredSite csite) { siteViewer.add(csite); if (added == null) added = new HashSet(); added.add(csite); // set the site as target for all jobs without a target for (int i=0; jobs != null && i<jobs.length; i++) if (jobs[i].getTargetSite() == null && getSiteVisibility(csite, jobs[i])) { jobs[i].setTargetSite(csite); } jobViewer.refresh(); siteViewer.setSelection(new StructuredSelection(csite)); siteViewer.getControl().setFocus(); } public void installSiteRemoved(IConfiguredSite csite) { siteViewer.remove(csite); if (added != null) added.remove(csite); // remove the target site for all jobs that use it // set the site as target for all jobs without a target boolean refreshJobs = false; for (int i=0; jobs != null && i<jobs.length; i++) if (jobs[i].getTargetSite() == csite) { jobs[i].setTargetSite(null); refreshJobs = true; } pageChanged(); jobViewer.refresh(); if (refreshJobs) { jobViewer.getControl().setFocus(); } else siteViewer.getControl().setFocus(); } } /** * Constructor for ReviewPage2 */ public TargetPage(IInstallConfiguration config) { super("Target"); //$NON-NLS-1$ setTitle(UpdateUI.getString("InstallWizard.TargetPage.title")); //$NON-NLS-1$ setDescription(UpdateUI.getString("InstallWizard.TargetPage.desc")); //$NON-NLS-1$ this.config = config; UpdateUI.getDefault().getLabelProvider().connect(this); configListener = new ConfigListener(); } public void setJobs(IInstallFeatureOperation[] jobs) { this.jobs = jobs; } public void dispose() { UpdateUI.getDefault().getLabelProvider().disconnect(this); config.removeInstallConfigurationChangedListener(configListener); super.dispose(); } public Control createContents(Composite parent) { Composite client = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.marginWidth = layout.marginHeight = 0; client.setLayout(layout); client.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite leftPanel = new Composite(client, SWT.NULL); GridLayout leftLayout = new GridLayout(); leftLayout.numColumns = 1; leftLayout.marginWidth = leftLayout.marginHeight = 0; leftPanel.setLayout(leftLayout); leftPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); Label label = new Label(leftPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.jobsLabel")); //$NON-NLS-1$ createJobViewer(leftPanel); Composite centerPanel = new Composite(client, SWT.NULL); GridLayout centerLayout = new GridLayout(); centerLayout.numColumns = 1; centerLayout.marginWidth = centerLayout.marginHeight = 0; centerPanel.setLayout(centerLayout); centerPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); label = new Label(centerPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.siteLabel")); //$NON-NLS-1$ createSiteViewer(centerPanel); Composite rightPanel = new Composite(client, SWT.NULL); GridLayout rightLayout = new GridLayout(); rightLayout.numColumns = 1; rightLayout.marginWidth = rightLayout.marginHeight = 0; rightPanel.setLayout(rightLayout); rightPanel.setLayoutData(new GridData(GridData.FILL_VERTICAL)); new Label(rightPanel, SWT.NULL); Composite buttonContainer = new Composite(rightPanel, SWT.NULL); GridLayout blayout = new GridLayout(); blayout.marginWidth = blayout.marginHeight = 0; buttonContainer.setLayout(blayout); buttonContainer.setLayoutData(new GridData(GridData.FILL_VERTICAL)); addButton = new Button(buttonContainer, SWT.PUSH); addButton.setText(UpdateUI.getString("InstallWizard.TargetPage.new")); //$NON-NLS-1$ addButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addTargetLocation(); } }); addButton.setEnabled(false); - addButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); + addButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); SWTUtil.setButtonDimensionHint(addButton); deleteButton = new Button(buttonContainer, SWT.PUSH); deleteButton.setText(UpdateUI.getString("InstallWizard.TargetPage.delete")); //$NON-NLS-1$ deleteButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { removeSelection(); } catch (CoreException ex) { UpdateUI.logException(ex); } } }); deleteButton.setEnabled(false); - deleteButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); + deleteButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); SWTUtil.setButtonDimensionHint(deleteButton); Composite status = new Composite(client, SWT.NULL); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan = 3; status.setLayoutData(gd); layout = new GridLayout(); layout.numColumns = 2; status.setLayout(layout); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.requiredSpace")); //$NON-NLS-1$ requiredSpaceLabel = new Label(status, SWT.NULL); requiredSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.availableSpace")); //$NON-NLS-1$ availableSpaceLabel = new Label(status, SWT.NULL); availableSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); WorkbenchHelp.setHelp(client, "org.eclipse.update.ui.MultiTargetPage2"); //$NON-NLS-1$ Dialog.applyDialogFont(parent); return client; } private void createJobViewer(Composite parent) { jobViewer = new TableViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); GridData gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 150; jobViewer.getTable().setLayoutData(gd); jobViewer.setContentProvider(new JobsContentProvider()); jobViewer.setLabelProvider(new JobsLabelProvider()); jobViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); IInstallFeatureOperation job = (IInstallFeatureOperation) selection.getFirstElement(); if (job != null) { siteViewer.setInput(job); //IConfiguredSite affinitySite = UpdateUtils.getAffinitySite(config, job.getFeature()); IConfiguredSite affinitySite = UpdateUtils.getDefaultTargetSite(config, job, true); addButton.setEnabled(affinitySite == null); if (job.getTargetSite() != null) { siteViewer.setSelection(new StructuredSelection(job.getTargetSite())); } } } }); } private void createSiteViewer(Composite parent) { siteViewer = new TableViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); GridData gd = new GridData(GridData.FILL_BOTH); gd.widthHint = 200; siteViewer.getTable().setLayoutData(gd); siteViewer.setContentProvider(new SitesContentProvider()); siteViewer.setLabelProvider(new SitesLabelProvider()); siteViewer.addFilter(new ViewerFilter() { public boolean select(Viewer v, Object parent, Object obj) { IInstallFeatureOperation job = (IInstallFeatureOperation) siteViewer.getInput(); return getSiteVisibility((IConfiguredSite) obj, job); } }); siteViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection ssel = (IStructuredSelection) event.getSelection(); selectTargetSite(ssel); jobViewer.refresh(); updateDeleteButton(ssel); } }); if (config != null) config.addInstallConfigurationChangedListener(configListener); } private void updateDeleteButton(IStructuredSelection selection) { boolean enable = added != null && !added.isEmpty(); if (enable) { for (Iterator iter = selection.iterator(); iter.hasNext();) { if (!added.contains(iter.next())) { enable = false; break; } } } deleteButton.setEnabled(enable); } public void setVisible(boolean visible) { if (visible) { initializeDefaultTargetSites(); jobViewer.setInput(jobs); if (jobViewer.getSelection().isEmpty() && jobs.length > 0) jobViewer.setSelection(new StructuredSelection(jobs[0])); } super.setVisible(visible); } private void verifyNotEmpty(boolean empty) { String errorMessage = null; if (empty) errorMessage = UpdateUI.getString("InstallWizard.TargetPage.location.empty"); //$NON-NLS-1$ setErrorMessage(errorMessage); setPageComplete(!empty); } private void selectTargetSite(IStructuredSelection selection) { IConfiguredSite site = (IConfiguredSite) selection.getFirstElement(); IInstallFeatureOperation job = (IInstallFeatureOperation) siteViewer.getInput(); if (job != null) { if (site != null) job.setTargetSite(site); pageChanged(); } updateStatus(site); } private void addTargetLocation() { DirectoryDialog dd = new DirectoryDialog(getContainer().getShell()); dd.setMessage(UpdateUI.getString("InstallWizard.TargetPage.location.message")); //$NON-NLS-1$ String path = dd.open(); if (path != null) { addConfiguredSite(getContainer().getShell(), config, new File(path)); } } private void removeSelection() throws CoreException { IStructuredSelection selection = (IStructuredSelection) siteViewer.getSelection(); for (Iterator iter = selection.iterator(); iter.hasNext();) { IConfiguredSite targetSite = (IConfiguredSite) iter.next(); config.removeConfiguredSite(targetSite); } } private IConfiguredSite addConfiguredSite( Shell shell, IInstallConfiguration config, File file) { try { IConfiguredSite csite = config.createConfiguredSite(file); IStatus status = csite.verifyUpdatableStatus(); if (status.isOK()) config.addConfiguredSite(csite); else throw new CoreException(status); return csite; } catch (CoreException e) { String title = UpdateUI.getString("InstallWizard.TargetPage.location.error.title"); //$NON-NLS-1$ ErrorDialog.openError(shell, title, null, e.getStatus()); UpdateUI.logException(e,false); return null; } } private void updateStatus(Object element) { if (element == null) { requiredSpaceLabel.setText(""); //$NON-NLS-1$ availableSpaceLabel.setText(""); //$NON-NLS-1$ return; } IConfiguredSite site = (IConfiguredSite) element; File file = new File(site.getSite().getURL().getFile()); long available = LocalSystemInfo.getFreeSpace(file); long required = computeRequiredSizeFor(site); if (required == -1) requiredSpaceLabel.setText(UpdateUI.getString("InstallWizard.TargetPage.unknownSize")); //$NON-NLS-1$ else requiredSpaceLabel.setText( UpdateUI.getFormattedMessage("InstallWizard.TargetPage.size", "" + required)); //$NON-NLS-1$ //$NON-NLS-2$ if (available == LocalSystemInfo.SIZE_UNKNOWN) availableSpaceLabel.setText(UpdateUI.getString("InstallWizard.TargetPage.unknownSize")); //$NON-NLS-1$ else availableSpaceLabel.setText( UpdateUI.getFormattedMessage("InstallWizard.TargetPage.size", "" + available)); //$NON-NLS-1$ //$NON-NLS-2$ } private long computeRequiredSizeFor(IConfiguredSite site) { long totalSize = 0; for (int i = 0; i < jobs.length; i++) { if (site.equals(jobs[i].getTargetSite())) { long jobSize = site.getSite().getInstallSizeFor(jobs[i].getFeature()); if (jobSize == -1) return -1; totalSize += jobSize; } } return totalSize; } private void pageChanged() { boolean empty = false; for (int i=0; jobs!=null && i<jobs.length; i++) { if (jobs[i].getTargetSite() == null) { empty = true; break; } IFeature feature = jobs[i].getFeature(); if (feature.isPatch()) { // Patches must go together with the features // they are patching. // Check current jobs IInstallFeatureOperation patchedFeatureJob = findPatchedFeature(feature); if (patchedFeatureJob != null && patchedFeatureJob.getTargetSite() != null && !jobs[i].getTargetSite().equals(patchedFeatureJob.getTargetSite())) { String msg = UpdateUI.getFormattedMessage( "InstallWizard.TargetPage.patchError", //$NON-NLS-1$ new String[] { feature.getLabel(), patchedFeatureJob.getFeature().getLabel()}); setErrorMessage(msg); setPageComplete(false); return; } // Check installed features IFeature patchedFeature = UpdateUtils.getPatchedFeature(feature); if (patchedFeature != null && !jobs[i].getTargetSite().equals(patchedFeature.getSite().getCurrentConfiguredSite())) { String msg = UpdateUI.getFormattedMessage( "InstallWizard.TargetPage.patchError2", //$NON-NLS-1$ new String[] { feature.getLabel(), patchedFeature.getLabel(), patchedFeature.getSite().getCurrentConfiguredSite().getSite().getURL().getFile()}); setErrorMessage(msg); setPageComplete(false); return; } } } verifyNotEmpty(empty); } void removeAddedSites() { if (added != null) { while (!added.isEmpty()) { Iterator it = added.iterator(); if (it.hasNext()) config.removeConfiguredSite((IConfiguredSite) it.next()); } } } private boolean getSiteVisibility(IConfiguredSite site, IInstallFeatureOperation job) { // Do not allow installing into a non-updateable site if (!site.isUpdatable()) return false; // If affinity site is known, only it should be shown IConfiguredSite affinitySite = UpdateUtils.getAffinitySite(config, job.getFeature()); if (affinitySite != null) { // Must compare referenced sites because // configured sites themselves may come from // different configurations return site.getSite().equals(affinitySite.getSite()); } // Co-locate updates with the old feature if (job.getOldFeature() != null) { IConfiguredSite oldSite = UpdateUtils.getSiteWithFeature(config, job.getOldFeature().getVersionedIdentifier().getIdentifier()); return (site == oldSite); } // Allow installing into any site that is updateable and there is no affinity specified return true; } private void initializeDefaultTargetSites() { for (int i = 0; i < jobs.length; i++) { if (jobs[i].getTargetSite() != null) continue; IConfiguredSite affinitySite = UpdateUtils.getAffinitySite(config, jobs[i].getFeature()); if (affinitySite != null) { jobs[i].setTargetSite(affinitySite); continue; } IConfiguredSite defaultSite = UpdateUtils.getDefaultTargetSite(config, jobs[i], false); if (defaultSite != null) { jobs[i].setTargetSite(defaultSite); continue; } jobs[i].setTargetSite(getFirstTargetSite(jobs[i])); } } private IConfiguredSite getFirstTargetSite(IInstallFeatureOperation job) { IConfiguredSite[] sites = config.getConfiguredSites(); for (int i = 0; i < sites.length; i++) { IConfiguredSite csite = sites[i]; if (getSiteVisibility(csite, job)) return csite; } return null; } public IInstallFeatureOperation findPatchedFeature(IFeature patch) { for (int i=0; i<jobs.length; i++) { IFeature target = jobs[i].getFeature(); if (!target.equals(patch) && UpdateUtils.isPatch(target, patch)) return jobs[i]; } return null; } }
false
true
public Control createContents(Composite parent) { Composite client = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.marginWidth = layout.marginHeight = 0; client.setLayout(layout); client.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite leftPanel = new Composite(client, SWT.NULL); GridLayout leftLayout = new GridLayout(); leftLayout.numColumns = 1; leftLayout.marginWidth = leftLayout.marginHeight = 0; leftPanel.setLayout(leftLayout); leftPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); Label label = new Label(leftPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.jobsLabel")); //$NON-NLS-1$ createJobViewer(leftPanel); Composite centerPanel = new Composite(client, SWT.NULL); GridLayout centerLayout = new GridLayout(); centerLayout.numColumns = 1; centerLayout.marginWidth = centerLayout.marginHeight = 0; centerPanel.setLayout(centerLayout); centerPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); label = new Label(centerPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.siteLabel")); //$NON-NLS-1$ createSiteViewer(centerPanel); Composite rightPanel = new Composite(client, SWT.NULL); GridLayout rightLayout = new GridLayout(); rightLayout.numColumns = 1; rightLayout.marginWidth = rightLayout.marginHeight = 0; rightPanel.setLayout(rightLayout); rightPanel.setLayoutData(new GridData(GridData.FILL_VERTICAL)); new Label(rightPanel, SWT.NULL); Composite buttonContainer = new Composite(rightPanel, SWT.NULL); GridLayout blayout = new GridLayout(); blayout.marginWidth = blayout.marginHeight = 0; buttonContainer.setLayout(blayout); buttonContainer.setLayoutData(new GridData(GridData.FILL_VERTICAL)); addButton = new Button(buttonContainer, SWT.PUSH); addButton.setText(UpdateUI.getString("InstallWizard.TargetPage.new")); //$NON-NLS-1$ addButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addTargetLocation(); } }); addButton.setEnabled(false); addButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); SWTUtil.setButtonDimensionHint(addButton); deleteButton = new Button(buttonContainer, SWT.PUSH); deleteButton.setText(UpdateUI.getString("InstallWizard.TargetPage.delete")); //$NON-NLS-1$ deleteButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { removeSelection(); } catch (CoreException ex) { UpdateUI.logException(ex); } } }); deleteButton.setEnabled(false); deleteButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); SWTUtil.setButtonDimensionHint(deleteButton); Composite status = new Composite(client, SWT.NULL); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan = 3; status.setLayoutData(gd); layout = new GridLayout(); layout.numColumns = 2; status.setLayout(layout); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.requiredSpace")); //$NON-NLS-1$ requiredSpaceLabel = new Label(status, SWT.NULL); requiredSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.availableSpace")); //$NON-NLS-1$ availableSpaceLabel = new Label(status, SWT.NULL); availableSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); WorkbenchHelp.setHelp(client, "org.eclipse.update.ui.MultiTargetPage2"); //$NON-NLS-1$ Dialog.applyDialogFont(parent); return client; }
public Control createContents(Composite parent) { Composite client = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.marginWidth = layout.marginHeight = 0; client.setLayout(layout); client.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite leftPanel = new Composite(client, SWT.NULL); GridLayout leftLayout = new GridLayout(); leftLayout.numColumns = 1; leftLayout.marginWidth = leftLayout.marginHeight = 0; leftPanel.setLayout(leftLayout); leftPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); Label label = new Label(leftPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.jobsLabel")); //$NON-NLS-1$ createJobViewer(leftPanel); Composite centerPanel = new Composite(client, SWT.NULL); GridLayout centerLayout = new GridLayout(); centerLayout.numColumns = 1; centerLayout.marginWidth = centerLayout.marginHeight = 0; centerPanel.setLayout(centerLayout); centerPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); label = new Label(centerPanel, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.siteLabel")); //$NON-NLS-1$ createSiteViewer(centerPanel); Composite rightPanel = new Composite(client, SWT.NULL); GridLayout rightLayout = new GridLayout(); rightLayout.numColumns = 1; rightLayout.marginWidth = rightLayout.marginHeight = 0; rightPanel.setLayout(rightLayout); rightPanel.setLayoutData(new GridData(GridData.FILL_VERTICAL)); new Label(rightPanel, SWT.NULL); Composite buttonContainer = new Composite(rightPanel, SWT.NULL); GridLayout blayout = new GridLayout(); blayout.marginWidth = blayout.marginHeight = 0; buttonContainer.setLayout(blayout); buttonContainer.setLayoutData(new GridData(GridData.FILL_VERTICAL)); addButton = new Button(buttonContainer, SWT.PUSH); addButton.setText(UpdateUI.getString("InstallWizard.TargetPage.new")); //$NON-NLS-1$ addButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addTargetLocation(); } }); addButton.setEnabled(false); addButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); SWTUtil.setButtonDimensionHint(addButton); deleteButton = new Button(buttonContainer, SWT.PUSH); deleteButton.setText(UpdateUI.getString("InstallWizard.TargetPage.delete")); //$NON-NLS-1$ deleteButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { removeSelection(); } catch (CoreException ex) { UpdateUI.logException(ex); } } }); deleteButton.setEnabled(false); deleteButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); SWTUtil.setButtonDimensionHint(deleteButton); Composite status = new Composite(client, SWT.NULL); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan = 3; status.setLayoutData(gd); layout = new GridLayout(); layout.numColumns = 2; status.setLayout(layout); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.requiredSpace")); //$NON-NLS-1$ requiredSpaceLabel = new Label(status, SWT.NULL); requiredSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); label = new Label(status, SWT.NULL); label.setText(UpdateUI.getString("InstallWizard.TargetPage.availableSpace")); //$NON-NLS-1$ availableSpaceLabel = new Label(status, SWT.NULL); availableSpaceLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); WorkbenchHelp.setHelp(client, "org.eclipse.update.ui.MultiTargetPage2"); //$NON-NLS-1$ Dialog.applyDialogFont(parent); return client; }
diff --git a/src/cz/krtinec/birthday/dto/BContact.java b/src/cz/krtinec/birthday/dto/BContact.java index 332eafe..2cebb71 100644 --- a/src/cz/krtinec/birthday/dto/BContact.java +++ b/src/cz/krtinec/birthday/dto/BContact.java @@ -1,86 +1,86 @@ package cz.krtinec.birthday.dto; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public final class BContact extends BContactParent implements Comparable<BContact>{ public static final DateFormat SHORT_FORMAT = new SimpleDateFormat("MMdd"); private static final Calendar TODAY = Calendar.getInstance(); static Calendar tempCalendar = new GregorianCalendar(); private Date bDay; private Integer age; private Integer daysToBirthday; private DateIntegrity integrity; private String bDaySort; private String pivot = SHORT_FORMAT.format(TODAY.getTime()); private boolean nextYear; public BContact(String displayName, long id, Date bDay, String lookupKey, String photoId, DateIntegrity integrity) { super(displayName, id, lookupKey, photoId); this.bDay = bDay; this.integrity = integrity; tempCalendar.setTime(bDay); bDaySort = SHORT_FORMAT.format(this.bDay); nextYear = bDaySort.compareTo(pivot) < 0; if (DateIntegrity.FULL == this.integrity) { age = TODAY.get(Calendar.YEAR) - tempCalendar.get(Calendar.YEAR); - age = nextYear ? age : age + 1; + age = nextYear ? age + 1: age; } else { age = null; } //due to leap years tempCalendar.set(Calendar.YEAR, TODAY.get(Calendar.YEAR)); daysToBirthday = tempCalendar.get(Calendar.DAY_OF_YEAR) - TODAY.get(Calendar.DAY_OF_YEAR); if (nextYear) { daysToBirthday = daysToBirthday + 365; } } public Date getbDay() { return bDay; } public Integer getAge() { return age; } public int getDaysToBirthday() { return daysToBirthday; } @Override public String toString() { return displayName + ":" + bDay.toGMTString(); } @Override public int compareTo(BContact another) { if (this.nextYear && !another.nextYear) { return 1; } else if (!this.nextYear && another.nextYear) { return -1; } int bCompare = this.bDaySort.compareTo(another.bDaySort); if (bCompare == 0) { return this.displayName.compareTo(another.displayName); } else { return bCompare; } } }
true
true
public BContact(String displayName, long id, Date bDay, String lookupKey, String photoId, DateIntegrity integrity) { super(displayName, id, lookupKey, photoId); this.bDay = bDay; this.integrity = integrity; tempCalendar.setTime(bDay); bDaySort = SHORT_FORMAT.format(this.bDay); nextYear = bDaySort.compareTo(pivot) < 0; if (DateIntegrity.FULL == this.integrity) { age = TODAY.get(Calendar.YEAR) - tempCalendar.get(Calendar.YEAR); age = nextYear ? age : age + 1; } else { age = null; } //due to leap years tempCalendar.set(Calendar.YEAR, TODAY.get(Calendar.YEAR)); daysToBirthday = tempCalendar.get(Calendar.DAY_OF_YEAR) - TODAY.get(Calendar.DAY_OF_YEAR); if (nextYear) { daysToBirthday = daysToBirthday + 365; } }
public BContact(String displayName, long id, Date bDay, String lookupKey, String photoId, DateIntegrity integrity) { super(displayName, id, lookupKey, photoId); this.bDay = bDay; this.integrity = integrity; tempCalendar.setTime(bDay); bDaySort = SHORT_FORMAT.format(this.bDay); nextYear = bDaySort.compareTo(pivot) < 0; if (DateIntegrity.FULL == this.integrity) { age = TODAY.get(Calendar.YEAR) - tempCalendar.get(Calendar.YEAR); age = nextYear ? age + 1: age; } else { age = null; } //due to leap years tempCalendar.set(Calendar.YEAR, TODAY.get(Calendar.YEAR)); daysToBirthday = tempCalendar.get(Calendar.DAY_OF_YEAR) - TODAY.get(Calendar.DAY_OF_YEAR); if (nextYear) { daysToBirthday = daysToBirthday + 365; } }
diff --git a/wayback-core/src/main/java/org/archive/wayback/resourceindex/cdxserver/EmbeddedCDXServerIndex.java b/wayback-core/src/main/java/org/archive/wayback/resourceindex/cdxserver/EmbeddedCDXServerIndex.java index 35b552dbe..fd09ffefb 100644 --- a/wayback-core/src/main/java/org/archive/wayback/resourceindex/cdxserver/EmbeddedCDXServerIndex.java +++ b/wayback-core/src/main/java/org/archive/wayback/resourceindex/cdxserver/EmbeddedCDXServerIndex.java @@ -1,446 +1,446 @@ package org.archive.wayback.resourceindex.cdxserver; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.util.URIUtil; import org.archive.cdxserver.CDXQuery; import org.archive.cdxserver.CDXServer; import org.archive.cdxserver.auth.AuthToken; import org.archive.cdxserver.writer.HttpCDXWriter; import org.archive.format.cdx.CDXLine; import org.archive.format.cdx.StandardCDXLineFactory; import org.archive.url.UrlSurtRangeComputer.MatchType; import org.archive.util.binsearch.impl.HTTPSeekableLineReader; import org.archive.util.binsearch.impl.HTTPSeekableLineReader.BadHttpStatusException; import org.archive.util.binsearch.impl.HTTPSeekableLineReaderFactory; import org.archive.util.binsearch.impl.http.ApacheHttp31SLRFactory; import org.archive.wayback.ResourceIndex; import org.archive.wayback.core.CaptureSearchResult; import org.archive.wayback.core.CaptureSearchResults; import org.archive.wayback.core.SearchResults; import org.archive.wayback.core.WaybackRequest; import org.archive.wayback.exception.AccessControlException; import org.archive.wayback.exception.AdministrativeAccessControlException; import org.archive.wayback.exception.BadQueryException; import org.archive.wayback.exception.ResourceIndexNotAvailableException; import org.archive.wayback.exception.ResourceNotInArchiveException; import org.archive.wayback.exception.RobotAccessControlException; import org.archive.wayback.exception.WaybackException; import org.archive.wayback.memento.MementoConstants; import org.archive.wayback.memento.MementoHandler; import org.archive.wayback.memento.MementoUtils; import org.archive.wayback.resourceindex.filters.SelfRedirectFilter; import org.archive.wayback.util.webapp.AbstractRequestHandler; import org.archive.wayback.webapp.PerfStats; import org.json.JSONException; import org.json.JSONObject; import org.springframework.web.bind.ServletRequestBindingException; public class EmbeddedCDXServerIndex extends AbstractRequestHandler implements MementoHandler, ResourceIndex { private static final Logger LOGGER = Logger.getLogger( EmbeddedCDXServerIndex.class.getName()); protected CDXServer cdxServer; protected int timestampDedupLength = 0; protected int limit = 0; private SelfRedirectFilter selfRedirFilter; protected String remoteCdxPath; private HTTPSeekableLineReaderFactory remoteCdxHttp = new ApacheHttp31SLRFactory(); private StandardCDXLineFactory cdxLineFactory = new StandardCDXLineFactory("cdx11"); private String remoteAuthCookie; enum PerfStat { IndexLoad; } // public void init() // { // initAuthCookie(); // } // // protected String initAuthCookie() // { // if (cdxServer == null) { // return; // } // // AuthChecker check = cdxServer.getAuthChecker(); // if (!(check instanceof PrivTokenAuthChecker)) { // return; // } // // List<String> list = ((PrivTokenAuthChecker)check).getAllCdxFieldsAccessTokens(); // // if (list == null || list.isEmpty()) { // return; // } // // return CDXServer.CDX_AUTH_TOKEN + ": " + list.get(0); // } @Override public SearchResults query(WaybackRequest wbRequest) throws ResourceIndexNotAvailableException, ResourceNotInArchiveException, BadQueryException, AccessControlException { try { PerfStats.timeStart(PerfStat.IndexLoad); return doQuery(wbRequest); } finally { PerfStats.timeEnd(PerfStat.IndexLoad); } } public SearchResults doQuery(WaybackRequest wbRequest) throws ResourceIndexNotAvailableException, ResourceNotInArchiveException, BadQueryException, AccessControlException { //AuthToken waybackAuthToken = new AuthToken(wbRequest.get(CDXServer.CDX_AUTH_TOKEN)); AuthToken waybackAuthToken = new AuthToken(); waybackAuthToken.setAllCdxFieldsAllow(); CDXToSearchResultWriter resultWriter = null; if (wbRequest.isReplayRequest() || wbRequest.isCaptureQueryRequest()) { resultWriter = this.getCaptureSearchWriter(wbRequest); } else if (wbRequest.isUrlQueryRequest()) { resultWriter = this.getUrlSearchWriter(wbRequest); } else { throw new BadQueryException("Unknown Query Type"); } try { if (remoteCdxPath != null) { this.remoteCdxServerQuery(resultWriter.getQuery(), waybackAuthToken, resultWriter); } else { cdxServer.getCdx(resultWriter.getQuery(), waybackAuthToken, resultWriter); } } catch (IOException e) { throw new ResourceIndexNotAvailableException(e.toString()); } catch (RuntimeException rte) { Throwable cause = rte.getCause(); if (cause instanceof AccessControlException) { throw (AccessControlException)cause; } if (cause instanceof IOException) { throw new ResourceIndexNotAvailableException(cause.toString()); } throw new ResourceIndexNotAvailableException(rte.getMessage()); } if (resultWriter.getErrorMsg() != null) { throw new BadQueryException(resultWriter.getErrorMsg()); } SearchResults searchResults = resultWriter.getSearchResults(); if (searchResults.getReturnedCount() == 0) { throw new ResourceNotInArchiveException(wbRequest.getRequestUrl() + " was not found"); } return searchResults; } protected CDXQuery createQuery(WaybackRequest wbRequest) { CDXQuery query = new CDXQuery(wbRequest.getRequestUrl()); query.setLimit(limit); //query.setSort(CDXQuery.SortType.reverse); String statusFilter = "!statuscode:(500|502|504)"; if (wbRequest.isReplayRequest()) { if (wbRequest.isBestLatestReplayRequest()) { statusFilter = "statuscode:[23].."; } if (wbRequest.isTimestampSearchKey()) { query.setClosest(wbRequest.getReplayTimestamp()); } } else { if (timestampDedupLength > 0) { //query.setCollapse(new String[]{"timestamp:" + timestampDedupLength}); query.setCollapseTime(timestampDedupLength); } } query.setFilter(new String[]{statusFilter}); return query; } protected void remoteCdxServerQuery(CDXQuery query, AuthToken authToken, CDXToSearchResultWriter resultWriter) throws IOException, AccessControlException { HTTPSeekableLineReader reader = null; //Do local access/url validation check String urlkey = selfRedirFilter.getCanonicalizer().urlStringToKey(query.getUrl()); cdxServer.getAuthChecker().createAccessFilter(authToken).includeUrl(urlkey, query.getUrl()); try { StringBuilder sb = new StringBuilder(remoteCdxPath); sb.append("?url="); //sb.append(URLEncoder.encode(query.getUrl(), "UTF-8")); sb.append(query.getUrl()); sb.append("&limit="); sb.append(query.getLimit()); sb.append("&filter="); sb.append(query.getFilter()[0]); - if (!query.getClosest().isEmpty()) { - sb.append("&closest="); - sb.append(query.getClosest()); - } +// if (!query.getClosest().isEmpty()) { +// sb.append("&closest="); +// sb.append(query.getClosest().substring(0, 4)); +// } if (query.getCollapseTime() > 0) { sb.append("&collapseTime="); sb.append(query.getCollapseTime()); } sb.append("&gzip=true"); String finalUrl = URIUtil.encodePathQuery(sb.toString(), "UTF-8"); reader = this.remoteCdxHttp.get(finalUrl); if (remoteAuthCookie != null) { reader.setCookie(CDXServer.CDX_AUTH_TOKEN + "=" + remoteAuthCookie); } reader.setSaveErrHeader(HttpCDXWriter.RUNTIME_ERROR_HEADER); reader.seekWithMaxRead(0, true, -1); if (LOGGER.isLoggable(Level.FINE)) { String cacheInfo = reader.getHeaderValue("X-Page-Cache"); if (cacheInfo != null && cacheInfo.equals("HIT")) { LOGGER.fine("CACHED"); } } String rawLine = null; resultWriter.begin(); while ((rawLine = reader.readLine()) != null && !resultWriter.isAborted()) { CDXLine line = cdxLineFactory.createStandardCDXLine(rawLine, StandardCDXLineFactory.cdx11); resultWriter.writeLine(line); } resultWriter.end(); } catch (BadHttpStatusException badStatus) { if (reader != null) { String header = reader.getErrHeader(); if (header != null) { if (header.contains("Robot")) { throw new RobotAccessControlException(query.getUrl() + " is blocked by the sites robots.txt file"); } else if (header.contains("AdministrativeAccess")) { throw new AdministrativeAccessControlException(query.getUrl() + " is not available in the Wayback Machine."); } } } throw badStatus; } finally { if (reader != null) { reader.close(); } } } protected CDXToSearchResultWriter getCaptureSearchWriter(WaybackRequest wbRequest) { final CDXQuery query = createQuery(wbRequest); boolean resolveRevisits = wbRequest.isReplayRequest(); // For now, not using seek single capture to allow for run time checking of additional records boolean seekSingleCapture = resolveRevisits && wbRequest.isTimestampSearchKey(); //boolean seekSingleCapture = resolveRevisits && (wbRequest.isTimestampSearchKey() || (wbRequest.isBestLatestReplayRequest() && !wbRequest.hasMementoAcceptDatetime())); CDXToCaptureSearchResultsWriter captureWriter = new CDXToCaptureSearchResultsWriter(query, resolveRevisits, seekSingleCapture); captureWriter.setTargetTimestamp(wbRequest.getReplayTimestamp()); captureWriter.setSelfRedirFilter(selfRedirFilter); return captureWriter; } protected CDXToSearchResultWriter getUrlSearchWriter(WaybackRequest wbRequest) { final CDXQuery query = new CDXQuery(wbRequest.getRequestUrl()); query.setCollapse(new String[]{CDXLine.urlkey}); query.setMatchType(MatchType.prefix); query.setShowGroupCount(true); query.setShowUniqCount(true); query.setLastSkipTimestamp(true); query.setFl("urlkey,original,timestamp,endtimestamp,groupcount,uniqcount"); return new CDXToUrlSearchResultWriter(query); } @Override public boolean renderMementoTimemap(WaybackRequest wbRequest, HttpServletRequest request, HttpServletResponse response) throws WaybackException, IOException { try { PerfStats.timeStart(PerfStat.IndexLoad); String format = wbRequest.getMementoTimemapFormat(); if ((format != null) && format.equals(MementoConstants.FORMAT_LINK)) { SearchResults cResults = wbRequest.getAccessPoint().queryIndex(wbRequest); MementoUtils.printTimemapResponse((CaptureSearchResults)cResults, wbRequest, response); return true; } CDXQuery query = new CDXQuery(wbRequest.getRequestUrl()); query.setOutput(wbRequest.getMementoTimemapFormat()); String from = wbRequest.get(MementoConstants.PAGE_STARTS); if (from != null) { query.setFrom(from); } try { query.fill(request); } catch (ServletRequestBindingException e1) { //Ignore } cdxServer.getCdx(request, response, query); } finally { PerfStats.timeEnd(PerfStat.IndexLoad); } return true; } @Override public boolean handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException { CDXQuery query = new CDXQuery(httpRequest); cdxServer.getCdx(httpRequest, httpResponse, query); return true; } @Override public void shutdown() throws IOException { // TODO Auto-generated method stub } public CDXServer getCdxServer() { return cdxServer; } public void setCdxServer(CDXServer cdxServer) { this.cdxServer = cdxServer; } public int getTimestampDedupLength() { return timestampDedupLength; } public void setTimestampDedupLength(int timestampDedupLength) { this.timestampDedupLength = timestampDedupLength; } public SelfRedirectFilter getSelfRedirFilter() { return selfRedirFilter; } public void setSelfRedirFilter(SelfRedirectFilter selfRedirFilter) { this.selfRedirFilter = selfRedirFilter; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } @Override public void addTimegateHeaders( HttpServletResponse response, CaptureSearchResults results, WaybackRequest wbRequest, boolean includeOriginal) { MementoUtils.addTimegateHeaders(response, results, wbRequest, includeOriginal); // Add custom JSON header CaptureSearchResult result = results.getClosest(); JSONObject obj = new JSONObject(); JSONObject closestSnapshot = new JSONObject(); try { obj.put("wb_url", MementoUtils.getMementoPrefix(wbRequest.getAccessPoint()) + wbRequest.getAccessPoint().getUriConverter().makeReplayURI(result.getCaptureTimestamp(), wbRequest.getRequestUrl())); obj.put("timestamp", result.getCaptureTimestamp()); obj.put("status", result.getHttpCode()); closestSnapshot.put("closest", obj); } catch (JSONException je) { } String json = closestSnapshot.toString(); json = json.replace("\\/", "/"); response.setHeader("X-Link-JSON", json); } public String getRemoteCdxPath() { return remoteCdxPath; } public void setRemoteCdxPath(String remoteCdxPath) { this.remoteCdxPath = remoteCdxPath; } public String getRemoteAuthCookie() { return remoteAuthCookie; } public void setRemoteAuthCookie(String remoteAuthCookie) { this.remoteAuthCookie = remoteAuthCookie; } public HTTPSeekableLineReaderFactory getRemoteCdxHttp() { return remoteCdxHttp; } public void setRemoteCdxHttp(HTTPSeekableLineReaderFactory remoteCdxHttp) { this.remoteCdxHttp = remoteCdxHttp; } }
true
true
protected void remoteCdxServerQuery(CDXQuery query, AuthToken authToken, CDXToSearchResultWriter resultWriter) throws IOException, AccessControlException { HTTPSeekableLineReader reader = null; //Do local access/url validation check String urlkey = selfRedirFilter.getCanonicalizer().urlStringToKey(query.getUrl()); cdxServer.getAuthChecker().createAccessFilter(authToken).includeUrl(urlkey, query.getUrl()); try { StringBuilder sb = new StringBuilder(remoteCdxPath); sb.append("?url="); //sb.append(URLEncoder.encode(query.getUrl(), "UTF-8")); sb.append(query.getUrl()); sb.append("&limit="); sb.append(query.getLimit()); sb.append("&filter="); sb.append(query.getFilter()[0]); if (!query.getClosest().isEmpty()) { sb.append("&closest="); sb.append(query.getClosest()); } if (query.getCollapseTime() > 0) { sb.append("&collapseTime="); sb.append(query.getCollapseTime()); } sb.append("&gzip=true"); String finalUrl = URIUtil.encodePathQuery(sb.toString(), "UTF-8"); reader = this.remoteCdxHttp.get(finalUrl); if (remoteAuthCookie != null) { reader.setCookie(CDXServer.CDX_AUTH_TOKEN + "=" + remoteAuthCookie); } reader.setSaveErrHeader(HttpCDXWriter.RUNTIME_ERROR_HEADER); reader.seekWithMaxRead(0, true, -1); if (LOGGER.isLoggable(Level.FINE)) { String cacheInfo = reader.getHeaderValue("X-Page-Cache"); if (cacheInfo != null && cacheInfo.equals("HIT")) { LOGGER.fine("CACHED"); } } String rawLine = null; resultWriter.begin(); while ((rawLine = reader.readLine()) != null && !resultWriter.isAborted()) { CDXLine line = cdxLineFactory.createStandardCDXLine(rawLine, StandardCDXLineFactory.cdx11); resultWriter.writeLine(line); } resultWriter.end(); } catch (BadHttpStatusException badStatus) { if (reader != null) { String header = reader.getErrHeader(); if (header != null) { if (header.contains("Robot")) { throw new RobotAccessControlException(query.getUrl() + " is blocked by the sites robots.txt file"); } else if (header.contains("AdministrativeAccess")) { throw new AdministrativeAccessControlException(query.getUrl() + " is not available in the Wayback Machine."); } } } throw badStatus; } finally { if (reader != null) { reader.close(); } } }
protected void remoteCdxServerQuery(CDXQuery query, AuthToken authToken, CDXToSearchResultWriter resultWriter) throws IOException, AccessControlException { HTTPSeekableLineReader reader = null; //Do local access/url validation check String urlkey = selfRedirFilter.getCanonicalizer().urlStringToKey(query.getUrl()); cdxServer.getAuthChecker().createAccessFilter(authToken).includeUrl(urlkey, query.getUrl()); try { StringBuilder sb = new StringBuilder(remoteCdxPath); sb.append("?url="); //sb.append(URLEncoder.encode(query.getUrl(), "UTF-8")); sb.append(query.getUrl()); sb.append("&limit="); sb.append(query.getLimit()); sb.append("&filter="); sb.append(query.getFilter()[0]); // if (!query.getClosest().isEmpty()) { // sb.append("&closest="); // sb.append(query.getClosest().substring(0, 4)); // } if (query.getCollapseTime() > 0) { sb.append("&collapseTime="); sb.append(query.getCollapseTime()); } sb.append("&gzip=true"); String finalUrl = URIUtil.encodePathQuery(sb.toString(), "UTF-8"); reader = this.remoteCdxHttp.get(finalUrl); if (remoteAuthCookie != null) { reader.setCookie(CDXServer.CDX_AUTH_TOKEN + "=" + remoteAuthCookie); } reader.setSaveErrHeader(HttpCDXWriter.RUNTIME_ERROR_HEADER); reader.seekWithMaxRead(0, true, -1); if (LOGGER.isLoggable(Level.FINE)) { String cacheInfo = reader.getHeaderValue("X-Page-Cache"); if (cacheInfo != null && cacheInfo.equals("HIT")) { LOGGER.fine("CACHED"); } } String rawLine = null; resultWriter.begin(); while ((rawLine = reader.readLine()) != null && !resultWriter.isAborted()) { CDXLine line = cdxLineFactory.createStandardCDXLine(rawLine, StandardCDXLineFactory.cdx11); resultWriter.writeLine(line); } resultWriter.end(); } catch (BadHttpStatusException badStatus) { if (reader != null) { String header = reader.getErrHeader(); if (header != null) { if (header.contains("Robot")) { throw new RobotAccessControlException(query.getUrl() + " is blocked by the sites robots.txt file"); } else if (header.contains("AdministrativeAccess")) { throw new AdministrativeAccessControlException(query.getUrl() + " is not available in the Wayback Machine."); } } } throw badStatus; } finally { if (reader != null) { reader.close(); } } }
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/BugzillaTaskEditor.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/BugzillaTaskEditor.java index 64dc8d63a..ea4cb708f 100644 --- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/BugzillaTaskEditor.java +++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/BugzillaTaskEditor.java @@ -1,824 +1,824 @@ /******************************************************************************* * Copyright (c) 2003, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.bugzilla.ui.editor; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.fieldassist.ContentProposalAdapter; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.TextViewer; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCorePlugin; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCustomField; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaReportElement; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants; import org.eclipse.mylyn.internal.bugzilla.core.RepositoryConfiguration; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants.BUGZILLA_OPERATION; import org.eclipse.mylyn.internal.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.RepositoryOperation; import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylyn.tasks.ui.DatePicker; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; import org.eclipse.mylyn.tasks.ui.editors.AbstractRepositoryTaskEditor; import org.eclipse.mylyn.tasks.ui.editors.TaskEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.ImageHyperlink; import org.eclipse.ui.forms.widgets.Section; /** * An editor used to view a bug report that exists on a server. It uses a <code>BugReport</code> object to store the * data. * * @author Mik Kersten (hardening of prototype) * @author Rob Elves * @author Jeff Pound (Attachment work) */ public class BugzillaTaskEditor extends AbstractRepositoryTaskEditor { private static final String LABEL_TIME_TRACKING = "Bugzilla Time Tracking"; private static final String LABEL_CUSTOM_FIELD = "Custom Fields"; protected Text keywordsText; protected Text estimateText; protected Text actualText; protected Text remainingText; protected Text addTimeText; protected Text deadlineText; protected DatePicker deadlinePicker; protected Text votesText; protected Text assignedTo; /** * Creates a new <code>ExistingBugEditor</code>. */ public BugzillaTaskEditor(FormEditor editor) { super(editor); // Set up the input for comparing the bug report to the server // CompareConfiguration config = new CompareConfiguration(); // config.setLeftEditable(false); // config.setRightEditable(false); // config.setLeftLabel("Local Bug Report"); // config.setRightLabel("Remote Bug Report"); // config.setLeftImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); // config.setRightImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); // compareInput = new BugzillaCompareInput(config); } @Override protected boolean supportsCommentSort() { return false; } @Override protected void createCustomAttributeLayout(Composite composite) { RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.DEPENDSON.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).applyTo(textFieldComposite); GridLayoutFactory.swtDefaults().margins(1, 3).spacing(0, 3).applyTo(textFieldComposite); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } attribute = this.taskData.getAttribute(BugzillaReportElement.BLOCKED.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 3; textLayout.verticalSpacing = 3; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } String dependson = taskData.getAttributeValue(BugzillaReportElement.DEPENDSON.getKeyString()); String blocked = taskData.getAttributeValue(BugzillaReportElement.BLOCKED.getKeyString()); boolean addHyperlinks = (dependson != null && dependson.length() > 0) || (blocked != null && blocked.length() > 0); if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.DEPENDSON.getKeyString()); } if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.BLOCKED.getKeyString()); } + // NOTE: urlText should not be back ported to 3.3 due to background color failure attribute = this.taskData.getAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); TextViewer urlTextViewer = addTextEditor(repository, composite, attribute.getValue(), // false, SWT.FLAT); - // false, SWT.FLAT | SWT.SINGLE); final StyledText urlText = urlTextViewer.getTextWidget(); urlText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); urlText.setIndent(2); final RepositoryTaskAttribute urlAttribute = attribute; urlTextViewer.setEditable(true); urlTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = urlText.getText(); if (!newValue.equals(urlAttribute.getValue())) { urlAttribute.setValue(newValue); attributeChanged(urlAttribute); } } }); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; urlText.setLayoutData(textData); if (hasChanged(attribute)) { urlText.setBackground(getColorIncoming()); } } attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); if (attribute == null) { this.taskData.setAttributeValue(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString(), ""); attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); } if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text whiteboardField = createTextField(composite, attribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(whiteboardField); } try { addKeywordsList(composite); } catch (IOException e) { MessageDialog.openInformation(null, "Attribute Display Error", "Could not retrieve keyword list, ensure proper configuration in " + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + "\n\nError reported: " + e.getMessage()); } addVoting(composite); // If groups is available add roles if (taskData.getAttribute(BugzillaReportElement.GROUP.getKeyString()) != null) { addRoles(composite); } if (taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) addBugzillaTimeTracker(getManagedForm().getToolkit(), composite); try { RepositoryConfiguration configuration = BugzillaCorePlugin.getRepositoryConfiguration(this.repository, false); if (configuration != null) { List<BugzillaCustomField> customFields = configuration.getCustomFields(); if (!customFields.isEmpty()) { Section cfSection = getManagedForm().getToolkit().createSection(composite, ExpandableComposite.SHORT_TITLE_BAR); cfSection.setText(LABEL_CUSTOM_FIELD); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; cfSection.setLayout(gl); cfSection.setLayoutData(gd); Composite cfComposite = getManagedForm().getToolkit().createComposite(cfSection); gl = new GridLayout(4, false); cfComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; cfComposite.setLayoutData(gd); for (BugzillaCustomField bugzillaCustomField : customFields) { List<String> optionList = bugzillaCustomField.getOptions(); attribute = this.taskData.getAttribute(bugzillaCustomField.getName()); if (attribute == null) { RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute( bugzillaCustomField.getName(), bugzillaCustomField.getDescription(), false); newattribute.setReadOnly(false); this.taskData.addAttribute(bugzillaCustomField.getName(), newattribute); } final RepositoryTaskAttribute cfattribute = this.taskData.getAttribute(bugzillaCustomField.getName()); Label label = createLabel(cfComposite, cfattribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); if (optionList != null && !optionList.isEmpty()) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; final CCombo attributeCombo = new CCombo(cfComposite, SWT.FLAT | SWT.READ_ONLY); getManagedForm().getToolkit().adapt(attributeCombo, true, true); attributeCombo.setFont(TEXT_FONT); attributeCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); if (hasChanged(cfattribute)) { attributeCombo.setBackground(getColorIncoming()); } attributeCombo.setLayoutData(data); for (String val : optionList) { if (val != null) { attributeCombo.add(val); } } String value = cfattribute.getValue(); if (value == null) { value = ""; } if (attributeCombo.indexOf(value) != -1) { attributeCombo.select(attributeCombo.indexOf(value)); } attributeCombo.clearSelection(); attributeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { if (attributeCombo.getSelectionIndex() > -1) { String sel = attributeCombo.getItem(attributeCombo.getSelectionIndex()); cfattribute.setValue(sel); attributeChanged(cfattribute); attributeCombo.clearSelection(); } } }); } else { Text cfField = createTextField(cfComposite, cfattribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(cfField); } } getManagedForm().getToolkit().paintBordersFor(cfComposite); cfSection.setClient(cfComposite); } } } catch (CoreException e) { // ignore } } private boolean hasCustomAttributeChanges() { if (taskData == null) return false; String customAttributeKeys[] = { BugzillaReportElement.BUG_FILE_LOC.getKeyString(), BugzillaReportElement.DEPENDSON.getKeyString(), BugzillaReportElement.BLOCKED.getKeyString(), BugzillaReportElement.KEYWORDS.getKeyString(), BugzillaReportElement.VOTES.getKeyString(), BugzillaReportElement.REPORTER_ACCESSIBLE.getKeyString(), BugzillaReportElement.CCLIST_ACCESSIBLE.getKeyString(), BugzillaReportElement.ESTIMATED_TIME.getKeyString(), BugzillaReportElement.REMAINING_TIME.getKeyString(), BugzillaReportElement.ACTUAL_TIME.getKeyString(), BugzillaReportElement.DEADLINE.getKeyString(), BugzillaReportElement.STATUS_WHITEBOARD.getKeyString() }; for (String key : customAttributeKeys) { RepositoryTaskAttribute attribute = taskData.getAttribute(key); if (hasChanged(attribute)) { return true; } } return false; } @Override protected boolean hasVisibleAttributeChanges() { return super.hasVisibleAttributeChanges() || this.hasCustomAttributeChanges(); } private void addBugHyperlinks(Composite composite, String key) { Composite hyperlinksComposite = getManagedForm().getToolkit().createComposite(composite); RowLayout rowLayout = new RowLayout(); rowLayout.marginBottom = 0; rowLayout.marginLeft = 0; rowLayout.marginRight = 0; rowLayout.marginTop = 0; rowLayout.spacing = 0; hyperlinksComposite.setLayout(new RowLayout()); String values = taskData.getAttributeValue(key); if (values != null && values.length() > 0) { for (String bugNumber : values.split(",")) { final String bugId = bugNumber.trim(); final String bugUrl = repository.getRepositoryUrl() + IBugzillaConstants.URL_GET_SHOW_BUG + bugId; final AbstractTask task = TasksUiPlugin.getTaskListManager().getTaskList().getTask(repository.getRepositoryUrl(), bugId); createTaskListHyperlink(hyperlinksComposite, bugId, bugUrl, task); } } } protected void addRoles(Composite parent) { Section rolesSection = getManagedForm().getToolkit().createSection(parent, ExpandableComposite.SHORT_TITLE_BAR); rolesSection.setText("Users in the roles selected below can always view this bug"); rolesSection.setDescription("(The assignee can always see a bug, and this section does not take effect unless the bug is restricted to at least one group.)"); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; rolesSection.setLayout(gl); rolesSection.setLayoutData(gd); Composite rolesComposite = getManagedForm().getToolkit().createComposite(rolesSection); GridLayout attributesLayout = new GridLayout(); attributesLayout.numColumns = 4; attributesLayout.horizontalSpacing = 5; attributesLayout.verticalSpacing = 4; rolesComposite.setLayout(attributesLayout); GridData attributesData = new GridData(GridData.FILL_BOTH); attributesData.horizontalSpan = 1; attributesData.grabExcessVerticalSpace = false; rolesComposite.setLayoutData(attributesData); rolesSection.setClient(rolesComposite); RepositoryTaskAttribute attribute = taskData.getAttribute(BugzillaReportElement.REPORTER_ACCESSIBLE.getKeyString()); if (attribute == null) { taskData.setAttributeValue(BugzillaReportElement.REPORTER_ACCESSIBLE.getKeyString(), "0"); attribute = taskData.getAttribute(BugzillaReportElement.REPORTER_ACCESSIBLE.getKeyString()); } Button button = addButtonField(rolesComposite, attribute, SWT.CHECK); if (hasChanged(attribute)) { button.setBackground(getColorIncoming()); } attribute = null; attribute = taskData.getAttribute(BugzillaReportElement.CCLIST_ACCESSIBLE.getKeyString()); if (attribute == null) { taskData.setAttributeValue(BugzillaReportElement.CCLIST_ACCESSIBLE.getKeyString(), "0"); attribute = taskData.getAttribute(BugzillaReportElement.CCLIST_ACCESSIBLE.getKeyString()); } button = addButtonField(rolesComposite, attribute, SWT.CHECK); if (hasChanged(attribute)) { button.setBackground(getColorIncoming()); } } @Override protected boolean hasContentAssist(RepositoryTaskAttribute attribute) { return BugzillaReportElement.NEWCC.getKeyString().equals(attribute.getId()); } @Override protected boolean hasContentAssist(RepositoryOperation repositoryOperation) { BUGZILLA_OPERATION operation; try { operation = BUGZILLA_OPERATION.valueOf(repositoryOperation.getKnobName()); } catch (RuntimeException e) { // FIXME: ? StatusHandler.log(new Status(IStatus.INFO, BugzillaUiPlugin.PLUGIN_ID, "Unrecognized operation: " + repositoryOperation.getKnobName(), e)); operation = null; } if (operation != null && operation == BUGZILLA_OPERATION.reassign) { return true; } else { return false; } } private Button addButtonField(Composite rolesComposite, RepositoryTaskAttribute attribute, int style) { if (attribute == null) { return null; } String name = attribute.getName(); if (hasOutgoingChange(attribute)) { name += "*"; } final Button button = getManagedForm().getToolkit().createButton(rolesComposite, name, style); if (!attribute.isReadOnly()) { button.setData(attribute); button.setSelection(attribute.getValue().equals("1")); button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String sel = "1"; if (!button.getSelection()) { sel = "0"; } RepositoryTaskAttribute a = (RepositoryTaskAttribute) button.getData(); a.setValue(sel); attributeChanged(a); } }); } return button; } protected void addBugzillaTimeTracker(FormToolkit toolkit, Composite parent) { Section timeSection = toolkit.createSection(parent, ExpandableComposite.SHORT_TITLE_BAR); timeSection.setText(LABEL_TIME_TRACKING); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; timeSection.setLayout(gl); timeSection.setLayoutData(gd); Composite timeComposite = toolkit.createComposite(timeSection); gl = new GridLayout(4, false); timeComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; timeComposite.setLayoutData(gd); RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { createLabel(timeComposite, attribute); estimateText = createTextField(timeComposite, attribute, SWT.FLAT); estimateText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); } Label label = toolkit.createLabel(timeComposite, "Current Estimate:"); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); float total = 0; try { total = (Float.parseFloat(taskData.getAttributeValue(BugzillaReportElement.ACTUAL_TIME.getKeyString())) + Float.parseFloat(taskData.getAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString()))); } catch (Exception e) { // ignore likely NumberFormatException } Text currentEstimate = toolkit.createText(timeComposite, "" + total); currentEstimate.setFont(TEXT_FONT); currentEstimate.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); currentEstimate.setEditable(false); attribute = this.taskData.getAttribute(BugzillaReportElement.ACTUAL_TIME.getKeyString()); if (attribute != null) { createLabel(timeComposite, attribute); Text actualText = createTextField(timeComposite, attribute, SWT.FLAT); actualText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); actualText.setEditable(false); } // Add Time taskData.setAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString(), "0"); final RepositoryTaskAttribute addTimeAttribute = this.taskData.getAttribute(BugzillaReportElement.WORK_TIME.getKeyString()); if (addTimeAttribute != null) { createLabel(timeComposite, addTimeAttribute); addTimeText = toolkit.createText(timeComposite, taskData.getAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString()), SWT.BORDER); addTimeText.setFont(TEXT_FONT); addTimeText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); addTimeText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { addTimeAttribute.setValue(addTimeText.getText()); attributeChanged(addTimeAttribute); } }); } attribute = this.taskData.getAttribute(BugzillaReportElement.REMAINING_TIME.getKeyString()); if (attribute != null) { createLabel(timeComposite, attribute); createTextField(timeComposite, attribute, SWT.FLAT); } attribute = this.taskData.getAttribute(BugzillaReportElement.DEADLINE.getKeyString()); if (attribute != null) { createLabel(timeComposite, attribute); Composite dateWithClear = toolkit.createComposite(timeComposite); GridLayout layout = new GridLayout(2, false); layout.marginWidth = 1; dateWithClear.setLayout(layout); deadlinePicker = new DatePicker(dateWithClear, /* SWT.NONE */SWT.BORDER, taskData.getAttributeValue(BugzillaReportElement.DEADLINE.getKeyString()), false); deadlinePicker.setFont(TEXT_FONT); deadlinePicker.setDatePattern("yyyy-MM-dd"); if (hasChanged(attribute)) { deadlinePicker.setBackground(getColorIncoming()); } deadlinePicker.addPickerSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent e) { Calendar cal = deadlinePicker.getDate(); if (cal != null) { Date d = cal.getTime(); SimpleDateFormat f = (SimpleDateFormat) SimpleDateFormat.getDateInstance(); f.applyPattern("yyyy-MM-dd"); taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), f.format(d)); attributeChanged(taskData.getAttribute(BugzillaReportElement.DEADLINE.getKeyString())); // TODO goes dirty even if user presses cancel // markDirty(true); } else { taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), ""); attributeChanged(taskData.getAttribute(BugzillaReportElement.DEADLINE.getKeyString())); deadlinePicker.setDate(null); } } }); ImageHyperlink clearDeadlineDate = toolkit.createImageHyperlink(dateWithClear, SWT.NONE); clearDeadlineDate.setImage(TasksUiImages.getImage(TasksUiImages.REMOVE)); clearDeadlineDate.setToolTipText("Clear"); clearDeadlineDate.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), ""); attributeChanged(taskData.getAttribute(BugzillaReportElement.DEADLINE.getKeyString())); deadlinePicker.setDate(null); } }); } timeSection.setClient(timeComposite); } protected void addKeywordsList(Composite attributesComposite) throws IOException { // newLayout(attributesComposite, 1, "Keywords:", PROPERTY); final RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.KEYWORDS); if (attribute == null) return; Label label = createLabel(attributesComposite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); // toolkit.createText(attributesComposite, keywords) keywordsText = createTextField(attributesComposite, attribute, SWT.FLAT); keywordsText.setFont(TEXT_FONT); GridData keywordsData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); keywordsData.horizontalSpan = 2; keywordsData.widthHint = 200; keywordsText.setLayoutData(keywordsData); Button changeKeywordsButton = getManagedForm().getToolkit().createButton(attributesComposite, "Edit...", SWT.FLAT); GridData keyWordsButtonData = new GridData(); changeKeywordsButton.setLayoutData(keyWordsButtonData); changeKeywordsButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { String keywords = attribute.getValue(); Shell shell = null; if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) { shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); } else { shell = new Shell(PlatformUI.getWorkbench().getDisplay()); } List<String> validKeywords = new ArrayList<String>(); try { validKeywords = BugzillaCorePlugin.getRepositoryConfiguration(repository, false).getKeywords(); } catch (Exception ex) { // ignore } KeywordsDialog keywordsDialog = new KeywordsDialog(shell, keywords, validKeywords); int responseCode = keywordsDialog.open(); String newKeywords = keywordsDialog.getSelectedKeywordsString(); if (responseCode == Dialog.OK && keywords != null) { keywordsText.setText(newKeywords); attribute.setValue(newKeywords); attributeChanged(attribute); } else { return; } } }); } protected void addVoting(Composite attributesComposite) { Label label = getManagedForm().getToolkit().createLabel(attributesComposite, "Votes:"); label.setForeground(getManagedForm().getToolkit().getColors().getColor(IFormColors.TITLE)); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite votingComposite = getManagedForm().getToolkit().createComposite(attributesComposite); GridLayout layout = new GridLayout(3, false); layout.marginHeight = 0; layout.marginWidth = 0; votingComposite.setLayout(layout); RepositoryTaskAttribute votesAttribute = taskData.getAttribute(BugzillaReportElement.VOTES.getKeyString()); votesText = createTextField(votingComposite, votesAttribute, SWT.FLAT | SWT.READ_ONLY); votesText.setFont(TEXT_FONT); GridDataFactory.fillDefaults().minSize(30, SWT.DEFAULT).hint(30, SWT.DEFAULT).applyTo(votesText); if (votesAttribute != null && hasChanged(votesAttribute)) { votesText.setBackground(getColorIncoming()); } votesText.setEditable(false); Hyperlink showVotesHyperlink = getManagedForm().getToolkit().createHyperlink(votingComposite, "Show votes", SWT.NONE); showVotesHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { if (BugzillaTaskEditor.this.getEditor() instanceof TaskEditor) { TasksUiUtil.openUrl(repository.getRepositoryUrl() + IBugzillaConstants.URL_SHOW_VOTES + taskData.getTaskId()); } } }); Hyperlink voteHyperlink = getManagedForm().getToolkit().createHyperlink(votingComposite, "Vote", SWT.NONE); voteHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { if (BugzillaTaskEditor.this.getEditor() instanceof TaskEditor) { TasksUiUtil.openUrl(repository.getRepositoryUrl() + IBugzillaConstants.URL_VOTE + taskData.getTaskId()); } } }); } @Override protected void validateInput() { } @Override protected String getHistoryUrl() { if (repository != null && taskData != null) { return repository.getRepositoryUrl() + IBugzillaConstants.URL_BUG_ACTIVITY + taskData.getTaskId(); } else { return null; } } /** * @author Frank Becker (bug 198027) FIXME: A lot of duplicated code here between this and NewBugzillataskEditor */ @Override protected void addAssignedTo(Composite peopleComposite) { RepositoryTaskAttribute assignedAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (assignedAttribute != null) { String bugzillaVersion; try { bugzillaVersion = BugzillaCorePlugin.getRepositoryConfiguration(repository, false).getInstallVersion(); } catch (CoreException e1) { // ignore bugzillaVersion = "2.18"; } if (bugzillaVersion.compareTo("3.1") < 0) { // old bugzilla workflow is used super.addAssignedTo(peopleComposite); return; } Label label = createLabel(peopleComposite, assignedAttribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); assignedTo = createTextField(peopleComposite, assignedAttribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).applyTo(assignedTo); assignedTo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String sel = assignedTo.getText(); RepositoryTaskAttribute a = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (!(a.getValue().equals(sel))) { a.setValue(sel); markDirty(true); } } }); ContentAssistCommandAdapter adapter = applyContentAssist(assignedTo, createContentProposalProvider(assignedAttribute)); ILabelProvider propsalLabelProvider = createProposalLabelProvider(assignedAttribute); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); FormToolkit toolkit = getManagedForm().getToolkit(); Label dummylabel = toolkit.createLabel(peopleComposite, ""); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(dummylabel); RepositoryTaskAttribute attribute = taskData.getAttribute(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString()); if (attribute == null) { taskData.setAttributeValue(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString(), "0"); attribute = taskData.getAttribute(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString()); } addButtonField(peopleComposite, attribute, SWT.CHECK); } } protected boolean attributeChanged(RepositoryTaskAttribute attribute) { if (attribute == null) { return false; } // Support comment wrapping for bugzilla 2.18 if (attribute.getId().equals(BugzillaReportElement.NEW_COMMENT.getKeyString())) { if (repository.getVersion().startsWith("2.18")) { attribute.setValue(BugzillaUiPlugin.formatTextToLineWrap(attribute.getValue(), true)); } } return super.attributeChanged(attribute); } @Override protected void addSelfToCC(Composite composite) { // XXX: Work around for adding QAContact to People section. Update once bug#179254 is complete boolean haveRealName = false; RepositoryTaskAttribute qaContact = taskData.getAttribute(BugzillaReportElement.QA_CONTACT_NAME.getKeyString()); if (qaContact == null) { qaContact = taskData.getAttribute(BugzillaReportElement.QA_CONTACT.getKeyString()); } else { haveRealName = true; } if (qaContact != null) { Label label = createLabel(composite, qaContact); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text textField; if (qaContact.isReadOnly()) { textField = createTextField(composite, qaContact, SWT.FLAT | SWT.READ_ONLY); } else { textField = createTextField(composite, qaContact, SWT.FLAT); ContentAssistCommandAdapter adapter = applyContentAssist(textField, createContentProposalProvider(qaContact)); ILabelProvider propsalLabelProvider = createProposalLabelProvider(qaContact); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); } GridDataFactory.fillDefaults().grab(true, false).applyTo(textField); if (haveRealName) { textField.setText(textField.getText() + " <" + taskData.getAttributeValue(BugzillaReportElement.QA_CONTACT.getKeyString()) + ">"); } } super.addSelfToCC(composite); } }
false
true
protected void createCustomAttributeLayout(Composite composite) { RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.DEPENDSON.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).applyTo(textFieldComposite); GridLayoutFactory.swtDefaults().margins(1, 3).spacing(0, 3).applyTo(textFieldComposite); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } attribute = this.taskData.getAttribute(BugzillaReportElement.BLOCKED.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 3; textLayout.verticalSpacing = 3; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } String dependson = taskData.getAttributeValue(BugzillaReportElement.DEPENDSON.getKeyString()); String blocked = taskData.getAttributeValue(BugzillaReportElement.BLOCKED.getKeyString()); boolean addHyperlinks = (dependson != null && dependson.length() > 0) || (blocked != null && blocked.length() > 0); if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.DEPENDSON.getKeyString()); } if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.BLOCKED.getKeyString()); } attribute = this.taskData.getAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); TextViewer urlTextViewer = addTextEditor(repository, composite, attribute.getValue(), // false, SWT.FLAT); // false, SWT.FLAT | SWT.SINGLE); final StyledText urlText = urlTextViewer.getTextWidget(); urlText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); urlText.setIndent(2); final RepositoryTaskAttribute urlAttribute = attribute; urlTextViewer.setEditable(true); urlTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = urlText.getText(); if (!newValue.equals(urlAttribute.getValue())) { urlAttribute.setValue(newValue); attributeChanged(urlAttribute); } } }); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; urlText.setLayoutData(textData); if (hasChanged(attribute)) { urlText.setBackground(getColorIncoming()); } } attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); if (attribute == null) { this.taskData.setAttributeValue(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString(), ""); attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); } if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text whiteboardField = createTextField(composite, attribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(whiteboardField); } try { addKeywordsList(composite); } catch (IOException e) { MessageDialog.openInformation(null, "Attribute Display Error", "Could not retrieve keyword list, ensure proper configuration in " + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + "\n\nError reported: " + e.getMessage()); } addVoting(composite); // If groups is available add roles if (taskData.getAttribute(BugzillaReportElement.GROUP.getKeyString()) != null) { addRoles(composite); } if (taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) addBugzillaTimeTracker(getManagedForm().getToolkit(), composite); try { RepositoryConfiguration configuration = BugzillaCorePlugin.getRepositoryConfiguration(this.repository, false); if (configuration != null) { List<BugzillaCustomField> customFields = configuration.getCustomFields(); if (!customFields.isEmpty()) { Section cfSection = getManagedForm().getToolkit().createSection(composite, ExpandableComposite.SHORT_TITLE_BAR); cfSection.setText(LABEL_CUSTOM_FIELD); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; cfSection.setLayout(gl); cfSection.setLayoutData(gd); Composite cfComposite = getManagedForm().getToolkit().createComposite(cfSection); gl = new GridLayout(4, false); cfComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; cfComposite.setLayoutData(gd); for (BugzillaCustomField bugzillaCustomField : customFields) { List<String> optionList = bugzillaCustomField.getOptions(); attribute = this.taskData.getAttribute(bugzillaCustomField.getName()); if (attribute == null) { RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute( bugzillaCustomField.getName(), bugzillaCustomField.getDescription(), false); newattribute.setReadOnly(false); this.taskData.addAttribute(bugzillaCustomField.getName(), newattribute); } final RepositoryTaskAttribute cfattribute = this.taskData.getAttribute(bugzillaCustomField.getName()); Label label = createLabel(cfComposite, cfattribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); if (optionList != null && !optionList.isEmpty()) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; final CCombo attributeCombo = new CCombo(cfComposite, SWT.FLAT | SWT.READ_ONLY); getManagedForm().getToolkit().adapt(attributeCombo, true, true); attributeCombo.setFont(TEXT_FONT); attributeCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); if (hasChanged(cfattribute)) { attributeCombo.setBackground(getColorIncoming()); } attributeCombo.setLayoutData(data); for (String val : optionList) { if (val != null) { attributeCombo.add(val); } } String value = cfattribute.getValue(); if (value == null) { value = ""; } if (attributeCombo.indexOf(value) != -1) { attributeCombo.select(attributeCombo.indexOf(value)); } attributeCombo.clearSelection(); attributeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { if (attributeCombo.getSelectionIndex() > -1) { String sel = attributeCombo.getItem(attributeCombo.getSelectionIndex()); cfattribute.setValue(sel); attributeChanged(cfattribute); attributeCombo.clearSelection(); } } }); } else { Text cfField = createTextField(cfComposite, cfattribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(cfField); } } getManagedForm().getToolkit().paintBordersFor(cfComposite); cfSection.setClient(cfComposite); } } } catch (CoreException e) { // ignore } }
protected void createCustomAttributeLayout(Composite composite) { RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.DEPENDSON.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.CENTER).applyTo(textFieldComposite); GridLayoutFactory.swtDefaults().margins(1, 3).spacing(0, 3).applyTo(textFieldComposite); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } attribute = this.taskData.getAttribute(BugzillaReportElement.BLOCKED.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 3; textLayout.verticalSpacing = 3; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } String dependson = taskData.getAttributeValue(BugzillaReportElement.DEPENDSON.getKeyString()); String blocked = taskData.getAttributeValue(BugzillaReportElement.BLOCKED.getKeyString()); boolean addHyperlinks = (dependson != null && dependson.length() > 0) || (blocked != null && blocked.length() > 0); if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.DEPENDSON.getKeyString()); } if (addHyperlinks) { getManagedForm().getToolkit().createLabel(composite, ""); addBugHyperlinks(composite, BugzillaReportElement.BLOCKED.getKeyString()); } // NOTE: urlText should not be back ported to 3.3 due to background color failure attribute = this.taskData.getAttribute(BugzillaReportElement.BUG_FILE_LOC.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); TextViewer urlTextViewer = addTextEditor(repository, composite, attribute.getValue(), // false, SWT.FLAT); final StyledText urlText = urlTextViewer.getTextWidget(); urlText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); urlText.setIndent(2); final RepositoryTaskAttribute urlAttribute = attribute; urlTextViewer.setEditable(true); urlTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = urlText.getText(); if (!newValue.equals(urlAttribute.getValue())) { urlAttribute.setValue(newValue); attributeChanged(urlAttribute); } } }); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; urlText.setLayoutData(textData); if (hasChanged(attribute)) { urlText.setBackground(getColorIncoming()); } } attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); if (attribute == null) { this.taskData.setAttributeValue(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString(), ""); attribute = this.taskData.getAttribute(BugzillaReportElement.STATUS_WHITEBOARD.getKeyString()); } if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text whiteboardField = createTextField(composite, attribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(whiteboardField); } try { addKeywordsList(composite); } catch (IOException e) { MessageDialog.openInformation(null, "Attribute Display Error", "Could not retrieve keyword list, ensure proper configuration in " + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + "\n\nError reported: " + e.getMessage()); } addVoting(composite); // If groups is available add roles if (taskData.getAttribute(BugzillaReportElement.GROUP.getKeyString()) != null) { addRoles(composite); } if (taskData.getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) addBugzillaTimeTracker(getManagedForm().getToolkit(), composite); try { RepositoryConfiguration configuration = BugzillaCorePlugin.getRepositoryConfiguration(this.repository, false); if (configuration != null) { List<BugzillaCustomField> customFields = configuration.getCustomFields(); if (!customFields.isEmpty()) { Section cfSection = getManagedForm().getToolkit().createSection(composite, ExpandableComposite.SHORT_TITLE_BAR); cfSection.setText(LABEL_CUSTOM_FIELD); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, false, false); gd.horizontalSpan = 4; cfSection.setLayout(gl); cfSection.setLayoutData(gd); Composite cfComposite = getManagedForm().getToolkit().createComposite(cfSection); gl = new GridLayout(4, false); cfComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; cfComposite.setLayoutData(gd); for (BugzillaCustomField bugzillaCustomField : customFields) { List<String> optionList = bugzillaCustomField.getOptions(); attribute = this.taskData.getAttribute(bugzillaCustomField.getName()); if (attribute == null) { RepositoryTaskAttribute newattribute = new RepositoryTaskAttribute( bugzillaCustomField.getName(), bugzillaCustomField.getDescription(), false); newattribute.setReadOnly(false); this.taskData.addAttribute(bugzillaCustomField.getName(), newattribute); } final RepositoryTaskAttribute cfattribute = this.taskData.getAttribute(bugzillaCustomField.getName()); Label label = createLabel(cfComposite, cfattribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); if (optionList != null && !optionList.isEmpty()) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; final CCombo attributeCombo = new CCombo(cfComposite, SWT.FLAT | SWT.READ_ONLY); getManagedForm().getToolkit().adapt(attributeCombo, true, true); attributeCombo.setFont(TEXT_FONT); attributeCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); if (hasChanged(cfattribute)) { attributeCombo.setBackground(getColorIncoming()); } attributeCombo.setLayoutData(data); for (String val : optionList) { if (val != null) { attributeCombo.add(val); } } String value = cfattribute.getValue(); if (value == null) { value = ""; } if (attributeCombo.indexOf(value) != -1) { attributeCombo.select(attributeCombo.indexOf(value)); } attributeCombo.clearSelection(); attributeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { if (attributeCombo.getSelectionIndex() > -1) { String sel = attributeCombo.getItem(attributeCombo.getSelectionIndex()); cfattribute.setValue(sel); attributeChanged(cfattribute); attributeCombo.clearSelection(); } } }); } else { Text cfField = createTextField(cfComposite, cfattribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(135, SWT.DEFAULT).applyTo(cfField); } } getManagedForm().getToolkit().paintBordersFor(cfComposite); cfSection.setClient(cfComposite); } } } catch (CoreException e) { // ignore } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListNotificationPopup.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListNotificationPopup.java index 59fe5e6eb..43fc1e0da 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListNotificationPopup.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListNotificationPopup.java @@ -1,218 +1,218 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.tasks.ui; import java.util.List; import org.eclipse.jface.dialogs.PopupDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.mylar.internal.tasks.ui.views.TaskListView; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.ImageHyperlink; import org.eclipse.ui.forms.widgets.Section; /** * @author Rob Elves */ public class TaskListNotificationPopup extends PopupDialog { private static final String NOTIFICATIONS_HIDDEN = " more changes..."; private static final int NUM_NOTIFICATIONS_TO_DISPLAY = 3; private static final String MYLAR_NOTIFICATION_LABEL = "Mylar Notification"; private Form form; private Rectangle bounds; private List<ITaskListNotification> notifications; private Composite sectionClient; private FormToolkit toolkit; public TaskListNotificationPopup(Shell parent) { super(parent, PopupDialog.INFOPOPUP_SHELLSTYLE | SWT.ON_TOP, false, false, false, false, null, null); toolkit = new FormToolkit(parent.getDisplay()); } public void setContents(List<ITaskListNotification> notifications) { this.notifications = notifications; } @Override protected Control createContents(Composite parent) { getShell().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_GRAY)); return createDialogArea(parent); } @Override protected final Control createDialogArea(final Composite parent) { getShell().setText(MYLAR_NOTIFICATION_LABEL); form = toolkit.createForm(parent); form.getBody().setLayout(new GridLayout()); Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR); section.setText(MYLAR_NOTIFICATION_LABEL); section.setLayout(new GridLayout()); sectionClient = toolkit.createComposite(section); sectionClient.setLayout(new GridLayout(2, false)); int count = 0; for (final ITaskListNotification notification : notifications) { if (count < NUM_NOTIFICATIONS_TO_DISPLAY) { Label notificationLabelIcon = toolkit.createLabel(sectionClient, ""); notificationLabelIcon.setImage(notification.getOverlayIcon()); ImageHyperlink link = toolkit.createImageHyperlink(sectionClient, SWT.BEGINNING | SWT.WRAP); link.setText(notification.getLabel()); link.setImage(notification.getNotificationIcon()); link.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { notification.openTask(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { Shell windowShell = window.getShell(); if (windowShell != null) { windowShell.setMaximized(true); windowShell.open(); } } } }); String descriptionText = null; if (notification.getDescription() != null) { descriptionText = notification.getDescription(); } if (descriptionText != null) { Label descriptionLabel = toolkit.createLabel(sectionClient, descriptionText); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(descriptionLabel); } } else { int numNotificationsRemain = notifications.size() - count; Hyperlink remainingHyperlink = toolkit.createHyperlink(sectionClient, numNotificationsRemain + NOTIFICATIONS_HIDDEN, SWT.NONE); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(remainingHyperlink); remainingHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { - TaskListView.getFromActivePerspective().setFocus(); + TaskListView.openInActivePerspective().setFocus(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { Shell windowShell = window.getShell(); if (windowShell != null) { windowShell.setMaximized(true); windowShell.open(); } } } }); break; } count++; } section.setClient(sectionClient); ImageHyperlink hyperlink = new ImageHyperlink(section, SWT.NONE); toolkit.adapt(hyperlink, true, true); hyperlink.setBackground(null); hyperlink.setImage(TasksUiImages.getImage(TasksUiImages.NOTIFICATION_CLOSE)); hyperlink.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { close(); } }); section.setTextClient(hyperlink); form.pack(); return parent; } /** * Initialize the shell's bounds. */ @Override public void initializeBounds() { getShell().setBounds(restoreBounds()); } private Rectangle restoreBounds() { bounds = form.getBounds(); Rectangle maxBounds = null; IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { maxBounds = window.getShell().getMonitor().getClientArea(); } else { // fallback Display display = Display.getCurrent(); if (display == null) display = Display.getDefault(); if (display != null && !display.isDisposed()) maxBounds = display.getPrimaryMonitor().getClientArea(); } if (bounds.width > -1 && bounds.height > -1) { if (maxBounds != null) { bounds.width = Math.min(bounds.width, maxBounds.width); bounds.height = Math.min(bounds.height, maxBounds.height); } // Enforce an absolute minimal size bounds.width = Math.max(bounds.width, 30); bounds.height = Math.max(bounds.height, 30); } if (bounds.x > -1 && bounds.y > -1 && maxBounds != null) { // bounds.x = Math.max(bounds.x, maxBounds.x); // bounds.y = Math.max(bounds.y, maxBounds.y); if (bounds.width > -1 && bounds.height > -1) { bounds.x = maxBounds.x + maxBounds.width - bounds.width; bounds.y = maxBounds.y + maxBounds.height - bounds.height; } } return bounds; } @Override public boolean close() { if (toolkit != null) { if (toolkit.getColors() != null) { toolkit.dispose(); } } return super.close(); } }
true
true
protected final Control createDialogArea(final Composite parent) { getShell().setText(MYLAR_NOTIFICATION_LABEL); form = toolkit.createForm(parent); form.getBody().setLayout(new GridLayout()); Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR); section.setText(MYLAR_NOTIFICATION_LABEL); section.setLayout(new GridLayout()); sectionClient = toolkit.createComposite(section); sectionClient.setLayout(new GridLayout(2, false)); int count = 0; for (final ITaskListNotification notification : notifications) { if (count < NUM_NOTIFICATIONS_TO_DISPLAY) { Label notificationLabelIcon = toolkit.createLabel(sectionClient, ""); notificationLabelIcon.setImage(notification.getOverlayIcon()); ImageHyperlink link = toolkit.createImageHyperlink(sectionClient, SWT.BEGINNING | SWT.WRAP); link.setText(notification.getLabel()); link.setImage(notification.getNotificationIcon()); link.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { notification.openTask(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { Shell windowShell = window.getShell(); if (windowShell != null) { windowShell.setMaximized(true); windowShell.open(); } } } }); String descriptionText = null; if (notification.getDescription() != null) { descriptionText = notification.getDescription(); } if (descriptionText != null) { Label descriptionLabel = toolkit.createLabel(sectionClient, descriptionText); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(descriptionLabel); } } else { int numNotificationsRemain = notifications.size() - count; Hyperlink remainingHyperlink = toolkit.createHyperlink(sectionClient, numNotificationsRemain + NOTIFICATIONS_HIDDEN, SWT.NONE); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(remainingHyperlink); remainingHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { TaskListView.getFromActivePerspective().setFocus(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { Shell windowShell = window.getShell(); if (windowShell != null) { windowShell.setMaximized(true); windowShell.open(); } } } }); break; } count++; } section.setClient(sectionClient); ImageHyperlink hyperlink = new ImageHyperlink(section, SWT.NONE); toolkit.adapt(hyperlink, true, true); hyperlink.setBackground(null); hyperlink.setImage(TasksUiImages.getImage(TasksUiImages.NOTIFICATION_CLOSE)); hyperlink.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { close(); } }); section.setTextClient(hyperlink); form.pack(); return parent; }
protected final Control createDialogArea(final Composite parent) { getShell().setText(MYLAR_NOTIFICATION_LABEL); form = toolkit.createForm(parent); form.getBody().setLayout(new GridLayout()); Section section = toolkit.createSection(form.getBody(), Section.TITLE_BAR); section.setText(MYLAR_NOTIFICATION_LABEL); section.setLayout(new GridLayout()); sectionClient = toolkit.createComposite(section); sectionClient.setLayout(new GridLayout(2, false)); int count = 0; for (final ITaskListNotification notification : notifications) { if (count < NUM_NOTIFICATIONS_TO_DISPLAY) { Label notificationLabelIcon = toolkit.createLabel(sectionClient, ""); notificationLabelIcon.setImage(notification.getOverlayIcon()); ImageHyperlink link = toolkit.createImageHyperlink(sectionClient, SWT.BEGINNING | SWT.WRAP); link.setText(notification.getLabel()); link.setImage(notification.getNotificationIcon()); link.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { notification.openTask(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { Shell windowShell = window.getShell(); if (windowShell != null) { windowShell.setMaximized(true); windowShell.open(); } } } }); String descriptionText = null; if (notification.getDescription() != null) { descriptionText = notification.getDescription(); } if (descriptionText != null) { Label descriptionLabel = toolkit.createLabel(sectionClient, descriptionText); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(descriptionLabel); } } else { int numNotificationsRemain = notifications.size() - count; Hyperlink remainingHyperlink = toolkit.createHyperlink(sectionClient, numNotificationsRemain + NOTIFICATIONS_HIDDEN, SWT.NONE); GridDataFactory.fillDefaults().span(2, SWT.DEFAULT).applyTo(remainingHyperlink); remainingHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { TaskListView.openInActivePerspective().setFocus(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { Shell windowShell = window.getShell(); if (windowShell != null) { windowShell.setMaximized(true); windowShell.open(); } } } }); break; } count++; } section.setClient(sectionClient); ImageHyperlink hyperlink = new ImageHyperlink(section, SWT.NONE); toolkit.adapt(hyperlink, true, true); hyperlink.setBackground(null); hyperlink.setImage(TasksUiImages.getImage(TasksUiImages.NOTIFICATION_CLOSE)); hyperlink.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { close(); } }); section.setTextClient(hyperlink); form.pack(); return parent; }
diff --git a/grails/src/java/org/codehaus/groovy/grails/web/binding/GrailsDataBinder.java b/grails/src/java/org/codehaus/groovy/grails/web/binding/GrailsDataBinder.java index 7dbabe192..ac84465f6 100644 --- a/grails/src/java/org/codehaus/groovy/grails/web/binding/GrailsDataBinder.java +++ b/grails/src/java/org/codehaus/groovy/grails/web/binding/GrailsDataBinder.java @@ -1,775 +1,775 @@ /* Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.binding; import grails.util.GrailsNameUtils; import groovy.lang.*; import org.apache.commons.collections.Factory; import org.apache.commons.collections.list.LazyList; import org.apache.commons.collections.set.ListOrderedSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.StringUtils; import org.codehaus.groovy.grails.commons.*; import org.codehaus.groovy.grails.commons.metaclass.CreateDynamicMethod; import org.codehaus.groovy.grails.validation.ConstrainedProperty; import org.codehaus.groovy.grails.web.context.ServletContextHolder; import org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap; import org.codehaus.groovy.runtime.InvokerHelper; import org.springframework.beans.*; import org.springframework.beans.PropertyValue; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.beans.propertyeditors.LocaleEditor; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.ServletRequestParameterPropertyValues; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor; import org.springframework.web.multipart.support.StringMultipartFileEditor; import org.springframework.web.servlet.support.RequestContextUtils; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import java.beans.PropertyEditor; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.*; /** * A data binder that handles binding dates that are specified with a "struct"-like syntax in request parameters. * For example for a set of fields defined as: * * <code> * <input type="hidden" name="myDate_year" value="2005" /> * <input type="hidden" name="myDate_month" value="6" /> * <input type="hidden" name="myDate_day" value="12" /> * <input type="hidden" name="myDate_hour" value="13" /> * <input type="hidden" name="myDate_minute" value="45" /> * </code> * * This would set the property "myDate" of type java.util.Date with the specified values. * * @author Graeme Rocher * @since 05-Jan-2006 */ public class GrailsDataBinder extends ServletRequestDataBinder { private static final Log LOG = LogFactory.getLog(GrailsDataBinder.class); protected BeanWrapper bean; public static final String[] GROOVY_DISALLOWED = new String[] { "metaClass", "properties" }; public static final String[] DOMAINCLASS_DISALLOWED = new String[] { "id", "version" }; public static final String[] GROOVY_DOMAINCLASS_DISALLOWED = new String[] { "metaClass", "properties", "id", "version" }; public static final String NULL_ASSOCIATION = "null"; private static final String PREFIX_SEPERATOR = "."; private static final String[] ALL_OTHER_FIELDS_ALLOWED_BY_DEFAULT = new String[0]; private static final String CONSTRAINTS_PROPERTY = "constraints"; private static final String BLANK = ""; private static final String STRUCTURED_PROPERTY_SEPERATOR = "_"; private static final char PATH_SEPARATOR = '.'; private static final String IDENTIFIER_SUFFIX = ".id"; private List transients = Collections.EMPTY_LIST; private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.S"; /** * Create a new GrailsDataBinder instance. * * @param target target object to bind onto * @param objectName objectName of the target object */ public GrailsDataBinder(Object target, String objectName) { super(target, objectName); bean = (BeanWrapper)((BeanPropertyBindingResult)super.getBindingResult()).getPropertyAccessor(); Object tmpTransients = GrailsClassUtils.getStaticPropertyValue(bean.getWrappedClass(), GrailsDomainClassProperty.TRANSIENT); if(tmpTransients instanceof List) { this.transients = (List) tmpTransients; } String[] disallowed = new String[0]; GrailsApplication grailsApplication = ApplicationHolder.getApplication(); if (grailsApplication!=null && grailsApplication.isArtefactOfType(DomainClassArtefactHandler.TYPE, target.getClass())) { if (target instanceof GroovyObject) { disallowed = GROOVY_DOMAINCLASS_DISALLOWED; } else { disallowed = DOMAINCLASS_DISALLOWED; } } else if (target instanceof GroovyObject) { disallowed = GROOVY_DISALLOWED; } setDisallowedFields(disallowed); setAllowedFields(ALL_OTHER_FIELDS_ALLOWED_BY_DEFAULT); setIgnoreInvalidFields(true); } /** * Collects all PropertyEditorRegistrars in the application context and * calls them to register their custom editors * @param registry The PropertyEditorRegistry instance */ private static void registerCustomEditors(PropertyEditorRegistry registry) { final ServletContext servletContext = ServletContextHolder.getServletContext(); if(servletContext != null) { WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext); if(context != null) { Map editors = context.getBeansOfType(PropertyEditorRegistrar.class); for (Object o : editors.entrySet()) { PropertyEditorRegistrar editorRegistrar = (PropertyEditorRegistrar) ((Map.Entry) o).getValue(); editorRegistrar.registerCustomEditors(registry); } } } } /** * Utility method for creating a GrailsDataBinder instance * * @param target The target object to bind to * @param objectName The name of the object * @param request A request instance * @return A GrailsDataBinder instance */ public static GrailsDataBinder createBinder(Object target, String objectName, HttpServletRequest request) { GrailsDataBinder binder = createBinder(target,objectName); Locale locale = RequestContextUtils.getLocale(request); registerCustomEditors(binder, locale); return binder; } /** * Registers all known * @param registry * @param locale */ public static void registerCustomEditors(PropertyEditorRegistry registry, Locale locale) { // Formatters for the different number types. NumberFormat floatFormat = NumberFormat.getInstance(locale); NumberFormat integerFormat = NumberFormat.getIntegerInstance(locale); DateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT, locale); registry.registerCustomEditor( Date.class, new CustomDateEditor(dateFormat,true) ); registry.registerCustomEditor( BigDecimal.class, new CustomNumberEditor(BigDecimal.class, floatFormat, true)); registry.registerCustomEditor( BigInteger.class, new CustomNumberEditor(BigInteger.class, floatFormat, true)); registry.registerCustomEditor( Double.class, new CustomNumberEditor(Double.class, floatFormat, true)); registry.registerCustomEditor( double.class, new CustomNumberEditor(Double.class, floatFormat, true)); registry.registerCustomEditor( Float.class, new CustomNumberEditor(Float.class, floatFormat, true)); registry.registerCustomEditor( float.class, new CustomNumberEditor(Float.class, floatFormat, true)); registry.registerCustomEditor( Long.class, new CustomNumberEditor(Long.class, integerFormat, true)); registry.registerCustomEditor( long.class, new CustomNumberEditor(Long.class, integerFormat, true)); registry.registerCustomEditor( Integer.class, new CustomNumberEditor(Integer.class, integerFormat, true)); registry.registerCustomEditor( int.class, new CustomNumberEditor(Integer.class, integerFormat, true)); registry.registerCustomEditor( Short.class, new CustomNumberEditor(Short.class, integerFormat, true)); registry.registerCustomEditor( short.class, new CustomNumberEditor(Short.class, integerFormat, true)); registry.registerCustomEditor( Date.class, new StructuredDateEditor(dateFormat,true)); registry.registerCustomEditor( Calendar.class, new StructuredDateEditor(dateFormat,true)); registerCustomEditors(registry); } /** * Utility method for creating a GrailsDataBinder instance * * @param target The target object to bind to * @param objectName The name of the object * @return A GrailsDataBinder instance */ public static GrailsDataBinder createBinder(Object target, String objectName) { GrailsDataBinder binder = new GrailsDataBinder(target,objectName); binder.registerCustomEditor( byte[].class, new ByteArrayMultipartFileEditor()); binder.registerCustomEditor( String.class, new StringMultipartFileEditor()); binder.registerCustomEditor( Currency.class, new CurrencyEditor()); binder.registerCustomEditor( Locale.class, new LocaleEditor()); binder.registerCustomEditor( TimeZone.class, new TimeZoneEditor()); binder.registerCustomEditor( URI.class, new UriEditor()); registerCustomEditors(binder); return binder; } public void bind(PropertyValues propertyValues) { bind(propertyValues, null); } /** * Binds from a GrailsParameterMap object * * @param params The GrailsParameterMap object */ public void bind(GrailsParameterMap params) { bind(params,null); } public void bind(GrailsParameterMap params, String prefix) { Map paramsMap = params; if(prefix != null) { Object o = params.get(prefix); if(o instanceof Map) paramsMap = (Map) o; } bindWithRequestAndPropertyValues(params.getRequest(), new MutablePropertyValues(paramsMap)); } public void bind(PropertyValues propertyValues, String prefix) { PropertyValues values = filterPropertyValues(propertyValues, prefix); if(propertyValues instanceof MutablePropertyValues) { MutablePropertyValues mutablePropertyValues = (MutablePropertyValues) propertyValues; preProcessMutablePropertyValues(mutablePropertyValues); } super.bind(values); } public void bind(ServletRequest request) { bind(request, null); } public void bind(ServletRequest request, String prefix) { MutablePropertyValues mpvs; if (prefix != null) { mpvs = new ServletRequestParameterPropertyValues(request, prefix, PREFIX_SEPERATOR); } else { mpvs = new ServletRequestParameterPropertyValues(request); } bindWithRequestAndPropertyValues(request, mpvs); } private void bindWithRequestAndPropertyValues(ServletRequest request, MutablePropertyValues mpvs) { preProcessMutablePropertyValues(mpvs); if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; bindMultipartFiles(multipartRequest.getFileMap(), mpvs); } doBind(mpvs); } private void preProcessMutablePropertyValues(MutablePropertyValues mpvs) { checkStructuredProperties(mpvs); autoCreateIfPossible(mpvs); bindAssociations(mpvs); } protected void doBind(MutablePropertyValues mpvs) { filterNestedParameterMaps(mpvs); filterBlankValuesWhenTargetIsNullable(mpvs); super.doBind(mpvs); } private void filterBlankValuesWhenTargetIsNullable(MutablePropertyValues mpvs) { Object target = getTarget(); MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(target.getClass()); if(mc.hasProperty(target, CONSTRAINTS_PROPERTY) != null) { Map constrainedProperties = (Map)mc.getProperty(target, CONSTRAINTS_PROPERTY); PropertyValue[] valueArray = mpvs.getPropertyValues(); for (PropertyValue propertyValue : valueArray) { ConstrainedProperty cp = getConstrainedPropertyForPropertyValue(constrainedProperties, propertyValue); if (shouldNullifyBlankString(propertyValue, cp)) { propertyValue.setConvertedValue(null); } } } } private ConstrainedProperty getConstrainedPropertyForPropertyValue(Map constrainedProperties, PropertyValue propertyValue) { final String propertyName = propertyValue.getName(); if(propertyName.indexOf(PATH_SEPARATOR) > -1) { String[] propertyNames = propertyName.split("\\."); Object target = getTarget(); Object value = getPropertyValueForPath(target, propertyNames); if(value != null) { MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(value.getClass()); if(mc.hasProperty(value, CONSTRAINTS_PROPERTY) != null) { Map nestedConstrainedProperties = (Map)mc.getProperty(value, CONSTRAINTS_PROPERTY); return (ConstrainedProperty)nestedConstrainedProperties.get(propertyNames[propertyNames.length-1]); } } } else { return (ConstrainedProperty)constrainedProperties.get(propertyName); } return null; } private Object getPropertyValueForPath(Object target, String[] propertyNames) { BeanWrapper bean = new BeanWrapperImpl(target); Object obj = target; for (int i = 0; i < propertyNames.length-1; i++) { String propertyName = propertyNames[i]; if(bean.isReadableProperty(propertyName)) { obj = bean.getPropertyValue(propertyName); if(obj == null) break; bean = new BeanWrapperImpl(obj); } } return obj; } private boolean shouldNullifyBlankString(PropertyValue propertyValue, ConstrainedProperty cp) { return cp!= null && cp.isNullable() && BLANK.equals(propertyValue.getValue()); } private void filterNestedParameterMaps(MutablePropertyValues mpvs) { PropertyValue[] values = mpvs.getPropertyValues(); for (PropertyValue pv : values) { if (pv.getValue() instanceof GrailsParameterMap) { mpvs.removePropertyValue(pv); } } } private PropertyValues filterPropertyValues(PropertyValues propertyValues, String prefix) { if(prefix == null || prefix.length() == 0) return propertyValues; PropertyValue[] valueArray = propertyValues.getPropertyValues(); MutablePropertyValues newValues = new MutablePropertyValues(); for (PropertyValue propertyValue : valueArray) { if (propertyValue.getName().startsWith(prefix + PREFIX_SEPERATOR)) { newValues.addPropertyValue(propertyValue.getName().replaceFirst(prefix + PREFIX_SEPERATOR, ""), propertyValue.getValue()); } } return newValues; } /** * Method that auto-creates the a type if it is null and is possible to auto-create * * @param mpvs A MutablePropertyValues instance */ protected void autoCreateIfPossible(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String propertyName = pv.getName(); //super. if (propertyName.indexOf(PATH_SEPARATOR) > -1) { String[] propertyNames = propertyName.split("\\."); BeanWrapper currentBean = bean; for (String name : propertyNames) { Object created = autoCreatePropertyIfPossible(currentBean, name, pv.getValue()); if (created != null) currentBean = new BeanWrapperImpl(created); else break; } } else { autoCreatePropertyIfPossible(bean, propertyName, pv.getValue()); } } } private Object autoCreatePropertyIfPossible(BeanWrapper bean, String propertyName, Object propertyValue) { propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName); int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR); int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR); String propertyNameWithIndex = propertyName; if(currentKeyStart>-1) { propertyName = propertyName.substring(0, currentKeyStart); } Class type = bean.getPropertyType(propertyName); Object val = bean.isReadableProperty(propertyName) ? bean.getPropertyValue(propertyName) : null; LOG.debug("Checking if auto-create is possible for property ["+propertyName+"] and type ["+type+"]"); - if(type != null && val == null && GroovyObject.class.isAssignableFrom(type)) { + if(type != null && val == null && DomainClassArtefactHandler.isDomainClass(type)) { if(!shouldPropertyValueSkipAutoCreate(propertyValue) && isNullAndWritableProperty(bean, propertyName)) { Object created = autoInstantiateDomainInstance(type); if(created!=null) { val = created; bean.setPropertyValue(propertyName,created); } } } else { final Object beanInstance = bean.getWrappedInstance(); if(type!= null && Collection.class.isAssignableFrom(type)) { Collection c; final Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance); if(isNullAndWritableProperty(bean, propertyName)) { c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type), referencedType); } else { c = decorateCollectionForDomainAssociation((Collection) bean.getPropertyValue(propertyName), referencedType); } bean.setPropertyValue(propertyName, c); val = c; if(c!= null && currentKeyStart > -1 && currentKeyEnd > -1) { String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd); int index = Integer.parseInt(indexString); if(DomainClassArtefactHandler.isDomainClass(referencedType)) { Object instance = findIndexedValue(c, index); if(instance != null) { val = instance; } else { instance = autoInstantiateDomainInstance(referencedType); if(instance !=null) { val = instance; if(index == c.size()) { addAssociationToTarget(propertyName, beanInstance, instance); } else if(index > c.size()) { while(index > c.size()) { addAssociationToTarget(propertyName, beanInstance, autoInstantiateDomainInstance(referencedType)); } addAssociationToTarget(propertyName, beanInstance, instance); } } } } } } else if(type!=null && Map.class.isAssignableFrom(type)) { Map map; if(isNullAndWritableProperty(bean, propertyName)) { map = new HashMap(); bean.setPropertyValue(propertyName,map); } else { map = (Map) bean.getPropertyValue(propertyName); } val = map; bean.setPropertyValue(propertyName, val); if(currentKeyStart > -1 && currentKeyEnd > -1) { String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd); Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance); if(DomainClassArtefactHandler.isDomainClass(referencedType)) { final Object domainInstance = autoInstantiateDomainInstance(referencedType); val = domainInstance; map.put(indexString, domainInstance); } } } } return val; } private boolean shouldPropertyValueSkipAutoCreate(Object propertyValue) { return (propertyValue instanceof Map) || ((propertyValue instanceof String) && StringUtils.isBlank((String) propertyValue)); } private Collection decorateCollectionForDomainAssociation(Collection c, final Class referencedType) { if(canDecorateWithLazyList(c, referencedType)) { c = LazyList.decorate((List)c, new Factory() { public Object create() { return autoInstantiateDomainInstance(referencedType); } }); } else if(canDecorateWithListOrderedSet(c, referencedType)) { c = ListOrderedSet.decorate((Set) c); } return c; } private boolean canDecorateWithListOrderedSet(Collection c, Class referencedType) { return (c instanceof Set) && !(c instanceof ListOrderedSet) && !(c instanceof SortedSet) && DomainClassArtefactHandler.isDomainClass(referencedType); } private boolean canDecorateWithLazyList(Collection c, Class referencedType) { return (c instanceof List) && !(c instanceof LazyList) && DomainClassArtefactHandler.isDomainClass(referencedType); } private Object findIndexedValue(Collection c, int index) { if(index < c.size()) { if(c instanceof List) { return ((List)c).get(index); } else { int j =0; for (Iterator i = c.iterator(); i.hasNext();j++) { Object o = i.next(); if(j == index) return o; } } } return null; } private Object autoInstantiateDomainInstance(Class type) { Object created = null; try { MetaClass mc = GroovySystem.getMetaClassRegistry() .getMetaClass(type); if(mc!=null) { created = mc.invokeStaticMethod(type, CreateDynamicMethod.METHOD_NAME, new Object[0]); } } catch(MissingMethodException mme) { LOG.warn("Unable to auto-create type, 'create' method not found"); } catch(GroovyRuntimeException gre) { LOG.warn("Unable to auto-create type, Groovy Runtime error: " + gre.getMessage(),gre) ; } return created; } private boolean isNullAndWritableProperty(ConfigurablePropertyAccessor bean, String propertyName) { return bean.getPropertyValue(propertyName) == null && bean.isWritableProperty(propertyName); } /** * Interrogates the specified properties looking for properites that represent associations to other * classes (e.g., 'author.id'). If such a property is found, this method attempts to load the specified * instance of the association (by ID) and set it on the target object. * * @param mpvs the <code>MutablePropertyValues</code> object holding the parameters from the request */ protected void bindAssociations(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String propertyName = pv.getName(); if (propertyName.endsWith(IDENTIFIER_SUFFIX)) { propertyName = propertyName.substring(0, propertyName.length() - 3); if (isReadableAndPersistent(propertyName) && bean.isWritableProperty(propertyName)) { if (NULL_ASSOCIATION.equals(pv.getValue())) { bean.setPropertyValue(propertyName, null); mpvs.removePropertyValue(pv); } else { Class type = bean.getPropertyType(propertyName); Object persisted = getPersistentInstance(type, pv.getValue()); if (persisted != null) { bean.setPropertyValue(propertyName, persisted); } } } } else { if (isReadableAndPersistent(propertyName)) { Class type = bean.getPropertyType(propertyName); if (Collection.class.isAssignableFrom(type)) { bindCollectionAssociation(mpvs, pv); } } } } } private boolean isReadableAndPersistent(String propertyName) { return bean.isReadableProperty(propertyName) && !transients.contains(propertyName); } private Object getPersistentInstance(Class type, Object id) { Object persisted;// In order to load the association instance using InvokerHelper below, we need to // temporarily change this thread's ClassLoader to use the Grails ClassLoader. // (Otherwise, we'll get a ClassNotFoundException.) ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader grailsClassLoader = getTarget().getClass().getClassLoader(); try { try { Thread.currentThread().setContextClassLoader(grailsClassLoader); } catch (java.security.AccessControlException e) { // container doesn't allow, probably related to WAR deployment on AppEngine. proceed. } try { persisted = InvokerHelper.invokeStaticMethod(type, "get", id); } catch (MissingMethodException e) { return null; // GORM not installed, continue to operate as normal } } finally { try { Thread.currentThread().setContextClassLoader(currentClassLoader); } catch (java.security.AccessControlException e) { // container doesn't allow, probably related to WAR deployment on AppEngine. proceed. } } return persisted; } private void bindCollectionAssociation(MutablePropertyValues mpvs, PropertyValue pv) { Object v = pv.getValue(); Collection collection = (Collection) bean.getPropertyValue(pv.getName()); collection.clear(); if(v != null && v.getClass().isArray()) { Object[] identifiers = (Object[])v; for (Object id : identifiers) { if (id != null) { associateObjectForId(pv, id); } } mpvs.removePropertyValue(pv); } else if(v!=null && (v instanceof String)) { associateObjectForId(pv,v); mpvs.removePropertyValue(pv); } } private void associateObjectForId(PropertyValue pv, Object id) { final Object target = getTarget(); final Class associatedType = getReferencedTypeForCollection(pv.getName(), target); if(isDomainAssociation(associatedType)) { final Object obj = getPersistentInstance(associatedType, id); addAssociationToTarget(pv.getName(), target, obj); } } private boolean isDomainAssociation(Class associatedType) { return associatedType != null && DomainClassArtefactHandler.isDomainClass(associatedType); } private void addAssociationToTarget(String name, Object target, Object obj) { if(obj!=null) { MetaClassRegistry reg = GroovySystem.getMetaClassRegistry(); MetaClass mc = reg.getMetaClass(target.getClass()); final String addMethodName = "addTo" + GrailsNameUtils.getClassNameRepresentation(name); mc.invokeMethod(target, addMethodName,obj); } } private Class getReferencedTypeForCollection(String name, Object target) { final GrailsApplication grailsApplication = ApplicationHolder.getApplication(); if(grailsApplication!=null) { GrailsDomainClass domainClass = (GrailsDomainClass) grailsApplication.getArtefact(DomainClassArtefactHandler.TYPE, target.getClass().getName()); if(domainClass!=null) { GrailsDomainClassProperty domainProperty = domainClass.getPropertyByName(name); if(domainProperty!=null && (domainProperty.isOneToMany()|| domainProperty.isManyToMany())) { return domainProperty.getReferencedPropertyType(); } } } return null; } private String getNameOf(PropertyValue propertyValue) { String name = propertyValue.getName(); if (name.indexOf(STRUCTURED_PROPERTY_SEPERATOR) == -1) { return name; } return name.substring(0, name.indexOf(STRUCTURED_PROPERTY_SEPERATOR)); } private boolean isStructured(PropertyValue propertyValue) { String name = propertyValue.getName(); return name.indexOf(STRUCTURED_PROPERTY_SEPERATOR) != -1; } /** * Checks for structured properties. Structured properties are properties with a name * containg a "_" * @param propertyValues */ private void checkStructuredProperties(MutablePropertyValues propertyValues) { PropertyValue[] pvs = propertyValues.getPropertyValues(); for (PropertyValue propertyValue : pvs) { if (!isStructured(propertyValue)) { continue; } String propertyName = getNameOf(propertyValue); Class type = bean.getPropertyType(propertyName); if (type != null) { PropertyEditor editor = findCustomEditor(type, propertyName); if (null != editor && StructuredPropertyEditor.class.isAssignableFrom(editor.getClass())) { StructuredPropertyEditor structuredEditor = (StructuredPropertyEditor) editor; List fields = new ArrayList(); fields.addAll(structuredEditor.getRequiredFields()); fields.addAll(structuredEditor.getOptionalFields()); Map<String, String> fieldValues = new HashMap<String, String>(); try { for (Object field1 : fields) { String field = (String) field1; PropertyValue requiredProperty = propertyValues.getPropertyValue(propertyName + STRUCTURED_PROPERTY_SEPERATOR + field); if (requiredProperty == null && structuredEditor.getRequiredFields().contains(field)) { break; } else if (requiredProperty == null) continue; fieldValues.put(field, getStringValue(requiredProperty)); } try { Object value = structuredEditor.assemble(type, fieldValues); if (null != value) { for (Object field : fields) { String requiredField = (String) field; PropertyValue requiredProperty = propertyValues.getPropertyValue(propertyName + STRUCTURED_PROPERTY_SEPERATOR + requiredField); if (null != requiredProperty) { requiredProperty.setConvertedValue(getStringValue(requiredProperty)); } } propertyValues.addPropertyValue(new PropertyValue(propertyName, value)); } } catch (IllegalArgumentException iae) { LOG.warn("Unable to parse structured date from request for date [" + propertyName + "]", iae); } } catch (InvalidPropertyException ipe) { // ignore } } } } } private String getStringValue(PropertyValue yearProperty) { Object value = yearProperty.getValue(); if(value == null) return null; else if(value.getClass().isArray()) { return ((String[])value)[0]; } return (String)value ; } }
true
true
private Object autoCreatePropertyIfPossible(BeanWrapper bean, String propertyName, Object propertyValue) { propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName); int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR); int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR); String propertyNameWithIndex = propertyName; if(currentKeyStart>-1) { propertyName = propertyName.substring(0, currentKeyStart); } Class type = bean.getPropertyType(propertyName); Object val = bean.isReadableProperty(propertyName) ? bean.getPropertyValue(propertyName) : null; LOG.debug("Checking if auto-create is possible for property ["+propertyName+"] and type ["+type+"]"); if(type != null && val == null && GroovyObject.class.isAssignableFrom(type)) { if(!shouldPropertyValueSkipAutoCreate(propertyValue) && isNullAndWritableProperty(bean, propertyName)) { Object created = autoInstantiateDomainInstance(type); if(created!=null) { val = created; bean.setPropertyValue(propertyName,created); } } } else { final Object beanInstance = bean.getWrappedInstance(); if(type!= null && Collection.class.isAssignableFrom(type)) { Collection c; final Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance); if(isNullAndWritableProperty(bean, propertyName)) { c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type), referencedType); } else { c = decorateCollectionForDomainAssociation((Collection) bean.getPropertyValue(propertyName), referencedType); } bean.setPropertyValue(propertyName, c); val = c; if(c!= null && currentKeyStart > -1 && currentKeyEnd > -1) { String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd); int index = Integer.parseInt(indexString); if(DomainClassArtefactHandler.isDomainClass(referencedType)) { Object instance = findIndexedValue(c, index); if(instance != null) { val = instance; } else { instance = autoInstantiateDomainInstance(referencedType); if(instance !=null) { val = instance; if(index == c.size()) { addAssociationToTarget(propertyName, beanInstance, instance); } else if(index > c.size()) { while(index > c.size()) { addAssociationToTarget(propertyName, beanInstance, autoInstantiateDomainInstance(referencedType)); } addAssociationToTarget(propertyName, beanInstance, instance); } } } } } } else if(type!=null && Map.class.isAssignableFrom(type)) { Map map; if(isNullAndWritableProperty(bean, propertyName)) { map = new HashMap(); bean.setPropertyValue(propertyName,map); } else { map = (Map) bean.getPropertyValue(propertyName); } val = map; bean.setPropertyValue(propertyName, val); if(currentKeyStart > -1 && currentKeyEnd > -1) { String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd); Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance); if(DomainClassArtefactHandler.isDomainClass(referencedType)) { final Object domainInstance = autoInstantiateDomainInstance(referencedType); val = domainInstance; map.put(indexString, domainInstance); } } } } return val; }
private Object autoCreatePropertyIfPossible(BeanWrapper bean, String propertyName, Object propertyValue) { propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName); int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR); int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR); String propertyNameWithIndex = propertyName; if(currentKeyStart>-1) { propertyName = propertyName.substring(0, currentKeyStart); } Class type = bean.getPropertyType(propertyName); Object val = bean.isReadableProperty(propertyName) ? bean.getPropertyValue(propertyName) : null; LOG.debug("Checking if auto-create is possible for property ["+propertyName+"] and type ["+type+"]"); if(type != null && val == null && DomainClassArtefactHandler.isDomainClass(type)) { if(!shouldPropertyValueSkipAutoCreate(propertyValue) && isNullAndWritableProperty(bean, propertyName)) { Object created = autoInstantiateDomainInstance(type); if(created!=null) { val = created; bean.setPropertyValue(propertyName,created); } } } else { final Object beanInstance = bean.getWrappedInstance(); if(type!= null && Collection.class.isAssignableFrom(type)) { Collection c; final Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance); if(isNullAndWritableProperty(bean, propertyName)) { c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type), referencedType); } else { c = decorateCollectionForDomainAssociation((Collection) bean.getPropertyValue(propertyName), referencedType); } bean.setPropertyValue(propertyName, c); val = c; if(c!= null && currentKeyStart > -1 && currentKeyEnd > -1) { String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd); int index = Integer.parseInt(indexString); if(DomainClassArtefactHandler.isDomainClass(referencedType)) { Object instance = findIndexedValue(c, index); if(instance != null) { val = instance; } else { instance = autoInstantiateDomainInstance(referencedType); if(instance !=null) { val = instance; if(index == c.size()) { addAssociationToTarget(propertyName, beanInstance, instance); } else if(index > c.size()) { while(index > c.size()) { addAssociationToTarget(propertyName, beanInstance, autoInstantiateDomainInstance(referencedType)); } addAssociationToTarget(propertyName, beanInstance, instance); } } } } } } else if(type!=null && Map.class.isAssignableFrom(type)) { Map map; if(isNullAndWritableProperty(bean, propertyName)) { map = new HashMap(); bean.setPropertyValue(propertyName,map); } else { map = (Map) bean.getPropertyValue(propertyName); } val = map; bean.setPropertyValue(propertyName, val); if(currentKeyStart > -1 && currentKeyEnd > -1) { String indexString = propertyNameWithIndex.substring(currentKeyStart+1, currentKeyEnd); Class referencedType = getReferencedTypeForCollection(propertyName, beanInstance); if(DomainClassArtefactHandler.isDomainClass(referencedType)) { final Object domainInstance = autoInstantiateDomainInstance(referencedType); val = domainInstance; map.put(indexString, domainInstance); } } } } return val; }
diff --git a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/ASTEvaluationEngine.java b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/ASTEvaluationEngine.java index 7bf0d282e..8122d5b25 100644 --- a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/ASTEvaluationEngine.java +++ b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/ASTEvaluationEngine.java @@ -1,269 +1,260 @@ /* * (c) Copyright IBM Corp. 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.debug.eval.ast; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.DebugException; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Message; import org.eclipse.jdt.debug.core.IJavaDebugTarget; import org.eclipse.jdt.debug.core.IJavaObject; import org.eclipse.jdt.debug.core.IJavaStackFrame; import org.eclipse.jdt.debug.core.IJavaThread; import org.eclipse.jdt.debug.core.IJavaValue; import org.eclipse.jdt.debug.eval.IEvaluationEngine; import org.eclipse.jdt.debug.eval.IEvaluationListener; import org.eclipse.jdt.debug.eval.ast.model.ICompiledExpression; import org.eclipse.jdt.debug.eval.ast.model.IRuntimeContext; import org.eclipse.jdt.debug.eval.ast.model.IValue; import org.eclipse.jdt.debug.eval.ast.model.IVariable; import org.eclipse.jdt.internal.debug.eval.ast.engine.ASTAPIVisitor; import org.eclipse.jdt.internal.debug.eval.ast.engine.InstructionSequence; import org.eclipse.jdt.internal.debug.core.model.JDIThread; import org.eclipse.jdt.internal.debug.eval.EvaluationResult; /** * @version 1.0 * @author */ public class ASTEvaluationEngine implements IEvaluationEngine { private IJavaProject fProject; private IJavaDebugTarget fDebugTarget; private boolean fEvaluationCancelled; private boolean fEvaluationComplete; public ASTEvaluationEngine(IJavaProject project, IJavaDebugTarget debugTarget) { setJavaProject(project); setDebugTarget(debugTarget); } public void setJavaProject(IJavaProject project) { fProject = project; } public void setDebugTarget(IJavaDebugTarget debugTarget) { fDebugTarget = debugTarget; } /* * @see IEvaluationEngine#evaluate(String, IJavaThread, IEvaluationListener) */ public void evaluate(String snippet, IJavaThread thread, IEvaluationListener listener) throws DebugException { } /** * @see IEvaluationEngine#evaluate(String, IJavaStackFrame, IEvaluationListener) */ public void evaluate(String snippet, IJavaStackFrame frame, IEvaluationListener listener) throws DebugException { ICompiledExpression expression= getCompiledExpression(snippet, frame); evaluate(expression, frame, listener); } /** * @see IEvaluationEngine#evaluate(ICompiledExpression, IJavaStackFrame, IEvaluationListener) */ public void evaluate(final ICompiledExpression expression, final IJavaStackFrame frame, final IEvaluationListener listener) { RuntimeContext context = new RuntimeContext(getJavaProject(), frame); evaluate(expression, context, (IJavaThread)frame.getThread(), listener); } /** * @see IEvaluationEngine#evaluate(String, IJavaObject, IJavaThread, IEvaluationListener) */ public void evaluate(String snippet, IJavaObject thisContext, IJavaThread thread, IEvaluationListener listener) throws DebugException { ICompiledExpression expression= getCompiledExpression(snippet, thisContext, thread); evaluate(expression, thisContext, thread, listener); } /** * @see IEvaluationEngine#evaluate(ICompiledExpression, IJavaObject, IJavaThread, IEvaluationListener) */ public void evaluate(final ICompiledExpression expression, final IJavaObject thisContext, final IJavaThread thread, final IEvaluationListener listener) { IRuntimeContext context = new JavaObjectRuntimeContext(thisContext, getJavaProject(), thread); evaluate(expression, context, thread, listener); } /** * Performs the evaluation. */ public void evaluate(final ICompiledExpression expression, final IRuntimeContext context, final IJavaThread thread, final IEvaluationListener listener) { Thread evaluationThread= new Thread(new Runnable() { public void run() { fEvaluationCancelled= false; fEvaluationComplete= false; EvaluationResult result = new EvaluationResult(ASTEvaluationEngine.this, expression.getSnippet(), thread); if (expression.hasErrors()) { Message[] errors= expression.getErrors(); for (int i= 0, numErrors= errors.length; i < numErrors; i++) { result.addError(errors[i]); } listener.evaluationComplete(result); return; } IValue value = null; Thread timeoutThread= new Thread(new Runnable() { public void run() { while (!fEvaluationComplete && !fEvaluationCancelled) { try { Thread.currentThread().sleep(3000); // 10 second timeout for now } catch(InterruptedException e) { } - if (!fEvaluationComplete) { - try { - ((JDIThread)thread).suspendQuiet(); - if (!listener.evaluationTimedOut(thread)) { - fEvaluationCancelled= true; - } else { - // Keep waiting - ((JDIThread)thread).resumeQuiet(); - } - } catch(DebugException e) { - } + if (!fEvaluationComplete && !listener.evaluationTimedOut(thread)) { + fEvaluationCancelled= true; } } } }, "Evaluation timeout thread"); timeoutThread.start(); value= expression.evaluate(context); fEvaluationComplete= true; if (fEvaluationCancelled) { // Don't notify the listener if the evaluation has been cancelled return; } CoreException exception= expression.getException(); if (value != null) { IJavaValue jv = ((EvaluationValue)value).getJavaValue(); result.setValue(jv); } result.setException(exception); listener.evaluationComplete(result); } }, "Evaluation thread"); evaluationThread.start(); } /* * @see IEvaluationEngine#getCompiledExpression(String, IJavaStackFrame) */ public ICompiledExpression getCompiledExpression(String snippet, IJavaStackFrame frame) throws DebugException { IJavaProject javaProject = getJavaProject(); RuntimeContext context = new RuntimeContext(javaProject, frame); ASTCodeSnippetToCuMapper mapper = null; CompilationUnit unit = null; try { IVariable[] locals = context.getLocals(); int numLocals= locals.length; int[] localModifiers = new int[locals.length]; String[] localTypesNames= new String[numLocals]; String[] localVariables= new String[numLocals]; for (int i = 0; i < numLocals; i++) { localVariables[i] = locals[i].getName(); localTypesNames[i] = ((EvaluationValue)locals[i].getValue()).getJavaValue().getReferenceTypeName(); localModifiers[i]= 0; } mapper = new ASTCodeSnippetToCuMapper(new String[0], localModifiers, localTypesNames, localVariables, snippet); unit = AST.parseCompilationUnit(mapper.getSource(frame).toCharArray(), mapper.getCompilationUnitName(), javaProject); } catch (JavaModelException e) { throw new DebugException(e.getStatus()); } catch (CoreException e) { throw new DebugException(e.getStatus()); } return genExpressionFromAST(snippet, mapper, unit); } public ICompiledExpression getCompiledExpression(String snippet, IJavaObject thisContext, IJavaThread thread) throws DebugException { IJavaProject javaProject = getJavaProject(); ASTCodeSnippetToCuMapper mapper = null; CompilationUnit unit = null; try { mapper = new ASTCodeSnippetToCuMapper(new String[0], new int[0], new String[0], new String[0], snippet); unit = AST.parseCompilationUnit(mapper.getSource(thisContext, javaProject).toCharArray(), mapper.getCompilationUnitName(), javaProject); } catch (CoreException e) { throw new DebugException(e.getStatus()); } return genExpressionFromAST(snippet, mapper, unit); } private ICompiledExpression genExpressionFromAST(String snippet, ASTCodeSnippetToCuMapper mapper, CompilationUnit unit) { Message[] messages= unit.getMessages(); if (messages.length != 0) { boolean error= false; InstructionSequence errorSequence= new InstructionSequence(snippet); int codeSnippetStartOffset= mapper.getStartPosition(); int codeSnippetEndOffset= codeSnippetStartOffset + snippet.length(); for (int i = 0; i < messages.length; i++) { Message message= messages[i]; int errorOffset= message.getSourcePosition(); // TO DO: Internationalize "void method..." error message check if (codeSnippetStartOffset <= errorOffset && errorOffset <= codeSnippetEndOffset && !"Void methods cannot return a value".equals(message.getMessage())) { errorSequence.addError(message); error = true; } } if (error) { return errorSequence; } } ASTAPIVisitor visitor = new ASTAPIVisitor(mapper.getStartPosition(), snippet); unit.accept(visitor); return visitor.getInstructions(); } /* * @see IEvaluationEngine#getJavaProject() */ public IJavaProject getJavaProject() { return fProject; } /* * @see IEvaluationEngine#getDebugTarget() */ public IJavaDebugTarget getDebugTarget() { return fDebugTarget; } /* * @see IEvaluationEngine#dispose() */ public void dispose() { } /** * @see IEvaluationEngine#evaluate(ICompiledExpression, IJavaThread, IEvaluationListener) */ public void evaluate(ICompiledExpression expression, IJavaThread thread, IEvaluationListener listener) throws DebugException { } /** * @see IEvaluationEngine#getCompiledExpression(String, IJavaThread) */ public ICompiledExpression getCompiledExpression(String snippet, IJavaThread thread) throws DebugException { return null; } }
true
true
public void evaluate(final ICompiledExpression expression, final IRuntimeContext context, final IJavaThread thread, final IEvaluationListener listener) { Thread evaluationThread= new Thread(new Runnable() { public void run() { fEvaluationCancelled= false; fEvaluationComplete= false; EvaluationResult result = new EvaluationResult(ASTEvaluationEngine.this, expression.getSnippet(), thread); if (expression.hasErrors()) { Message[] errors= expression.getErrors(); for (int i= 0, numErrors= errors.length; i < numErrors; i++) { result.addError(errors[i]); } listener.evaluationComplete(result); return; } IValue value = null; Thread timeoutThread= new Thread(new Runnable() { public void run() { while (!fEvaluationComplete && !fEvaluationCancelled) { try { Thread.currentThread().sleep(3000); // 10 second timeout for now } catch(InterruptedException e) { } if (!fEvaluationComplete) { try { ((JDIThread)thread).suspendQuiet(); if (!listener.evaluationTimedOut(thread)) { fEvaluationCancelled= true; } else { // Keep waiting ((JDIThread)thread).resumeQuiet(); } } catch(DebugException e) { } } } } }, "Evaluation timeout thread"); timeoutThread.start(); value= expression.evaluate(context); fEvaluationComplete= true; if (fEvaluationCancelled) { // Don't notify the listener if the evaluation has been cancelled return; } CoreException exception= expression.getException(); if (value != null) { IJavaValue jv = ((EvaluationValue)value).getJavaValue(); result.setValue(jv); } result.setException(exception); listener.evaluationComplete(result); } }, "Evaluation thread"); evaluationThread.start(); }
public void evaluate(final ICompiledExpression expression, final IRuntimeContext context, final IJavaThread thread, final IEvaluationListener listener) { Thread evaluationThread= new Thread(new Runnable() { public void run() { fEvaluationCancelled= false; fEvaluationComplete= false; EvaluationResult result = new EvaluationResult(ASTEvaluationEngine.this, expression.getSnippet(), thread); if (expression.hasErrors()) { Message[] errors= expression.getErrors(); for (int i= 0, numErrors= errors.length; i < numErrors; i++) { result.addError(errors[i]); } listener.evaluationComplete(result); return; } IValue value = null; Thread timeoutThread= new Thread(new Runnable() { public void run() { while (!fEvaluationComplete && !fEvaluationCancelled) { try { Thread.currentThread().sleep(3000); // 10 second timeout for now } catch(InterruptedException e) { } if (!fEvaluationComplete && !listener.evaluationTimedOut(thread)) { fEvaluationCancelled= true; } } } }, "Evaluation timeout thread"); timeoutThread.start(); value= expression.evaluate(context); fEvaluationComplete= true; if (fEvaluationCancelled) { // Don't notify the listener if the evaluation has been cancelled return; } CoreException exception= expression.getException(); if (value != null) { IJavaValue jv = ((EvaluationValue)value).getJavaValue(); result.setValue(jv); } result.setException(exception); listener.evaluationComplete(result); } }, "Evaluation thread"); evaluationThread.start(); }
diff --git a/src/integrationtest/org/asteriskjava/live/OriginateTest.java b/src/integrationtest/org/asteriskjava/live/OriginateTest.java index d353309f..6018cf3c 100644 --- a/src/integrationtest/org/asteriskjava/live/OriginateTest.java +++ b/src/integrationtest/org/asteriskjava/live/OriginateTest.java @@ -1,102 +1,114 @@ /* * (c) 2004 Stefan Reuter * * Created on Oct 28, 2004 */ package org.asteriskjava.live; /** * @author srt * @version $Id$ */ public class OriginateTest extends AsteriskServerTestCase { private AsteriskChannel channel; private Long timeout = 10000L; @Override public void setUp() throws Exception { super.setUp(); this.channel = null; } public void XtestOriginate() throws Exception { AsteriskChannel channel; channel = server.originateToExtension("Local/1310@default", "from-local", "1330", 1, timeout); System.err.println(channel); System.err.println(channel.getVariable("AJ_TRACE_ID")); Thread.sleep(20000L); System.err.println(channel); System.err.println(channel.getVariable("AJ_TRACE_ID")); } public void testOriginateAsync() throws Exception { final String source; - //source = "SIP/1301"; - source = "Local/1313@from-local"; + //source = "SIP/1313"; + source = "Local/1313@from-local/n"; server.originateToExtensionAsync(source, "from-local", "1399", 1, timeout, new CallerId("AJ Test Call", "08003301000"), null, new OriginateCallback() { public void onSuccess(AsteriskChannel c) { channel = c; System.err.println("Success: " + c); showInfo(c); + try + { + c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC, "/usr/local/bin/2wav2mp3"); + c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC_ARGS, "a b"); + c.startMonitoring("mtest", "wav", true); + Thread.sleep(2000L); + c.stopMonitoring(); + } + catch (Exception e) + { + e.printStackTrace(); + } } public void onNoAnswer(AsteriskChannel c) { channel = c; System.err.println("No Answer: " + c); showInfo(c); } public void onBusy(AsteriskChannel c) { channel = c; System.err.println("Busy: " + c); showInfo(c); } public void onFailure(LiveException cause) { System.err.println("Failed: " + cause.getMessage()); } }); Thread.sleep(20000L); System.err.println("final state: " + channel); if (channel != null) { System.err.println("final state linked channels: " + channel.getLinkedChannelHistory()); } } void showInfo(AsteriskChannel channel) { String name; String otherName; AsteriskChannel otherChannel; System.err.println("linkedChannelHistory: " + channel.getLinkedChannelHistory()); System.err.println("dialedChannelHistory: " + channel.getDialedChannelHistory()); name = channel.getName(); if (name.startsWith("Local/")) { otherName = name.substring(0, name.length() - 1) + "2"; System.err.println("other name: " + otherName); otherChannel = server.getChannelByName(otherName); System.err.println("other channel: " + otherChannel); System.err.println("other dialedChannel: " + otherChannel.getDialedChannel()); System.err.println("other linkedChannelHistory: " + otherChannel.getLinkedChannelHistory()); System.err.println("other dialedChannelHistory: " + otherChannel.getDialedChannelHistory()); } } }
false
true
public void testOriginateAsync() throws Exception { final String source; //source = "SIP/1301"; source = "Local/1313@from-local"; server.originateToExtensionAsync(source, "from-local", "1399", 1, timeout, new CallerId("AJ Test Call", "08003301000"), null, new OriginateCallback() { public void onSuccess(AsteriskChannel c) { channel = c; System.err.println("Success: " + c); showInfo(c); } public void onNoAnswer(AsteriskChannel c) { channel = c; System.err.println("No Answer: " + c); showInfo(c); } public void onBusy(AsteriskChannel c) { channel = c; System.err.println("Busy: " + c); showInfo(c); } public void onFailure(LiveException cause) { System.err.println("Failed: " + cause.getMessage()); } }); Thread.sleep(20000L); System.err.println("final state: " + channel); if (channel != null) { System.err.println("final state linked channels: " + channel.getLinkedChannelHistory()); } }
public void testOriginateAsync() throws Exception { final String source; //source = "SIP/1313"; source = "Local/1313@from-local/n"; server.originateToExtensionAsync(source, "from-local", "1399", 1, timeout, new CallerId("AJ Test Call", "08003301000"), null, new OriginateCallback() { public void onSuccess(AsteriskChannel c) { channel = c; System.err.println("Success: " + c); showInfo(c); try { c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC, "/usr/local/bin/2wav2mp3"); c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC_ARGS, "a b"); c.startMonitoring("mtest", "wav", true); Thread.sleep(2000L); c.stopMonitoring(); } catch (Exception e) { e.printStackTrace(); } } public void onNoAnswer(AsteriskChannel c) { channel = c; System.err.println("No Answer: " + c); showInfo(c); } public void onBusy(AsteriskChannel c) { channel = c; System.err.println("Busy: " + c); showInfo(c); } public void onFailure(LiveException cause) { System.err.println("Failed: " + cause.getMessage()); } }); Thread.sleep(20000L); System.err.println("final state: " + channel); if (channel != null) { System.err.println("final state linked channels: " + channel.getLinkedChannelHistory()); } }
diff --git a/src/infinity/resource/graphics/TisResource2.java b/src/infinity/resource/graphics/TisResource2.java index d473d48..2556e82 100644 --- a/src/infinity/resource/graphics/TisResource2.java +++ b/src/infinity/resource/graphics/TisResource2.java @@ -1,670 +1,671 @@ // Near Infinity - An Infinity Engine Browser and Editor // Copyright (C) 2001 - 2005 Jon Olav Hauglid // See LICENSE.txt for license information package infinity.resource.graphics; import infinity.NearInfinity; import infinity.datatype.DecNumber; import infinity.datatype.ResourceRef; import infinity.gui.ButtonPopupMenu; import infinity.gui.TileGrid; import infinity.gui.WindowBlocker; import infinity.icon.Icons; import infinity.resource.Closeable; import infinity.resource.Resource; import infinity.resource.ResourceFactory; import infinity.resource.ViewableContainer; import infinity.resource.key.ResourceEntry; import infinity.resource.wed.Overlay; import infinity.resource.wed.WedResource; import infinity.util.DynamicArray; import infinity.util.IntegerHashMap; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Image; import java.awt.Transparency; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.ProgressMonitor; import javax.swing.RootPaneContainer; import javax.swing.SwingWorker; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class TisResource2 implements Resource, Closeable, ActionListener, ChangeListener, ItemListener, KeyListener, PropertyChangeListener { private static final int DEFAULT_COLUMNS = 5; private static boolean showGrid = false; private final ResourceEntry entry; private TisDecoder decoder; private List<Image> tileImages; // stores one tile per image private TileGrid tileGrid; // the main component for displaying the tileset private JSlider slCols; // changes the tiles per row private JTextField tfCols; // input/output tiles per row private JCheckBox cbGrid; // show/hide frame around each tile private ButtonPopupMenu bpmExport; // "Export..." button menu private JMenuItem miExport, miExportLegacyTis, miExportPNG; private JPanel panel; // top-level panel of the viewer private RootPaneContainer rpc; private SwingWorker<List<byte[]>, Void> workerConvert, workerExport; private WindowBlocker blocker; public TisResource2(ResourceEntry entry) throws Exception { this.entry = entry; initTileset(); } //--------------------- Begin Interface ActionListener --------------------- @Override public void actionPerformed(ActionEvent event) { if (event.getSource() == miExport) { ResourceFactory.getInstance().exportResource(entry, panel.getTopLevelAncestor()); } else if (event.getSource() == miExportLegacyTis) { blocker = new WindowBlocker(rpc); blocker.setBlocked(true); workerConvert = new SwingWorker<List<byte[]>, Void>() { @Override public List<byte[]> doInBackground() { List<byte[]> list = new Vector<byte[]>(1); try { byte[] buf = convertToLegacyTis(); if (buf != null) { list.add(buf); } } catch (Exception e) { e.printStackTrace(); } return list; } }; workerConvert.addPropertyChangeListener(this); workerConvert.execute(); } else if (event.getSource() == miExportPNG) { blocker = new WindowBlocker(rpc); blocker.setBlocked(true); workerExport = new SwingWorker<List<byte[]>, Void>() { @Override public List<byte[]> doInBackground() { List<byte[]> list = new Vector<byte[]>(1); try { byte[] buf = exportPNG(); if (buf != null) { list.add(buf); } } catch (Exception e) { e.printStackTrace(); } return list; } }; workerExport.addPropertyChangeListener(this); workerExport.execute(); } } //--------------------- End Interface ActionListener --------------------- //--------------------- Begin Interface ChangeListener --------------------- @Override public void stateChanged(ChangeEvent event) { if (event.getSource() == slCols) { int cols = slCols.getValue(); tfCols.setText(Integer.toString(cols)); tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), cols)); } } //--------------------- End Interface ChangeListener --------------------- //--------------------- Begin Interface ItemListener --------------------- @Override public void itemStateChanged(ItemEvent event) { if (event.getSource() == cbGrid) { showGrid = cbGrid.isSelected(); tileGrid.setShowGrid(showGrid); } } //--------------------- End Interface ChangeListener --------------------- //--------------------- Begin Interface KeyListener --------------------- @Override public void keyPressed(KeyEvent event) { if (event.getSource() == tfCols) { if (event.getKeyCode() == KeyEvent.VK_ENTER) { int cols; try { cols = Integer.parseInt(tfCols.getText()); } catch (NumberFormatException e) { cols = slCols.getValue(); tfCols.setText(Integer.toString(slCols.getValue())); } if (cols != slCols.getValue()) { if (cols <= 0) cols = 1; if (cols >= decoder.info().tileCount()) cols = decoder.info().tileCount(); slCols.setValue(cols); tfCols.setText(Integer.toString(slCols.getValue())); tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), cols)); } slCols.requestFocus(); // remove focus from textfield } } } @Override public void keyReleased(KeyEvent event) { // nothing to do } @Override public void keyTyped(KeyEvent event) { // nothing to do } //--------------------- End Interface KeyListener --------------------- //--------------------- Begin Interface PropertyChangeListener --------------------- @Override public void propertyChange(PropertyChangeEvent event) { if (event.getSource() == workerConvert) { if ("state".equals(event.getPropertyName()) && SwingWorker.StateValue.DONE == event.getNewValue()) { if (blocker != null) { blocker.setBlocked(false); blocker = null; } byte[] tisData = null; try { List<byte[]> l = workerConvert.get(); if (l != null && !l.isEmpty()) { tisData = l.get(0); l.clear(); l = null; } } catch (Exception e) { e.printStackTrace(); } if (tisData != null) { if (tisData.length > 0) { ResourceFactory.getInstance().exportResource(entry, tisData, entry.toString(), panel.getTopLevelAncestor()); } else { JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Export has been cancelled.", "Information", JOptionPane.INFORMATION_MESSAGE); } tisData = null; } else { JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Error while exporting " + entry, "Error", JOptionPane.ERROR_MESSAGE); } } } else if (event.getSource() == workerExport) { if ("state".equals(event.getPropertyName()) && SwingWorker.StateValue.DONE == event.getNewValue()) { if (blocker != null) { blocker.setBlocked(false); blocker = null; } byte[] pngData = null; try { List<byte[]> l = workerExport.get(); if (l != null && !l.isEmpty()) { pngData = l.get(0); l.clear(); l = null; } } catch (Exception e) { e.printStackTrace(); } if (pngData != null) { if (pngData.length > 0) { String fileName = entry.toString().replace(".TIS", ".PNG"); ResourceFactory.getInstance().exportResource(entry, pngData, fileName, panel.getTopLevelAncestor()); } else { JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Export has been cancelled.", "Information", JOptionPane.INFORMATION_MESSAGE); } pngData = null; } else { JOptionPane.showMessageDialog(panel.getTopLevelAncestor(), "Error while exporting " + entry, "Error", JOptionPane.ERROR_MESSAGE); } } } } //--------------------- End Interface PropertyChangeListener --------------------- //--------------------- Begin Interface Closeable --------------------- @Override public void close() throws Exception { if (workerConvert != null) { if (!workerConvert.isDone()) { workerConvert.cancel(true); } workerConvert = null; } tileImages.clear(); tileImages = null; tileGrid.clearImages(); tileGrid = null; if (decoder != null) { decoder.close(); decoder = null; } System.gc(); } //--------------------- End Interface Closeable --------------------- //--------------------- Begin Interface Resource --------------------- @Override public ResourceEntry getResourceEntry() { return entry; } //--------------------- End Interface Resource --------------------- //--------------------- Begin Interface Viewable --------------------- @Override public JComponent makeViewer(ViewableContainer container) { if (container instanceof RootPaneContainer) { rpc = (RootPaneContainer)container; } else { rpc = NearInfinity.getInstance(); } int tileCount = decoder.info().tileCount(); + int defaultColumns = Math.min(tileCount, DEFAULT_COLUMNS); // 1. creating top panel // 1.1. creating label with text field JLabel lblTPR = new JLabel("Tiles per row:"); - tfCols = new JTextField(Integer.toString(DEFAULT_COLUMNS), 5); + tfCols = new JTextField(Integer.toString(defaultColumns), 5); tfCols.addKeyListener(this); JPanel tPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); tPanel1.add(lblTPR); tPanel1.add(tfCols); // 1.2. creating slider - slCols = new JSlider(JSlider.HORIZONTAL, 1, tileCount, DEFAULT_COLUMNS); + slCols = new JSlider(JSlider.HORIZONTAL, 1, tileCount, defaultColumns); if (tileCount > 1000) { slCols.setMinorTickSpacing(100); slCols.setMajorTickSpacing(1000); } else if (tileCount > 100) { slCols.setMinorTickSpacing(10); slCols.setMajorTickSpacing(100); } else { slCols.setMinorTickSpacing(1); slCols.setMajorTickSpacing(10); } slCols.setPaintTicks(true); slCols.addChangeListener(this); // 1.3. adding left side of the top panel together JPanel tlPanel = new JPanel(new GridLayout(2, 1)); tlPanel.add(tPanel1); tlPanel.add(slCols); // 1.4. configuring checkbox cbGrid = new JCheckBox("Show Grid", showGrid); cbGrid.addItemListener(this); JPanel trPanel = new JPanel(new GridLayout()); trPanel.add(cbGrid); // 1.5. putting top panel together BorderLayout bl = new BorderLayout(); JPanel topPanel = new JPanel(bl); topPanel.add(tlPanel, BorderLayout.CENTER); topPanel.add(trPanel, BorderLayout.LINE_END); // 2. creating main panel // 2.1. creating tiles table and scroll pane - tileGrid = new TileGrid(1, DEFAULT_COLUMNS, decoder.info().tileWidth(), decoder.info().tileHeight()); + tileGrid = new TileGrid(1, defaultColumns, decoder.info().tileWidth(), decoder.info().tileHeight()); tileGrid.addImage(tileImages); if (tileGrid.getImageCount() > 6) { int colSize = calcTileWidth(entry, tileGrid.getImageCount()); tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), colSize)); } else { // displaying overlay tilesets in a single row tileGrid.setGridSize(new Dimension(tileGrid.getImageCount(), 1)); } tileGrid.setShowGrid(showGrid); slCols.setValue(tileGrid.getTileColumns()); tfCols.setText(Integer.toString(tileGrid.getTileColumns())); JScrollPane scroll = new JScrollPane(tileGrid); scroll.getVerticalScrollBar().setUnitIncrement(16); scroll.getHorizontalScrollBar().setUnitIncrement(16); // 2.2. putting main panel together JPanel centerPanel = new JPanel(new BorderLayout()); centerPanel.add(scroll, BorderLayout.CENTER); // 3. creating bottom panel // 3.1. creating export button miExport = new JMenuItem("original"); miExport.addActionListener(this); if (decoder.info().type() == TisDecoder.TisInfo.TisType.PVRZ) { miExportLegacyTis = new JMenuItem("as legacy TIS"); miExportLegacyTis.addActionListener(this); } miExportPNG = new JMenuItem("as PNG"); miExportPNG.addActionListener(this); List<JMenuItem> list = new ArrayList<JMenuItem>(); if (miExport != null) list.add(miExport); if (miExportLegacyTis != null) list.add(miExportLegacyTis); if (miExportPNG != null) list.add(miExportPNG); JMenuItem[] mi = new JMenuItem[list.size()]; for (int i = 0; i < mi.length; i++) { mi[i] = list.get(i); } bpmExport = new ButtonPopupMenu("Export...", mi); bpmExport.setIcon(Icons.getIcon("Export16.gif")); bpmExport.setMnemonic('e'); // 3.2. putting bottom panel together JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); bottomPanel.add(bpmExport); // 4. packing all together panel = new JPanel(new BorderLayout()); panel.add(topPanel, BorderLayout.NORTH); panel.add(centerPanel, BorderLayout.CENTER); panel.add(bottomPanel, BorderLayout.SOUTH); centerPanel.setBorder(BorderFactory.createLoweredBevelBorder()); return panel; } //--------------------- End Interface Viewable --------------------- private void initTileset() { try { WindowBlocker.blockWindow(true); decoder = new TisDecoder(entry); int tileCount = decoder.info().tileCount(); tileImages = new ArrayList<Image>(tileCount); for (int tileIdx = 0; tileIdx < tileCount; tileIdx++) { final BufferedImage image = decoder.decodeTile(tileIdx); if (image != null) { tileImages.add(image); } else { tileImages.add(ColorConvert.createCompatibleImage(decoder.info().tileWidth(), decoder.info().tileHeight(), Transparency.BITMASK)); } } decoder.flush(); WindowBlocker.blockWindow(false); } catch (Exception e) { e.printStackTrace(); WindowBlocker.blockWindow(false); if (tileImages == null) tileImages = new ArrayList<Image>(); if (tileImages.isEmpty()) tileImages.add(ColorConvert.createCompatibleImage(1, 1, Transparency.BITMASK)); JOptionPane.showMessageDialog(NearInfinity.getInstance(), "Error while loading TIS resource: " + entry.getResourceName(), "Error", JOptionPane.ERROR_MESSAGE); } } // Converts the current PVRZ-based tileset into the old tileset variant. DO NOT call directly! private byte[] convertToLegacyTis() { byte[] buf = null; if (tileImages != null && !tileImages.isEmpty()) { String note = "Converting tile %1$d / %2$d"; int progressIndex = 0, progressMax = decoder.info().tileCount(); ProgressMonitor progress = new ProgressMonitor(panel.getTopLevelAncestor(), "Converting TIS...", String.format(note, progressIndex, progressMax), 0, progressMax); progress.setMillisToDecideToPopup(500); progress.setMillisToPopup(2000); buf = new byte[24 + decoder.info().tileCount()*5120]; // writing header data System.arraycopy("TIS V1 ".getBytes(Charset.forName("US-ASCII")), 0, buf, 0, 8); DynamicArray.putInt(buf, 8, decoder.info().tileCount()); DynamicArray.putInt(buf, 12, 0x1400); DynamicArray.putInt(buf, 16, 0x18); DynamicArray.putInt(buf, 20, 0x40); // writing tiles int bufOfs = 24; int[] palette = new int[255]; int[] hslPalette = new int[255]; byte[] tilePalette = new byte[1024]; byte[] tileData = new byte[64*64]; BufferedImage image = ColorConvert.createCompatibleImage(decoder.info().tileWidth(), decoder.info().tileHeight(), Transparency.BITMASK); IntegerHashMap<Byte> colorCache = new IntegerHashMap<Byte>(1536); // caching RGBColor -> index for (int tileIdx = 0; tileIdx < decoder.info().tileCount(); tileIdx++) { colorCache.clear(); if (progress.isCanceled()) { buf = new byte[0]; break; } progressIndex++; if ((progressIndex % 100) == 0) { progress.setProgress(progressIndex); progress.setNote(String.format(note, progressIndex, progressMax)); } int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData(); Arrays.fill(pixels, 0); // clearing garbage data Graphics2D g = (Graphics2D)image.getGraphics(); g.drawImage(tileImages.get(tileIdx), 0, 0, null); g.dispose(); g = null; if (ColorConvert.medianCut(pixels, 255, palette, false)) { ColorConvert.toHslPalette(palette, hslPalette); // filling palette // first palette entry denotes transparency tilePalette[0] = tilePalette[2] = tilePalette[3] = 0; tilePalette[1] = (byte)255; for (int i = 1; i < 256; i++) { tilePalette[(i << 2) + 0] = (byte)(palette[i - 1] & 0xff); tilePalette[(i << 2) + 1] = (byte)((palette[i - 1] >>> 8) & 0xff); tilePalette[(i << 2) + 2] = (byte)((palette[i - 1] >>> 16) & 0xff); tilePalette[(i << 2) + 3] = 0; colorCache.put(palette[i - 1], (byte)(i - 1)); } // filling pixel data for (int i = 0; i < tileData.length; i++) { if ((pixels[i] & 0xff000000) == 0) { tileData[i] = 0; } else { Byte palIndex = colorCache.get(pixels[i]); if (palIndex != null) { tileData[i] = (byte)(palIndex + 1); } else { byte color = (byte)ColorConvert.nearestColor(pixels[i], hslPalette); tileData[i] = (byte)(color + 1); colorCache.put(pixels[i], color); } } } } else { buf = null; break; } System.arraycopy(tilePalette, 0, buf, bufOfs, 1024); bufOfs += 1024; System.arraycopy(tileData, 0, buf, bufOfs, 4096); bufOfs += 4096; } image.flush(); image = null; tileData = null; tilePalette = null; hslPalette = null; palette = null; progress.close(); } return buf; } // Converts the tileset into the PNG format. DO NOT call directly! private byte[] exportPNG() { byte[] buffer = null; if (tileImages != null && !tileImages.isEmpty()) { int tilesX = tileGrid.getTileColumns(); int tilesY = tileGrid.getTileRows(); if (tilesX > 0 && tilesY > 0) { BufferedImage image = null; ProgressMonitor progress = new ProgressMonitor(panel.getTopLevelAncestor(), "Exporting TIS to PNG...", "", 0, 2); progress.setMillisToDecideToPopup(0); progress.setMillisToPopup(0); progress.setProgress(0); try { image = ColorConvert.createCompatibleImage(tilesX*64, tilesY*64, Transparency.BITMASK); Graphics2D g = (Graphics2D)image.getGraphics(); for (int idx = 0; idx < tileImages.size(); idx++) { if (tileImages.get(idx) != null) { int tx = idx % tilesX; int ty = idx / tilesX; g.drawImage(tileImages.get(idx), tx*64, ty*64, null); } } g.dispose(); progress.setProgress(1); ByteArrayOutputStream os = new ByteArrayOutputStream(); if (ImageIO.write(image, "png", os)) { buffer = os.toByteArray(); } } catch (Exception e) { } if (progress.isCanceled()) { buffer = new byte[0]; } progress.close(); } } return buffer; } // calculates a Dimension structure with the correct number of columns and rows from the specified arguments private static Dimension calcGridSize(int imageCount, int colSize) { if (imageCount >= 0 && colSize > 0) { int rowSize = imageCount / colSize; if (imageCount % colSize > 0) rowSize++; return new Dimension(colSize, Math.max(1, rowSize)); } return null; } // attempts to calculate the TIS width from an associated WED file private static int calcTileWidth(ResourceEntry entry, int tileCount) { // Try to fetch the correct width from an associated WED if available if (entry != null) { try { String tisNameBase = entry.getResourceName(); if (tisNameBase.lastIndexOf('.') > 0) tisNameBase = tisNameBase.substring(0, tisNameBase.lastIndexOf('.')); ResourceEntry wedEntry = null; while (tisNameBase.length() >= 6) { String wedFileName = tisNameBase + ".WED"; wedEntry = ResourceFactory.getInstance().getResourceEntry(wedFileName); if (wedEntry != null) break; else tisNameBase = tisNameBase.substring(0, tisNameBase.length() - 1); } if (wedEntry != null) { WedResource wedResource = new WedResource(wedEntry); Overlay overlay = (Overlay)wedResource.getAttribute("Overlay 0"); ResourceRef tisRef = (ResourceRef)overlay.getAttribute("Tileset"); ResourceEntry tisEntry = ResourceFactory.getInstance().getResourceEntry(tisRef.getResourceName()); if (tisEntry != null) { String tisName = tisEntry.getResourceName(); if (tisName.lastIndexOf('.') > 0) tisName = tisName.substring(0, tisName.lastIndexOf('.')); int maxLen = Math.min(tisNameBase.length(), tisName.length()); if (tisNameBase.startsWith(tisName.substring(0, maxLen))) { return ((DecNumber)overlay.getAttribute("Width")).getValue(); } } } } catch (Exception e) { } } // If WED is not available: approximate the most commonly used aspect ratio found in TIS files // Disadvantage: does not take extra tiles into account return (int)(Math.sqrt(tileCount)*1.18); } }
false
true
public JComponent makeViewer(ViewableContainer container) { if (container instanceof RootPaneContainer) { rpc = (RootPaneContainer)container; } else { rpc = NearInfinity.getInstance(); } int tileCount = decoder.info().tileCount(); // 1. creating top panel // 1.1. creating label with text field JLabel lblTPR = new JLabel("Tiles per row:"); tfCols = new JTextField(Integer.toString(DEFAULT_COLUMNS), 5); tfCols.addKeyListener(this); JPanel tPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); tPanel1.add(lblTPR); tPanel1.add(tfCols); // 1.2. creating slider slCols = new JSlider(JSlider.HORIZONTAL, 1, tileCount, DEFAULT_COLUMNS); if (tileCount > 1000) { slCols.setMinorTickSpacing(100); slCols.setMajorTickSpacing(1000); } else if (tileCount > 100) { slCols.setMinorTickSpacing(10); slCols.setMajorTickSpacing(100); } else { slCols.setMinorTickSpacing(1); slCols.setMajorTickSpacing(10); } slCols.setPaintTicks(true); slCols.addChangeListener(this); // 1.3. adding left side of the top panel together JPanel tlPanel = new JPanel(new GridLayout(2, 1)); tlPanel.add(tPanel1); tlPanel.add(slCols); // 1.4. configuring checkbox cbGrid = new JCheckBox("Show Grid", showGrid); cbGrid.addItemListener(this); JPanel trPanel = new JPanel(new GridLayout()); trPanel.add(cbGrid); // 1.5. putting top panel together BorderLayout bl = new BorderLayout(); JPanel topPanel = new JPanel(bl); topPanel.add(tlPanel, BorderLayout.CENTER); topPanel.add(trPanel, BorderLayout.LINE_END); // 2. creating main panel // 2.1. creating tiles table and scroll pane tileGrid = new TileGrid(1, DEFAULT_COLUMNS, decoder.info().tileWidth(), decoder.info().tileHeight()); tileGrid.addImage(tileImages); if (tileGrid.getImageCount() > 6) { int colSize = calcTileWidth(entry, tileGrid.getImageCount()); tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), colSize)); } else { // displaying overlay tilesets in a single row tileGrid.setGridSize(new Dimension(tileGrid.getImageCount(), 1)); } tileGrid.setShowGrid(showGrid); slCols.setValue(tileGrid.getTileColumns()); tfCols.setText(Integer.toString(tileGrid.getTileColumns())); JScrollPane scroll = new JScrollPane(tileGrid); scroll.getVerticalScrollBar().setUnitIncrement(16); scroll.getHorizontalScrollBar().setUnitIncrement(16); // 2.2. putting main panel together JPanel centerPanel = new JPanel(new BorderLayout()); centerPanel.add(scroll, BorderLayout.CENTER); // 3. creating bottom panel // 3.1. creating export button miExport = new JMenuItem("original"); miExport.addActionListener(this); if (decoder.info().type() == TisDecoder.TisInfo.TisType.PVRZ) { miExportLegacyTis = new JMenuItem("as legacy TIS"); miExportLegacyTis.addActionListener(this); } miExportPNG = new JMenuItem("as PNG"); miExportPNG.addActionListener(this); List<JMenuItem> list = new ArrayList<JMenuItem>(); if (miExport != null) list.add(miExport); if (miExportLegacyTis != null) list.add(miExportLegacyTis); if (miExportPNG != null) list.add(miExportPNG); JMenuItem[] mi = new JMenuItem[list.size()]; for (int i = 0; i < mi.length; i++) { mi[i] = list.get(i); } bpmExport = new ButtonPopupMenu("Export...", mi); bpmExport.setIcon(Icons.getIcon("Export16.gif")); bpmExport.setMnemonic('e'); // 3.2. putting bottom panel together JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); bottomPanel.add(bpmExport); // 4. packing all together panel = new JPanel(new BorderLayout()); panel.add(topPanel, BorderLayout.NORTH); panel.add(centerPanel, BorderLayout.CENTER); panel.add(bottomPanel, BorderLayout.SOUTH); centerPanel.setBorder(BorderFactory.createLoweredBevelBorder()); return panel; }
public JComponent makeViewer(ViewableContainer container) { if (container instanceof RootPaneContainer) { rpc = (RootPaneContainer)container; } else { rpc = NearInfinity.getInstance(); } int tileCount = decoder.info().tileCount(); int defaultColumns = Math.min(tileCount, DEFAULT_COLUMNS); // 1. creating top panel // 1.1. creating label with text field JLabel lblTPR = new JLabel("Tiles per row:"); tfCols = new JTextField(Integer.toString(defaultColumns), 5); tfCols.addKeyListener(this); JPanel tPanel1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); tPanel1.add(lblTPR); tPanel1.add(tfCols); // 1.2. creating slider slCols = new JSlider(JSlider.HORIZONTAL, 1, tileCount, defaultColumns); if (tileCount > 1000) { slCols.setMinorTickSpacing(100); slCols.setMajorTickSpacing(1000); } else if (tileCount > 100) { slCols.setMinorTickSpacing(10); slCols.setMajorTickSpacing(100); } else { slCols.setMinorTickSpacing(1); slCols.setMajorTickSpacing(10); } slCols.setPaintTicks(true); slCols.addChangeListener(this); // 1.3. adding left side of the top panel together JPanel tlPanel = new JPanel(new GridLayout(2, 1)); tlPanel.add(tPanel1); tlPanel.add(slCols); // 1.4. configuring checkbox cbGrid = new JCheckBox("Show Grid", showGrid); cbGrid.addItemListener(this); JPanel trPanel = new JPanel(new GridLayout()); trPanel.add(cbGrid); // 1.5. putting top panel together BorderLayout bl = new BorderLayout(); JPanel topPanel = new JPanel(bl); topPanel.add(tlPanel, BorderLayout.CENTER); topPanel.add(trPanel, BorderLayout.LINE_END); // 2. creating main panel // 2.1. creating tiles table and scroll pane tileGrid = new TileGrid(1, defaultColumns, decoder.info().tileWidth(), decoder.info().tileHeight()); tileGrid.addImage(tileImages); if (tileGrid.getImageCount() > 6) { int colSize = calcTileWidth(entry, tileGrid.getImageCount()); tileGrid.setGridSize(calcGridSize(tileGrid.getImageCount(), colSize)); } else { // displaying overlay tilesets in a single row tileGrid.setGridSize(new Dimension(tileGrid.getImageCount(), 1)); } tileGrid.setShowGrid(showGrid); slCols.setValue(tileGrid.getTileColumns()); tfCols.setText(Integer.toString(tileGrid.getTileColumns())); JScrollPane scroll = new JScrollPane(tileGrid); scroll.getVerticalScrollBar().setUnitIncrement(16); scroll.getHorizontalScrollBar().setUnitIncrement(16); // 2.2. putting main panel together JPanel centerPanel = new JPanel(new BorderLayout()); centerPanel.add(scroll, BorderLayout.CENTER); // 3. creating bottom panel // 3.1. creating export button miExport = new JMenuItem("original"); miExport.addActionListener(this); if (decoder.info().type() == TisDecoder.TisInfo.TisType.PVRZ) { miExportLegacyTis = new JMenuItem("as legacy TIS"); miExportLegacyTis.addActionListener(this); } miExportPNG = new JMenuItem("as PNG"); miExportPNG.addActionListener(this); List<JMenuItem> list = new ArrayList<JMenuItem>(); if (miExport != null) list.add(miExport); if (miExportLegacyTis != null) list.add(miExportLegacyTis); if (miExportPNG != null) list.add(miExportPNG); JMenuItem[] mi = new JMenuItem[list.size()]; for (int i = 0; i < mi.length; i++) { mi[i] = list.get(i); } bpmExport = new ButtonPopupMenu("Export...", mi); bpmExport.setIcon(Icons.getIcon("Export16.gif")); bpmExport.setMnemonic('e'); // 3.2. putting bottom panel together JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); bottomPanel.add(bpmExport); // 4. packing all together panel = new JPanel(new BorderLayout()); panel.add(topPanel, BorderLayout.NORTH); panel.add(centerPanel, BorderLayout.CENTER); panel.add(bottomPanel, BorderLayout.SOUTH); centerPanel.setBorder(BorderFactory.createLoweredBevelBorder()); return panel; }
diff --git a/java/src/org/broadinstitute/sting/utils/sam/GATKSAMRecord.java b/java/src/org/broadinstitute/sting/utils/sam/GATKSAMRecord.java index c4536d176..f3d9edab9 100755 --- a/java/src/org/broadinstitute/sting/utils/sam/GATKSAMRecord.java +++ b/java/src/org/broadinstitute/sting/utils/sam/GATKSAMRecord.java @@ -1,457 +1,457 @@ package org.broadinstitute.sting.utils.sam; import java.lang.reflect.Method; import java.util.*; import net.sf.samtools.*; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.exceptions.UserException; /** * @author ebanks * GATKSAMRecord * * this class extends the samtools SAMRecord class and caches important * (and oft-accessed) data that's not already cached by the SAMRecord class * * IMPORTANT NOTE: Because ReadGroups are not set through the SAMRecord, * if they are ever modified externally then one must also invoke the * setReadGroup() method here to ensure that the cache is kept up-to-date. * * 13 Oct 2010 - mhanna - this class is fundamentally flawed: it uses a decorator * pattern to wrap a heavyweight object, which can lead * to heinous side effects if the wrapping is not carefully * done. Hopefully SAMRecord will become an interface and * this will eventually be fixed. */ public class GATKSAMRecord extends SAMRecord { // the underlying SAMRecord which we are wrapping private final SAMRecord mRecord; // the SAMRecord data we're caching private String mReadString = null; private SAMReadGroupRecord mReadGroup = null; private boolean mNegativeStrandFlag; private boolean mUnmappedFlag; private Boolean mSecondOfPairFlag = null; // because some values can be null, we don't want to duplicate effort private boolean retrievedReadGroup = false; // These temporary attributes were added here to make life easier for // certain algorithms by providing a way to label or attach arbitrary data to // individual GATKSAMRecords. // These attributes exist in memory only, and are never written to disk. private Map<Object, Object> temporaryAttributes; public GATKSAMRecord(SAMRecord record, boolean useOriginalBaseQualities, byte defaultBaseQualities) { super(null); // it doesn't matter - this isn't used if ( record == null ) throw new IllegalArgumentException("The SAMRecord argument cannot be null"); mRecord = record; mNegativeStrandFlag = mRecord.getReadNegativeStrandFlag(); mUnmappedFlag = mRecord.getReadUnmappedFlag(); // because attribute methods are declared to be final (and we can't overload them), // we need to actually set all of the attributes here List<SAMTagAndValue> attributes = record.getAttributes(); for ( SAMTagAndValue attribute : attributes ) setAttribute(attribute.tag, attribute.value); // if we are using default quals, check if we need them, and add if necessary. // 1. we need if reads are lacking or have incomplete quality scores // 2. we add if defaultBaseQualities has a positive value if (defaultBaseQualities >= 0) { byte reads [] = record.getReadBases(); byte quals [] = record.getBaseQualities(); if (quals == null || quals.length < reads.length) { byte new_quals [] = new byte [reads.length]; for (int i=0; i<reads.length; i++) new_quals[i] = defaultBaseQualities; record.setBaseQualities(new_quals); } } // if we are using original quals, set them now if they are present in the record if ( useOriginalBaseQualities ) { byte[] originalQuals = mRecord.getOriginalBaseQualities(); if ( originalQuals != null ) mRecord.setBaseQualities(originalQuals); } // sanity check that the lengths of the base and quality strings are equal if ( getBaseQualities().length != getReadLength() ) - throw new UserException.MalformedBAM(this, String.format("Error: the number of base qualities does not match the number of bases in %s. Use -DBQ x to set a default base quality score to all reads so GATK can proceed.", mRecord.getReadName())); + throw new UserException.MalformedBAM(this, String.format("Error: the number of base qualities does not match the number of bases in %s.", mRecord.getReadName())); } /////////////////////////////////////////////////////////////////////////////// // *** The following methods are overloaded to cache the appropriate data ***// /////////////////////////////////////////////////////////////////////////////// public String getReadString() { if ( mReadString == null ) mReadString = mRecord.getReadString(); return mReadString; } public void setReadString(String s) { mRecord.setReadString(s); mReadString = s; } public SAMReadGroupRecord getReadGroup() { if ( !retrievedReadGroup ) { SAMReadGroupRecord tempReadGroup = mRecord.getReadGroup(); mReadGroup = (tempReadGroup == null ? tempReadGroup : new GATKSAMReadGroupRecord(tempReadGroup)); retrievedReadGroup = true; } return mReadGroup; } public void setReadGroup(SAMReadGroupRecord record) { mReadGroup = record; } public boolean getReadUnmappedFlag() { return mUnmappedFlag; } public void setReadUnmappedFlag(boolean b) { mRecord.setReadUnmappedFlag(b); mUnmappedFlag = b; } public boolean getReadNegativeStrandFlag() { return mNegativeStrandFlag; } public void setReadNegativeStrandFlag(boolean b) { mRecord.setReadNegativeStrandFlag(b); mNegativeStrandFlag = b; } public boolean getSecondOfPairFlag() { if( mSecondOfPairFlag == null ) { //not done in constructor because this method can't be called for //all SAMRecords. mSecondOfPairFlag = mRecord.getSecondOfPairFlag(); } return mSecondOfPairFlag; } public void setSecondOfPairFlag(boolean b) { mRecord.setSecondOfPairFlag(b); mSecondOfPairFlag = b; } /** * Checks whether an attribute has been set for the given key. * * Temporary attributes provide a way to label or attach arbitrary data to * individual GATKSAMRecords. These attributes exist in memory only, * and are never written to disk. * * @param key key * @return True if an attribute has been set for this key. */ public boolean containsTemporaryAttribute(Object key) { if(temporaryAttributes != null) { return temporaryAttributes.containsKey(key); } return false; } /** * Sets the key to the given value, replacing any previous value. The previous * value is returned. * * Temporary attributes provide a way to label or attach arbitrary data to * individual GATKSAMRecords. These attributes exist in memory only, * and are never written to disk. * * @param key key * @param value value * @return attribute */ public Object setTemporaryAttribute(Object key, Object value) { if(temporaryAttributes == null) { temporaryAttributes = new HashMap<Object, Object>(); } return temporaryAttributes.put(key, value); } /** * Looks up the value associated with the given key. * * Temporary attributes provide a way to label or attach arbitrary data to * individual GATKSAMRecords. These attributes exist in memory only, * and are never written to disk. * * @param key key * @return The value, or null. */ public Object getTemporaryAttribute(Object key) { if(temporaryAttributes != null) { return temporaryAttributes.get(key); } return null; } /** * Removes the attribute that has the given key. * * Temporary attributes provide a way to label or attach arbitrary data to * individual GATKSAMRecords. These attributes exist in memory only, * and are never written to disk. * * @param key key * @return The value that was associated with this key, or null. */ public Object removeTemporaryAttribute(Object key) { if(temporaryAttributes != null) { return temporaryAttributes.remove(key); } return null; } ///////////////////////////////////////////////////////////////////////////////// // *** The following methods just call the appropriate method in the record ***// ///////////////////////////////////////////////////////////////////////////////// public String getReadName() { return mRecord.getReadName(); } public int getReadNameLength() { return mRecord.getReadNameLength(); } public void setReadName(String s) { mRecord.setReadName(s); } public byte[] getReadBases() { return mRecord.getReadBases(); } public void setReadBases(byte[] bytes) { mRecord.setReadBases(bytes); } public int getReadLength() { return mRecord.getReadLength(); } public byte[] getBaseQualities() { return mRecord.getBaseQualities(); } public void setBaseQualities(byte[] bytes) { mRecord.setBaseQualities(bytes); } public String getBaseQualityString() { return mRecord.getBaseQualityString(); } public void setBaseQualityString(String s) { mRecord.setBaseQualityString(s); } public byte[] getOriginalBaseQualities() { return mRecord.getOriginalBaseQualities(); } public void setOriginalBaseQualities(byte[] bytes) { mRecord.setOriginalBaseQualities(bytes); } public String getReferenceName() { return mRecord.getReferenceName(); } public void setReferenceName(String s) { mRecord.setReferenceName(s); } public Integer getReferenceIndex() { return mRecord.getReferenceIndex(); } public void setReferenceIndex(int i) { mRecord.setReferenceIndex(i); } public String getMateReferenceName() { return mRecord.getMateReferenceName(); } public void setMateReferenceName(String s) { mRecord.setMateReferenceName(s); } public Integer getMateReferenceIndex() { return mRecord.getMateReferenceIndex(); } public void setMateReferenceIndex(int i) { mRecord.setMateReferenceIndex(i); } public int getAlignmentStart() { return mRecord.getAlignmentStart(); } public void setAlignmentStart(int i) { mRecord.setAlignmentStart(i); } public int getAlignmentEnd() { return mRecord.getAlignmentEnd(); } public int getUnclippedStart() { return mRecord.getUnclippedStart(); } public int getUnclippedEnd() { return mRecord.getUnclippedEnd(); } public void setAlignmentEnd(int i) { mRecord.setAlignmentEnd(i); } public int getMateAlignmentStart() { return mRecord.getMateAlignmentStart(); } public void setMateAlignmentStart(int i) { mRecord.setMateAlignmentStart(i); } public int getInferredInsertSize() { return mRecord.getInferredInsertSize(); } public void setInferredInsertSize(int i) { mRecord.setInferredInsertSize(i); } public int getMappingQuality() { return mRecord.getMappingQuality(); } public void setMappingQuality(int i) { mRecord.setMappingQuality(i); } public String getCigarString() { return mRecord.getCigarString(); } public void setCigarString(String s) { mRecord.setCigarString(s); } public Cigar getCigar() { return mRecord.getCigar(); } public int getCigarLength() { return mRecord.getCigarLength(); } public void setCigar(Cigar cigar) { mRecord.setCigar(cigar); } public int getFlags() { return mRecord.getFlags(); } public void setFlags(int i) { mRecord.setFlags(i); } public boolean getReadPairedFlag() { return mRecord.getReadPairedFlag(); } public boolean getProperPairFlag() { return mRecord.getProperPairFlag(); } public boolean getMateUnmappedFlag() { return mRecord.getMateUnmappedFlag(); } public boolean getMateNegativeStrandFlag() { return mRecord.getMateNegativeStrandFlag(); } public boolean getFirstOfPairFlag() { return mRecord.getFirstOfPairFlag(); } public boolean getNotPrimaryAlignmentFlag() { return mRecord.getNotPrimaryAlignmentFlag(); } public boolean getReadFailsVendorQualityCheckFlag() { return mRecord.getReadFailsVendorQualityCheckFlag(); } public boolean getDuplicateReadFlag() { return mRecord.getDuplicateReadFlag(); } public void setReadPairedFlag(boolean b) { mRecord.setReadPairedFlag(b); } public void setProperPairFlag(boolean b) { mRecord.setProperPairFlag(b); } public void setMateUnmappedFlag(boolean b) { mRecord.setMateUnmappedFlag(b); } public void setMateNegativeStrandFlag(boolean b) { mRecord.setMateNegativeStrandFlag(b); } public void setFirstOfPairFlag(boolean b) { mRecord.setFirstOfPairFlag(b); } public void setNotPrimaryAlignmentFlag(boolean b) { mRecord.setNotPrimaryAlignmentFlag(b); } public void setReadFailsVendorQualityCheckFlag(boolean b) { mRecord.setReadFailsVendorQualityCheckFlag(b); } public void setDuplicateReadFlag(boolean b) { mRecord.setDuplicateReadFlag(b); } public net.sf.samtools.SAMFileReader.ValidationStringency getValidationStringency() { return mRecord.getValidationStringency(); } public void setValidationStringency(net.sf.samtools.SAMFileReader.ValidationStringency validationStringency) { mRecord.setValidationStringency(validationStringency); } public Object getAttribute(final String tag) { return mRecord.getAttribute(tag); } public Integer getIntegerAttribute(final String tag) { return mRecord.getIntegerAttribute(tag); } public Short getShortAttribute(final String tag) { return mRecord.getShortAttribute(tag); } public Byte getByteAttribute(final String tag) { return mRecord.getByteAttribute(tag); } public String getStringAttribute(final String tag) { return mRecord.getStringAttribute(tag); } public Character getCharacterAttribute(final String tag) { return mRecord.getCharacterAttribute(tag); } public Float getFloatAttribute(final String tag) { return mRecord.getFloatAttribute(tag); } public byte[] getByteArrayAttribute(final String tag) { return mRecord.getByteArrayAttribute(tag); } protected Object getAttribute(final short tag) { Object attribute; try { Method method = mRecord.getClass().getDeclaredMethod("getAttribute",Short.TYPE); method.setAccessible(true); attribute = method.invoke(mRecord,tag); } catch(Exception ex) { throw new ReviewedStingException("Unable to invoke getAttribute method",ex); } return attribute; } public void setAttribute(final String tag, final Object value) { mRecord.setAttribute(tag,value); } protected void setAttribute(final short tag, final Object value) { try { Method method = mRecord.getClass().getDeclaredMethod("setAttribute",Short.TYPE,Object.class); method.setAccessible(true); method.invoke(mRecord,tag,value); } catch(Exception ex) { throw new ReviewedStingException("Unable to invoke setAttribute method",ex); } } public void clearAttributes() { mRecord.clearAttributes(); } protected void setAttributes(final SAMBinaryTagAndValue attributes) { try { Method method = mRecord.getClass().getDeclaredMethod("setAttributes",SAMBinaryTagAndValue.class); method.setAccessible(true); method.invoke(mRecord,attributes); } catch(Exception ex) { throw new ReviewedStingException("Unable to invoke setAttributes method",ex); } } protected SAMBinaryTagAndValue getBinaryAttributes() { SAMBinaryTagAndValue binaryAttributes; try { Method method = mRecord.getClass().getDeclaredMethod("getBinaryAttributes"); method.setAccessible(true); binaryAttributes = (SAMBinaryTagAndValue)method.invoke(mRecord); } catch(Exception ex) { throw new ReviewedStingException("Unable to invoke getBinaryAttributes method",ex); } return binaryAttributes; } public List<SAMTagAndValue> getAttributes() { return mRecord.getAttributes(); } public SAMFileHeader getHeader() { return mRecord.getHeader(); } public void setHeader(SAMFileHeader samFileHeader) { mRecord.setHeader(samFileHeader); } public byte[] getVariableBinaryRepresentation() { return mRecord.getVariableBinaryRepresentation(); } public int getAttributesBinarySize() { return mRecord.getAttributesBinarySize(); } public String format() { return mRecord.format(); } public List<AlignmentBlock> getAlignmentBlocks() { return mRecord.getAlignmentBlocks(); } public List<SAMValidationError> validateCigar(long l) { return mRecord.validateCigar(l); } @Override public boolean equals(Object o) { if (this == o) return true; // note -- this forbids a GATKSAMRecord being equal to its underlying SAMRecord if (!(o instanceof GATKSAMRecord)) return false; // note that we do not consider the GATKSAMRecord internal state at all return mRecord.equals(((GATKSAMRecord)o).mRecord); } public int hashCode() { return mRecord.hashCode(); } public List<SAMValidationError> isValid() { return mRecord.isValid(); } public Object clone() throws CloneNotSupportedException { return mRecord.clone(); } public String toString() { return mRecord.toString(); } public SAMFileSource getFileSource() { return mRecord.getFileSource(); } /** * Sets a marker providing the source reader for this file and the position in the file from which the read originated. * @param fileSource source of the given file. */ @Override protected void setFileSource(final SAMFileSource fileSource) { try { Method method = SAMRecord.class.getDeclaredMethod("setFileSource",SAMFileSource.class); method.setAccessible(true); method.invoke(mRecord,fileSource); } catch(Exception ex) { throw new ReviewedStingException("Unable to invoke setFileSource method",ex); } } }
true
true
public GATKSAMRecord(SAMRecord record, boolean useOriginalBaseQualities, byte defaultBaseQualities) { super(null); // it doesn't matter - this isn't used if ( record == null ) throw new IllegalArgumentException("The SAMRecord argument cannot be null"); mRecord = record; mNegativeStrandFlag = mRecord.getReadNegativeStrandFlag(); mUnmappedFlag = mRecord.getReadUnmappedFlag(); // because attribute methods are declared to be final (and we can't overload them), // we need to actually set all of the attributes here List<SAMTagAndValue> attributes = record.getAttributes(); for ( SAMTagAndValue attribute : attributes ) setAttribute(attribute.tag, attribute.value); // if we are using default quals, check if we need them, and add if necessary. // 1. we need if reads are lacking or have incomplete quality scores // 2. we add if defaultBaseQualities has a positive value if (defaultBaseQualities >= 0) { byte reads [] = record.getReadBases(); byte quals [] = record.getBaseQualities(); if (quals == null || quals.length < reads.length) { byte new_quals [] = new byte [reads.length]; for (int i=0; i<reads.length; i++) new_quals[i] = defaultBaseQualities; record.setBaseQualities(new_quals); } } // if we are using original quals, set them now if they are present in the record if ( useOriginalBaseQualities ) { byte[] originalQuals = mRecord.getOriginalBaseQualities(); if ( originalQuals != null ) mRecord.setBaseQualities(originalQuals); } // sanity check that the lengths of the base and quality strings are equal if ( getBaseQualities().length != getReadLength() ) throw new UserException.MalformedBAM(this, String.format("Error: the number of base qualities does not match the number of bases in %s. Use -DBQ x to set a default base quality score to all reads so GATK can proceed.", mRecord.getReadName())); }
public GATKSAMRecord(SAMRecord record, boolean useOriginalBaseQualities, byte defaultBaseQualities) { super(null); // it doesn't matter - this isn't used if ( record == null ) throw new IllegalArgumentException("The SAMRecord argument cannot be null"); mRecord = record; mNegativeStrandFlag = mRecord.getReadNegativeStrandFlag(); mUnmappedFlag = mRecord.getReadUnmappedFlag(); // because attribute methods are declared to be final (and we can't overload them), // we need to actually set all of the attributes here List<SAMTagAndValue> attributes = record.getAttributes(); for ( SAMTagAndValue attribute : attributes ) setAttribute(attribute.tag, attribute.value); // if we are using default quals, check if we need them, and add if necessary. // 1. we need if reads are lacking or have incomplete quality scores // 2. we add if defaultBaseQualities has a positive value if (defaultBaseQualities >= 0) { byte reads [] = record.getReadBases(); byte quals [] = record.getBaseQualities(); if (quals == null || quals.length < reads.length) { byte new_quals [] = new byte [reads.length]; for (int i=0; i<reads.length; i++) new_quals[i] = defaultBaseQualities; record.setBaseQualities(new_quals); } } // if we are using original quals, set them now if they are present in the record if ( useOriginalBaseQualities ) { byte[] originalQuals = mRecord.getOriginalBaseQualities(); if ( originalQuals != null ) mRecord.setBaseQualities(originalQuals); } // sanity check that the lengths of the base and quality strings are equal if ( getBaseQualities().length != getReadLength() ) throw new UserException.MalformedBAM(this, String.format("Error: the number of base qualities does not match the number of bases in %s.", mRecord.getReadName())); }
diff --git a/src/main/java/net/cubespace/RegionShop/Core/Sell.java b/src/main/java/net/cubespace/RegionShop/Core/Sell.java index fc818b0..4c1c218 100644 --- a/src/main/java/net/cubespace/RegionShop/Core/Sell.java +++ b/src/main/java/net/cubespace/RegionShop/Core/Sell.java @@ -1,223 +1,223 @@ package net.cubespace.RegionShop.Core; import com.j256.ormlite.dao.ForeignCollection; import net.cubespace.RegionShop.Bukkit.Plugin; import net.cubespace.RegionShop.Config.ConfigManager; import net.cubespace.RegionShop.Config.Files.Sub.Group; import net.cubespace.RegionShop.Database.Database; import net.cubespace.RegionShop.Database.ItemStorageHolder; import net.cubespace.RegionShop.Database.PlayerOwns; import net.cubespace.RegionShop.Database.Repository.TransactionRepository; import net.cubespace.RegionShop.Database.Table.ItemStorage; import net.cubespace.RegionShop.Database.Table.Items; import net.cubespace.RegionShop.Database.Table.Transaction; import net.cubespace.RegionShop.Util.ItemName; import net.cubespace.RegionShop.Util.Logger; import net.cubespace.RegionShop.Util.VaultBridge; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.sql.SQLException; import java.util.List; public class Sell { public static void sell(final ItemStack itemStack, List<Items> items, Player player, final ItemStorageHolder region) { player.getInventory().removeItem(itemStack); ForeignCollection<PlayerOwns> playerList = region.getOwners(); boolean isOwner = false; for(PlayerOwns player1 : playerList) { if(player1.getPlayer().getName().equals(player.getName().toLowerCase())) { isOwner = true; } } if(isOwner) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_NotYourItem); player.getInventory().setItemInHand(itemStack); return; } //Check if there is Place inside the Shop Group group = ConfigManager.groups.getGroup(region.getItemStorage().getSetting()); if(region.getItemStorage().getItemAmount() + itemStack.getAmount() >= group.Storage) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_FullStorage); player.getInventory().setItemInHand(itemStack); return; } //Check all items for(final Items item : items) { if (item != null && item.getBuy() > 0) { Float price = (itemStack.getAmount() / item.getUnitAmount()) * item.getBuy(); if (region.getItemStorage().isServershop() || VaultBridge.has(item.getOwner(), itemStack.getAmount() * item.getBuy()) ) { String dataName = ItemName.getDataName(itemStack); String niceItemName; if(dataName.endsWith(" ")) { niceItemName = dataName + ItemName.nicer(itemStack.getType().toString()); } else if(!dataName.equals("")) { niceItemName = dataName; } else { niceItemName = ItemName.nicer(itemStack.getType().toString()); } if(!region.getItemStorage().isServershop()) { OfflinePlayer owner = Plugin.getInstance().getServer().getOfflinePlayer(item.getOwner()); if (owner != null) { if(owner.isOnline()) { Plugin.getInstance().getServer().getPlayer(item.getOwner()).sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHint. replace("%player", player.getDisplayName()). replace("%amount", ((Integer)itemStack.getAmount()).toString()). replace("%item", niceItemName). replace("%shop", region.getName()). replace("%price", price.toString())); } TransactionRepository.generateTransaction(owner, Transaction.TransactionType.BUY, region.getName(), player.getWorld().getName(), player.getName(), item.getMeta().getItemID(), itemStack.getAmount(), item.getBuy().doubleValue(), 0.0, item.getUnitAmount()); } VaultBridge.withdrawPlayer(item.getOwner(), itemStack.getAmount() * item.getBuy()); } VaultBridge.depositPlayer(player.getName(), itemStack.getAmount() * item.getBuy()); player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_PlayerHint. replace("%player", player.getDisplayName()). replace("%amount", ((Integer) itemStack.getAmount()).toString()). replace("%item", niceItemName). replace("%shop", region.getName()). replace("%price", price.toString()). replace("%owner", item.getOwner())); item.setCurrentAmount(item.getCurrentAmount() + itemStack.getAmount()); item.setBought(item.getBought() + itemStack.getAmount()); ItemStorage itemStorage = region.getItemStorage(); itemStorage.setItemAmount(itemStorage.getItemAmount() + itemStack.getAmount()); try { Database.getDAO(ItemStorage.class).update(itemStorage); Database.getDAO(Items.class).update(item); } catch (SQLException e) { Logger.error("Could not update Items/ItemStorage", e); } TransactionRepository.generateTransaction(player, Transaction.TransactionType.SELL, region.getName(), player.getWorld().getName(), item.getOwner(), item.getMeta().getItemID(), itemStack.getAmount(), 0.0, item.getBuy().doubleValue(), item.getUnitAmount()); return; } } } //No item found :( player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHasNotEnoughMoney); player.getInventory().setItemInHand(itemStack); } public static void sell(final ItemStack itemStack, final Items item, Player player, final ItemStorageHolder region) { player.getInventory().removeItem(itemStack); ForeignCollection<PlayerOwns> playerList = region.getOwners(); boolean isOwner = false; for(PlayerOwns player1 : playerList) { if(player1.getPlayer().getName().equals(player.getName().toLowerCase())) { isOwner = true; } } if(isOwner) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_NotYourItem); player.getInventory().setItemInHand(itemStack); return; } if(item.getBuy() <= 0.0) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_DoesNotBuy); player.getInventory().setItemInHand(itemStack); return; } Group group = ConfigManager.groups.getGroup(region.getItemStorage().getSetting()); if(region.getItemStorage().getItemAmount() + itemStack.getAmount() >= group.Storage) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_FullStorage); player.getInventory().setItemInHand(itemStack); return; } Float price = (itemStack.getAmount() / item.getUnitAmount() ) * item.getBuy(); if (region.getItemStorage().isServershop() || VaultBridge.has(item.getOwner(), price)) { String dataName = ItemName.getDataName(itemStack); String niceItemName; if(dataName.endsWith(" ")) { niceItemName = dataName + ItemName.nicer(itemStack.getType().toString()); } else if(!dataName.equals("")) { niceItemName = dataName; } else { niceItemName = ItemName.nicer(itemStack.getType().toString()); } if(!region.getItemStorage().isServershop()) { OfflinePlayer owner = Plugin.getInstance().getServer().getOfflinePlayer(item.getOwner()); if (owner != null) { TransactionRepository.generateTransaction(owner, Transaction.TransactionType.BUY, region.getName(), player.getWorld().getName(), player.getName(), item.getMeta().getItemID(), itemStack.getAmount(), item.getBuy().doubleValue(), 0.0, item.getUnitAmount()); } VaultBridge.withdrawPlayer(item.getOwner(), price); } VaultBridge.depositPlayer(player.getName(), price); player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_PlayerHint. replace("%player", player.getDisplayName()). replace("%amount", ((Integer) itemStack.getAmount()).toString()). replace("%item", niceItemName). replace("%shop", region.getName()). - replace("%price", price.toString(). - replace("%owner", item.getOwner()))); + replace("%price", price.toString()). + replace("%owner", item.getOwner())); item.setCurrentAmount(item.getCurrentAmount() + itemStack.getAmount()); item.setBought(item.getBought() + itemStack.getAmount()); ItemStorage itemStorage = region.getItemStorage(); itemStorage.setItemAmount(itemStorage.getItemAmount() + itemStack.getAmount()); try { Database.getDAO(ItemStorage.class).update(itemStorage); Database.getDAO(Items.class).update(item); } catch (SQLException e) { Logger.error("Could not update Items/ItemStorage", e); } TransactionRepository.generateTransaction(player, Transaction.TransactionType.SELL, region.getName(), player.getWorld().getName(), item.getOwner(), item.getMeta().getItemID(), itemStack.getAmount(), 0.0, item.getBuy().doubleValue(), item.getUnitAmount()); } else { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHasNotEnoughMoney); player.getInventory().setItemInHand(itemStack); } } }
true
true
public static void sell(final ItemStack itemStack, final Items item, Player player, final ItemStorageHolder region) { player.getInventory().removeItem(itemStack); ForeignCollection<PlayerOwns> playerList = region.getOwners(); boolean isOwner = false; for(PlayerOwns player1 : playerList) { if(player1.getPlayer().getName().equals(player.getName().toLowerCase())) { isOwner = true; } } if(isOwner) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_NotYourItem); player.getInventory().setItemInHand(itemStack); return; } if(item.getBuy() <= 0.0) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_DoesNotBuy); player.getInventory().setItemInHand(itemStack); return; } Group group = ConfigManager.groups.getGroup(region.getItemStorage().getSetting()); if(region.getItemStorage().getItemAmount() + itemStack.getAmount() >= group.Storage) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_FullStorage); player.getInventory().setItemInHand(itemStack); return; } Float price = (itemStack.getAmount() / item.getUnitAmount() ) * item.getBuy(); if (region.getItemStorage().isServershop() || VaultBridge.has(item.getOwner(), price)) { String dataName = ItemName.getDataName(itemStack); String niceItemName; if(dataName.endsWith(" ")) { niceItemName = dataName + ItemName.nicer(itemStack.getType().toString()); } else if(!dataName.equals("")) { niceItemName = dataName; } else { niceItemName = ItemName.nicer(itemStack.getType().toString()); } if(!region.getItemStorage().isServershop()) { OfflinePlayer owner = Plugin.getInstance().getServer().getOfflinePlayer(item.getOwner()); if (owner != null) { TransactionRepository.generateTransaction(owner, Transaction.TransactionType.BUY, region.getName(), player.getWorld().getName(), player.getName(), item.getMeta().getItemID(), itemStack.getAmount(), item.getBuy().doubleValue(), 0.0, item.getUnitAmount()); } VaultBridge.withdrawPlayer(item.getOwner(), price); } VaultBridge.depositPlayer(player.getName(), price); player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_PlayerHint. replace("%player", player.getDisplayName()). replace("%amount", ((Integer) itemStack.getAmount()).toString()). replace("%item", niceItemName). replace("%shop", region.getName()). replace("%price", price.toString(). replace("%owner", item.getOwner()))); item.setCurrentAmount(item.getCurrentAmount() + itemStack.getAmount()); item.setBought(item.getBought() + itemStack.getAmount()); ItemStorage itemStorage = region.getItemStorage(); itemStorage.setItemAmount(itemStorage.getItemAmount() + itemStack.getAmount()); try { Database.getDAO(ItemStorage.class).update(itemStorage); Database.getDAO(Items.class).update(item); } catch (SQLException e) { Logger.error("Could not update Items/ItemStorage", e); } TransactionRepository.generateTransaction(player, Transaction.TransactionType.SELL, region.getName(), player.getWorld().getName(), item.getOwner(), item.getMeta().getItemID(), itemStack.getAmount(), 0.0, item.getBuy().doubleValue(), item.getUnitAmount()); } else { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHasNotEnoughMoney); player.getInventory().setItemInHand(itemStack); } }
public static void sell(final ItemStack itemStack, final Items item, Player player, final ItemStorageHolder region) { player.getInventory().removeItem(itemStack); ForeignCollection<PlayerOwns> playerList = region.getOwners(); boolean isOwner = false; for(PlayerOwns player1 : playerList) { if(player1.getPlayer().getName().equals(player.getName().toLowerCase())) { isOwner = true; } } if(isOwner) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_NotYourItem); player.getInventory().setItemInHand(itemStack); return; } if(item.getBuy() <= 0.0) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_DoesNotBuy); player.getInventory().setItemInHand(itemStack); return; } Group group = ConfigManager.groups.getGroup(region.getItemStorage().getSetting()); if(region.getItemStorage().getItemAmount() + itemStack.getAmount() >= group.Storage) { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_FullStorage); player.getInventory().setItemInHand(itemStack); return; } Float price = (itemStack.getAmount() / item.getUnitAmount() ) * item.getBuy(); if (region.getItemStorage().isServershop() || VaultBridge.has(item.getOwner(), price)) { String dataName = ItemName.getDataName(itemStack); String niceItemName; if(dataName.endsWith(" ")) { niceItemName = dataName + ItemName.nicer(itemStack.getType().toString()); } else if(!dataName.equals("")) { niceItemName = dataName; } else { niceItemName = ItemName.nicer(itemStack.getType().toString()); } if(!region.getItemStorage().isServershop()) { OfflinePlayer owner = Plugin.getInstance().getServer().getOfflinePlayer(item.getOwner()); if (owner != null) { TransactionRepository.generateTransaction(owner, Transaction.TransactionType.BUY, region.getName(), player.getWorld().getName(), player.getName(), item.getMeta().getItemID(), itemStack.getAmount(), item.getBuy().doubleValue(), 0.0, item.getUnitAmount()); } VaultBridge.withdrawPlayer(item.getOwner(), price); } VaultBridge.depositPlayer(player.getName(), price); player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_PlayerHint. replace("%player", player.getDisplayName()). replace("%amount", ((Integer) itemStack.getAmount()).toString()). replace("%item", niceItemName). replace("%shop", region.getName()). replace("%price", price.toString()). replace("%owner", item.getOwner())); item.setCurrentAmount(item.getCurrentAmount() + itemStack.getAmount()); item.setBought(item.getBought() + itemStack.getAmount()); ItemStorage itemStorage = region.getItemStorage(); itemStorage.setItemAmount(itemStorage.getItemAmount() + itemStack.getAmount()); try { Database.getDAO(ItemStorage.class).update(itemStorage); Database.getDAO(Items.class).update(item); } catch (SQLException e) { Logger.error("Could not update Items/ItemStorage", e); } TransactionRepository.generateTransaction(player, Transaction.TransactionType.SELL, region.getName(), player.getWorld().getName(), item.getOwner(), item.getMeta().getItemID(), itemStack.getAmount(), 0.0, item.getBuy().doubleValue(), item.getUnitAmount()); } else { player.sendMessage(ConfigManager.main.Chat_prefix + ConfigManager.language.Sell_OwnerHasNotEnoughMoney); player.getInventory().setItemInHand(itemStack); } }
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/preview/PreviewThread.java b/javafx.editor/src/org/netbeans/modules/javafx/preview/PreviewThread.java index 660d272a..51111ee9 100644 --- a/javafx.editor/src/org/netbeans/modules/javafx/preview/PreviewThread.java +++ b/javafx.editor/src/org/netbeans/modules/javafx/preview/PreviewThread.java @@ -1,166 +1,166 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.javafx.preview; import java.security.CodeSource; import java.security.PermissionCollection; import org.netbeans.modules.javafx.editor.*; import java.security.Permissions; import javax.swing.JComponent; //import sun.awt.AppContext; import org.openide.execution.ExecutionEngine; //import sun.awt.SunToolkit; import org.openide.execution.ExecutorTask; import org.openide.execution.NbClassPath; import org.openide.util.Exceptions; import org.openide.util.Task; import org.openide.util.TaskListener; import org.openide.windows.IOProvider; import org.openide.windows.InputOutput; import org.openide.util.RequestProcessor; public class PreviewThread extends Thread { private FXDocument doc; private JComponent comp = null; class EE extends ExecutionEngine { public EE() {} protected NbClassPath createLibraryPath() { return new NbClassPath(new String[0]); } protected PermissionCollection createPermissions(CodeSource cs, InputOutput io) { PermissionCollection allPerms = new Permissions(); //allPerms.add(new AllPermission()); //allPerms.setReadOnly(); return allPerms; } public ExecutorTask execute(String name, Runnable run, InputOutput io) { return new ET(run, name, io); } private class ET extends ExecutorTask { private RequestProcessor.Task task; private int resultValue; private final String name; private InputOutput io; public ET(Runnable run, String name, InputOutput io) { super(run); this.resultValue = resultValue; this.name = name; task = RequestProcessor.getDefault().post(this); } public void stop() { task.cancel(); } public int result() { waitFinished(); return resultValue; } public InputOutput getInputOutput() { return io; } public void run() { try { super.run(); } catch (RuntimeException x) { x.printStackTrace(); resultValue = 1; } } } } class R implements Runnable { public void run() { Object obj = null; try { obj = CodeManager.execute(doc); } catch (Exception ex) { Exceptions.printStackTrace(ex); } if (obj != null) comp = CodeManager.parseObj(obj); } } public PreviewThread(FXDocument doc) { super(new ThreadGroup("SACG"), "SACT"); //super(); this.doc = doc; } @Override public void run() { try { //SunToolkit.createNewAppContext(); //System.out.println("Current app context " + AppContext.getAppContext()); ExecutionEngine ee = new EE(); - ExecutorTask task = ee.execute("prim", new R(), IOProvider.getDefault().getIO("someName", false)); + ExecutorTask task = ee.execute("prim", new R(), IOProvider.getDefault().getIO("JavaFX preview", false)); task.addTaskListener(new TaskListener() { public void taskFinished(Task task) { ((JavaFXDocument)doc).renderPreview(comp); } }); } catch(Exception ex) { ex.printStackTrace(); } } }
true
true
public void run() { try { //SunToolkit.createNewAppContext(); //System.out.println("Current app context " + AppContext.getAppContext()); ExecutionEngine ee = new EE(); ExecutorTask task = ee.execute("prim", new R(), IOProvider.getDefault().getIO("someName", false)); task.addTaskListener(new TaskListener() { public void taskFinished(Task task) { ((JavaFXDocument)doc).renderPreview(comp); } }); } catch(Exception ex) { ex.printStackTrace(); } }
public void run() { try { //SunToolkit.createNewAppContext(); //System.out.println("Current app context " + AppContext.getAppContext()); ExecutionEngine ee = new EE(); ExecutorTask task = ee.execute("prim", new R(), IOProvider.getDefault().getIO("JavaFX preview", false)); task.addTaskListener(new TaskListener() { public void taskFinished(Task task) { ((JavaFXDocument)doc).renderPreview(comp); } }); } catch(Exception ex) { ex.printStackTrace(); } }
diff --git a/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/rdt/ui/wizards/RemoteMakefileWizardHandler.java b/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/rdt/ui/wizards/RemoteMakefileWizardHandler.java index dedbceea1..b6f6d4232 100644 --- a/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/rdt/ui/wizards/RemoteMakefileWizardHandler.java +++ b/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/rdt/ui/wizards/RemoteMakefileWizardHandler.java @@ -1,136 +1,136 @@ /******************************************************************************* * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM - Initial API and implementation *******************************************************************************/ package org.eclipse.ptp.rdt.ui.wizards; import java.net.URI; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.cdt.core.settings.model.ICProjectDescriptionManager; import org.eclipse.cdt.core.settings.model.extension.CConfigurationData; import org.eclipse.cdt.internal.core.envvar.EnvironmentVariableManager; import org.eclipse.cdt.internal.core.envvar.UserDefinedEnvironmentSupplier; import org.eclipse.cdt.managedbuilder.core.IBuilder; import org.eclipse.cdt.managedbuilder.core.IConfiguration; import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo; import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager; import org.eclipse.cdt.managedbuilder.internal.core.Configuration; import org.eclipse.cdt.managedbuilder.internal.core.ManagedBuildInfo; import org.eclipse.cdt.managedbuilder.internal.core.ManagedProject; import org.eclipse.cdt.managedbuilder.internal.core.ToolChain; import org.eclipse.cdt.managedbuilder.ui.wizards.CfgHolder; import org.eclipse.cdt.managedbuilder.ui.wizards.STDWizardHandler; import org.eclipse.cdt.ui.newui.UIMessages; import org.eclipse.cdt.utils.EFSExtensionManager; import org.eclipse.cdt.utils.envvar.StorableEnvironment; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.wizard.IWizard; import org.eclipse.ptp.rdt.core.remotemake.RemoteMakeBuilder; import org.eclipse.ptp.rdt.core.resources.RemoteMakeNature; import org.eclipse.swt.widgets.Composite; /** * This class handles what happens during project creation when the * user has selected "Remote Makefile Project". * * <strong>EXPERIMENTAL</strong>. This class or interface has been added as * part of a work in progress. There is no guarantee that this API will work or * that it will remain the same. Please do not use this API without consulting * with the RDT team. * * @author crecoskie * */ public class RemoteMakefileWizardHandler extends STDWizardHandler { private static final UserDefinedEnvironmentSupplier fUserSupplier = EnvironmentVariableManager.fUserSupplier; public RemoteMakefileWizardHandler(Composite p, IWizard w) { super(p, w); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see org.eclipse.cdt.managedbuilder.ui.wizards.STDWizardHandler#createProject(org.eclipse.core.resources.IProject, boolean, boolean, org.eclipse.core.runtime.IProgressMonitor) */ @Override public void createProject(IProject project, boolean defaults, boolean onFinish, IProgressMonitor monitor) throws CoreException { try { monitor.beginTask("", 100); //$NON-NLS-1$ ICProjectDescriptionManager mngr = CoreModel.getDefault().getProjectDescriptionManager(); ICProjectDescription des = mngr.createProjectDescription(project, false, !onFinish); ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(project); ManagedProject mProj = new ManagedProject(des); info.setManagedProject(mProj); cfgs = CfgHolder.unique(fConfigPage.getCfgItems(defaults)); cfgs = CfgHolder.reorder(cfgs); for (int i=0; i<cfgs.length; i++) { String s = (cfgs[i].getToolChain() == null) ? "0" : ((ToolChain)(cfgs[i].getToolChain())).getId(); //$NON-NLS-1$ Configuration cfg = new Configuration(mProj, (ToolChain)cfgs[i].getToolChain(), ManagedBuildManager.calculateChildId(s, null), cfgs[i].getName()); IBuilder bld = cfg.getEditableBuilder(); if (bld != null) { if(bld.isInternalBuilder()){ IConfiguration prefCfg = ManagedBuildManager.getPreferenceConfiguration(false); IBuilder prefBuilder = prefCfg.getBuilder(); cfg.changeBuilder(prefBuilder, ManagedBuildManager.calculateChildId(cfg.getId(), null), prefBuilder.getName()); bld = cfg.getEditableBuilder(); bld.setBuildPath(null); } bld.setManagedBuildOn(false); } else { System.out.println(UIMessages.getString("StdProjectTypeHandler.3")); //$NON-NLS-1$ } cfg.setArtifactName(removeSpaces(project.getName())); CConfigurationData data = cfg.getConfigurationData(); des.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, data); } mngr.setProjectDescription(project, des); RemoteMakeNature.updateProjectDescription(project, RemoteMakeBuilder.REMOTE_MAKE_BUILDER_ID, new NullProgressMonitor()); // set the build directory by default to be that of the project... the usual workspace macro doesn't work as the workspace resides locally // and the project resides remotely URI projectLocation = project.getLocationURI(); // assume that the path portion of the URI corresponds to the path on the remote machine // this may not work if the remote machine does not use UNIX paths but we have no real way of knowing the path // format, so we hope for the best... String pathString = EFSExtensionManager.getDefault().getPathFromURI(projectLocation); IPath buildPath = Path.fromPortableString(pathString); IManagedBuildInfo mbsInfo = ManagedBuildManager.getBuildInfo(project); mbsInfo.getDefaultConfiguration().getBuildData().setBuilderCWD(buildPath); mbsInfo.setDirty(true); ManagedBuildManager.saveBuildInfo(project, true); doTemplatesPostProcess(project); doCustom(project); //turn off append local environment variables for remote projects StorableEnvironment vars = EnvironmentVariableManager.fUserSupplier.getWorkspaceEnvironmentCopy(); vars.setAppendContributedEnvironment(false); vars.setAppendEnvironment(false); -// EnvironmentVariableManager.fUserSupplier.setWorkspaceEnvironment(vars); + EnvironmentVariableManager.fUserSupplier.setWorkspaceEnvironment(vars); } finally { monitor.done(); } } }
true
true
public void createProject(IProject project, boolean defaults, boolean onFinish, IProgressMonitor monitor) throws CoreException { try { monitor.beginTask("", 100); //$NON-NLS-1$ ICProjectDescriptionManager mngr = CoreModel.getDefault().getProjectDescriptionManager(); ICProjectDescription des = mngr.createProjectDescription(project, false, !onFinish); ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(project); ManagedProject mProj = new ManagedProject(des); info.setManagedProject(mProj); cfgs = CfgHolder.unique(fConfigPage.getCfgItems(defaults)); cfgs = CfgHolder.reorder(cfgs); for (int i=0; i<cfgs.length; i++) { String s = (cfgs[i].getToolChain() == null) ? "0" : ((ToolChain)(cfgs[i].getToolChain())).getId(); //$NON-NLS-1$ Configuration cfg = new Configuration(mProj, (ToolChain)cfgs[i].getToolChain(), ManagedBuildManager.calculateChildId(s, null), cfgs[i].getName()); IBuilder bld = cfg.getEditableBuilder(); if (bld != null) { if(bld.isInternalBuilder()){ IConfiguration prefCfg = ManagedBuildManager.getPreferenceConfiguration(false); IBuilder prefBuilder = prefCfg.getBuilder(); cfg.changeBuilder(prefBuilder, ManagedBuildManager.calculateChildId(cfg.getId(), null), prefBuilder.getName()); bld = cfg.getEditableBuilder(); bld.setBuildPath(null); } bld.setManagedBuildOn(false); } else { System.out.println(UIMessages.getString("StdProjectTypeHandler.3")); //$NON-NLS-1$ } cfg.setArtifactName(removeSpaces(project.getName())); CConfigurationData data = cfg.getConfigurationData(); des.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, data); } mngr.setProjectDescription(project, des); RemoteMakeNature.updateProjectDescription(project, RemoteMakeBuilder.REMOTE_MAKE_BUILDER_ID, new NullProgressMonitor()); // set the build directory by default to be that of the project... the usual workspace macro doesn't work as the workspace resides locally // and the project resides remotely URI projectLocation = project.getLocationURI(); // assume that the path portion of the URI corresponds to the path on the remote machine // this may not work if the remote machine does not use UNIX paths but we have no real way of knowing the path // format, so we hope for the best... String pathString = EFSExtensionManager.getDefault().getPathFromURI(projectLocation); IPath buildPath = Path.fromPortableString(pathString); IManagedBuildInfo mbsInfo = ManagedBuildManager.getBuildInfo(project); mbsInfo.getDefaultConfiguration().getBuildData().setBuilderCWD(buildPath); mbsInfo.setDirty(true); ManagedBuildManager.saveBuildInfo(project, true); doTemplatesPostProcess(project); doCustom(project); //turn off append local environment variables for remote projects StorableEnvironment vars = EnvironmentVariableManager.fUserSupplier.getWorkspaceEnvironmentCopy(); vars.setAppendContributedEnvironment(false); vars.setAppendEnvironment(false); // EnvironmentVariableManager.fUserSupplier.setWorkspaceEnvironment(vars); } finally { monitor.done(); } }
public void createProject(IProject project, boolean defaults, boolean onFinish, IProgressMonitor monitor) throws CoreException { try { monitor.beginTask("", 100); //$NON-NLS-1$ ICProjectDescriptionManager mngr = CoreModel.getDefault().getProjectDescriptionManager(); ICProjectDescription des = mngr.createProjectDescription(project, false, !onFinish); ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(project); ManagedProject mProj = new ManagedProject(des); info.setManagedProject(mProj); cfgs = CfgHolder.unique(fConfigPage.getCfgItems(defaults)); cfgs = CfgHolder.reorder(cfgs); for (int i=0; i<cfgs.length; i++) { String s = (cfgs[i].getToolChain() == null) ? "0" : ((ToolChain)(cfgs[i].getToolChain())).getId(); //$NON-NLS-1$ Configuration cfg = new Configuration(mProj, (ToolChain)cfgs[i].getToolChain(), ManagedBuildManager.calculateChildId(s, null), cfgs[i].getName()); IBuilder bld = cfg.getEditableBuilder(); if (bld != null) { if(bld.isInternalBuilder()){ IConfiguration prefCfg = ManagedBuildManager.getPreferenceConfiguration(false); IBuilder prefBuilder = prefCfg.getBuilder(); cfg.changeBuilder(prefBuilder, ManagedBuildManager.calculateChildId(cfg.getId(), null), prefBuilder.getName()); bld = cfg.getEditableBuilder(); bld.setBuildPath(null); } bld.setManagedBuildOn(false); } else { System.out.println(UIMessages.getString("StdProjectTypeHandler.3")); //$NON-NLS-1$ } cfg.setArtifactName(removeSpaces(project.getName())); CConfigurationData data = cfg.getConfigurationData(); des.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, data); } mngr.setProjectDescription(project, des); RemoteMakeNature.updateProjectDescription(project, RemoteMakeBuilder.REMOTE_MAKE_BUILDER_ID, new NullProgressMonitor()); // set the build directory by default to be that of the project... the usual workspace macro doesn't work as the workspace resides locally // and the project resides remotely URI projectLocation = project.getLocationURI(); // assume that the path portion of the URI corresponds to the path on the remote machine // this may not work if the remote machine does not use UNIX paths but we have no real way of knowing the path // format, so we hope for the best... String pathString = EFSExtensionManager.getDefault().getPathFromURI(projectLocation); IPath buildPath = Path.fromPortableString(pathString); IManagedBuildInfo mbsInfo = ManagedBuildManager.getBuildInfo(project); mbsInfo.getDefaultConfiguration().getBuildData().setBuilderCWD(buildPath); mbsInfo.setDirty(true); ManagedBuildManager.saveBuildInfo(project, true); doTemplatesPostProcess(project); doCustom(project); //turn off append local environment variables for remote projects StorableEnvironment vars = EnvironmentVariableManager.fUserSupplier.getWorkspaceEnvironmentCopy(); vars.setAppendContributedEnvironment(false); vars.setAppendEnvironment(false); EnvironmentVariableManager.fUserSupplier.setWorkspaceEnvironment(vars); } finally { monitor.done(); } }
diff --git a/RoboTech/src/personnages/Ennemis.java b/RoboTech/src/personnages/Ennemis.java index 5e817bc..43127b1 100644 --- a/RoboTech/src/personnages/Ennemis.java +++ b/RoboTech/src/personnages/Ennemis.java @@ -1,65 +1,65 @@ package personnages; import jeu.Monde; import net.phys2d.raw.Collide; import org.newdawn.slick.GameContainer; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.StateBasedGame; import weapon.Balle; import weapon.BalleEnnemiVert; public abstract class Ennemis extends Personnage { // l'image qui contient le sprite du robot private int deplacementAuto; private boolean deplacementAutoDroite; public Ennemis(float x, float y, float masse, float tailleBlockPerso, Monde monde) { super(x, y, masse, tailleBlockPerso, monde); deplacementAuto = 0; deplacementAutoDroite = true; } // gere le deplacement automatique des ennemies (a revoir, juste un test) public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { super.update(container, game, delta); // Balle balle; // if (deplacementAuto < 230 && deplacementAutoDroite) { // applyForce(100, getVelY()); // deplacementAuto++; // } else { // deplacementAutoDroite = false; // applyForce(-100, getVelY()); // deplacementAuto--; // if (deplacementAuto == 0) { // deplacementAutoDroite = true; // balle = new BalleEnnemiVert(getX(), getY(), // getDirectionDroite(), 0.01f, 2); // balle.applyForce(10000, 0); // monde.addBalles(balle); // // } // } if (deplacementAutoDroite && monde.estSolPosition((int)(this.getX()+16), (int)(this.getY()+32))) { applyForce(100, getVelY()); deplacementAutoDroite = true; if(!monde.estSolPosition((int)(this.getX()+32), (int)(this.getY()+32))) { deplacementAutoDroite = false; } } - else if (!deplacementAutoDroite && monde.estSolPosition((int)(this.getX()-32), (int)(this.getY()+32))) { + else if (!deplacementAutoDroite && monde.estSolPosition((int)(this.getX()-16), (int)(this.getY()+32))) { applyForce(-100, getVelY()); deplacementAutoDroite = false; - if(monde.estSolPosition((int)(this.getX()-32), (int)(this.getY()-32))) { + if(!monde.estSolPosition((int)(this.getX()-32), (int)(this.getY()+32))) { deplacementAutoDroite = true; } } } }
false
true
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { super.update(container, game, delta); // Balle balle; // if (deplacementAuto < 230 && deplacementAutoDroite) { // applyForce(100, getVelY()); // deplacementAuto++; // } else { // deplacementAutoDroite = false; // applyForce(-100, getVelY()); // deplacementAuto--; // if (deplacementAuto == 0) { // deplacementAutoDroite = true; // balle = new BalleEnnemiVert(getX(), getY(), // getDirectionDroite(), 0.01f, 2); // balle.applyForce(10000, 0); // monde.addBalles(balle); // // } // } if (deplacementAutoDroite && monde.estSolPosition((int)(this.getX()+16), (int)(this.getY()+32))) { applyForce(100, getVelY()); deplacementAutoDroite = true; if(!monde.estSolPosition((int)(this.getX()+32), (int)(this.getY()+32))) { deplacementAutoDroite = false; } } else if (!deplacementAutoDroite && monde.estSolPosition((int)(this.getX()-32), (int)(this.getY()+32))) { applyForce(-100, getVelY()); deplacementAutoDroite = false; if(monde.estSolPosition((int)(this.getX()-32), (int)(this.getY()-32))) { deplacementAutoDroite = true; } } }
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { super.update(container, game, delta); // Balle balle; // if (deplacementAuto < 230 && deplacementAutoDroite) { // applyForce(100, getVelY()); // deplacementAuto++; // } else { // deplacementAutoDroite = false; // applyForce(-100, getVelY()); // deplacementAuto--; // if (deplacementAuto == 0) { // deplacementAutoDroite = true; // balle = new BalleEnnemiVert(getX(), getY(), // getDirectionDroite(), 0.01f, 2); // balle.applyForce(10000, 0); // monde.addBalles(balle); // // } // } if (deplacementAutoDroite && monde.estSolPosition((int)(this.getX()+16), (int)(this.getY()+32))) { applyForce(100, getVelY()); deplacementAutoDroite = true; if(!monde.estSolPosition((int)(this.getX()+32), (int)(this.getY()+32))) { deplacementAutoDroite = false; } } else if (!deplacementAutoDroite && monde.estSolPosition((int)(this.getX()-16), (int)(this.getY()+32))) { applyForce(-100, getVelY()); deplacementAutoDroite = false; if(!monde.estSolPosition((int)(this.getX()-32), (int)(this.getY()+32))) { deplacementAutoDroite = true; } } }
diff --git a/src/dctc/java/com/dataiku/dctc/command/grep/ColorGrepPrinter.java b/src/dctc/java/com/dataiku/dctc/command/grep/ColorGrepPrinter.java index e1d251d..611b8a8 100644 --- a/src/dctc/java/com/dataiku/dctc/command/grep/ColorGrepPrinter.java +++ b/src/dctc/java/com/dataiku/dctc/command/grep/ColorGrepPrinter.java @@ -1,40 +1,44 @@ package com.dataiku.dctc.command.grep; import com.dataiku.dctc.file.GeneralizedFile; class ColorGrepPrinter implements GrepPrinter { ColorGrepPrinter(GrepMatcher matcher) { this.matcher = matcher; } public void print(String line) { while(!line.isEmpty()) { if (matcher.match(line)) { int begin = matcher.begin(line); + if (begin == -1) { + break; + } int end = matcher.end(begin, line); System.out.print(line.substring(0, begin)); - System.out.print("\u001B[1;31m" + line.substring(begin, end) + "\u001B[0m"); + System.out.print("\u001B[1;31m" + line.substring(begin, end) + + "\u001B[0m"); line = line.substring(end); } else { break; } } System.out.println(line); } public void end(GeneralizedFile file) { } public GrepMatcher getMatcher() { return matcher; } public void setMatcher(GrepMatcher matcher) { this.matcher = matcher; } public ColorGrepPrinter withMatcher(GrepMatcher matcher) { this.matcher = matcher; return this; } // Attributes private GrepMatcher matcher; }
false
true
public void print(String line) { while(!line.isEmpty()) { if (matcher.match(line)) { int begin = matcher.begin(line); int end = matcher.end(begin, line); System.out.print(line.substring(0, begin)); System.out.print("\u001B[1;31m" + line.substring(begin, end) + "\u001B[0m"); line = line.substring(end); } else { break; } } System.out.println(line); }
public void print(String line) { while(!line.isEmpty()) { if (matcher.match(line)) { int begin = matcher.begin(line); if (begin == -1) { break; } int end = matcher.end(begin, line); System.out.print(line.substring(0, begin)); System.out.print("\u001B[1;31m" + line.substring(begin, end) + "\u001B[0m"); line = line.substring(end); } else { break; } } System.out.println(line); }
diff --git a/JavaLib/src/com/punchline/javalib/entities/systems/render/RenderSystem.java b/JavaLib/src/com/punchline/javalib/entities/systems/render/RenderSystem.java index 0a0af91..2bfdeab 100644 --- a/JavaLib/src/com/punchline/javalib/entities/systems/render/RenderSystem.java +++ b/JavaLib/src/com/punchline/javalib/entities/systems/render/RenderSystem.java @@ -1,112 +1,112 @@ package com.punchline.javalib.entities.systems.render; import java.util.Comparator; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.punchline.javalib.entities.Entity; import com.punchline.javalib.entities.components.physical.Transform; import com.punchline.javalib.entities.components.render.Parallax; import com.punchline.javalib.entities.components.render.Renderable; import com.punchline.javalib.entities.systems.ComponentSystem; import com.punchline.javalib.utils.Convert; /** * System for rendering every {@link Entity} that has a {@link Renderable} component. * @author Natman64 * */ public final class RenderSystem extends ComponentSystem { /** * Comparator implementation used for properly layering Renderables. * @author Natman64 * */ private class RenderableComparator implements Comparator<Entity> { @Override public int compare(Entity o1, Entity o2) { Renderable r1 = o1.getComponent(Renderable.class); Renderable r2 = o2.getComponent(Renderable.class); return r1.getLayer() - r2.getLayer(); } } private Camera camera; private SpriteBatch spriteBatch; private RenderableComparator comparator = new RenderableComparator(); //region Initialization/Disposal /** * Constructs a RenderSystem. * @param camera The camera for rendering. */ @SuppressWarnings("unchecked") public RenderSystem(Camera camera) { super(Renderable.class); this.camera = camera; spriteBatch = new SpriteBatch(); spriteBatch.enableBlending(); } @Override public void dispose() { spriteBatch.dispose(); } //endregion //region Processing @Override public void processEntities() { if (processingListChanged) entities.sort(comparator); camera.update(); spriteBatch.setProjectionMatrix(camera.combined); spriteBatch.begin(); super.processEntities(); spriteBatch.end(); } @Override protected void process(Entity e) { Renderable r = (Renderable)e.getComponent(Renderable.class); if (e.hasComponent(Transform.class)) { Transform t = (Transform)e.getComponent(Transform.class); Vector2 pos = Convert.metersToPixels(t.getPosition().cpy()); float angle = t.getRotation(); - //Handle position setting for paralax scrolling. + //Handle position setting for parallax scrolling. if(e.hasComponent(Parallax.class)){ Parallax p = e.getComponent(Parallax.class); // v = (v - c.p) * modulus_velocity r.setPosition((new Vector2(p.getCameraPosition())).scl((1 - p.getDepthRatio())).add(pos.cpy())); } else r.setPosition(pos); r.setRotation((float)Math.toDegrees(angle)); } r.draw(spriteBatch, deltaSeconds()); } //endregion }
true
true
protected void process(Entity e) { Renderable r = (Renderable)e.getComponent(Renderable.class); if (e.hasComponent(Transform.class)) { Transform t = (Transform)e.getComponent(Transform.class); Vector2 pos = Convert.metersToPixels(t.getPosition().cpy()); float angle = t.getRotation(); //Handle position setting for paralax scrolling. if(e.hasComponent(Parallax.class)){ Parallax p = e.getComponent(Parallax.class); // v = (v - c.p) * modulus_velocity r.setPosition((new Vector2(p.getCameraPosition())).scl((1 - p.getDepthRatio())).add(pos.cpy())); } else r.setPosition(pos); r.setRotation((float)Math.toDegrees(angle)); } r.draw(spriteBatch, deltaSeconds()); }
protected void process(Entity e) { Renderable r = (Renderable)e.getComponent(Renderable.class); if (e.hasComponent(Transform.class)) { Transform t = (Transform)e.getComponent(Transform.class); Vector2 pos = Convert.metersToPixels(t.getPosition().cpy()); float angle = t.getRotation(); //Handle position setting for parallax scrolling. if(e.hasComponent(Parallax.class)){ Parallax p = e.getComponent(Parallax.class); // v = (v - c.p) * modulus_velocity r.setPosition((new Vector2(p.getCameraPosition())).scl((1 - p.getDepthRatio())).add(pos.cpy())); } else r.setPosition(pos); r.setRotation((float)Math.toDegrees(angle)); } r.draw(spriteBatch, deltaSeconds()); }
diff --git a/src/main/java/no/hials/muldvarpweb/service/CourseService.java b/src/main/java/no/hials/muldvarpweb/service/CourseService.java index 84d10cf..d6c5171 100644 --- a/src/main/java/no/hials/muldvarpweb/service/CourseService.java +++ b/src/main/java/no/hials/muldvarpweb/service/CourseService.java @@ -1,145 +1,146 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package no.hials.muldvarpweb.service; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import no.hials.muldvarpweb.domain.Course; import no.hials.muldvarpweb.domain.Exam; import no.hials.muldvarpweb.domain.ObligatoryTask; import no.hials.muldvarpweb.domain.Task; import no.hials.muldvarpweb.domain.Theme; /** * * @author kristoffer */ @Stateless @Path("course") public class CourseService { @PersistenceContext EntityManager em; @GET @Produces({MediaType.APPLICATION_JSON}) public List<Course> findCourses() { //return em.createQuery("SELECT c from Course c", Course.class).getResultList(); //testdata Course c = new Course("Test"); List<Course> retVal = new ArrayList<Course>(); retVal.add(c); c = new Course("Hei fra muldvarpweb"); c.setImageurl("http://developer.android.com/assets/images/bg_logo.png"); retVal.add(c); for(int i = 0; i <= 20; i++) { c = new Course("Fagnavn numero " + i); c.setDetail("Details"); retVal.add(c); } return retVal; } @GET @Path("{id}") @Produces({MediaType.APPLICATION_JSON}) public Course getCourse(@PathParam("id") Short id) { // TypedQuery<Course> q = em.createQuery("Select c from Course c where c.id = :id", Course.class); // q.setParameter("id", id); // return q.getSingleResult(); // testdata Course retVal = new Course("Fagnavn"); retVal.setDetail("Details"); DateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss"); Date date = new Date(); ArrayList<ObligatoryTask> obligTasks = new ArrayList<ObligatoryTask>(); try { date = df.parse("2013-11-28T12:34:56"); } catch (ParseException ex) { Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex); } ObligatoryTask oblig1 = new ObligatoryTask("Obligatorisk 1"); oblig1.setDueDate(date); obligTasks.add(oblig1); oblig1 = new ObligatoryTask("Obligatorisk 2"); Calendar c = Calendar.getInstance(); int year = 2012; int month = 11; int day = 28; int hour = 12; int minute = 34; + c.clear(); c.set(year, month, day, hour, minute); oblig1.setDueDate(c.getTime()); oblig1.setDone(true); obligTasks.add(oblig1); retVal.setObligatoryTasks(obligTasks); try { date = df.parse("2011-12-31T12:34:56"); } catch (ParseException ex) { Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<Exam> exams = new ArrayList<Exam>(); Exam exam = new Exam("Eksamen 1"); exam.setExamDate(date); exams.add(exam); exam = new Exam("Eksamen 2"); exam.setExamDate(date); exams.add(exam); retVal.setExams(exams); ArrayList<Theme> themes = new ArrayList<Theme>(); Theme theme1 = new Theme("Kult tema"); ArrayList<Task> tasks = new ArrayList<Task>(); Task task = new Task("Oppgave 1.1"); tasks.add(task); task = new Task("Oppgave 1.2"); tasks.add(task); theme1.setTasks(tasks); themes.add(theme1); Theme theme2 = new Theme("Dummy tema"); ArrayList<Task> tasks2 = new ArrayList<Task>(); task = new Task("Oppgave 2.1"); task.setDone(true); tasks2.add(task); task = new Task("Oppgave 2.2"); task.setDone(true); tasks2.add(task); theme2.setTasks(tasks2); themes.add(theme2); retVal.setThemes(themes); return retVal; } public List<Course> getCourse(String name) { TypedQuery<Course> q = em.createQuery("Select c from Course c where c.name LIKE :name", Course.class); q.setParameter("name", "%" + name + "%"); return q.getResultList(); } }
true
true
public Course getCourse(@PathParam("id") Short id) { // TypedQuery<Course> q = em.createQuery("Select c from Course c where c.id = :id", Course.class); // q.setParameter("id", id); // return q.getSingleResult(); // testdata Course retVal = new Course("Fagnavn"); retVal.setDetail("Details"); DateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss"); Date date = new Date(); ArrayList<ObligatoryTask> obligTasks = new ArrayList<ObligatoryTask>(); try { date = df.parse("2013-11-28T12:34:56"); } catch (ParseException ex) { Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex); } ObligatoryTask oblig1 = new ObligatoryTask("Obligatorisk 1"); oblig1.setDueDate(date); obligTasks.add(oblig1); oblig1 = new ObligatoryTask("Obligatorisk 2"); Calendar c = Calendar.getInstance(); int year = 2012; int month = 11; int day = 28; int hour = 12; int minute = 34; c.set(year, month, day, hour, minute); oblig1.setDueDate(c.getTime()); oblig1.setDone(true); obligTasks.add(oblig1); retVal.setObligatoryTasks(obligTasks); try { date = df.parse("2011-12-31T12:34:56"); } catch (ParseException ex) { Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<Exam> exams = new ArrayList<Exam>(); Exam exam = new Exam("Eksamen 1"); exam.setExamDate(date); exams.add(exam); exam = new Exam("Eksamen 2"); exam.setExamDate(date); exams.add(exam); retVal.setExams(exams); ArrayList<Theme> themes = new ArrayList<Theme>(); Theme theme1 = new Theme("Kult tema"); ArrayList<Task> tasks = new ArrayList<Task>(); Task task = new Task("Oppgave 1.1"); tasks.add(task); task = new Task("Oppgave 1.2"); tasks.add(task); theme1.setTasks(tasks); themes.add(theme1); Theme theme2 = new Theme("Dummy tema"); ArrayList<Task> tasks2 = new ArrayList<Task>(); task = new Task("Oppgave 2.1"); task.setDone(true); tasks2.add(task); task = new Task("Oppgave 2.2"); task.setDone(true); tasks2.add(task); theme2.setTasks(tasks2); themes.add(theme2); retVal.setThemes(themes); return retVal; }
public Course getCourse(@PathParam("id") Short id) { // TypedQuery<Course> q = em.createQuery("Select c from Course c where c.id = :id", Course.class); // q.setParameter("id", id); // return q.getSingleResult(); // testdata Course retVal = new Course("Fagnavn"); retVal.setDetail("Details"); DateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss"); Date date = new Date(); ArrayList<ObligatoryTask> obligTasks = new ArrayList<ObligatoryTask>(); try { date = df.parse("2013-11-28T12:34:56"); } catch (ParseException ex) { Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex); } ObligatoryTask oblig1 = new ObligatoryTask("Obligatorisk 1"); oblig1.setDueDate(date); obligTasks.add(oblig1); oblig1 = new ObligatoryTask("Obligatorisk 2"); Calendar c = Calendar.getInstance(); int year = 2012; int month = 11; int day = 28; int hour = 12; int minute = 34; c.clear(); c.set(year, month, day, hour, minute); oblig1.setDueDate(c.getTime()); oblig1.setDone(true); obligTasks.add(oblig1); retVal.setObligatoryTasks(obligTasks); try { date = df.parse("2011-12-31T12:34:56"); } catch (ParseException ex) { Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<Exam> exams = new ArrayList<Exam>(); Exam exam = new Exam("Eksamen 1"); exam.setExamDate(date); exams.add(exam); exam = new Exam("Eksamen 2"); exam.setExamDate(date); exams.add(exam); retVal.setExams(exams); ArrayList<Theme> themes = new ArrayList<Theme>(); Theme theme1 = new Theme("Kult tema"); ArrayList<Task> tasks = new ArrayList<Task>(); Task task = new Task("Oppgave 1.1"); tasks.add(task); task = new Task("Oppgave 1.2"); tasks.add(task); theme1.setTasks(tasks); themes.add(theme1); Theme theme2 = new Theme("Dummy tema"); ArrayList<Task> tasks2 = new ArrayList<Task>(); task = new Task("Oppgave 2.1"); task.setDone(true); tasks2.add(task); task = new Task("Oppgave 2.2"); task.setDone(true); tasks2.add(task); theme2.setTasks(tasks2); themes.add(theme2); retVal.setThemes(themes); return retVal; }