Datasets:

Modalities:
Text
Formats:
parquet
Languages:
code
ArXiv:
Libraries:
Datasets
Dask
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; }

Megadiff, a dataset of source code changes

Contains only single-function diffs.

If you use Megadiff, please cite the following technical report:

"Megadiff: A Dataset of 600k Java Source Code Changes Categorized by Diff Size". Technical Report 2108.04631, Arxiv; 2021.

@techreport{megadiff,
  TITLE = {{Megadiff: A Dataset of 600k Java Source Code Changes Categorized by Diff Size}},
  AUTHOR = {Martin Monperrus and Matias Martinez and He Ye and Fernanda Madeiral and Thomas Durieux and Zhongxing Yu},
  URL = {http://arxiv.org/pdf/2108.04631},
  INSTITUTION = {Arxiv},
  NUMBER = {2108.04631},
  YEAR = {2021},
}
Downloads last month
73