diff --git a/README.txt b/README.txt deleted file mode 100644 index 331ac4d..0000000 --- a/README.txt +++ /dev/null @@ -1,19 +0,0 @@ -P4Java is a java library for interacting with Perforce. It picked up where the official -library from Perforce, P4J, left off. (It left, much, much to be desired. You couldn’t -even use it with servers that required login via tickets) Among other projects, it is -used in things like the Hudson Continuous Integration server. (http://hudson.dev.java.net) - -P4Java documentation is located here: http://tek42.com/p4java - -However, earlier this year (2010), Perforce came out with a new library that completely -replaces the original one they wrote. In addition, it is completely native so you don’t -need to install the p4 client. I believe, it is pretty close to a total feature complete -client. So that is way cool. - -What isn’t way cool? That they ripped off the name, P4Java without even asking. They -just up and announced “P4Java is here!” Hey thanks guys, I would have been happy to say -go right ahead and use it. Maybe you could have even said thanks for saving your ass for -years while there wasn’t a suitable library from your own company? - -Bitter? Yes. That’s just plain uncouth. So you won’t find a link to the new library -here. Search for “perforce java library” on google. See which comes up. (not theirs) \ No newline at end of file diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml deleted file mode 100644 index 6964705..0000000 --- a/checkstyle-suppressions.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/checkstyle.xml b/checkstyle.xml deleted file mode 100644 index 888662e..0000000 --- a/checkstyle.xml +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/findbugs-exclusion-filter.xml b/findbugs-exclusion-filter.xml deleted file mode 100644 index 6f5ccc4..0000000 --- a/findbugs-exclusion-filter.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..24b9a8c --- /dev/null +++ b/index.html @@ -0,0 +1,101 @@ + + + + + + + digerata/P4Java @ GitHub + + + + + + + Fork me on GitHub + +
+ +
+ + + + +
+ +

P4Java + by digerata

+ +
+ P4Java is an open source Java library that allows you to interact with all Perforce SCM facilities. It provides additional support where the Perforce provided API leaves off. +
+ +

P4Java + +P4Java is an open source Java library that allows you to interact with all Perforce SCM facilities. It provides additional support where the Perforce provided API leaves off. + +Why? + +The public API from Perforce doesn't support newer features of the server and doesn't allow you to extend upon the existing code base. And by newer, I mean features after 2001. Additionally, there is no active development against it. The last known change was in 2002. The API isn't even listed on Perforce's website. + +There are several goals for this new project to pick up where the public API leaves off. Among these are: + +Good documentation. Let's make sure you can get up and running as quickly as possible. After all, you probably aren't using this API as your core development project. +Extensible. In the event the API doesn't do something you need, it has a more open design that allows you to extend it. No final classes here! +Dependency Injection. The new API is designed with Dependancy Injection in mind so that you can easily integrate with your existing system. No static singletons! + +License + +P4Java is licensed under the LGPL. For people looking to contribute or submit patches, please send an email to info@tek42.com. While the code is hosted on a Perforce repository, we don't yet have an open source license for people to access it. +

Dependencies

+

If you are building P4Java from source, you'll need a Perforce server to run the tests against. If you don't care, there is always -Dmaven.test.skip=true

+

License

+

LGPL

+

Authors

+

Mike Wille (mike@tek42.com)

+

Contact

+

Mike Wille (mike.wille@flowz.com)

+ + +

Download

+

+ You can download this project in either + zip or + tar formats. +

+

You can also clone the project with Git + by running: +

$ git clone git://github.com/digerata/P4Java
+

+ + + +
+ + + + diff --git a/p4java.iml b/p4java.iml deleted file mode 100644 index fe1c436..0000000 --- a/p4java.iml +++ /dev/null @@ -1,147 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/p4java.ipr b/p4java.ipr deleted file mode 100644 index d86e796..0000000 --- a/p4java.ipr +++ /dev/null @@ -1,264 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/pom.xml b/pom.xml deleted file mode 100644 index a3505af..0000000 --- a/pom.xml +++ /dev/null @@ -1,223 +0,0 @@ - - 4.0.0 - com.tek42.perforce - p4java - jar - 0.7.6 - P4Java - http://tek42.com/p4java - 2007 - - Open Source Java Library to interact with Perforce SCM Repositories. - - - - LGPL - - P4Java - java integration with Perforce SCM - Copyright (C) 2007-, Mike Wille, Tek42 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - You can contact the author at: - - Web: http://tek42.com - Email: mike@tek42.com - Mail: 755 W Big Beaver Road - Suite 1110 - Troy, MI 48084 - - - - - - junit - junit - 4.4 - test - - - org.slf4j - slf4j-api - 1.4.3 - compile - - - org.slf4j - slf4j-simple - 1.4.3 - compile - - - commons-digester - commons-digester - 1.8 - compile - - - - - tek42.com - scp://tek42.com/var/www/www.tek42.com/web/maven2 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - org.codehaus.mojo - cobertura-maven-plugin - - - - clean - check - - - - - - - **/*.class - - - - com/perforce/api/**/*.class - **/*Test.class - - - - 0 - 0 - false - 0 - 0 - 0 - 0 - - - com.tek42.* - 0 - 0 - - - - - - - - - org.apache.maven.wagon - wagon-ssh-external - 1.0-beta-2 - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - org.codehaus.mojo - cobertura-maven-plugin - - - html - xml - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.xml - checkstyle-suppressions.xml - - - - org.codehaus.mojo - findbugs-maven-plugin - 1.1.1 - - true - Low - Max - false - false - - findbugs-exclusion-filter.xml - - - - - - - - diff --git a/src/main/java/com/perforce/api/Branch.java b/src/main/java/com/perforce/api/Branch.java deleted file mode 100644 index 2e0e3d7..0000000 --- a/src/main/java/com/perforce/api/Branch.java +++ /dev/null @@ -1,437 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control branch. There are static class methods - * that can be used to list all P4 branches or to - * get a particular branch. - * - * @author David Markley - * @version $Date: 2002/08/05 $ $Revision: #3 $ - */ -public class Branch extends Mapping { - private static HashDecay branches = null; - - /** - * Default no-argument constructor. - */ - public Branch() { - super(); - getCache(); - } - - /** - * Constructor that is passed the branch name. - */ - public Branch(String name) { - this(); - setName(name); - } - - private static HashDecay setCache() { - if(null == branches) { - branches = new HashDecay(1200000); - branches.start(); - } - return branches; - } - - public HashDecay getCache() { - return setCache(); - } - - /** - * Returns a list of branches that begin with the specified prefix. - * - * @param prefix - * Prefix for all branches to be returned - * @return List of branches matching the prefix. - */ - public static Enumeration lookupBranches(String prefix) { - return lookupMappings(branches, prefix); - } - - /** - * Loads the list of branches using the default environment. - * - * @see Env - */ - public static void loadBranches() { - loadBranches(null); - } - - /** - * Loads a list of all the branches into an internal class HashDecay. This - * method will only be called by the class itself if the HashDecay is empty. - * Users should call this method if they believe the p4 branch information - * needs to be brought up to date. - * - * @param env - * Environment to use when working with P4 - * @see HashDecay - */ - public static void loadBranches(Env env) { - String l, name; - String[] cmd = { "p4", "branches" }; - StringTokenizer st; - Branch b; - - setCache(); - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(!l.startsWith("Branch")) { - continue; - } - st = new StringTokenizer(l); - if(6 > st.countTokens()) { - continue; - } - st.nextToken(); - name = st.nextToken(); - synchronized(branches) { - if(null == (b = (Branch) branches.get(name))) { - b = new Branch(name); - b.setEnv(env); - } else { - b.refreshUpdateTime(); - continue; - } - } - st.nextToken(); - st.nextToken("'"); - b.setDescription(st.nextToken()); - branches.put(b.getName(), b); - } - } catch(Exception ex) { - ex.printStackTrace(); - } - } - - /** - * Returns list of all branch names. - * - * @return Enumeration of Strings containing - * branch names. - */ - public static Enumeration getBranchNames(Env env) { - loadBranches(env); - return branches.keys(); - } - - /** - * Returns list of all branches. - * - * @return Enumeration of Branches. - * @deprecated - */ - public static Enumeration getBranches() { - return getBranches(null); - } - - /** - * @param env - * Source control environment. - * @return Enumeration of Branches. - */ - public static Enumeration getBranches(Env env) { - return Utils.getEnumeration(getBranchIterator(env)); - } - - /** - * @param env - * Source control environment. - * @return Iterator of Branches. - */ - public static Iterator getBranchIterator(Env env) { - loadBranches(env); - Enumeration en = branches.elements(); - TreeSet ts = new TreeSet(); - while(en.hasMoreElements()) { - ts.add(en.nextElement()); - } - return ts.iterator(); - } - - /** - * Returns a Branch with the specified name, or null if not found. - * - * @param name - * Name of the branch to find. - */ - public static synchronized Branch getBranch(String name) { - return getBranch(null, name, true); - } - - /** - * Returns a Branch with the specified name, or null if not found. - * - * @param env - * Environment to use when working with P4. - * @param name - * Name of the branch to find. - * @param force - * Indicates that the Branch should be sync'd. - */ - public static synchronized Branch getBranch(Env env, String name, boolean force) { - Branch b; - if(null == name || name.trim().equals("")) - return null; - if(null == (b = (Branch) setCache().get(name))) - b = new Branch(name); - if(null != env) - b.setEnv(env); - b.sync(); - branches.put(name, b); - return b; - } - - /** - * Integrate a set of files using the named branch. Creates a Change that - * contains the integraed files. The change will be *PENDING* after this - * completes. - * - * @param env - * environment to use when working with P4. - * @param fents - * list of FileEntries to be integrated. - * @param branch - * name of the branch to integrate with. - * @param sb - * buffer that will contain a log of the integration. - * @param description - * description to be used for the Change created. - * @return Change containing the files integrated. - * @see Change - */ - public static Change integrate(Env env, Vector fents, String branch, StringBuffer sb, String description) - throws CommitException, PerforceException { - Change c = new Change(); - c.setEnv(env); - c.setDescription(description); - c.setUser(User.getUser(env.getUser())); - c.setClientName(env.getClient()); - c.commit(); - return integrate(env, fents, branch, sb, c); - } - - /** - * Integrate a set of files using the named branch. Uses the Change passed - * in to contain the integraed files. The change will be *PENDING* after - * this completes. - * - * @param env - * environment to use when working with P4. - * @param fents - * list of FileEntries to be integrated. - * @param branch - * name of the branch to integrate with. - * @param sb - * buffer that will contain a log of the integration. - * @param c - * Change to be used to contain the integrated files. - * @return Change containing the files integrated. - * @see Change - */ - public static Change integrate(Env env, Vector fents, String branch, StringBuffer sb, Change c) - throws PerforceException { - FileEntry fent; - - Enumeration en = fents.elements(); - while(en.hasMoreElements()) { - fent = (FileEntry) en.nextElement(); - integrate(env, fent.getDepotPath() + "#" + fent.getHeadRev(), branch, sb, c); - } - return c; - } - - /** - * Class method for integrating using the instantiated Branch. - * - * @param source - * source files to integrate from. - * @param sb - * buffer that will contain a log of the integration. - * @param c - * Change to be used to contain the integrated files. - * @see Branch#integrate(Env,String,String,StringBuffer,Change) - */ - public Change integrate(String source, StringBuffer sb, Change c) throws PerforceException { - if(null == c) { - c = new Change(); - c.setDescription("Automated Integration"); - c.commit(); - } - return Branch.integrate(this.getEnv(), source, this.getName(), sb, c); - } - - /** - * Integrate a set of files using the named branch. Uses the Change passed - * in to contain the integraed files. The change will be *PENDING* after - * this completes. - * - * @param env - * environment to use when working with P4. - * @param source - * source files to integrate from. - * @param branch - * name of the branch to integrate with. - * @param sb - * buffer that will contain a log of the integration. - * @param c - * Change to be used to contain the integrated files. - * @return Change containing the files integrated. - * @see Change - */ - public static Change integrate(Env env, String source, String branch, StringBuffer sb, Change c) - throws PerforceException { - String[] intcmd = { "p4", "integrate", "-v", "-d", "-c", String.valueOf(c.getNumber()), "-b", branch, "-s", - source }; - P4Process p; - String l; - - intcmd[5] = String.valueOf(c.getNumber()); - for(int i = 0; i < 8; i++) { - sb.append(intcmd[i]); - sb.append(' '); - } - sb.append('\n'); - try { - p = new P4Process(env); - p.exec(intcmd); - while(null != (l = p.readLine())) { - if(null != sb) { - sb.append(l); - sb.append('\n'); - } - } - p.close(); - } catch(Exception ex) { - throw new PerforceException(ex.getMessage()); - } - return c; - } - - /** - * Stores the branch information back into p4, creating the branch if it - * didn't already exist. - * - * @deprecated Use {@link #commit() commit()} instead. - */ - public void store() throws CommitException { - this.commit(); - } - - public void commit() throws CommitException { - String[] cmd = { "p4", "branch", "-i" }; - String l; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - p.println("Branch: " + getName()); - p.println("Owner: " + getOwner()); - p.println("View:"); - p.println(getView()); - p.flush(); - p.outClose(); - while(null != (l = p.readLine())) { - } - p.close(); - } - } catch(Exception ex) { - throw new CommitException(ex.getMessage()); - } - } - - public void sync() { - sync(getName()); - } - - /** - * Synchronizes the Branch with the latest information from P4. This method - * forces the Branch to contain the latest, correct information if it didn't - * already. - * - * @param name - * Name of the Branch to synchronize. - */ - public void sync(String name) { - if(!outOfSync(300000)) - return; - setName(name); - String description = ""; - String l; - String[] cmd = { "p4", "branch", "-o", "name" }; - cmd[3] = name; - - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("#")) { - continue; - } - if(l.startsWith("Branch:")) { - setName(l.substring(8).trim()); - } else if(l.startsWith("Owner:")) { - setOwner(l.substring(7).trim()); - } else if(l.startsWith("Description:")) { - while(null != (l = p.readLine())) { - if(!l.startsWith("\t")) - break; - description += l + "\n"; - } - setDescription(description); - } else if(l.startsWith("View:")) { - while(null != (l = p.readLine())) { - if(!(l.startsWith("\t") || l.startsWith(" ") || l.startsWith("//"))) - break; - this.addView(l); - } - } - } - p.close(); - inSync(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - sb.append(super.toXML()); - sb.append(""); - return sb.toString(); - } -} diff --git a/src/main/java/com/perforce/api/Cacheable.java b/src/main/java/com/perforce/api/Cacheable.java deleted file mode 100644 index ed6eecd..0000000 --- a/src/main/java/com/perforce/api/Cacheable.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * An interface that indicates the implementing class can be cached for some - * period of time. Implementing classes will be stored in a - * HashDecay instance. Each instantiating class must create its - * own HashDecay instance and return a reference to it through - * the getCache method. - * - * The update time is what is used by the HasDecay to determine - * when an object will decay and be discarded. - * - * @see HashDecay - * @author David Markley - * @version $Date: 2002/01/15 $ $Revision: #2 $ - */ -public interface Cacheable { - - /** Returns the time, in milliseconds, for this object's last update. */ - public long getUpdateTime(); - - /** Sets the update time for this object to the current time. */ - public void refreshUpdateTime(); - - /** Returns the time, in milliseconds, that this object was synchronized. */ - public long getSyncTime(); - - /** - * Tests this object to see if it is out of sync. Checks to see if the - * expiration time is within the specified number of milliseconds. - * - * @param threshold - * Number of milliseconds. - * @return True if the object will be out of sync within the threshold. - */ - public boolean outOfSync(long threshold); - - /** Invalidates this object. */ - public void invalidate(); - - /** Marks this object as being in in sync or valid. */ - public void inSync(); - - /** Removes any cached objects. */ - public void clearCache(); - - /** Returns the HashDecay instance for this class */ - public HashDecay getCache(); - - /** - * Stores this object back into Perforce, creating it if it didn't already - * exist. - */ - public void commit() throws CommitException; - - /** - * Brings this object back into sync with Perforce. This also sets the sets - * the update and sync time for this object. - */ - public void sync() throws PerforceException; -} diff --git a/src/main/java/com/perforce/api/Change.java b/src/main/java/com/perforce/api/Change.java deleted file mode 100644 index ed95e94..0000000 --- a/src/main/java/com/perforce/api/Change.java +++ /dev/null @@ -1,810 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control change. This class can be used to - * determine information for a particular p4 change. It can be constructed using - * the change number, but will not contain any additional change information - * until the sync() method is called. - * - * @author David Markley - * @version $Date: 2002/08/05 $ $Revision: #10 $ - */ -public final class Change extends SourceControlObject { - private int number = -1; - - private User user = null; - - private String client_name = ""; - - private String modtime_string = ""; - - private String description = ""; - - private int status = PENDING; - - private static HashDecay changes = null; - - /** Indicates that the Change is pending submission. */ - public final static int PENDING = 1; - - /** Indicates that the Change has been submitted. */ - public final static int SUBMITTED = 2; - - /** - * Default no-argument constructor. - */ - public Change() { - super(); - getCache(); - } - - public Change(Env environ) { - this(); - this.setEnv(environ); - } - - /** - * Constructor that accepts the change number. This change is not populated - * with the correct information until the sync() method is called on it. - * - * @param number - * Change number - */ - public Change(int number) { - this(); - this.number = number; - } - - public Change(String number) { - this(); - this.number = Integer.valueOf(number).intValue(); - } - - private static HashDecay setCache() { - if(null == changes) { - changes = new HashDecay(300000); - changes.start(); - } - return changes; - } - - public HashDecay getCache() { - return setCache(); - } - - public static Change getChange(String number) { - return getChange(null, number, true); - } - - public static Change getChange(String number, boolean force) { - return getChange(null, number, force); - } - - public static Change getChange(Env env, String number, boolean force) { - return getChange(env, (Integer.valueOf(number)).intValue(), force); - } - - public static Change getChange(int number) { - return getChange(null, number, true); - } - - public static Change getChange(int number, boolean force) { - return getChange(null, number, force); - } - - public static Change getChange(Env env, int number, boolean force) { - Change c; - if(null == (c = (Change) setCache().get(new Integer(number)))) { - c = new Change(number); - force = true; - } - if(null != env) - c.setEnv(env); - if(force) - c.sync(); - changes.put(new Integer(number), c); - return c; - } - - public String getClientName() { - return client_name; - } - - public void setClientName(String name) { - this.client_name = name; - } - - public String getModtimeString() { - return modtime_string; - } - - public void setModtimeString(String modtime) { - this.modtime_string = modtime; - } - - /** - * Sets the change number for the Change. This invalidates all the other - * data for the Change. - * - * @param number - * Change number - */ - public void setNumber(int number) { - this.number = number; - user = null; - description = ""; - status = PENDING; - } - - /** - * Returns the number of this Change. - */ - public int getNumber() { - return number; - } - - /** - * Sets the User that owns this Change. - * - * @param user - * Owning user. - */ - public void setUser(User user) { - this.user = user; - } - - /** - * Returns the User that owns this Change. - */ - public User getUser() { - return user; - } - - /** - * Sets the description for the change. - */ - public void setDescription(String description) { - String l; - try { - StringBuffer sb = new StringBuffer(); - BufferedReader b = new BufferedReader(new StringReader(description)); - while(null != (l = b.readLine())) { - sb.append('\t'); - sb.append(l.trim()); - sb.append('\n'); - } - this.description = sb.toString(); - } catch(IOException ex) { - this.description = description; - } - } - - /** - * Returns the description for the Change. This description includes not - * only the textual description provided by the user, but also the list of - * affected files and how they were affected. - * - * The String returned includes newline characters. - */ - public String getDescription() { - return description; - } - - public String getShortDescription() { - return getShortDescription(false); - } - - public String getShortDescription(boolean blurb) { - StringBuffer sb = new StringBuffer(); - String l; - try { - BufferedReader b = new BufferedReader(new StringReader(getDescription())); - while(null != (l = b.readLine())) { - if(blurb && l.startsWith("Change")) - continue; - if(blurb && l.startsWith("Jobs fixed")) - break; - if(l.startsWith("Affected file")) { - break; - } else { - sb.append(l); - sb.append('\n'); - } - } - } catch(IOException ex) { - } - return sb.toString(); - } - - /** - * Returns a Vector filled with the files (including revision numbers) that - * were affected by this change. What was done to each file as a result of - * this Change is stripped off. - * - * This method uses the value of the Change's description to determine the - * files that are affected. - * - * @return Vector of Strings of files - * affected. - */ - public Vector getFiles() { - Vector v = new Vector(); - try { - BufferedReader b = new BufferedReader(new StringReader(getDescription())); - String l, t; - int pos; - while(null != (l = b.readLine())) { - t = l.trim(); -// if (t.startsWith("... ")) { - if(t.startsWith("//")) { - if(-1 != (pos = t.lastIndexOf(" "))) { - v.addElement(t.substring(0, pos).trim()); - } - } - } - } catch(IOException e) { - } - return v; - } - - /** - * Returns a Vector filled with the files (including revision numbers) that - * were affected by this change. What was done to each file as a result of - * this Change is stripped off. - * - * This method uses the value of the Change's description to determine the - * files that are affected. - * - * @return Vector of FileEntry objects of - * files affected. - */ - public Vector getFileEntries() { - if(PENDING == getStatus() && 0 < getNumber()) { - return FileEntry.getOpened(getEnv(), false, false, getNumber(), null); - } - Vector v = new Vector(); - FileEntry fent; - try { - BufferedReader b = new BufferedReader(new StringReader(getDescription())); - String l, t; - int beg, end; - while(null != (l = b.readLine())) { - t = l.trim(); - if(t.startsWith("//")) { - fent = new FileEntry(); - fent.setEnv(getEnv()); - beg = 0; - end = 4; - if(-1 != (end = t.indexOf('#', beg))) { - fent.setDepotPath(t.substring(beg, end)); - beg = end + 1; - if(-1 != (end = t.indexOf(' ', beg))) { - fent.setHeadRev(Integer.valueOf(t.substring(beg, end).trim()).intValue()); - fent.setHeadAction(t.substring(end + 1)); - } - } else { - fent.setDepotPath(t); - } - v.addElement(fent); - } - } - } catch(IOException e) { - } - return v; - } - - /** - * Adds the given FileEntry to the changelist. If the - * changelist has not been committed to the server, that is done first. - * - * @param fent - * file entry to be added. - */ - public void addFile(FileEntry fent) throws PerforceException { - if(-1 == number) - commit(); - fent.reopen(null, this); - } - - /** - * Resolves this file. If the force flag is false, and auto-resolve is - * attempted (p4 resolve -am). If the force flag is true, an "accept theirs" - * resolve is completed (p4 resolve -at). - * - * @see FileEntry#resolve(boolean) - * @param force - * Indicates whether the resolve should be forced. - */ - public String resolve(boolean force) throws PerforceException { - StringBuffer sb = new StringBuffer(); - Enumeration en = getFileEntries().elements(); - - try { - while(en.hasMoreElements()) { - sb.append(((FileEntry) en.nextElement()).resolve(force)); - } - } catch(Exception ex) { - throw new PerforceException(ex.getMessage()); - } - return sb.toString(); - } - - /** - * Sets status for the Change. This can be either PENDING or SUBMITTED. - */ - public void setStatus(int status) { - this.status = status; - } - - /** - * Returns the status for the Change. This can be either PENDING or - * SUBMITTED. - */ - public int getStatus() { - return status; - } - - /** - * Submits the change, if it is pending. - * - * @throws SubmitException - * If the submit fails. - */ - public String submit() throws SubmitException { - String l; - StringBuffer sb = new StringBuffer(); - if(PENDING != status) { - throw new SubmitException("Change already submitted."); - } - String[] cmd = { "p4", "submit", "-c", String.valueOf(getNumber()) }; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - sb.append(l); - sb.append('\n'); - } - p.close(); - } catch(Exception ex) { - throw new SubmitException(ex.getMessage() + "\n\n" + sb.toString()); - } - return sb.toString(); - } - - /** - * Updates the change or creates a pending change. - * - * @deprecated Use {@link #commit() commit()} instead. - */ - public void store() throws CommitException { - this.commit(); - } - - public void commit() throws CommitException { - Enumeration en; - Vector fents = getFileEntries(); - StringBuffer sb = new StringBuffer(); - String[] cmd = { "p4", "change", "-i" }; - String l; - int pos; - boolean store_failed = false; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - try { - Thread.sleep(1000); - } catch(InterruptedException intex) { /* Ignoring Exception */ - } - if(0 > number) { - p.println("Change: new"); - } else { - p.println("Change: " + getNumber()); - } - p.println("Client: " + getClientName()); - if(null == getUser() && null != getEnv()) { - p.println("User: " + getEnv().getUser()); - } else { - p.println("User: " + user.getId()); - } - p.println("Description: "); - p.println(getDescription()); - if(null != fents && 0 < fents.size()) { - FileEntry fent; - p.println("Files: "); - en = fents.elements(); - while(en.hasMoreElements()) { - fent = (FileEntry) en.nextElement(); - p.println("\t" + fent.getDepotPath()); - } - } - if(Utils.isWindows()) { - p.println("\032\n\032"); - } - p.flush(); - p.outClose(); - Debug.notify("Change.store(): Wrote change info."); - while(null != (l = p.readLine())) { - Debug.notify("READ: " + l); - if(l.startsWith("Change ") && (-1 != (pos = l.indexOf("created")))) { - setNumber(Integer.valueOf(l.substring(7, pos - 1).trim()).intValue()); - } - if(l.startsWith("Error")) - store_failed = true; - sb.append(l); - sb.append('\n'); - } - p.close(); - Debug.notify("Change.store(): All done reading."); - } catch(Exception ex) { - throw new CommitException(ex.getMessage()); - } - if(store_failed || 0 > getNumber()) { - throw new CommitException(sb.toString()); - } - } - - /** - * Synchronizes the Change with the correct information from P4, using - * whatever change number has already been set in the Change. After this - * method is called, all the information in the Change is valid. - */ - public void sync() { - sync(number); - } - - /** - * Sycnhronizes the Change with the correct information from P4. After this - * method is called, all the information in the Change is valid. - * - * @param number - * Change number - */ - public void sync(int number) { - if(SUBMITTED == status && !outOfSync(60000)) - return; - this.number = number; - String l, tstr; - String[] cmd = { "p4", "describe", "-s", "number" }; - cmd[3] = String.valueOf(number); - boolean wasFound = false; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(!wasFound && l.startsWith("Change")) { - tstr = l.substring(l.indexOf("by") + 3).trim(); - tstr = tstr.substring(0, tstr.indexOf("@")); - user = User.getUser(getEnv(), tstr); - modtime_string = l.substring(l.indexOf(" on ") + 4).trim(); - if(-1 == l.indexOf("pending")) { - status = SUBMITTED; - } - description = l; - wasFound = true; - } else { - description += l.trim() + "\n"; - } - } - p.close(); - inSync(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - } - - /** - * Reverts all the files associated with a pending changelist. - */ - public void revert() throws PerforceException { - if(PENDING != status) { - throw new PerforceException("Change already submitted."); - } - Enumeration en = getFileEntries().elements(); - try { - while(en.hasMoreElements()) { - ((FileEntry) en.nextElement()).revert(); - } - } catch(Exception ex) { - throw new PerforceException(ex.getMessage()); - } - } - - /** - * Delete the pending changelist. This method will revert any open files - * associated with the changelist and then delete it. - * - * @return log of delete command. - */ - public String delete() throws PerforceException { - this.revert(); - return this.deleteEmptyChange(); - } - - /** - * Deletes the Changelist if it is empty. - * - * @deprecated Use delete method instead. - * @return String Contents of the information returned by P4 as a result of - * the delete call. - */ - public String deleteEmptyChange() throws PerforceException { - String l; - StringBuffer sb = new StringBuffer(); - if(PENDING != status) { - throw new PerforceException("Change already submitted."); - } - - String[] cmd = { "p4", "change", "-d", String.valueOf(getNumber()) }; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - sb.append(l); - sb.append('\n'); - } - p.close(); - } catch(Exception ex) { - throw new PerforceException(ex.getMessage() + "\n\n" + sb.toString()); - } - return sb.toString(); - } - - /** - * Overrides the default toString() method. - */ - public String toString() { - StringBuffer sb = new StringBuffer("Change: "); - sb.append(number); - sb.append("\nUser: "); - sb.append(user); - sb.append("\nDescription:\n"); - sb.append(description); - return sb.toString(); - } - - public static Change[] getChanges(Env env, String path) throws PerforceException { - return getChanges(env, path, 100, null, null, false, null); - } - - public static Change[] getChanges(String path) throws PerforceException { - return getChanges(null, path, 100, null, null, false, null); - } - - public static Change[] getChanges(Env env, String path, int max, String start, String end, boolean use_integs, - String ufilter) throws PerforceException { - int cmdlen = 8; - String[] cmd; - String tpath = path; - - if(use_integs) - cmdlen++; - if(null == tpath) - tpath = ""; - - if(null != start && !start.trim().equals("")) { - tpath += "@" + start; - if(null != end && !end.trim().equals("")) { - tpath += "," + end; - } - } - - if(tpath.trim().equals("")) - cmdlen--; - cmd = new String[cmdlen]; - if(!tpath.trim().equals("")) - cmd[cmdlen - 1] = tpath; - - cmd[0] = "p4"; - cmd[1] = "changes"; - cmd[2] = "-m"; - cmd[3] = String.valueOf(max); - cmd[4] = "-l"; - cmd[5] = "-s"; - cmd[6] = "submitted"; - if(use_integs) - cmd[7] = "-i"; - Vector v = new Vector(); - Change[] chngs; - StringTokenizer st; - int num; - String l, id, description = ""; - User user; - Change c = null; - String modtime, client_name; - - try { - P4Process p = new P4Process(env); - p.setRawMode(true); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("info: Change")) { - l = l.substring(6).trim(); - st = new StringTokenizer(l); - if(!st.nextToken().equals("Change")) - continue; - try { - num = Integer.parseInt(st.nextToken()); - } catch(Exception ex) { - throw new PerforceException("Could not parse change number from line: " + l); - } - if(!st.nextToken().equals("on")) - continue; - modtime = st.nextToken(); - if(!st.nextToken().equals("by")) - continue; - id = st.nextToken(); - int pos = id.indexOf("@"); - client_name = id.substring(pos + 1); - id = id.substring(0, pos); - user = User.getUser(env, id); - if(null != c) { - c.setDescription(description); - } - description = ""; - c = new Change(num); - c.setEnv(env); - c.setUser(user); - c.setClientName(client_name); - c.setModtimeString(modtime); - if(null == ufilter || id.equals(ufilter)) { - v.addElement(c); - } - } else { - l = l.substring(5).trim(); - description += l + "\n"; - } - } - if(null != c) { - c.setDescription(description); - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - chngs = new Change[v.size()]; - for(int i = 0; i < v.size(); i++) { - chngs[i] = (Change) v.elementAt(i); - changes.put(new Integer(chngs[i].getNumber()), chngs[i]); - } - return chngs; - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - sb.append(""); - sb.append(getDescription()); - sb.append(""); - - Vector v = getFileEntries(); - FileEntry fent = null; - if(null != v && 0 != v.size()) { - sb.append(""); - for(int i = 0; i < v.size(); i++) { - fent = (FileEntry) v.elementAt(i); - sb.append(""); - } - sb.append(""); - } - - sb.append(""); - return sb.toString(); - } - - /** - * Determine the users that review this changelist. This method returns an - * array of Users that need to be informed. - */ - public User[] reviews() throws PerforceException { - Vector users = new Vector(); - User[] usrs = new User[0]; - User chng; - User usr; - String uid; - String email; - String name, t; - StringTokenizer st; - String l; - String[] cmd = { "p4", "reviews", "-c", String.valueOf(this.number) }; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.length() < 4) - continue; - st = new StringTokenizer(l); - uid = st.nextToken(); - email = st.nextToken("<> \t"); - name = st.nextToken("<> ()\t"); - try { - while(null != (t = st.nextToken("<> ()\t"))) { - name += (" " + t); - } - } catch(NoSuchElementException ex) { - } - // System.out.print("U: "+uid+", E: "+email+", N: "+name+"\n"); - usr = new User(uid); - usr.setEnv(getEnv()); - usr.setEmail(email); - usr.setFullName(name); - users.addElement(usr); - } - p.close(); - } catch(Exception ex) { - throw new PerforceException(ex.getMessage()); - } - if(0 == users.size()) - return null; - return (User[]) users.toArray(usrs); - } - - /** - * Used for testing. - * - * @deprecated Actually in use, but this keeps it out of the docs. - */ - public static void main(String[] args) { - String propfile = "/etc/p4.conf"; - Env environ = null; - Debug.setDebugLevel(Debug.VERBOSE); - if(0 < args.length) - propfile = args[0]; - try { - environ = new Env(propfile); - } catch(PerforceException ex) { - System.out.println("Could not load properties from " + propfile + ": " + ex); - System.exit(-1); - } - System.out.println(environ); - Change chng = new Change(environ); - chng.setDescription("This is a test changelist."); - try { - chng.commit(); - } catch(CommitException e) { - System.err.println("Unable to store new change."); - e.printStackTrace(System.err); - System.exit(-1); - } - System.out.println("New Changelist Generated: " + chng.getNumber()); - Utils.cleanUp(); - } -} diff --git a/src/main/java/com/perforce/api/Client.java b/src/main/java/com/perforce/api/Client.java deleted file mode 100644 index f8812c3..0000000 --- a/src/main/java/com/perforce/api/Client.java +++ /dev/null @@ -1,420 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control client. This class can be used to retrieve - * and hold p4 client information. It's class methods can be used to list all loaded clients or list those beginning with a particular prefix. - * Before these class methods are called, the class method loadClients() must be called to ensure the client - * list is up to date. - * - * @author David Markley - * @version $Date: 2002/08/05 $ $Revision: #4 $ - */ -public final class Client extends Mapping { - private String root = ""; - - private String options = ""; - - private final static int DECAY_TIMEOUT = 86400000; - - private static HashDecay clients = null; - - private static long load_time = 0; - - /** - * Default no-argument constructor. - */ - public Client() { - super(); - getCache(); - } - - /** - * Constructor that is passed the client name. - */ - public Client(String name) { - this((Env) null, name); - } - - /** - * Constructor that is passed the client name. - */ - public Client(Env env, String name) { - this(); - setEnv(env); - setName(name); - } - - private synchronized static HashDecay setCache() { - if(null == clients) { - clients = new HashDecay(DECAY_TIMEOUT); - clients.start(); - } - if(clients.isEmpty()) - load_time = 0; - - return clients; - } - - public HashDecay getCache() { - return setCache(); - } - - /** - * Sets the options for the Client. - * - * @param options - * Options of the client. - */ - public void setOptions(String options) { - this.options = options; - } - - /** Returns the Client options. */ - public String getOptions() { - return options; - } - - /** - * Sets the root for the Client. - * - * @param root - * Root of the client. - */ - public void setRoot(String root) { - this.root = root; - } - - /** Returns the Client root. */ - public String getRoot() { - return root; - } - - /** - * Returns a Client with the specified name, or null if not found. It is - * important to keep in mind that the Client returned may not hold valid - * information, other than its name. To ensure the Client has valid - * information, the sync() method must be called. - * - * @param name - * Name of the client to find. - */ - public static synchronized Client getClient(Env env, String name) { - Client c; - if(null == name || name.trim().equals("")) - return null; - if(null == (c = (Client) setCache().get(name))) - c = new Client(name); - if(null != env) - c.setEnv(env); - c.sync(); - synchronized(clients) { - clients.put(name, c); - } - return c; - } - - /** - * Returns a Client with the specified name, or null if not found. - * - * @see #getClient(Env, String) - */ - public static synchronized Client getClient(String name) { - return getClient(null, name); - } - - /** - * Returns a list of clients that begin with the specified prefix. - * - * @param env - * P4 environment to use. - * @param prefix - * Prefix for all clients to be returned. - * @return List of clients matching the prefix. - */ - public static Enumeration lookupClient(Env env, String prefix) { - loadClients(env); - return lookupMappings(clients, prefix); - } - - /** - * Returns a list of clients that begin with the specified prefix. - * - * @param prefix - * Prefix for all clients to be returned - * @return List of clients matching the prefix. - */ - public static Enumeration lookupClient(String prefix) { - loadClients(null); - return lookupMappings(clients, prefix); - } - - /** - * Returns a list of all the clients currently loaded. - * - * @return List of all clients currently loaded. - * @deprecated - */ - public static Enumeration getClients() { - loadClients(null); - return clients.keys(); - } - - /** - * @param env - * Environment to use when working with P4 - * @return Enumeration of all clients currently loaded. - */ - public static Enumeration getClients(Env env) { - return Utils.getEnumeration(getClientIterator(env)); - } - - /** - * @param env - * Environment to use when working with P4 - * @return Iterator for all clients currently loaded. - */ - public static Iterator getClientIterator(Env env) { - loadClients(env); - Enumeration en = clients.elements(); - TreeSet ts = new TreeSet(); - while(en.hasMoreElements()) { - ts.add(en.nextElement()); - } - return ts.iterator(); - } - - /** - * Loads a list of all the clients into an internal class Hashtable. This - * method will only be called by the class itself if the Hashtable is empty. - * Users should call this method if they believe the p4 client information - * needs to be brought up to date. - * - * @see java.util.Hashtable - */ - public static void loadClients() { - loadClients(null); - } - - /** - * Loads a list of all the clients into an internal class Hashtable. - * - * @see #loadClients() - * @param env - * Source conrol environment to use. - */ - public static void loadClients(Env env) { - String l, name; - Client c; - String[] cmd = { "p4", "clients" }; - StringTokenizer st; - - setCache(); - synchronized(clients) { - if((clients.getDelay() * 0.5) > ((new Date()).getTime() - load_time)) - return; - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(!l.startsWith("Client")) { - continue; - } - try { - st = new StringTokenizer(l.trim()); - if(6 > st.countTokens()) { - continue; - } - st.nextToken(); - name = st.nextToken(); - if(null == (c = (Client) clients.get(name))) { - c = new Client(name); - c.setEnv(env); - } else { - c.refreshUpdateTime(); - continue; - } - st.nextToken(); // Skip modtime for now. - st.nextToken(); // Skip 'root' text. - c.setRoot(st.nextToken()); - if(null != (st.nextToken("'"))) { - c.setDescription(st.nextToken()); - } else { - c.setDescription(""); - } - clients.put(c.getName(), c); - } catch(NoSuchElementException ex) { - // We'll just skip this one. - } - } - load_time = (new Date()).getTime(); - } catch(Exception ex) { - ex.printStackTrace(System.out); - System.out.flush(); - } - } - } - - /** - * Stores the client information back into p4, creating the client if it - * didn't already exist. - * - * @deprecated Use {@link #commit() commit()} instead. - */ - public void store() throws CommitException { - this.commit(); - } - - public void commit() throws CommitException { - String[] cmd = { "p4", "client", "-i" }; - String l; - int cnt = 0; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - p.println("Client: " + getName()); - p.println("Owner: " + getOwner()); - p.println("Root: " + getRoot()); - p.println("Description: " + getDescription()); - p.println("View:"); - p.println(getView()); - p.flush(); - p.outClose(); - while(null != (l = p.readLine())) { - if(0 == cnt++) - continue; - } - p.close(); - } catch(Exception ex) { - throw new CommitException(ex.getMessage()); - } - } - - public void sync() { - sync(getName()); - } - - /** - * Synchronizes the Client with the latest information from P4. This method - * forces the Client to contain the latest, correct information if it didn't - * already. - * - * @param name - * Name of the Client to synchronize. - */ - public void sync(String name) { - if(!outOfSync(60000)) - return; - String description = ""; - String l; - String[] cmd = { "p4", "client", "-o", "name" }; - cmd[3] = name; - setName(name); - - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("#")) { - continue; - } - if(l.startsWith("Client:")) { - setName(l.substring(8).trim()); - } else if(l.startsWith("Owner:")) { - setOwner(l.substring(7).trim()); - } else if(l.startsWith("Root:")) { - setRoot(l.substring(6).trim()); - } else if(l.startsWith("Options:")) { - setOptions(l.substring(9).trim()); - } else if(l.startsWith("Description:")) { - while(null != (l = p.readLine())) { - if(!l.startsWith("\t")) - break; - description += l + "\n"; - } - setDescription(description); - } else if(l.startsWith("View:")) { - while(null != (l = p.readLine())) { - if(!(l.startsWith("\t") || l.startsWith(" ") || l.startsWith("//"))) - break; - addView(l); - } - } - } - p.close(); - inSync(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - refreshUpdateTime(); - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - sb.append(super.toXML()); - sb.append(""); - return sb.toString(); - } - - /** - * Used for testing. - * - * @deprecated Actually in use, but this keeps it out of the docs. - */ - public static void main(String[] argv) { - if(argv.length < 2) { - System.err.println("Usage: p4.Client []"); - System.exit(-1); - } - System.out.println("Clients on " + argv[0] + ":"); - Env environ = new Env(); - environ.setPort(argv[0]); - environ.setUser(argv[1]); - if(3 == argv.length) { - environ.setPassword(argv[2]); - } - Enumeration en = getClients(environ); - Client c; - while(en.hasMoreElements()) { - c = (Client) en.nextElement(); - System.out.println(c); - } - System.exit(0); - } -} diff --git a/src/main/java/com/perforce/api/CommitException.java b/src/main/java/com/perforce/api/CommitException.java deleted file mode 100644 index 9a1b19b..0000000 --- a/src/main/java/com/perforce/api/CommitException.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.perforce.api; - -import java.io.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Signals that an exception occurred during the process of committing a - * cacheable object to perforce. - * - * @author David Markley - * @version $Date: 2001/11/05 $ $Revision: #1 $ - * @see Cacheable - */ -public final class CommitException extends PerforceException { - - public CommitException(String msg) { - super(msg); - } -} diff --git a/src/main/java/com/perforce/api/Counter.java b/src/main/java/com/perforce/api/Counter.java deleted file mode 100644 index f8b2e3a..0000000 --- a/src/main/java/com/perforce/api/Counter.java +++ /dev/null @@ -1,324 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of perforce counters. This class can be used to set and get - * the value of a counter. It can also be used to determine who reviews the - * changes represented by a particular value. - * - * @author David Markley - * @version $Date: 2002/01/23 $ $Revision: #2 $ - */ -public final class Counter extends SourceControlObject { - private String name = ""; - - private int value = -1; - - private static HashDecay counters = null; - - /** - * Default no-argument constructor. - */ - public Counter() { - super(); - getCache(); - } - - public Counter(String name) { - this(null, name); - } - - public Counter(Env environ, String name) { - this(); - this.setEnv(environ); - this.name = name; - } - - private static HashDecay setCache() { - if(null == counters) { - counters = new HashDecay(300000); - counters.start(); - } - return counters; - } - - public HashDecay getCache() { - return setCache(); - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - /** - * Sets the value for the Counter. - * - * @param value - * New counter value - */ - public void setValue(int value) { - this.value = value; - } - - /** - * Returns the value of this Counter. - */ - public int getValue() { - return this.value; - } - - public void commit() throws CommitException { - boolean valid = false; - String l; - this.value = value; - String[] cmd = { "p4", "counter", this.name, String.valueOf(this.value) }; - P4Process p = null; - try { - p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("Counter") && l.endsWith("set.")) - valid = true; - } - p.close(); - } catch(Exception ex) { - try { - if(null != p) - p.close(); - } catch(Exception ign) { /* Ignoring */ - } - throw new CommitException(ex.getMessage()); - } - if(!valid) - throw new CommitException("Counter " + name + " not set."); - } - - public void sync() throws PerforceException { - String l; - String[] cmd = { "p4", "counter", this.name }; - P4Process p = null; - try { - p = new P4Process(getEnv()); - p.exec(cmd); - l = p.readLine(); - value = Integer.valueOf(l).intValue(); - while(null != (l = p.readLine())) { - } - p.close(); - } catch(Exception ex) { - try { - if(null != p) - p.close(); - } catch(Exception ign) { /* Ignoring */ - } - throw new PerforceException(ex.getMessage()); - } - } - - /** - * Returns an array of all the Counters established on the server. - */ - public static Counter[] getCounters(Env env) throws PerforceException { - Vector v = new Vector(); - Counter cntr; - int num; - StringTokenizer st; - String l, name; - String[] cmd = { "p4", "counters" }; - P4Process p = null; - try { - p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - st = new StringTokenizer(l); - name = st.nextToken(); - if(!st.nextToken().equals("=")) - continue; - num = Integer.parseInt(st.nextToken()); - cntr = new Counter(env, name); - cntr.setValue(num); - v.addElement(cntr); - } - p.close(); - } catch(Exception ex) { - try { - if(null != p) - p.close(); - } catch(Exception ign) { /* Ignoring */ - } - throw new PerforceException(ex.getMessage()); - } - if(0 == v.size()) - return null; - return (Counter[]) v.toArray(new Counter[0]); - } - - /** - * Determine the changelists that need to be reviewed. This method returns - * an array of Changes that need to be reviewed. - */ - public Change[] review() throws PerforceException { - Vector v = new Vector(); - Change chng; - User usr; - int num; - String uid; - String email; - String name, t; - StringTokenizer st; - String l; - String[] cmd = { "p4", "review", "-t", this.name }; - P4Process p = null; - try { - p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("Change")) { - st = new StringTokenizer(l); - if(!st.nextToken().equals("Change")) - continue; - num = Integer.parseInt(st.nextToken()); - uid = st.nextToken(); - email = st.nextToken("<> \t"); - name = st.nextToken("<> ()\t"); - try { - while(null != (t = st.nextToken("<> ()\t"))) { - name += (" " + t); - } - } catch(NoSuchElementException ex) { - } - // System.out.print("U: "+uid+", E: "+email+", N: - // "+name+"\n"); - chng = new Change(getEnv()); - chng.setNumber(num); - usr = new User(uid); - usr.setEnv(getEnv()); - usr.setEmail(email); - usr.setFullName(name); - chng.setUser(usr); - v.addElement(chng); - } - - } - p.close(); - } catch(Exception ex) { - try { - if(null != p) - p.close(); - } catch(Exception ign) { /* Ignoring */ - } - throw new PerforceException(ex.getMessage()); - } - if(0 == v.size()) - return null; - return (Change[]) v.toArray(new Change[0]); - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - return sb.toString(); - } - - /** - * Used for testing. - * - * @deprecated Actually in use, but this keeps it out of the docs. - */ - public static void main(String[] argv) { - Debug.setDebugLevel(Debug.VERBOSE); - Properties props = new Properties(System.getProperties()); - try { - props.load(new BufferedInputStream(new FileInputStream(argv[0]))); - System.setProperties(props); - } catch(Exception e) { - System.err.println("Unable to load properties."); - e.printStackTrace(System.err); - System.exit(-1); - } - Env environ = new Env(props); - System.out.println(environ); - Counter cnt = new Counter(environ, "testval"); - try { - cnt.setValue(42); - cnt.commit(); - System.out.println("VAL(1): " + cnt.getValue()); - cnt.setValue(66); - cnt.commit(); - System.out.println("VAL(2): " + cnt.getValue()); - cnt = new Counter(environ, "testval"); - cnt.sync(); - System.out.println("VAL(3): " + cnt.getValue()); - cnt.setValue(6850); - cnt.commit(); - System.out.println("VAL(4): " + cnt.getValue()); - Change[] chngs = cnt.review(); - User[] usrs; - int i, max = 0; - for(i = 0; i < chngs.length; i++) { - System.out.println("Must review change(1): " + chngs[i].getNumber()); - if(max < chngs[i].getNumber()) - max = chngs[i].getNumber(); - usrs = chngs[i].reviews(); - if(null != usrs) { - for(int j = 0; j < usrs.length; j++) { - System.out.println("\t" + usrs[j].getFullName()); - } - } - } - cnt.setValue(max); - cnt.commit(); - chngs = cnt.review(); - if(null != chngs && chngs.length > 0) { - for(i = 0; i < chngs.length; i++) { - System.out.println("Must review change(2): " + chngs[i].getNumber()); - if(max < chngs[i].getNumber()) - max = chngs[i].getNumber(); - } - } - Counter[] cntrs = Counter.getCounters(environ); - for(i = 0; i < cntrs.length; i++) { - System.out.println("Counter " + cntrs[i].getName() + ": " + cntrs[i].getValue()); - } - } catch(PerforceException e) { - System.err.println("Unable to set counter value."); - e.printStackTrace(); - System.exit(-1); - } - System.err.println("Cleaning up."); - Utils.cleanUp(); - } - -} diff --git a/src/main/java/com/perforce/api/Debug.java b/src/main/java/com/perforce/api/Debug.java deleted file mode 100644 index 5d538f2..0000000 --- a/src/main/java/com/perforce/api/Debug.java +++ /dev/null @@ -1,446 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; -import java.text.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Utility class used for debugging. The level of debugging determines the - * amount of debugging information that is generated. The process using this - * class for debugging should ensure that it - * {@link #setDebugLevel(int) sets the debugging level} appropriately. - * - * @author David Markley - * @version $Date: 2001/11/05 $ $Revision: #1 $ - */ -public final class Debug { - /** No debug messages are displayed. */ - public final static int NONE = 0; - - /** Only error messages are displayed. */ - public final static int ERROR = 1; - - /** Error and warning messages are displayed. */ - public final static int WARNING = 2; - - /** Error, warning, and notice messages are displayed. */ - public final static int NOTICE = 3; - - /** Error, warning, notice, and verbose messages are displayed. */ - public final static int VERBOSE = 99; - - /** Debugging output is discarded entirely. */ - public final static int LOG_NONE = 0; - - /** - * Debugging output is sent to standard out and to the - * {@link EventLog EventLog}. - */ - public final static int LOG_SPLIT = 1; - - /** Debugging output is sent only to the {@link EventLog EventLog}. */ - public final static int LOG_ONLY = 3; - - private static int level = NONE; - - private static EventLog elog = null; - - private static int log_level = LOG_ONLY; - - private static boolean show_thread = false; - - /** - * Returns the name associated with the specified level. - * - * @see #setDebugLevel(int) - */ - public static String getLevelName(int level) { - if(NONE >= level) { - return "NONE"; - } else if(ERROR >= level) { - return "ERROR"; - } else if(WARNING >= level) { - return "WARNING"; - } else if(NOTICE >= level) { - return "NOTICE"; - } - return "VERBOSE"; - } - - /** - * Sets the debug level for the application. If this is 0, no debug - * information is generated. - * - * @see #NONE - * @see #ERROR - * @see #WARNING - * @see #NOTICE - * @see #VERBOSE - * @param l - * The level of debugging to use. - */ - public static void setDebugLevel(int l) { - level = l; - } - - /** - * Returns the current debug level. - * - * @see #setDebugLevel(int) - */ - public static int getDebugLevel() { - return level; - } - - /** - * If set true, the thread number is included in all - * debugging output. - */ - public static void setShowThread(boolean show) { - show_thread = show; - } - - /** - * Returns the state of showing threads in degugging output. - */ - public static boolean getShowThread() { - return show_thread; - } - - /** - * Sets the EventLog that debugging output should be sent to. - * - * @param elog - * EventLog to use. - */ - public static void setEventLog(EventLog elog) { - Debug.elog = elog; - } - - /** - * Returns the current EventLog in use. - */ - public static EventLog getEventLog() { - return elog; - } - - /** - * Sets the logging level. This determines where the debugging output will - * be sent. Valid values are "none", "only", or "split". The default is - * "only". The default value will be set, if the String does - * not match. - */ - public static void setLogLevel(String level) { - if(level.equalsIgnoreCase("split")) { - setLogLevel(Debug.LOG_SPLIT); - } else if(level.equalsIgnoreCase("only")) { - setLogLevel(Debug.LOG_ONLY); - } else { - setLogLevel(Debug.LOG_NONE); - } - } - - /** - * Sets the logging level from the supplied Properties. This - * looks for the "p4.log_level" property with the value of either "none", - * "split", or "only". - */ - public static void setProperties(Properties props) { - String log = props.getProperty("p4.log_level", "none"); - if(log.equalsIgnoreCase("split")) { - Debug.log_level = Debug.LOG_SPLIT; - } else if(log.equalsIgnoreCase("only")) { - Debug.log_level = Debug.LOG_ONLY; - } else { - Debug.log_level = Debug.LOG_NONE; - } - } - - /** - * Sets the logging level. This determines where the debugging output will - * be sent. Valid values are: {@link #LOG_SPLIT LOG_SPLIT}, - * {@link #LOG_ONLY LOG_ONLY}, and {@link #LOG_NONE LOG_NONE}. The default - * is {@link #LOG_ONLY LOG_ONLY}. - *

- * If the log level is set to {@link #LOG_NONE LOG_NONE}, then the debug - * level is automatically set to {@link #NONE NONE}. - */ - public static void setLogLevel(int log_level) { - Debug.log_level = log_level; - if(Debug.LOG_NONE == Debug.log_level) - Debug.level = Debug.NONE; - } - - /** - * Returns the current logging level. - */ - public static int getLogLevel() { - return Debug.log_level; - } - - /** - * Sends the message to the EventLog - * - * @see EventLog - */ - private static void errLog(String msg, String level) { - if(null == elog) - return; - elog.log(getThreadName() + msg, level); - } - - /** - * @return The current Thread Name if show_thread is true - */ - private static String getThreadName() { - return show_thread ? Thread.currentThread().getName() + ": " : ""; - } - - /** - * Displays an error message for debugging. If the debugging level is set - * below ERROR, then no message is displayed. - * - * @param msg - * The debugging error message. - */ - public static void error(String msg) { - if(ERROR > level) - return; - System.out.println(getThreadName() + "ERROR: " + msg); - System.out.flush(); - if(LOG_SPLIT <= log_level) { - errLog(msg, "ERROR"); - } - } - - /** - * Displays a warning message for debugging. If the debugging level is set - * below WARNING, then no message is displayed. - * - * @param msg - * The debugging warning message. - */ - public static void warn(String msg) { - if(WARNING > level) - return; - if(LOG_SPLIT >= log_level) { - System.out.println(getThreadName() + "WARNING: " + msg); - System.out.flush(); - } - if(LOG_SPLIT <= log_level) { - errLog(msg, "WARNING"); - } - } - - /** - * Displays a notice message for debugging. If the debugging level is set - * below NOTICE, then no message is displayed. - * - * @param msg - * The debugging notice message. - */ - public static void notify(String msg) { - if(NOTICE > level) - return; - if(LOG_SPLIT >= log_level) { - System.out.println(getThreadName() + msg); - System.out.flush(); - } - if(LOG_SPLIT <= log_level) { - errLog(msg, "NOTIFY"); - } - } - - /** - * Displays a notice message for debugging. If the debugging level is set - * below NOTICE, then no message is displayed. - * - * @param msg - * The debugging notice message. - * @param arry - * Array containing useful debug information. - */ - public static void notify(String msg, String[] arry) { - if(NOTICE > level) - return; - StringBuffer sb = new StringBuffer(); - for(int i = 0; i < arry.length; i++) { - sb.append(arry[i]); - sb.append(' '); - } - if(LOG_SPLIT >= log_level) { - System.out.println(getThreadName() + msg + sb); - System.out.flush(); - } - if(LOG_SPLIT <= log_level) { - errLog(msg + sb, "NOTIFY"); - } - } - - /** - * Displays a verbose message for debugging. If the debugging level is set - * below VERBOSE, then no message is displayed. - * - * @param msg - * The debugging notice message. - */ - public static void verbose(String msg) { - if(VERBOSE > level) - return; - if(LOG_SPLIT >= log_level) { - System.out.println(getThreadName() + msg); - System.out.flush(); - } - if(LOG_SPLIT <= log_level) { - errLog(msg, "VERBOSE"); - } - } - - /** - * Displays a verbose message for debugging. If the debugging level is set - * below VERBOSE, then no message is displayed. - * - * @param msg - * The debugging notice message. - * @param arry - * Array containing useful debug information. - */ - public static void verbose(String msg, String[] arry) { - if(VERBOSE > level) - return; - StringBuffer sb = new StringBuffer(); - for(int i = 0; i < arry.length; i++) { - sb.append(arry[i]); - sb.append(' '); - } - if(LOG_SPLIT >= log_level) { - System.out.println(getThreadName() + msg + sb); - System.out.flush(); - } - if(LOG_SPLIT <= log_level) { - errLog(msg + sb, "VERBOSE"); - } - } - - /** - * Writes the message associated with the Throwable to the - * debugging output. - * - * @param level - * Debugging level to associate with the message. - * @param t - * Throwable that contains the message. - */ - public static void out(int level, Throwable t) { - out("{0}", level, t); - } - - /** - * Writes the formatted message associated with the Throwable - * to the debugging output. The message will be placed in the string - * generated wherever the '{0}' attribute is placed. - * - * @see java.text.MessageFormat - * @param format - * Format to use for the debugging output. - * @param level - * Debugging level to associate with the message. - * @param t - * Throwable that contains the message. - */ - public static void out(String format, int level, Throwable t) { - - if(level > Debug.level) - return; - try { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - t.printStackTrace(pw); - pw.close(); - Object[] args = { sw.toString() }; - String msg = MessageFormat.format(format, args); - if(LOG_SPLIT >= log_level) { - System.out.println(getThreadName() + msg); - System.out.flush(); - } - if(LOG_SPLIT <= log_level) { - errLog(msg, Debug.getLevelName(level)); - } - } catch(Exception ex) { - System.err.println(t); - System.err.flush(); - } - } - - /** - * Writes the message to the debugging output. - * - * @param level - * Debugging level to associate with the message. - * @param msg - * Debugging message. - */ - public static void out(int level, String msg) { - if(level > Debug.level) - return; - if(LOG_SPLIT >= log_level) { - System.out.println(getThreadName() + msg); - System.out.flush(); - } - if(LOG_SPLIT <= log_level) { - errLog(msg, Debug.getLevelName(level)); - } - } - - /** - * Writes the message and associated array of Strings to the debugging - * output. The message will be followed by all the elements in the - * arry. - * - * @param level - * Debugging level to associate with the message. - * @param msg - * Debugging message. - * @param arry - * Array of strings to be sent to the debugging output. - */ - public static void out(int level, String msg, String[] arry) { - if(level > Debug.level) - return; - StringBuffer sb = new StringBuffer(); - for(int i = 0; i < arry.length; i++) { - sb.append(arry[i]); - sb.append(' '); - } - if(LOG_SPLIT >= log_level) { - System.out.println(getThreadName() + msg + sb); - System.out.flush(); - } - if(LOG_SPLIT <= log_level) { - errLog(msg + sb, Debug.getLevelName(level)); - } - } -} diff --git a/src/main/java/com/perforce/api/DirEntry.java b/src/main/java/com/perforce/api/DirEntry.java deleted file mode 100644 index f44f7ac..0000000 --- a/src/main/java/com/perforce/api/DirEntry.java +++ /dev/null @@ -1,377 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control directory. - * - * @author David Markley - * @version $Date: 2001/11/05 $ $Revision: #1 $ - */ -public final class DirEntry extends SourceControlObject { - private String path; - - private DirEntry parent; - - private boolean opened = false; - - private Vector subdirs = null; - - private Vector files = null; - - private static HashDecay dirs = null; - - /** Default, no-argument constructor. */ - public DirEntry() { - super(); - subdirs = new Vector(); - files = new Vector(); - setCache(); - } - - /** - * Constructs a directory entry. - * - * @param e - * Source control environment to use. - */ - public DirEntry(Env e) { - this(); - setEnv(e); - } - - /** - * Constructs a directory entry. - * - * @param e - * Source control environment to use. - * @param path - * The path for this directory. - */ - public DirEntry(Env e, String path) { - this(e); - setPath(path); - } - - /** - * Constructs a directory entry. - * - * @param base - * Another DirEntry used to set the environment. - * @param path - * The path for this directory. - */ - public DirEntry(DirEntry base, String path) { - this(); - setEnv(base.getEnv()); - setPath(path); - } - - /** - * Loads the directories and files for this directory. - */ - public void sync() { - try { - loadDirs(getEnv()); - loadFiles(getEnv(), path); - inSync(); - } catch(Exception ex) { - } - } - - /** - * Does nothing. Doesn't do anything here, since directories are not really - * stored in perforce. - */ - public void commit() { - } - - private static HashDecay setCache() { - if(null == dirs) { - dirs = new HashDecay(120000); - dirs.start(); - } - return dirs; - } - - public HashDecay getCache() { - return setCache(); - } - - /** - * Returns a directory entry for the supplied path. - * - * @param env - * Source control environment to use. - * @param path - * The path for this directory. - * @param sync - * Forces the directory information to be current. - */ - public static DirEntry getDirEntry(Env env, String path, boolean sync) { - DirEntry de; - if(null == path || path.trim().equals("")) - return null; - if(null == (de = (DirEntry) setCache().get(path))) { - de = new DirEntry(env, path); - } - if(null != env) - de.setEnv(env); - if(sync) - de.sync(); - dirs.put(path, de); - return de; - } - - /** - * Sets the path for this directory. - * - * @param path - * New path for this directory. - */ - public void setPath(String path) { - if(null == path) - return; - path = path.trim(); - if(path.equals("") || !path.startsWith("//")) - return; - // TODO: Add checks for wildcards here!!! - /* - * if (null != alldirs) { synchronized (alldirs) { if (this == - * (DirEntry)(alldirs.get(this.path))) { alldirs.remove(this.path); } - * alldirs.put(path, this); } } - */ - this.path = path; - } - - /** - * Returns the path for this directory. - */ - public String getPath() { - return this.path; - } - - /** - * Returns the base path for this directory. This includes everything up to - * the last path delimeter. - */ - public String getBasePath() { - int pos = path.lastIndexOf('/'); - if(-1 == pos) { - return "//"; - } - return path.substring(0, pos + 1); - } - - /** - * Returns the parent director. Constructs a new DirEntry - * that represents the parent and returns it. - */ - public DirEntry getParent() { - DirEntry parent = null; - int pos; - - if(-1 == (pos = path.lastIndexOf('/'))) - return null; - String parent_path = path.substring(0, pos); - if(parent_path.equals("/")) - return null; - /* - * if (null != alldirs) { synchronized (alldirs) { parent = - * (DirEntry)alldirs.get(parent_path); } } - */ - if(null == parent) { - parent = new DirEntry(this, parent_path); - } - return parent; - } - - /** - * Returns an array of directory names. - */ - public String[] getDirNames() { - return getDirNames(getEnv()); - } - - /** - * Returns an array of directory names. - * - * @param env - * Source control environment to use. - */ - public String[] getDirNames(Env env) { - String[] names; - loadDirs(env); - synchronized(subdirs) { - names = v2a(subdirs); - } - return names; - } - - /** - * Loads the directories, using the default environment. - */ - private void loadDirs() { - loadDirs(getEnv()); - } - - /** - * Loads the directories, using the specified environment. - * - * @param env - * Source control environment to use. - */ - private void loadDirs(Env env) { - if(!outOfSync(60000)) - return; - String[] cmd = { "p4", "dirs", path + "%1" }; - String l, dir; - int pos; - - synchronized(subdirs) { - subdirs.removeAllElements(); - } - - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - if((!l.startsWith("//")) || (-1 != l.indexOf(" - "))) { - continue; - } - dir = l.trim(); - if(-1 != (pos = dir.lastIndexOf('/'))) { - dir = dir.substring(pos + 1).trim(); - } - synchronized(subdirs) { - subdirs.addElement(dir); - } - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - } - - /** - * Converts a Vector to a String. This shows - * how old this code is. Vector didn't always do this for us. - */ - private String[] v2a(Vector v) { - String[] tmp = new String[v.size()]; - for(int i = 0; i < v.size(); i++) { - tmp[i] = (String) v.elementAt(i); - } - return tmp; - } - - /** - * Returns an array of file entries for this directory. - */ - public FileEntry[] getFiles() { - return getFiles(getEnv()); - } - - /** - * Returns an array of file entries for this directory. - * - * @param env - * Source control environment to use. - */ - public FileEntry[] getFiles(Env env) { - loadFiles(env, path); - if(null == files) - return null; - FileEntry[] tmp; - synchronized(files) { - tmp = new FileEntry[files.size()]; - for(int i = 0; i < files.size(); i++) { - tmp[i] = (FileEntry) files.elementAt(i); - tmp[i].setEnv(env); - } - } - return tmp; - } - - /** - * Returns an array of file names for this directory. - */ - public String[] getFileNames() { - return getFileNames(getEnv()); - } - - /** - * Returns an array of file names for this directory. - * - * @param env - * Source control environment to use. - */ - public String[] getFileNames(Env env) { - String[] names; - loadFiles(env, path); - if(null == files) { - names = new String[1]; - names[0] = ""; - return names; - } - synchronized(files) { - names = new String[files.size()]; - for(int i = 0; i < files.size(); i++) { - names[i] = ((FileEntry) files.elementAt(i)).getName(); - } - } - return names; - } - - /** - * Loads the files in this directory. - */ - private void loadFiles() { - loadFiles(getEnv(), path); - } - - /** - * Loads the files in this directory. - * - * @param env - * Source control environment to use. - * @param path - * Directory path to use, instead of this one. - */ - private void loadFiles(Env env, String path) { - if(!outOfSync(60000)) - return; - files = FileEntry.getFiles(env, path); - } - - public String toXML() { - StringBuffer sb = new StringBuffer("

"); - return sb.toString(); - } -} diff --git a/src/main/java/com/perforce/api/Env.java b/src/main/java/com/perforce/api/Env.java deleted file mode 100644 index 7a64060..0000000 --- a/src/main/java/com/perforce/api/Env.java +++ /dev/null @@ -1,683 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control environment. This information is typically - * passed to a P4Process instance by the - * SourceControlObject instances. It can also be set in the - * {@link P4Process#getBase() base} P4Process instance. This will cause it to be - * used as the default environment for all command execution. - *

- * Values for the environment can be easily loaded from a - * {@link java.util.Properties Properties} file. This makes configuration of the - * environment much simpler. - * - * @see java.util.Properties - * @author David Markley - * @version $Date: 2002/05/16 $ $Revision: #5 $ - */ -public class Env { - private boolean envp_valid = false; - - private String[] envp; - - private Hashtable environ; - - private Properties props; - - private String p4_exe; // Full path to the P4 executable. - - private String sep_path = null; - - private String sep_file = null; - - private long threshold = 10000; - - /** Default, no-argument constructor. */ - public Env() { - super(); - environ = new Hashtable(); - environ.put("P4USER", "robot"); - environ.put("P4CLIENT", "robot-client"); - environ.put("P4PORT", "localhost:1666"); - environ.put("P4PASSWD", ""); - environ.put("PATH", "C:\\Program Files\\Perforce"); - environ.put("CLASSPATH", "/usr/share/java/p4.jar"); - environ.put("SystemDrive", "C:"); - environ.put("SystemRoot", "C:\\WINNT"); - environ.put("PATHEXT", ".COM;.EXE;.BAT;.CMD"); - setFromProperties(new Properties(System.getProperties())); - } - - /** - * Constructs an environment from a properties file. - * - * @param propfile - * full path to a properties file. - */ - public Env(String propfile) throws PerforceException { - this(); - - setFromProperties(propfile); - } - - /** - * Constructor that uses another environment as its basis. This is useful - * for cloning environments and then changing a few attributes. - * - * @param base - * Environment to be copied into the new environment. - */ - public Env(Env base) { - this(); - this.environ = (Hashtable) base.environ.clone(); - this.props = (Properties) base.props.clone(); - this.p4_exe = base.getExecutable(); - } - - /** - * Constructor that uses a set of Properties to set up the - * environment. - * - * @see #setFromProperties(Properties) - * @param props - * Used to construct the environment. - */ - public Env(Properties props) { - this(); - setFromProperties(props); - } - - /** - * Allows the user to set any environment variable. If the variable name - * starts with 'P4', the value can not be set to null. It will instead be - * set to the empty string. For all other variable, supplying a null value - * will remove that variable form the environment. - * - * @param name - * environment variable name - * @param value - * environment variable value - */ - public void setenv(String name, String value) { - if(null == name) - return; - synchronized(environ) { - if(null == value) { - if(name.startsWith("P4")) { - environ.put(name, ""); - } else { - environ.remove(name); - } - } else { - environ.put(name, value); - } - } - envp_valid = false; - } - - /** - * Returns the value for the named environment variable. - * - * @param name - * environment variable name - */ - public String getenv(String name) { - synchronized(environ) { - return (String) environ.get(name); - } - } - - /** - * Returns the environment in a String array. - */ - public String[] getEnvp() { - String var; - if(!envp_valid) { - synchronized(environ) { - envp = new String[environ.size()]; - Enumeration en = environ.keys(); - int i = 0; - while(en.hasMoreElements()) { - var = (String) en.nextElement(); - envp[i++] = var + "=" + environ.get(var); - } - } - envp_valid = true; - } - return envp; - } - - /** - * Checks the environment to see if it is valid. To check the validity of - * the environment, the user information is accessed. This ensures that the - * server can be contacted and that the password is set properly. - *

- * If the environment is valid, this method will return quietly. Otherwise, - * it will throw a PerforceException with a message regarding - * the failure. - */ - public void checkValidity() throws PerforceException { - String[] msg = { "Connect to server failed; check $P4PORT", "Perforce password (P4PASSWD) invalid or unset.", - "Can't create a new user - over license quota." }; - int msgndx = -1, i, cnt = 0; - - P4Process p = null; - String l; - String[] cmd = { "p4", "user", "-o" }; - - try { - p = new P4Process(this); - p.exec(cmd); - while(null != (l = p.readLine())) { - cnt++; - for(i = 0; i < msg.length; i++) { - if(-1 != l.indexOf(msg[i])) - msgndx = i; - } - } - p.close(); - } catch(IOException ex) { - if(null != p) { - try { - p.close(); - } catch(Exception ignex) { /* Ignored Exception */ - } - } - } - if(-1 != msgndx) - throw new PerforceException(msg[msgndx]); - if(0 == cnt) - throw new PerforceException("No output from p4 user -o"); - } - - /** - * Returns a Vector containing the property value list, as - * split up by the commas. This is used to get the values for a property in - * the form of: - *

- * some.property.key=val1,val2,val3 - *

- * Will always return a Vector, even if it is empty. - * - * @param key - * the property key - * @param defaultValue - * a default value - */ - public Vector getPropertyList(String key, String defaultValue) { - return getPropertyList(key, defaultValue, ","); - } - - /** - * Returns a Vector containing the property value list, as - * split up by the specified delimeter. This is used to get the values for a - * property in the form of: - *

- * some.property.key=val1,val2,val3 - *

- * Will always return a Vector, even if it is empty. - * - * @param key - * the property key - * @param defaultValue - * a default value - * @param delimeter - * string that seperates the values - */ - public Vector getPropertyList(String key, String defaultValue, String delimeter) { - Vector v = new Vector(); - String val, tok; - StringTokenizer st; - - val = getProperty(key, defaultValue); - st = new StringTokenizer(val, delimeter); - while(st.hasMoreTokens()) { - v.addElement(st.nextToken()); - } - return v; - } - - /** - * Returns a new Properties instance that is set using the - * environments properties as its default. - */ - public Properties getProperties() { - return new Properties(props); - } - - /** - * Searches for the property with the specified key in this property list. - * If the key is not found in this property list, the default property list, - * and its defaults, recursively, are then checked. The method returns the - * default value argument if the property is not found. - * - * @param key - * the property key - * @param defaultValue - * a default value - * @return the value in this property list with the specified key value - * @see java.util.Properties - */ - public String getProperty(String key, String defaultValue) { - if(null == props) - return defaultValue; - return props.getProperty(key, defaultValue); - } - - /** - * Searches for the property with the specified key in this property list. - * If the key is not found in this property list, the default property list, - * and its defaults, recursively, are then checked. The method returns null - * if the property is not found. - * - * @param key - * the property key - * @return the value in this property list with the specified key value - * @see java.util.Properties - */ - public String getProperty(String key) { - return getProperty(key, null); - } - - /** - * Calls the hashtable method put. Provided for parallelism with the - * getProperty method. Enforces use of strings for property keys and values. - * - * @param key - * the key to be placed into this property list. - * @param value - * the value corresponding to key. - * @see java.util.Properties#setProperty(String,String) - */ - public String setProperty(String key, String value) { - String val = (String) props.setProperty(key, value); - if(!key.startsWith("p4.")) { - return val; - } - if(key.equals("p4.user")) { - setUser(value); - } else if(key.equals("p4.client")) { - setClient(value); - } else if(key.equals("p4.port")) { - setPort(value); - } else if(key.equals("p4.password")) { - setPassword(value); - } else if(key.equals("p4.executable")) { - setExecutable(value); - } else if(key.equals("p4.sysdrive")) { - setSystemDrive(value); - } else if(key.equals("p4.sysroot")) { - setSystemRoot(value); - } else if(key.equals("p4.threshold")) { - try { - setServerTimeout(Integer.valueOf(value).intValue()); - } catch(Exception ex) { /* Ignored Exception */ - } - } - return val; - } - - /** - * Sets the environment using the specified properties file. - * - * @see #setFromProperties(Properties) - * @param propfile - * Path to a properties file. - */ - public void setFromProperties(String propfile) throws PerforceException { - Properties props = new Properties(System.getProperties()); - if(null != propfile) { - try { - props.load(new BufferedInputStream(new FileInputStream(propfile))); - System.setProperties(props); - } catch(Exception e) { - System.err.println("Unable to load properties."); - e.printStackTrace(System.err); - throw new PerforceException("Unable to load properties from " + propfile); - } - } - setFromProperties(props); - } - - /** - * Uses a set of Properties to set up the environment. The - * properties that are used used by this method are: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
PropertyValue Set
p4.userP4USER
p4.clientP4CLIENT
p4.portP4PORT
p4.passwordP4PASSWORD
p4.executableExecutable
p4.sysdriveSystemDrive
p4.sysrootSystemRoot
p4.thresholdServer Timeout Threshold
- * - * @param props - * Used to construct the environment. - */ - public void setFromProperties(Properties props) { - this.props = props; - sep_path = getProperty("path.separator", ";"); - sep_file = getProperty("file.separator", "/"); - setUser(getProperty("p4.user", "robot")); - setClient(getProperty("p4.client", "robot-client")); - setPort(getProperty("p4.port", "localhost:1666")); - setPassword(getProperty("p4.password", "")); - setExecutable(getProperty("p4.executable", "P4")); - setSystemDrive(getProperty("p4.sysdrive", "C:")); - setSystemRoot(getProperty("p4.sysroot", "C:\\WINNT")); - try { - setServerTimeout(Integer.valueOf(getProperty("p4.threshold", "10000")).intValue()); - } catch(Exception ex) { /* Ignored Exception */ - } - - String os = props.getProperty("os.name"); - if(null == os) { - return; - } - if(os.startsWith("Windows")) { - String windir = props.getProperty("com.ms.windir"); - if(null != windir) { - appendPath(windir.substring(0, 1) + "\\Program Files\\Perforce"); - setSystemDrive(windir.substring(0, 1)); - setSystemRoot(windir); - } - } - } - - /** - * Sets the P4USER in the class information. - * - * @param user - * P4USER value. - */ - public void setUser(String user) { - if(null == user) - return; - environ.put("P4USER", user); - props.setProperty("p4.user", user); - envp_valid = false; - } - - /** Returns the P4USER. */ - public String getUser() { - return (String) environ.get("P4USER"); - } - - /** - * Sets the P4CLIENT in the class information. - * - * @param user - * P4CLIENT value. - */ - public void setClient(String client) { - if(null == client) - return; - environ.put("P4CLIENT", client); - props.setProperty("p4.client", client); - envp_valid = false; - } - - /** Returns the P4CLIENT. */ - public String getClient() { - return (String) environ.get("P4CLIENT"); - } - - /** - * Sets the P4PORT in the class information. - * - * @param user - * P4PORT value. - */ - public void setPort(String port) { - if(null == port) - return; - environ.put("P4PORT", port); - props.setProperty("p4.port", port); - envp_valid = false; - } - - /** Returns the P4PORT. */ - public String getPort() { - return (String) environ.get("P4PORT"); - } - - /** - * Sets the P4PASSWD in the class information. - * - * @param user - * P4PASSWD value. - */ - public void setPassword(String password) { - if(null == password) - return; - environ.put("P4PASSWD", password); - props.setProperty("p4.password", password); - envp_valid = false; - } - - /** Returns the P4PASSWORD. */ - public String getPassword() { - return (String) environ.get("P4PASSWD"); - } - - /** - * Sets the PATH in the class information. - * - * @param path - * PATH value. - */ - public void setPath(String path) { - if(null == path) - return; - environ.put("PATH", path); - props.setProperty("p4.path", path); - envp_valid = false; - } - - /** - * Append the path element to the existing path. If the path element given - * is already in the path, no change is made. - * - * @param path - * the path element to be appended. - */ - public void appendPath(String path) { - String tok; - if(null == path) - return; - String orig_path = (String) environ.get("PATH"); - if(null == sep_path || null == orig_path) { - setPath(path); - return; - } - StringTokenizer st = new StringTokenizer(orig_path, sep_path); - StringBuffer sb = new StringBuffer(); - while(st.hasMoreTokens()) { - tok = (String) st.nextToken(); - if(tok.equals(path)) - return; - sb.append(tok); - sb.append(sep_path); - } - sb.append(path); - setPath(path); - } - - /** Returns the PATH. */ - public String getPath() { - return (String) environ.get("PATH"); - } - - /** - * Sets the SystemDrive in the class information. This is only meaningful - * under Windows. - * - * @param user - * SystemDrive value. - */ - public void setSystemDrive(String drive) { - if(null == drive) - return; - environ.put("SystemDrive", drive); - props.setProperty("p4.sysdrive", drive); - envp_valid = false; - } - - /** - * Sets the SystemRoot in the class information. This is only meaningful - * under Windows. - * - * @param user - * SystemRoot value. - */ - public void setSystemRoot(String root) { - if(null == root) - return; - environ.put("SystemRoot", root); - props.setProperty("p4.sysroot", root); - envp_valid = false; - } - - /** - * Sets up the path to reach the p4 executable. The full path passed in must - * contain the executable or at least end in the system's file separator - * character. This gotten from the file.separator property. For example: - * - *

-	 * p4.executable=/usr/bin/p4   # This will work
-	 * p4.executable=/usr/bin/     # This will work
-	 * <font color=Red>p4.executable=/usr/bin      # This won't work</font>
-	 * 
- * - * @param exe - * Full path to the p4 executable. - */ - public void setExecutable(String exe) { - int pos; - if(null == exe) - return; - p4_exe = exe; - if(null == sep_file) { - sep_file = System.getProperties().getProperty("file.separator", "\\"); - } - if(-1 == (pos = exe.lastIndexOf(sep_file))) - return; - if(null == sep_path) { - sep_path = System.getProperties().getProperty("path.separator", ";"); - } - appendPath(exe.substring(0, pos)); - props.setProperty("p4.executable", p4_exe); - envp_valid = false; - } - - /** Returns the path to the executable. */ - public String getExecutable() { - return p4_exe; - } - - /** Set the server timeout threshold. */ - public void setServerTimeout(long threshold) { - this.threshold = threshold; - props.setProperty("p4.threshold", String.valueOf(threshold)); - } - - /** Return the server timeout threshold. */ - public long getServerTimeout() { - return threshold; - } - - public String toString() { - String[] envp = getEnvp(); - StringBuffer sb = new StringBuffer(); - for(int i = 0; i < envp.length; i++) { - sb.append(envp[i]); - sb.append("\n"); - } - return sb.toString(); - } - - /** - * Returns an XML representation of the environment. - */ - public String toXML() { - StringBuffer sb = new StringBuffer(""); - sb.append(getExecutable()); - sb.append(""); - sb.append(getPath()); - sb.append(""); - return sb.toString(); - } -} diff --git a/src/main/java/com/perforce/api/EventLog.java b/src/main/java/com/perforce/api/EventLog.java deleted file mode 100644 index ab11b14..0000000 --- a/src/main/java/com/perforce/api/EventLog.java +++ /dev/null @@ -1,307 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; -import java.net.*; -import java.text.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * This class controls an event log. A set number of log entries are kept in - * memory, but all log entries are sent to a log file. - * - * @author David Markley - * @version $Date: 2001/11/05 $ $Revision: #1 $ - */ -public class EventLog { - private static EventLog primary = null; - - private String title = "EventLog"; - - private String filename = "log.txt"; - - private PrintWriter fout = null; - - private Vector events; - - private int max_events = 100; - - private DateFormat fmt; - - /** - * Default, no-argument constructor. This initialized the Vector of events - * and the date and time format. - * - * @see Vector - */ - public EventLog() { - this(null, null); - } - - /** - * Constructor that accepts the title for this. The title is used when the - * webSend() method is invoked. - * - * @param title - * The title for this log. - */ - public EventLog(String title) { - this(title, null); - } - - /** - * Constructor that sets the log title and ouput filename. - * - * @param title - * The title for this log. - * @param filename - * Name for the output file. - */ - public EventLog(String title, String filename) { - super(); - - this.title = (null == title) ? "EventLog" : title; - this.filename = (null == filename) ? "log.txt" : filename; - events = new Vector(); - fmt = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); - if(null == primary) { - primary = this; - } - try { - fout = new PrintWriter(new FileOutputStream(filename, true)); - } catch(Exception ex) { - fout = null; - } - } - - /** - * Returns the output file name. - */ - public String getFileName() { - return filename; - } - - /** - * Returns the size of the event log memory. This is the maximum number of - * lines that will be maintained in memory. - */ - public int getSize() { - return max_events; - } - - /** - * Sets the size of the log. This is the maximum number of lines that the - * log will maintain in memory. - * - * @param size - * The number of lines to keep in the log. - */ - public synchronized void setSize(int size) { - max_events = size; - } - - /** - * Logs an event to the common log. The event passed in is added to the log. - * If the log is beyond its maximum size, then the oldest events are - * dropped. - * - * @param event - * The event to be logged. - * @param level - * Level for the logged event. - * @param encode - * Indicates that the output should be XML/HTML encoded. - */ - public static void commonLog(String event, String level, boolean encode) { - if(null != primary) { - primary.log(event, level, encode); - } else { - System.out.println(event); - } - } - - /** - * Logs an event to the common log. The event passed in is added to the log. - * If the log is beyond its maximum size, then the oldest events are - * dropped. - * - * @param event - * The event to be logged. - * @param level - * Level for the logged event. - */ - public static void commonLog(String event, String level) { - if(null != primary) { - primary.log(event, level); - } else { - System.out.println(event); - } - } - - /** - * Logs an event to the common log. The event passed in is added to the log. - * If the log is beyond its maximum size, then the oldest events are - * dropped. - * - * @param event - * The event to be logged. - */ - public static void commonLog(String event) { - if(null != primary) { - primary.log(event); - } else { - System.out.println(event); - } - } - - /** - * Logs an event to this log. The event passed in is added to the log. If - * the log is beyond its maximum size, then the oldest events are dropped. - * - * @param event - * The event to be logged. - */ - public synchronized void log(String event) { - log(event, null, true); - } - - /** - * Logs an event to this log. The event passed in is added to the log. If - * the log is beyond its maximum size, then the oldest events are dropped. - * - * @param event - * The event to be logged. - * @param level - * Level for the logged event. - */ - public synchronized void log(String event, String level) { - log(event, level, true); - } - - /** - * Logs an event to this log. The event passed in is added to the log. If - * the log is beyond its maximum size, then the oldest events are dropped. - * - * @param event - * The event to be logged. - * @param level - * Level for the logged event. - * @param encode - * Indicates that the output should be XML/HTML encoded. - */ - public synchronized void log(String event, String level, boolean encode) { - StringBuffer sb = new StringBuffer(""); - if(encode) { - sb.append(Utils.HTMLEncode(event)); - } else { - sb.append(event); - } - sb.append(""); - String msg = sb.toString(); - events.insertElementAt(msg, 0); - if(null != fout) { - fout.println(msg); - fout.flush(); - } - if(max_events < events.size()) { - events.removeElementAt(max_events); - } - } - - /** - * Returns an Enumeration that contains all the events in the log. - * - * @return List of Strings in the log. - */ - public synchronized Enumeration getLog() { - return events.elements(); - } - - /** - * Prints this log, using the specified format. Each line is placed in the - * format string where {0} occurs. - * - * @param out - * Print output. - * @param format - * Format to use. - * @see java.text.MessageFormat - */ - public static void printLog(PrintWriter out, String format) { - printLog(primary, out, format); - } - - /** - * Prints a log, using the specified format. Each line is placed in the - * format string where {0} occurs. - * - * @param elog - * EventLog to print. - * @param out - * Print output. - * @param format - * Format to use. - * @see java.text.MessageFormat - */ - public static void printLog(EventLog elog, PrintWriter out, String format) { - Object[] args = { "foo" }; - synchronized(elog) { - Enumeration en = elog.events.elements(); - while(en.hasMoreElements()) { - args[0] = ((String) en.nextElement()); - out.println(MessageFormat.format(format, args)); - } - } - } - - /** - * Sets the title for this log. - * - * @param title - * The title of the log. - */ - public synchronized void setTitle(String title) { - this.title = title; - } - - /** - * Gets the title of the log. - */ - public synchronized String getTitle() { - return title; - } -} diff --git a/src/main/java/com/perforce/api/FileEntry.java b/src/main/java/com/perforce/api/FileEntry.java deleted file mode 100644 index 0bad41a..0000000 --- a/src/main/java/com/perforce/api/FileEntry.java +++ /dev/null @@ -1,1264 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; -import java.text.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control file. - * - * @see Hashtable - * @author David Markley - * @version $Date: 2002/06/05 $ $Revision: #8 $ - */ -public final class FileEntry extends SourceControlObject { - private String depot_path = null; - - private String client_path = null; - - private String description = ""; - - private String owner = ""; - - private FileEntry source = null; - - private int head_change = -1; - - private int head_rev = 0; - - private String head_type = "unknown"; - - private long head_time = 0; - - private int have_rev = 0; - - private int other_cnt = 0; - - private String head_action = ""; - - private Vector others; - - private static HashDecay fentries; - - private String file_content = ""; - - private DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); - - /** Default no-argument constructor. */ - public FileEntry() { - this((Env) null); - } - - /** - * Constructs a file entry using the environment. - * - * @param env - * Source control environement to use. - */ - public FileEntry(Env env) { - super(env); - if(null == others) { - others = new Vector(); - } - } - - /** - * Constructs a file entry using the environment and path. - * - * @param env - * Source control environement to use. - * @param p - * Path to the file. - */ - public FileEntry(Env env, String p) { - this(env); - if(p.startsWith("//")) { - depot_path = p; - } else { - client_path = p; - } - } - - /** - * Constructs a file entry using the path. - * - * @param p - * Path to the file. - */ - public FileEntry(String p) { - this(null, p); - } - - private static HashDecay setCache() { - if(null == fentries) { - fentries = new HashDecay(120000); - fentries.start(); - } - return fentries; - } - - public HashDecay getCache() { - return setCache(); - } - - /** Sets the decription for this file */ - public void setDescription(String d) { - description = d; - } - - /** Returns the decription for this file */ - public String getDescription() { - return description; - } - - /** Sets the owner for this file */ - public void setOwner(String o) { - int pos; - owner = o; - if(-1 != (pos = owner.indexOf('@'))) { - owner = owner.substring(0, pos); - } - } - - /** Returns the owner for this file */ - public String getOwner() { - return owner; - } - - /** Sets the source file entry associated with this file. */ - public void setSource(FileEntry fent) { - source = fent; - } - - /** Returns the source file entry associated with this file. */ - public FileEntry getSource() { - return source; - } - - /** Sets the head revision type for this file. */ - public void setHeadType(String type) { - this.head_type = type; - } - - /** Returns the head revision type for this file. */ - public String getHeadType() { - return this.head_type; - } - - /** - * Sets the head date for this file. The expected format for the date is - * yyyy/MM/dd. The time will default to 12:00:00 AM. - */ - public void setHeadDate(String date) { - // Format the current time. - SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); - // Parse the previous string back into a Date. - ParsePosition pos = new ParsePosition(0); - Date hDate = formatter.parse(date, pos); - this.head_time = hDate.getTime() / 1000; - } - - /** - * Returns a String representation of date for the head revsision of the - * file. The format is yyyy/MM/dd. - */ - public String getHeadDate() { - // Format the current time. - SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); - return formatter.format(new Date(this.head_time * 1000)); - } - - /** Sets the head revision time for this file. */ - public void setHeadTime(long time) { - this.head_time = time; - } - - /** Returns the head revision time for this file. */ - public long getHeadTime() { - return this.head_time; - } - - /** - * Sets the format used by the getHeadTimeString method. The format of this - * string is that of the SimpleDateFormat class. - *

- * An example format would be setTimeFormat("MM/dd HH:mm:ss"); - * - * @see SimpleDateFormat - */ - public void setTimeFormat(String format) { - if(null == format) - return; - fmt = new SimpleDateFormat(format); - } - - /** Returns the head revision time as a String for this file. */ - public String getHeadTimeString() { - Date d = new Date(this.head_time * 1000); - - if(null == fmt) { - fmt = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); - fmt.setTimeZone(TimeZone.getTimeZone("EST")); - } - return fmt.format(d); - } - - /** Sets the head revision action for this file. */ - public void setHeadAction(String action) { - this.head_action = action; - } - - /** Returns the head revision action for this file. */ - public String getHeadAction() { - return this.head_action; - } - - /** Sets the head revision change number for this file. */ - public void setHeadChange(int change) { - this.head_change = change; - } - - /** Returns the head revision change number for this file. */ - public int getHeadChange() { - return this.head_change; - } - - /** Sets the head revision number for this file. */ - public void setHeadRev(int rev) { - this.head_rev = rev; - } - - /** Returns the head revision number for this file. */ - public int getHeadRev() { - return this.head_rev; - } - - /** Sets the revision number the client has for this file. */ - public void setHaveRev(int rev) { - this.have_rev = rev; - } - - /** Returns the revision number the client has for this file. */ - public int getHaveRev() { - return this.have_rev; - } - - /** - * Sets the depot path for this file. - * - * @param p - * path for this file in the depot. - */ - public void setDepotPath(String p) { - this.depot_path = p; - } - - /** Returns the depot path for this file. */ - public String getDepotPath() { - return depot_path; - } - - /** Returns the path in local format. Uses the local path delimeter. */ - public static String localizePath(String path) { - return customizePath(path, '/', File.separatorChar); - } - - /** Returns the path in depot format. Uses the depot delimeter: '/'. */ - public static String depotizePath(String path) { - return customizePath(path, File.separatorChar, '/'); - } - - /** - * Returns the path after converting characters. - * - * @param str - * String to convert. - * @param from_char - * Character to be changed from. - * @param to_char - * Character to be changed to. - */ - public static String customizePath(String str, char from_char, char to_char) { - StringBuffer strbuf = new StringBuffer(); - int beg = 0, end = 0; - while(-1 != (end = str.indexOf(from_char, beg))) { - strbuf.append(str.substring(beg, end)); - strbuf.append(to_char); - beg = end + 1; - } - strbuf.append(str.substring(beg)); - return strbuf.toString(); - } - - /** - * Resolves this file. If the force flag is false, and auto-resolve is - * attempted (p4 resolve -am). If the force flag is true, an "accept theirs" - * resolve is completed (p4 resolve -at). - * - * @param force - * Indicates whether the resolve should be forced. - */ - public String resolve(boolean force) throws IOException { - StringBuffer sb = new StringBuffer(); - String l; - String[] rescmd = { "p4", "resolve", "-am", "fileRev" }; - if(force || -1 != (getHeadType().indexOf("binary")) || -1 != (getHeadType().indexOf("link"))) { - rescmd[2] = "-at"; - } else { - rescmd[2] = "-am"; - } - rescmd[3] = getDepotPath(); - P4Process p = new P4Process(getEnv()); - p.exec(rescmd); - while(null != (l = p.readLine())) { - if(null != sb) { - sb.append(l); - sb.append('\n'); - } - } - p.close(); - return sb.toString(); - } - - /** - * Forces a resolve on a set of files. The Enumeration - * contains the set of FileEntry objects that need resolved. - * - * @param env - * Source control environment to use. - * @param en - * Enumeration of FileEntry. - */ - public static String resolveAT(Env env, Enumeration en) throws IOException { - StringBuffer sb = new StringBuffer(); - FileEntry fent; - String l; - String[] rescmd = { "p4", "-x", "-", "resolve", "-at" }; - P4Process p = new P4Process(env); - p.exec(rescmd); - while(en.hasMoreElements()) { - fent = (FileEntry) en.nextElement(); - p.println(fent.getDepotPath()); - Debug.notify("resolveAT(): " + fent.getDepotPath()); - } - p.println("\032\n\032"); - p.flush(); - p.outClose(); - Debug.notify("FileEntry.resolveAT(): Reading more lines."); - while(null != (l = p.readLine())) { - if(null != sb) { - sb.append(l); - sb.append('\n'); - } - } - p.close(); - return sb.toString(); - } - - /** - * Resolves all the files in the path. The flags are used by the 'p4 - * resolve' command to resolve any files in the path. This is just a simple - * way to execute the 'p4 resolve' command. - * - * @param env - * Source control environment to use. - * @param flags - * 'p4 resolve' command flags. - * @param path - * Path over which to resolve. May include wildcards. - */ - public static String resolveAll(Env env, String flags, String path) throws IOException { - StringBuffer sb = new StringBuffer(); - FileEntry fent; - String l; - String[] rescmd = { "p4", "resolve", flags, path }; - P4Process p = new P4Process(env); - p.exec(rescmd); - Debug.notify("FileEntry.resolveAll(): Reading more lines."); - while(null != (l = p.readLine())) { - if(null != sb) { - sb.append(l); - sb.append('\n'); - } - } - p.close(); - return sb.toString(); - } - - /** - * @deprecated Don't use this anymore. - */ - public static String HTMLEncode(String str) { - if(null == str) - return null; - StringBuffer strbuf = new StringBuffer(str.length()); - char tmp; - for(int i = 0; i < str.length(); i++) { - tmp = str.charAt(i); - if('<' == tmp) { - strbuf.append("<"); - } else if('>' == tmp) { - strbuf.append(">"); - } else { - strbuf.append(tmp); - } - } - return strbuf.toString(); - } - - /** Returns the file name. */ - public String getName() { - int pos; - String path = getDepotPath(); - if(null == path) { - path = getClientPath(); - } - if(null == path) { - return ""; - } - if(-1 == (pos = path.lastIndexOf('/'))) { - return path; - } - return path.substring(pos + 1); - } - - /** - * Sets the client path for this file. - * - * @param p - * path for this file on the client system. - */ - public void setClientPath(String p) { - this.client_path = p; - } - - /** Returns the client path for this file. */ - public String getClientPath() { - return client_path; - } - - /** - * Gets the file information for the specified path. - * - * @param p - * Path of the file to gather information about. - */ - public static synchronized FileEntry getFile(String p) { - FileEntry f = new FileEntry(p); - f.sync(); - return f; - } - - /** - * Returns the list of files for the path. The path may include wildcards. - * - * @param env - * Source control environment to use. - * @param path - * Path for set of files. - */ - public static Vector getFiles(Env env, String path) { - Vector v = null; - String[] cmd = { "p4", "fstat", path + "%1" }; - if(null == path) - return null; - - try { - P4Process p = new P4Process(env); - p.exec(cmd); - v = parseFstat(null, p, true); - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - return v; - } - - /** - * Returns a list of FileEntry objects that represent the - * history of the specified file. - * - * @param env - * Source control environment to use. - * @param path - * Path to the file. Must be specific. No wildcards. - */ - public static Vector getFileLog(Env env, String path) { - String[] cmd = { "p4", "filelog", path }; - String l, tmp; - StringTokenizer st; - P4Process p; - FileEntry fent = null, tmpent = null; - Vector v = new Vector(); - int beg, end; - - if(null == path) - return v; - try { - p = new P4Process(env); - p.setRawMode(true); - p.exec(cmd); - while(null != (l = p.readLine())) { - l = l.trim(); - if(l.startsWith("info2: ") && null != fent) { - tmpent = new FileEntry(env); - beg = 8; - if(-1 == (end = l.indexOf(' ', beg))) { - continue; - } - tmpent.setHeadAction(l.substring(beg, end)); - beg = end; - if(-1 == (end = l.indexOf("from "))) { - tmpent.setDepotPath(path); - } else { - beg = end + 5; - if(-1 == (end = l.indexOf('#', beg))) { - tmpent.setDepotPath(l.substring(beg)); - } else { - tmpent.setDepotPath(l.substring(beg, end)); - } - } - if(-1 != (end = l.lastIndexOf('#'))) { - if(-1 != (beg = l.lastIndexOf('#', end - 1))) { - tmpent.setHaveRev(Integer.parseInt(l.substring(beg + 1, end - 1))); - } - tmpent.setHeadRev(Integer.parseInt(l.substring(end + 1))); - } - fent.setSource(tmpent); - } else if(l.startsWith("info1: ")) { - if(null != fent) { - v.addElement(fent); - } - fent = new FileEntry(env); - fent.setDepotPath(path); - st = new StringTokenizer(l.substring(8)); - fent.setHeadRev(Integer.parseInt(st.nextToken())); - st.nextToken(); // change - fent.setHeadChange(Integer.parseInt(st.nextToken())); - fent.setHeadAction(st.nextToken()); - st.nextToken(); // on - fent.setHeadDate(st.nextToken()); - st.nextToken(); // by - fent.setOwner(st.nextToken()); - tmp = st.nextToken(); - fent.setHeadType(tmp.substring(1, tmp.length() - 1)); - if(1 < (end = l.lastIndexOf('\''))) { - if(-1 < (beg = l.lastIndexOf('\'', end - 1))) { - if(end - beg - 1 > 0) { - fent.setDescription(l.substring(beg + 1, end - 1)); - } - } - } - } - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - if(null != fent && null != fent.getDepotPath()) { - v.addElement(fent); - } - return v; - } - - /** - * Opens the file on the path for edit under the change. If the change is - * null, the file is opened under the default changelist. - * - * @param env - * P4 Environment - * @param path - * Depot or client path to the file being opened for edit. - * @param sync - * If true, the file will be sync'd before opened for edit. - * @param force - * If true, the file will be opened for edit even if it isn't the - * most recent version. - * @param lock - * If true, the file will be locked once opened. - * @param chng - * The change that the file will be opened for edit in. - */ - public static FileEntry openForEdit(Env env, String path, boolean sync, boolean force, boolean lock, Change chng) - throws Exception { - if(sync) { - FileEntry.syncWorkspace(env, path); - } - FileEntry fent = new FileEntry(env, path); - fent.openForEdit(force, lock, chng); - return fent; - } - - /** - * Opens this file for edit. - * - * @see #openForEdit(Env, String, boolean, boolean, boolean, Change) - */ - public void openForEdit() throws Exception { - openForEdit(true, false, null); - } - - /** - * Opens this file for edit. - * - * @see #openForEdit(Env, String, boolean, boolean, boolean, Change) - */ - public void openForEdit(boolean force, boolean lock) throws Exception { - openForEdit(force, lock, null); - } - - /** - * Opens this file for edit. - * - * @see #openForEdit(Env, String, boolean, boolean, boolean, Change) - */ - public void openForEdit(boolean force, boolean lock, Change chng) throws Exception { - String[] cmd1; - String[] cmd2; - String l; - P4Process p; - int i = 0; - sync(); - if(force) { - cmd1 = new String[4]; - cmd1[2] = "-f"; - } else { - cmd1 = new String[3]; - } - cmd1[0] = "p4"; - cmd1[1] = "sync"; - cmd1[cmd1.length - 1] = getDepotPath(); - - cmd2 = new String[(null == chng) ? 3 : 5]; - cmd2[i++] = "p4"; - cmd2[i++] = "edit"; - if(null != chng) { - cmd2[i++] = "-c"; - cmd2[i++] = String.valueOf(chng.getNumber()); - } - cmd2[i++] = getClientPath(); - - p = new P4Process(getEnv()); - p.exec(cmd1); - while(null != (l = p.readLine())) { - } - p.close(); - p = new P4Process(getEnv()); - p.exec(cmd2); - while(null != (l = p.readLine())) { - } - p.close(); - if(lock) - obtainLock(); - } - - /** - * Obtains the lock for this file. The file must have been opened for edit - * prior to this method being called. - */ - public void obtainLock() throws Exception { - String[] cmd = { "p4", "lock", getDepotPath() }; - String l; - P4Process p; - - p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - } - p.close(); - } - - /** - * Opens the file on the path for add under the change. If the change is - * null, the file is opened under the default changelist. - * - * @param env - * P4 Environment - * @param path - * Depot or client path to the file being opened for add. - * @param chng - * The change that the file will be opened for add in. - */ - public static FileEntry openForAdd(Env env, String path, Change chng) throws Exception { - FileEntry fent = new FileEntry(env, path); - fent.openForAdd(chng); - return fent; - } - - /** - * Opens this file for addition. - * - * @see #openForAdd(Env, String, Change) - */ - public void openForAdd() throws Exception { - openForAdd(null); - } - - /** - * Opens this file for addition. - * - * @see #openForAdd(Env, String, Change) - */ - public void openForAdd(Change chng) throws Exception { - String[] cmd; - int i = 0; - cmd = new String[(null == chng) ? 3 : 5]; - cmd[i++] = "p4"; - cmd[i++] = "add"; - if(null != chng) { - cmd[i++] = "-c"; - cmd[i++] = String.valueOf(chng.getNumber()); - } - cmd[i++] = getClientPath(); - String l; - P4Process p; - - if(null == getClientPath()) { - throw new Exception("No Client Path"); - } - - p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - } - p.close(); - } - - /** - * Checks in a file that has already been opened on the client using the - * description given. A new changelist is created and used for this - * submission. The returned FileEntry contains the latest - * information for the checked-in file. - */ - public static FileEntry checkIn(Env env, String path, String description) throws PerforceException { - FileEntry fent = new FileEntry(env, path); - Change chng = new Change(env); - chng.setDescription(description); - chng.addFile(fent); - chng.submit(); - fent.sync(); - return fent; - } - - /** - * Reopens the file with the new type or in the new change list. - */ - public void reopen(String type, Change chng) throws PerforceException { - String[] cmd; - int i = 0; - String l; - P4Process p = null; - - if(null == getClientPath()) { - try { - sync(); - } catch(Exception ex) { /* Ignored Exception */ - } - if(null == getClientPath()) { - throw new PerforceException("No Client Path"); - } - } - - if(null == type && null == chng) - return; - cmd = new String[(null == type || null == chng) ? 5 : 7]; - cmd[i++] = "p4"; - cmd[i++] = "reopen"; - if(null != type) { - cmd[i++] = "-t"; - cmd[i++] = type; - } - if(null != chng) { - cmd[i++] = "-c"; - cmd[i++] = String.valueOf(chng.getNumber()); - } - cmd[i++] = getClientPath(); - - try { - p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if((-1 != l.indexOf("not opened on this client")) || (-1 != l.indexOf("Invalid file type")) - || (-1 != l.indexOf("unknown"))) { - throw new PerforceException(l); - } - } - } catch(Exception ex) { - throw new PerforceException(ex.getMessage()); - } finally { - if(null != p) { - try { - p.close(); - } catch(IOException ioex) { /* Ignored Exception */ - } - } - } - } - - /** - * Reverts this file. - */ - public boolean revert() { - String[] cmd1 = { "p4", "revert", getDepotPath() }; - String[] cmd2 = { "p4", "sync", getDepotPath() + "#none" }; - String l; - P4Process p; - - try { - p = new P4Process(getEnv()); - p.exec(cmd1); - while(null != (l = p.readLine())) { - } - p.close(); - p = new P4Process(getEnv()); - p.exec(cmd2); - while(null != (l = p.readLine())) { - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - return false; - } - return true; - } - - /** - * Returns a list of files that are open for edit or add. The list is a - * Vectore of FileEntry objects. The only - * information that is valid for the object will be the path, until the - * {@link #sync() sync} method is called. - */ - public static Vector getOpened() { - return getOpened(null, true, false, -1, null); - } - - /** - * Returns a list of files that are open for edit or add. The list is a - * Vectore of FileEntry objects. - *

- * Getting the stats for each FileEntry is a more expensive - * operation. By default, this is not done. What this means is that the only - * information that is valid for the object will be the path, until the - * {@link #sync() sync} method is called. - * - * @param env - * Source control environment to use. - * @param stat - * Indicates that file statistics should be gathered. - */ - public static Vector getOpened(Env env, boolean stat) { - return getOpened(env, stat, false, -1, null); - } - - /** - * Returns a list of files that are open for edit or add. The list is a - * Vector of FileEntry objects. - *

- * Getting the stats for each FileEntry is a more expensive - * operation. By default, this is not done. What this means is that the only - * information that is valid for the object will be the path, until the - * {@link #sync() sync} method is called. - *

- * If changelist is 0, all the changes in the default changelist are - * returned. If it is less than 0, all opened files are returned. - * - * @param env - * Source control environment to use. - * @param stat - * Indicates that file statistics should be gathered. - * @param all - * Indicates that all open files should be returned. - * @param changelist - * If non-zero, show files open in this changelist. - * @param files - * If non-null, show files open in this Vector of - * FileEntry objects. - */ - public static Vector getOpened(Env env, boolean stat, boolean all, int changelist, Vector files) { - Vector v = new Vector(); - String l, str; - StringTokenizer st; - int i = 0, cnt = 2; - String[] cmd; - FileEntry fent; - if(all) - cnt++; - if(0 <= changelist) - cnt += 2; - if(null != files) - cnt += files.size(); - cmd = new String[cnt]; - cmd[i++] = "p4"; - cmd[i++] = "opened"; - if(all) - cmd[i++] = "-a"; - if(0 <= changelist) { - cmd[i++] = "-c"; - cmd[i++] = (0 == changelist) ? "default" : String.valueOf(changelist); - } - if(null != files) { - Enumeration en = files.elements(); - while(en.hasMoreElements()) { - cmd[i++] = (String) en.nextElement(); - } - } - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(!l.startsWith("//")) { - continue; - } - st = new StringTokenizer(l, "#"); - if(null == (str = st.nextToken())) { - continue; - } - fent = new FileEntry(env, str); - if(null == (str = st.nextToken("# \t"))) { - continue; - } - fent.setHeadRev(Integer.valueOf(str).intValue()); - st.nextToken(" \t"); // Should be the dash here. - if(null == (str = st.nextToken())) { - continue; - } - fent.setHeadAction(str); - if(null == (str = st.nextToken())) { - continue; - } - if(str.equals("default")) { - fent.setHeadChange(-1); - st.nextToken(); // Change here. - } else if(str.equals("change")) { - if(null == (str = st.nextToken())) { - continue; - } // Change number - fent.setHeadChange(Integer.valueOf(str).intValue()); - } - if(null == (str = st.nextToken(" \t()"))) { - continue; - } - fent.setHeadType(str); - // Insertion sort...slow but effective. - for(i = 0; i < v.size(); i++) { - if(((FileEntry) v.elementAt(i)).getHeadChange() > fent.getHeadChange()) - break; - } - v.insertElementAt(fent, i); - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - if(stat) { - Enumeration en = v.elements(); - while(en.hasMoreElements()) { - fent = (FileEntry) en.nextElement(); - fent.setEnv(env); - fent.sync(); - } - } - return v; - } - - /** - * No-op. This makes no sense for a FileEntry. - */ - public void commit() { - } - - /** - * @deprecated - * @see #syncWorkspace(Env, String) - */ - public String syncMySpace(Env env, String path) throws IOException { - return FileEntry.syncWorkspace(env, path); - } - - /** - * Returns a Vector of FileEntry objects that - * reflect what files were changed by the sync process. If path is null, the - * entire workspace is synchronized to the head revision. The path may - * contain wildcard characters, as with the command line 'p4 sync' command. - * - * @param env - * Source control environment. - * @param path - * Path to synchronize. May include wildcards. - */ - public static Vector synchronizeWorkspace(Env env, String path) throws IOException { - String[] cmd; - if(null == path || path.trim().equals("")) { - cmd = new String[2]; - } else { - cmd = new String[3]; - cmd[2] = path; - } - cmd[0] = "p4"; - cmd[1] = "sync"; - - String l; - int pos1, pos2; - Vector v = new Vector(); - FileEntry fent = null; - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - fent = null; - if(!l.startsWith("//")) { - continue; - } - pos1 = 0; - if(-1 == (pos2 = l.indexOf('#'))) - continue; - fent = new FileEntry(env, l.substring(pos1, pos2)); - pos1 = pos2 + 1; - if(-1 == (pos2 = l.indexOf(' ', pos1))) - continue; - try { - fent.setHeadRev(Integer.parseInt(l.substring(pos1, pos2))); - } catch(Exception ex) { - fent = null; - continue; - } - pos1 = pos2 + 1; - if(-1 != (pos2 = l.indexOf("updating ")) || -1 != (pos2 = l.indexOf("added as "))) { - fent.setClientPath(l.substring(pos2 + 9).trim()); - } - if(null != fent) { - v.addElement(fent); - fent = null; - } - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - throw ex; - } - return v; - } - - /** - * Synchronizes the workspace. - * - * @param env - * Source control environment. - * @param path - * Path to synchronize. May include wildcards. - */ - public static String syncWorkspace(Env env, String path) throws IOException { - String[] cmd; - if(null == path || path.trim().equals("")) { - cmd = new String[3]; - cmd[2] = path; - } else { - cmd = new String[2]; - } - cmd[0] = "p4"; - cmd[1] = "sync"; - - String l, str = ""; - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - str += l + "\n"; - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - throw ex; - } - return str; - } - - /** - * Returns a String that contains this file's contents. This - * only works well for text files. - */ - public String getFileContents() { - return getFileContents(getEnv(), getDepotPath()); - } - - /** - * Returns a String that contains this file's contents. This - * only works well for text files. - * - * @param env - * Source control environment. - * @param path - * Path to the file. Must be specific. No wildcards. - */ - public String getFileContents(Env env, String path) { - String l; - StringBuffer ret = null; - String[] cmd = { "p4", "print", path }; - try { - P4Process p = new P4Process(env); - p.setRawMode(true); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(null == ret) { - ret = new StringBuffer(); - } else if(l.startsWith("text: ")) { - ret.append(l.substring(6)); - if(!l.endsWith("\n")) - ret.append('\n'); - } - } - if(null == ret) { - ret = new StringBuffer(); - } - - if(0 != p.close()) { - throw new IOException("P4 exited with and error:" + p.getExitCode()); - } - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - file_content = ret.toString(); - return file_content; - } - - public void sync() { - String l; - String[] cmd = { "p4", "fstat", "path" }; - if(null != depot_path) { - cmd[2] = depot_path; - } else if(null != client_path) { - cmd[2] = client_path; - } else { - return; - } - if(0 != head_rev) { - cmd[2] += "#" + head_rev; - } - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - parseFstat(this, p, false); - if(0 != p.close()) { - throw new IOException("P4 exited with an error:" + p.getExitCode()); - } - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - } - - /** - * Useful method for parsing that lovely fstat format information. - */ - private static Vector parseFstat(FileEntry fe, P4Process p, boolean igndel) { - FileEntry nfe; - String l; - Vector v = new Vector(); - String dataname, datavalue; - boolean multiple = false; - - if(null == p) - return null; - if(null == (nfe = fe)) - nfe = new FileEntry(p.getEnv()); - - while(null != (l = p.readLine())) { - StringTokenizer tokes = new StringTokenizer(l, " "); - - dataname = (String) (tokes.hasMoreElements() ? tokes.nextElement() : null); - datavalue = (String) (tokes.hasMoreElements() ? tokes.nextElement() : null); - if(dataname.equals("clientFile")) { - nfe.setClientPath(datavalue); - } else if(dataname.equals("depotFile")) { - if(multiple) - nfe = new FileEntry(p.getEnv()); - nfe.setDepotPath(datavalue); - v.add(nfe); - multiple = true; - } else if(dataname.equals("headAction")) { - nfe.setHeadAction(datavalue); - } else if(dataname.equals("headChange")) { - nfe.setHeadChange(new Integer(datavalue).intValue()); - } else if(dataname.equals("headRev")) { - nfe.setHeadRev(new Integer(datavalue).intValue()); - } else if(dataname.equals("headType")) { - nfe.setHeadType(datavalue); - } else if(dataname.equals("headTime")) { - nfe.setHeadTime(new Long(datavalue).longValue()); - } else if(dataname.equals("haveRev")) { - nfe.setHaveRev(new Integer(datavalue).intValue()); - } else if(dataname.equals("action")) { - - } else if(dataname.equals("change")) { - - } else if(dataname.equals("unresolved")) { - - } else if(dataname.equals("otherOpen")) { - - } else if(dataname.equals("otherLock")) { - - } else if(dataname.equals("ourLock")) { - - } - } - return v; - } - - public String toString() { - return depot_path + "\n" + client_path + "\nothers: " + other_cnt; - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - sb.append(""); - ; - sb.append(getDepotPath()); - sb.append(""); - sb.append(""); - ; - sb.append(getClientPath()); - sb.append(""); - if(null != getDescription()) { - sb.append(""); - ; - sb.append(getDescription()); - sb.append(""); - } - sb.append(""); - return sb.toString(); - } -} diff --git a/src/main/java/com/perforce/api/HashDecay.java b/src/main/java/com/perforce/api/HashDecay.java deleted file mode 100644 index d33d721..0000000 --- a/src/main/java/com/perforce/api/HashDecay.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.perforce.api; - -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * This hashtable build to contain objects that will decay over time. The - * objects stored must implement the Cacheable interface. - * - * @author David Markley - * @version $Date: 2001/12/04 $ $Revision: #2 $ - * @see java.util.Hashtable - * @see Cacheable - */ -public final class HashDecay extends Hashtable implements Runnable { - /** The minimum delay allowed */ - public final static long MIN_DELAY = 0; - - private long delay = MIN_DELAY; - - private Thread decay_thread; - - private boolean runForever = true; - - private static Vector started = new Vector(); - - static { - started = new Vector(); - } - - public HashDecay() { - super(); - } - - public HashDecay(long delay) { - this(); - setDelay(delay); - } - - /** - * Sets the delay, in milliseconds, before items in the hashtable are - * discarded. - */ - public void setDelay(long delay) { - this.delay = (MIN_DELAY > delay) ? MIN_DELAY : delay; - } - - /** - * Returns the delay. - */ - public long getDelay() { - return delay; - } - - public void run() { - while(runForever) { - try { - Thread.sleep(delay); - } catch(InterruptedException iex) { - } - decay(); - } - } - - private synchronized void decay() { - long now = (new Date()).getTime(); - Enumeration en = keys(); - Object key; - while(en.hasMoreElements()) { - key = en.nextElement(); - if(delay >= (now - ((Cacheable) get(key)).getUpdateTime())) { - super.remove(key); - } - } - } - - public Object put(Object key, Object value) { - if(!(value instanceof Cacheable)) - return null; - return put(key, (Cacheable) value); - } - - public Object put(Object key, Cacheable value) { - value.refreshUpdateTime(); - super.remove(key); - Object obj = super.put(key, value); - return obj; - } - - public void start() { - if(null != decay_thread) - return; - runForever = true; - decay_thread = new Thread(this); - decay_thread.start(); - started.addElement(this); - } - - public void stop() { - runForever = false; - if(null == decay_thread) - return; - try { - decay_thread.interrupt(); - decay_thread.join(100); - } catch(InterruptedException ex) { - decay_thread.destroy(); - } catch(SecurityException ex) { - decay_thread.destroy(); - } - } - - /** - * Stops running threads for all HashDecay instances. - */ - public static void stopAll() { - HashDecay hd; - Enumeration en = started.elements(); - while(en.hasMoreElements()) { - hd = (HashDecay) en.nextElement(); - hd.stop(); - } - } -} diff --git a/src/main/java/com/perforce/api/Job.java b/src/main/java/com/perforce/api/Job.java deleted file mode 100644 index bdd5391..0000000 --- a/src/main/java/com/perforce/api/Job.java +++ /dev/null @@ -1,748 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control job. This class can be used to determine - * information for a particular p4 job. It can be constructed using the job - * name, but will not contain any additional change information until the sync() method is called. - * - * @author David Markley - * @version $Date: 2002/08/05 $ $Revision: #2 $ - */ -public final class Job extends SourceControlObject { - private String name = "new"; - - private String user = null; - - private String modtime_string = ""; - - private String description = "\tUseless description. This must be changed."; - - private int status = OPEN; - - private Hashtable fields = new Hashtable(); - - private static HashDecay jobs = new HashDecay(); - - private Change[] changes = null; - - /** Indicates that the Job is open. */ - public final static int OPEN = 1; - - /** Indicates that the Job is closed. */ - public final static int CLOSED = 2; - - /** Indicates that the Job is suspended. */ - public final static int SUSPENDED = 4; - - /** - * Default no-argument constructor. - */ - public Job(Env env) { - super(); - if(null == fields) { - fields = new Hashtable(); - } - getCache(); - setEnv(env); - } - - private static HashDecay setCache() { - if(null == jobs) { - jobs = new HashDecay(300000); - jobs.start(); - } - return jobs; - } - - public HashDecay getCache() { - return setCache(); - } - - /** - * Constructor that accepts the job number. This job is not populated with - * the correct information until the sync() method is called on it. - * - * @param name - * Job name - */ - public Job(String name) { - this((Env) null); - this.name = name; - } - - public Job() { - this((Env) null); - } - - public Job(Env env, String name) { - this(env); - this.name = name; - } - - /** Returns the job with the specified name. */ - public static Job getJob(String name) { - return getJob(null, name); - } - - /** Returns the job with the specified name. */ - public static Job getJob(Env env, String name) { - Job j = new Job(name); - if(null != env) - j.setEnv(env); - j.sync(); - return j; - } - - /** Returns the job's modification time */ - public String getModtimeString() { - return modtime_string; - } - - /** Sets the job's modification time */ - public void setModtimeString(String modtime) { - this.modtime_string = modtime; - } - - /** - * Sets the job name for the Job. This invalidates all the other data for - * the Job. - * - * @param name - * Job name - */ - public void setName(String name) { - this.name = name; - user = null; - description = ""; - status = OPEN; - } - - /** - * Returns the name of this Job. - */ - public String getName() { - return name; - } - - /** - * Sets the User that owns this Job. - * - * @param user - * Owning user. - */ - public void setUser(String user) { - this.user = user; - } - - /** - * Returns the User that owns this Job. - */ - public String getUser() { - return user; - } - - /** - * Sets the description for the job. - */ - public void setDescription(String description) { - String l; - try { - StringBuffer sb = new StringBuffer(); - BufferedReader b = new BufferedReader(new StringReader(description)); - while(null != (l = b.readLine())) { - sb.append('\t'); - sb.append(l.trim()); - sb.append('\n'); - } - this.description = sb.toString(); - } catch(IOException ex) { - this.description = description; - } - } - - /** - * Returns the description for the Job. This description includes not only - * the textual description provided by the user, but also the list of - * affected files and how they were affected. - * - * The String returned includes newline characters. - */ - public String getDescription() { - return description; - } - - public Enumeration getFieldNames() { - return fields.keys(); - } - - public void setField(String name, String value) { - fields.put(name.toLowerCase(), value); - } - - public String getField(String name) { - return (String) fields.get(name.toLowerCase()); - } - - public Vector getFileEntries() { - Vector v = new Vector(); - Integer pos; - Hashtable h = new Hashtable(); - Enumeration en; - FileEntry fent; - changes = getChanges(); - for(int i = 0; i < changes.length; i++) { - changes[i].sync(); - en = changes[i].getFileEntries().elements(); - while(en.hasMoreElements()) { - fent = (FileEntry) en.nextElement(); - if(null != (pos = (Integer) h.get(fent.getDepotPath()))) { - if(((FileEntry) v.elementAt(pos.intValue())).getHeadRev() < fent.getHeadRev()) { - v.setElementAt(fent, pos.intValue()); - } - } else { - v.addElement(fent); - h.put(fent.getDepotPath(), new Integer(v.size() - 1)); - } - } - } - return v; - } - - /** - * Sets status for the Job. This can be either OPEN, CLOSED, or SUSPENDED. - */ - public void setStatus(String status) { - if(-1 != status.indexOf("closed")) { - this.status = CLOSED; - } else if(-1 != status.indexOf("suspended")) { - this.status = SUSPENDED; - } else { - this.status = OPEN; - } - } - - /** - * Sets status for the Job. This can be either OPEN, CLOSED, or SUSPENDED. - */ - public void setStatus(int status) { - this.status = status; - } - - /** - * Returns the status for the Job. This can be either OPEN, CLOSED, or - * SUSPENDED. - */ - public int getStatus() { - return status; - } - - public String getStatusName() { - switch(status) { - case SUSPENDED: - return "suspended"; - case CLOSED: - return "closed"; - default: - return "open"; - } - } - - /** - * Stores the job information back into perforce. - * - * @deprecated Use {@link #commit() commit()} instead. - */ - public void store() throws CommitException { - this.commit(); - } - - public void commit() throws CommitException { - StringBuffer sb = new StringBuffer(); - String[] cmd = { "p4", "job", "-i" }; - String l, key; - int pos; - boolean store_failed = false; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - p.println("Job: " + getName()); - p.println("Status: " + getStatusName()); - if(null == getUser() && null != getEnv()) { - p.println("User: " + getEnv().getUser()); - } else { - p.println("User: " + user); - } - p.println("Description: "); - p.println(getDescription()); - Enumeration en = fields.keys(); - while(en.hasMoreElements()) { - key = (String) en.nextElement(); - p.println(key + ": " + (String) fields.get(key)); - } - p.flush(); - p.outClose(); - while(null != (l = p.readLine())) { - if(l.startsWith("Job ") && (-1 != (pos = l.indexOf("saved")))) { - setName(l.substring(4, pos - 1).trim()); - } - if(l.startsWith("Error")) - store_failed = true; - sb.append(l); - sb.append('\n'); - } - p.close(); - } catch(Exception ex) { - throw new CommitException(ex.getMessage()); - } - if(store_failed) { - throw new CommitException(sb.toString()); - } - } - - /** - * Synchronizes the Job with the correct information from P4, using whatever - * job number has already been set in the Job. After this method is called, - * all the information in the Job is valid. - */ - public void sync() { - sync(name); - } - - /** - * Sycnhronizes the Job with the correct information from P4. After this - * method is called, all the information in the Job is valid. - * - * @param number - * Job number - */ - public void sync(String name) { - this.name = name; - int pos; - String l; - String[] cmd = { "p4", "job", "-o", "jobname" }; - cmd[3] = name; - String tmpdesc = ""; - - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - p.setRawMode(true); - while(null != (l = p.readLine())) { - if(l.startsWith("info: ")) { - l = l.substring(6); - } else { - continue; - } - if(l.startsWith("#")) - continue; - if(l.startsWith("Job:")) { - name = l.substring(4).trim(); - } else if(l.startsWith("Status:")) { - setStatus(l.substring(8).trim()); - } else if(l.startsWith("ReportedBy:")) { - user = l.substring(11).trim(); - } else if(l.startsWith("ReportedDate:")) { - modtime_string = l.substring(14).trim(); - } else if(l.startsWith("Description:")) { - while(null != (l = p.readLine()) && l.startsWith("info: \t")) { - tmpdesc += l.substring(6).trim() + "\n"; - } - setDescription(tmpdesc); - } else if(-1 != (pos = l.indexOf(':'))) { - setField(l.substring(0, pos).trim(), l.substring(pos + 1).trim()); - } - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - } - - public static void fix(Env env, String changelist, boolean del, String job) { - Vector jobs = new Vector(); - jobs.addElement(job); - fix(env, changelist, del, jobs); - } - - public static void fix(Env env, String changelist, boolean del, Vector jobs) { - if(null == jobs) - return; - int i = 0, len = (del) ? 5 : 4; - len += jobs.size(); - String cmd[] = new String[len]; - String l; - cmd[i++] = "p4"; - cmd[i++] = "fix"; - cmd[i++] = "-c"; - cmd[i++] = changelist; - if(del) - cmd[i++] = "-d"; - Enumeration en = jobs.elements(); - while(en.hasMoreElements()) { - cmd[i++] = (String) en.nextElement(); - } - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - } - - public void removeFix(int changelist) { - } - - /** - * Overrides the default toString() method. - */ - public String toString() { - StringBuffer sb = new StringBuffer("Job: "); - sb.append(name); - sb.append("\nUser: "); - sb.append(user); - sb.append("\nDescription:\n"); - sb.append(description); - return sb.toString(); - } - - public static Job[] getJobs(Env env) { - return getJobs(env, (String) null, 0, false, (String[]) null); - } - - public static Job[] getJobs(Env env, String jobview, int max, boolean use_integs, String[] files) { - int args = 3, pos = 0; - if(null != jobview) - args += 2; - if(use_integs) - args++; - if(0 < max) - args += 2; - if(null != files) - args += files.length; - String[] cmd = new String[args]; - cmd[pos++] = "p4"; - cmd[pos++] = "jobs"; - cmd[pos++] = "-l"; - if(null != jobview) { - cmd[pos++] = "-e"; - cmd[pos++] = jobview; - } - if(use_integs) { - cmd[pos++] = "-i"; - } - if(0 < max) { - cmd[pos++] = "-m"; - cmd[pos++] = String.valueOf(max); - } - if(null != files) { - for(int i = 0; i < files.length; i++) { - cmd[pos++] = files[i]; - } - } - - Vector v = new Vector(); - Job[] jobs; - Job j = null; - StringTokenizer st; - String l, name, user, tmpdesc = "", modtime, state; - - try { - P4Process p = new P4Process(env); - p.exec(cmd); - p.setRawMode(true); - while(null != (l = p.readLine())) { - if(l.startsWith("info: \t")) { - tmpdesc += l.substring(7) + "\n"; - continue; - } else if(l.trim().equals("info:")) { - continue; - } - if(null != j) { - j.setDescription(tmpdesc); - v.addElement(j); - } - tmpdesc = ""; - j = null; - st = new StringTokenizer(l); - if(2 > st.countTokens()) - continue; - st.nextToken(); /* Skip 'info:' */ - name = st.nextToken(); - if(!st.nextToken().equals("on")) - continue; - modtime = st.nextToken(); - if(!st.nextToken().equals("by")) - continue; - user = st.nextToken(); - state = st.nextToken(); - j = new Job(env, name); - j.setModtimeString(modtime); - j.setStatus(state); - j.setUser(user); - } - p.close(); - if(null != j) { - j.setDescription(tmpdesc); - v.addElement(j); - } - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - jobs = new Job[v.size()]; - for(int i = 0; i < v.size(); i++) { - jobs[i] = (Job) v.elementAt(i); - } - return jobs; - } - - /** - * @return Array of changes that are fixed by this job. - */ - public Change[] getChanges() { - if(null == changes) { - changes = getChangeFixes(getEnv(), getName(), null); - } - return changes; - } - - /** - * Returns an array of changes that are fixed by the named job, limited to - * the list of files if specified. - * - * @param env - * Perforce environment to use. - * @param jobname - * Named job to get fixes for. - * @param files - * array of files (including wildcards) used to limit to lookup. - * @return array of changes fixed by the named job. - */ - public static Change[] getChangeFixes(Env env, String jobname, String[] files) { - Vector[] fixes = getFixes(env, jobname, null, files); - Vector vc = fixes[0]; - Change[] changes = new Change[vc.size()]; - for(int i = 0; i < vc.size(); i++) { - changes[i] = (Change) vc.elementAt(i); - } - return changes; - } - - /** - * Returns an array of jobs that fix the specified change, limited to the - * list of files if specified. - * - * @param env - * Perforce environment to use. - * @param change - * Change number (as a String) to lookup jobs - * for. - * @param files - * array of files (including wildcards) used to limit to lookup. - * @return array of jobs that fix the specified change. - */ - public static Job[] getJobFixes(Env env, String change, String[] files) { - Vector[] fixes = getFixes(env, null, change, files); - Vector vj = fixes[1]; - Job[] jobs = new Job[vj.size()]; - for(int i = 0; i < vj.size(); i++) { - jobs[i] = (Job) vj.elementAt(i); - } - return jobs; - } - - /** - * Returns an array of two Vectors. The first - * Vector in the array is filled with the changes fixed. The - * second Vector contains the jobs that fix those changes. - * - * @param env - * Perforce environment to use. - * @param jobname - * Named job to get fixes for. - * @param change - * Change number (as a String) to lookup jobs - * for. - * @param files - * array of files (including wildcards) used to limit to lookup. - * @return an array of two Vectors that contains changes and - * jobs fixed. - */ - private static Vector[] getFixes(Env env, String jobname, String change, String[] files) { - int args = 2, pos = 0; - if(null != jobname) { - args += 2; - jobname = jobname.trim(); - } - if(null != change) { - args += 2; - change = change.trim(); - } - if(null != files) - args += files.length; - String[] cmd = new String[args]; - cmd[pos++] = "p4"; - cmd[pos++] = "fixes"; - if(null != jobname) { - cmd[pos++] = "-j"; - cmd[pos++] = jobname; - } - if(null != change) { - cmd[pos++] = "-c"; - cmd[pos++] = change; - } - if(null != files) { - for(int i = 0; i < files.length; i++) { - cmd[pos++] = files[i]; - } - } - Vector vc = new Vector(); - Vector vj = new Vector(); - Change c = null; - Job jb = null; - StringTokenizer st; - String l, jbname, number, user, tmpdesc = "", modtime, state; - - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - st = new StringTokenizer(l); - jbname = st.nextToken(); - jb = new Job(env, jbname); - vj.addElement(jb); - if(!st.nextToken().equals("fixed")) - continue; - if(!st.nextToken().equals("by")) - continue; - if(!st.nextToken().equals("change")) - continue; - c = new Change(st.nextToken()); - c.setEnv(env); - if(!st.nextToken().equals("on")) - continue; - c.setModtimeString(st.nextToken()); - if(!st.nextToken().equals("by")) - continue; - c.setClientName(st.nextToken()); - if(null != c) { - vc.addElement(c); - c = null; - } - } - p.close(); - } catch(IOException ex) { - Debug.out(Debug.ERROR, ex); - } - Vector[] fixes = new Vector[2]; - fixes[0] = vc; - fixes[1] = vj; - return fixes; - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - sb.append(getDescription()); - sb.append(""); - - Enumeration en = fields.keys(); - String key; - while(en.hasMoreElements()) { - key = (String) en.nextElement(); - sb.append(""); - } - sb.append(""); - return sb.toString(); - } - - /** - * Used for testing. - * - * @deprecated Actually in use, but this keeps it out of the docs. - */ - public static void main(String[] args) { - String propfile = "/etc/p4.conf"; - Env environ = null; - /* - * Debug.setDebugLevel(Debug.VERBOSE); - * Debug.setLogLevel(Debug.LOG_SPLIT); - */ - if(0 < args.length) - propfile = args[0]; - try { - environ = new Env(propfile); - } catch(PerforceException ex) { - System.out.println("Could not load properties from " + propfile + ": " + ex); - System.exit(-1); - } - System.out.println(environ); - Job[] jobs = getJobs(environ); - for(int i = 0; i < jobs.length; i++) { - System.out.println(jobs[i].getName() + " [" + jobs[i].getUser() + "]:\n\n" + jobs[i].getDescription()); - } - - System.out.println("\n---------\n"); - Job j = getJob(environ, "job000002"); - System.out.println(j.getName() + " [" + j.getUser() + "]:\n\n" + j.getDescription()); - - System.out.println("\n---------\n"); - System.out.println("Job " + j.getName() + " fixes:"); - Change[] chngs = j.getChanges(); - for(int x = 0; x < chngs.length; x++) { - System.out.println("\t change #" + chngs[x].getNumber()); - } - - if(0 < chngs.length) { - System.out.println("\n---------\n"); - System.out.println("Change " + chngs[0].getNumber() + " is fixed by:"); - Job[] jfixes = getJobFixes(environ, String.valueOf(chngs[0].getNumber()), null); - for(int x = 0; x < jfixes.length; x++) { - System.out.println("\t job " + jfixes[x].getName()); - } - } - - Utils.cleanUp(); - } - -} diff --git a/src/main/java/com/perforce/api/JobField.java b/src/main/java/com/perforce/api/JobField.java deleted file mode 100644 index 5caa717..0000000 --- a/src/main/java/com/perforce/api/JobField.java +++ /dev/null @@ -1,302 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Data class for p4 jobspec field information. This class can be used to - * contain field information for a particular field within the jobspec. - *

- * TBD: This class is not really used anywhere else. It is intended to be used - * for more interaction with the jobs interface. - * - * @author David Markley - * @version $Date: 2002/08/05 $ $Revision: #2 $ - */ -public final class JobField { - private int code = 0; - - private String name = ""; - - private int data_type = 0; - - private int len = 0; - - private int field_type = 0; - - private Vector values; - - private String preset; - - private static Hashtable fields; - - private JobField[] fieldarray; - - private final static int BASECODE = 101; - - private final static int MAXCODE = 199; - - /** Data type is a single word (any value) */ - public final static int WORD = 1; - - /** Data type is a date/time field */ - public final static int DATE = 2; - - /** Data type is one of a set of words */ - public final static int SELECT = 3; - - /** Data type is a one-liner */ - public final static int LINE = 4; - - /** Data type is a block of text */ - public final static int TEXT = 5; - - /** Field type has no default, not required to be present */ - public final static int OPTIONAL = 6; - - /** Field type has default provided, still not required */ - public final static int DEFAULT = 7; - - /** Field type has default provided, value must be present */ - public final static int REQUIRED = 8; - - /** Field type has set once to the default and never changed */ - public final static int ONCE = 9; - - /** Field type has always reset to the default upon saving */ - public final static int ALWAYS = 10; - - public JobField() { - super(); - if(null == fields) { - fields = new Hashtable(); - } - if(null == fieldarray) { - fieldarray = new JobField[MAXCODE - BASECODE + 1]; - } - values = new Vector(); - } - - public JobField(int code, String name, int dtype, int len, int ftype) { - this(); - setDataType(dtype); - setLength(len); - setFieldType(ftype); - setName(name); - setCode(code); - } - - public JobField(int code, String name, String dtype, int len, String ftype) { - this(); - setDataType(dtype); - setLength(len); - setFieldType(ftype); - setName(name); - setCode(code); - } - - private static JobField parseField(String def) { - StringTokenizer st = new StringTokenizer(def); - int code, len; - String name, dtype, ftype; - JobField jf; - - try { - st.nextToken(); /* Skip 'info:' */ - code = Integer.valueOf(st.nextToken()).intValue(); - name = st.nextToken(); - dtype = st.nextToken(); - len = Integer.valueOf(st.nextToken()).intValue(); - ftype = st.nextToken(); - jf = new JobField(code, name, dtype, len, ftype); - } catch(Exception ex) { - ex.printStackTrace(System.out); - return null; - } - return jf; - } - - public static void loadFields(Env env, boolean redo) { - if(!redo && null != fields) { - return; - } - fields = new Hashtable(); - String cmd[] = { "p4", "jobspec", "-o" }; - String l; - JobField jf = null; - try { - P4Process p = new P4Process(env); - p.setRawMode(true); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("#")) - continue; - if(l.startsWith("info: Fields:")) { - while(null != (l = p.readLine()) && l.startsWith("info: \t")) { - jf = JobField.parseField(l); - } - } - if(l.startsWith("Preset:")) { - } - if(l.startsWith("Values:")) { - } - } - p.close(); - } catch(IOException ex) { - } - } - - public static JobField getField(String name) { - if(null == fields) { - fields = new Hashtable(); - } - return (JobField) fields.get(name); - } - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getName() { - return name; - } - - public void setName(String name) { - if(name.trim().equals("")) - return; - if(!this.name.trim().equals("")) { - fields.remove(this.name); - } - this.name = name; - fields.put(this.name, this); - } - - public int getDataType() { - return data_type; - } - - public void setDataType(int dtype) { - this.data_type = dtype; - } - - public void setDataType(String dtype) { - if(dtype.equals("word")) { - this.data_type = JobField.WORD; - } else if(dtype.equals("date")) { - this.data_type = JobField.DATE; - } else if(dtype.equals("select")) { - this.data_type = JobField.SELECT; - } else if(dtype.equals("line")) { - this.data_type = JobField.LINE; - } else { - this.data_type = JobField.TEXT; - } - } - - public int getLength() { - return len; - } - - public void setLength(int len) { - this.len = len; - } - - public int getFieldType() { - return field_type; - } - - public void setFieldType(int ftype) { - this.field_type = ftype; - } - - public void setFieldType(String ftype) { - if(ftype.equals("optional")) { - this.field_type = JobField.OPTIONAL; - } else if(ftype.equals("always")) { - this.field_type = JobField.ALWAYS; - } else if(ftype.equals("required")) { - this.field_type = JobField.REQUIRED; - } else if(ftype.equals("once")) { - this.field_type = JobField.ONCE; - } else { - this.field_type = JobField.DEFAULT; - } - } - - public void setPreset(String value) { - this.preset = value; - } - - public String getPreset() { - return this.preset; - } - - public void addValue(String value) { - values.addElement(value); - } - - public Enumeration getValues() { - return values.elements(); - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - sb.append(""); - return sb.toString(); - } - - /** - * Used for testing. - * - * @deprecated Actually in use, but this keeps it out of the docs. - */ - public static void main(String[] args) { - String propfile = "/etc/p4.conf"; - Env environ = null; - Debug.setDebugLevel(Debug.VERBOSE); - if(0 < args.length) - propfile = args[0]; - try { - environ = new Env(propfile); - } catch(PerforceException ex) { - System.out.println("Could not load properties from " + propfile + ": " + ex); - System.exit(-1); - } - System.out.println(environ); - loadFields(environ, true); - Enumeration en = fields.keys(); - JobField jf; - while(en.hasMoreElements()) { - jf = (JobField) fields.get(en.nextElement()); - System.out.println(jf.getName() + " [" + jf.getCode() + "]: " + jf.getDataType()); - } - Utils.cleanUp(); - } -} diff --git a/src/main/java/com/perforce/api/Label.java b/src/main/java/com/perforce/api/Label.java deleted file mode 100644 index 039bcce..0000000 --- a/src/main/java/com/perforce/api/Label.java +++ /dev/null @@ -1,352 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control lablel. There are static class methods - * that can be used to list all P4 labels or to get - * a particular label. - * - * @author David Markley - * @version $Date: 2002/08/05 $ $Revision: #2 $ - */ -public class Label extends Mapping { - private static HashDecay labels = null; - - /** - * Default no-argument constructor. - */ - public Label() { - super(); - getCache(); - } - - /** - * Constructor that is passed the label name. - */ - public Label(String name) { - this(); - setName(name); - } - - private synchronized static HashDecay setCache() { - if(null == labels) { - labels = new HashDecay(1200000); - labels.start(); - } - return labels; - } - - public HashDecay getCache() { - return setCache(); - } - - /** - * Returns a list of labels that begin with the specified prefix. - * - * @param prefix - * Prefix for all labels to be returned - * @return List of labels matching the prefix. - * @deprecated Use - * {@link #lookupLabels(Env, String) lookupLabels(Env, String)} - * instead. - */ - public static Enumeration lookupLabels(String prefix) { - return lookupMappings(labels, prefix); - } - - /** - * Returns a list of labels that begin with the specified prefix. - * - * @param prefix - * Prefix for all labels to be returned - * @return List of labels matching the prefix. - */ - public static Enumeration lookupLabels(Env env, String prefix) { - loadLabels(env); - return lookupMappings(labels, prefix); - } - - /** - * Loads the list of labels using the default environment. - * - * @deprecated Use {@link #loadLabels(Env) loadLabels(Env, String)} instead. - */ - public static void loadLabels() { - loadLabels(null); - } - - /** - * Loads a list of all the labels into an internal class HashDecay. This - * method will only be called by the class itself if the HashDecay is empty. - * Users should call this method if they believe the p4 label information - * needs to be brought up to date. - * - * @param env - * Environment to use when working with P4 - * @see HashDecay - */ - public static void loadLabels(Env env) { - String l, name; - String[] cmd = { "p4", "labels" }; - StringTokenizer st; - Label b; - - setCache(); - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(!l.startsWith("Label")) { - continue; - } - st = new StringTokenizer(l); - if(6 > st.countTokens()) { - continue; - } - st.nextToken(); - name = st.nextToken(); - synchronized(labels) { - if(null == (b = (Label) labels.get(name))) { - b = new Label(name); - b.setEnv(env); - } else { - b.refreshUpdateTime(); - continue; - } - } - st.nextToken(); - st.nextToken("'"); - b.setDescription(st.nextToken()); - labels.put(b.getName(), b); - } - } catch(Exception ex) { - ex.printStackTrace(); - } - } - - /** - * @param env - * Environment to use when working with P4 - * @return List of all label names (Enumeration of String instances). - */ - public static Enumeration getLabelNames(Env env) { - loadLabels(env); - return labels.keys(); - } - - /** - * @return List of all labels (Enumeration of Label instances). - * @deprecated Use {@link #getLabels(Env) getLabels(Env)} instead. - */ - public static Enumeration getLabels() { - return getLabels(null); - } - - /** - * @param env - * Environment to use when working with P4 - * @return Enumeration of all labels (set of Label instances). - */ - public static Enumeration getLabels(Env env) { - return Utils.getEnumeration(getLabelIterator(env)); - } - - /** - * @param env - * Environment to use when working with P4 - * @return Iterator for all labels (set of Label instances). - */ - public static Iterator getLabelIterator(Env env) { - loadLabels(env); - Enumeration en = labels.elements(); - TreeSet ts = new TreeSet(); - while(en.hasMoreElements()) { - ts.add(en.nextElement()); - } - return ts.iterator(); - } - - /** - * Returns a Label with the specified name, or null if not found. - * - * @param name - * Name of the label to find. - */ - public static synchronized Label getLabel(String name) { - return getLabel(null, name, true); - } - - /** - * Returns a Label with the specified name, or null if not found. - * - * @param env - * Environment to use when working with P4. - * @param name - * Name of the label to find. - * @param force - * Indicates that the Label should be sync'd. - */ - public static synchronized Label getLabel(Env env, String name, boolean force) { - Label b; - if(null == name || name.trim().equals("")) - return null; - if(null == (b = (Label) setCache().get(name))) - b = new Label(name); - if(null != env) - b.setEnv(env); - b.sync(); - labels.put(name, b); - return b; - } - - /** - * Stores the label information back into p4, creating the label if it - * didn't already exist. - * - * @deprecated Use {@link #commit() commit()} instea.d - */ - public void store() throws CommitException { - this.commit(); - } - - public void commit() throws CommitException { - String[] cmd = { "p4", "label", "-i" }; - String l; - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - p.println("Label: " + getName()); - p.println("Owner: " + getOwner()); - if(null != getDescription()) - p.println("Description:\n" + getDescription()); - p.println("View:"); - Enumeration en = getViews(); - while(en.hasMoreElements()) - p.println((String) en.nextElement()); - p.println(""); - p.flush(); - p.outClose(); - while(null != (l = p.readLine())) { - } - p.close(); - } - } catch(Exception ex) { - throw new CommitException(ex.getMessage()); - } - } - - public void sync() { - sync(getName()); - } - - /** - * Synchronizes the Label with the latest information from P4. This method - * forces the Label to contain the latest, correct information if it didn't - * already. - * - * @param name - * Name of the Label to synchronize. - */ - public void sync(String name) { - if(!outOfSync(300000)) - return; - setName(name); - String description = ""; - String l; - String[] cmd = { "p4", "label", "-o", "name" }; - cmd[3] = name; - - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("#")) { - continue; - } - if(l.startsWith("Label:")) { - setName(l.substring(8).trim()); - } else if(l.startsWith("Owner:")) { - setOwner(l.substring(7).trim()); - } else if(l.startsWith("Description:")) { - while(null != (l = p.readLine())) { - if(!l.startsWith("\t")) - break; - description += l + "\n"; - } - setDescription(description); - } else if(l.startsWith("View:")) { - while(null != (l = p.readLine())) { - if(!(l.startsWith("\t") || l.startsWith(" ") || l.startsWith("//"))) - break; - this.addView(l); - } - } - } - p.close(); - inSync(); - } catch(IOException ex) { - } - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - return sb.toString(); - } - - public static void main(String[] args) { - String propfile = "/etc/p4.conf"; - Env environ = null; - Enumeration labels = null; - Label lbl = null; - - Debug.setDebugLevel(Debug.VERBOSE); - if(0 < args.length) - propfile = args[0]; - try { - environ = new Env(propfile); - } catch(PerforceException ex) { - System.out.println("Could not load properties from " + propfile + ": " + ex); - System.exit(-1); - } - System.out.println(environ); - - labels = getLabels(environ); - while(labels.hasMoreElements()) { - lbl = (Label) labels.nextElement(); - System.out.println(lbl.getName()); - } - Utils.cleanUp(); - } -} diff --git a/src/main/java/com/perforce/api/Mapping.java b/src/main/java/com/perforce/api/Mapping.java deleted file mode 100644 index 435eaf4..0000000 --- a/src/main/java/com/perforce/api/Mapping.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control mapping. This handles a named set of file - * mappings. - * - * @author David Markley - * @version $Date: 2002/08/05 $ $Revision: #2 $ - */ -public abstract class Mapping extends SourceControlObject implements Comparable { - private String name = ""; - - private String owner = ""; - - private String description = ""; - - private Hashtable views; - - private Vector view_list; - - /** - * Default no-argument constructor. - */ - public Mapping() { - super(); - views = new Hashtable(); - view_list = new Vector(); - } - - /** - * Constructor that is passed the mapping name. - */ - public Mapping(String name) { - this(); - setName(name); - } - - public int compareTo(Object o) { - return getName().compareTo(((Mapping) o).getName()); - } - - /** - * Sets the name of the Mapping. - * - * @param name - * Name of the mapping. - */ - public void setName(String name) { - HashDecay mappings = getCache(); - synchronized(mappings) { - mappings.remove(this.name); - this.name = name; - if(null != name && !name.trim().equals("")) { - mappings.put(this.name, this); - } - } - } - - /** Returns the name of the Mapping. */ - public String getName() { - return name; - } - - /** - * Sets the owner of the Mapping. - * - * @param owner - * Owner of the mapping. - */ - public void setOwner(String owner) { - this.owner = owner; - } - - /** Returns the owner of the Mapping. */ - public String getOwner() { - return owner; - } - - /** - * Sets the description for the Mapping. - * - * @param description - * Description of the mapping. - */ - public void setDescription(String description) { - this.description = description; - } - - /** Returns the Mapping description. */ - public String getDescription() { - return description; - } - - /** - * Add a view to the Mapping. - * - * @param view - * View for the mapping. - */ - public synchronized void addView(String from, String to) { - views.put(from, to); - if(null == to) { - view_list.addElement(from); - } else { - view_list.addElement(from + " " + to); - } - } - - public void addView(String line) { - int from, to; - line = line.trim(); - if(-1 == (from = line.indexOf("//"))) - return; - if(-1 == (to = line.lastIndexOf("//"))) - return; - if(from == to) { - addView(line.substring(0, to).trim(), null); - } else { - addView(line.substring(0, to).trim(), line.substring(to - 1).trim()); - } - } - - /** - * @return String version of all the views in this mapping. - */ - public synchronized String getView() { - StringBuffer sb = new StringBuffer(); - Enumeration en = views.keys(); - String key, val; - while(en.hasMoreElements()) { - key = (String) en.nextElement(); - val = (String) views.get(key); - sb.append('\t'); - sb.append(key); - if(null != val) { - sb.append(' '); - sb.append(val); - } - sb.append('\n'); - } - return sb.toString(); - } - - /** - * @return Enumerated list of the views in this mapping. - */ - public Enumeration getViews() { - return view_list.elements(); - } - - /** - * Returns a list of mappings that begin with the specified prefix. - * - * @param prefix - * Prefix for all mappings to be returned - * @return List of mappings matching the prefix. - */ - public static Enumeration lookupMappings(HashDecay mappings, String prefix) { - Vector v = new Vector(); - synchronized(mappings) { - Enumeration en = mappings.keys(); - while(en.hasMoreElements()) { - String key = (String) en.nextElement(); - if(key.startsWith(prefix)) { - v.addElement(key); - } - } - } - return v.elements(); - } - - /** - * @return Name of the mapping. - */ - public String toString() { - return name; - } - - public abstract void commit() throws CommitException; - - /** - * Synchronizes the Mapping with the latest information from P4. This method - * forces the Mapping to contain the latest, correct information if it - * didn't already. - * - * @param name - * Name of the Mapping to synchronize. - */ - public abstract void sync(String name); - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - Enumeration en = views.keys(); - String key, val; - while(en.hasMoreElements()) { - key = (String) en.nextElement(); - val = (String) views.get(key); - sb.append(""); - sb.append(key); - sb.append(""); - if(null != val) { - sb.append(""); - sb.append(val); - sb.append(""); - } - sb.append(""); - } - sb.append(""); - return sb.toString(); - } -} diff --git a/src/main/java/com/perforce/api/P4JNI.java b/src/main/java/com/perforce/api/P4JNI.java deleted file mode 100644 index 59edeb0..0000000 --- a/src/main/java/com/perforce/api/P4JNI.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * This class handles the Java Native Interface to the P4 libraries. - * - * @author David Markley - * @version $Date: 2001/11/05 $ $Revision: #1 $ - */ -public class P4JNI extends Thread { - private String cmd[]; - - private Object listener; - - private Env environ; - - private static boolean valid = false; - - private boolean has_pipes = false; - - // This Pipe Set is used for reading from the Perforce shared library. - private BufferedReader in_reader; - - private PipedWriter in_writer; - - // This Pipe Set is used for writing to the Perforce shared library. - private PipedReader out_reader; - - private BufferedWriter out_writer; - - static { - try { - System.loadLibrary("perforce"); - valid = true; - } catch(UnsatisfiedLinkError err) { - valid = false; - } - } - - private native synchronized void exec(String[] cmd, Object listener, String port, String user, String password, - String client); - - public P4JNI() { - setupPipes(); - } - - private void setupPipes() { - if(has_pipes) - return; - try { - in_writer = new PipedWriter(); - in_reader = new BufferedReader(new PipedReader(in_writer)); - out_reader = new PipedReader(); - out_writer = new BufferedWriter(new PipedWriter(out_reader)); - has_pipes = true; - } catch(IOException ex) { - } - } - - public static boolean isValid() { - return valid; - } - - public boolean isPiped() { - return has_pipes; - } - - public BufferedReader getReader() { - return in_reader; - } - - public BufferedWriter getWriter() { - return out_writer; - } - - public void runCommand(Object listener, String[] cmd, Env environ) { - this.listener = listener; - this.cmd = cmd; - this.environ = environ; - start(); - } - - public synchronized void in_write(char[] cbuf, int off, int len) { - try { - in_writer.write(cbuf, off, len); - } catch(IOException ex) { - } - } - - public synchronized void in_close() { - try { - in_writer.close(); - } catch(IOException ex) { - } - } - - public synchronized void in_flush() { - try { - in_writer.flush(); - } catch(IOException ex) { - } - } - - public synchronized int out_read(char[] cbuf, int off, int len) { - try { - return out_reader.read(cbuf, off, len); - } catch(IOException ex) { - return -1; - } - } - - public void run() { - exec(cmd, listener, environ.getPort(), environ.getUser(), environ.getPassword(), environ.getClient()); - } - - public static void main(String[] args) { - String cmd[] = { "p4", "dirs", "//depot/pd/ttg/%1" }; - String cmd2[] = { "p4", "fstat", "//depot/pd/ttg/..." }; - String cmd3[] = { "p4", "client", "-i" }; - - if(!P4JNI.isValid()) { - System.err.println("No Perforce shared library available."); - System.exit(-1); - } - - String txt = "Client: dmarkley-testit\nOwner: vss\nDescription:\n\tCreated by JNI interface.\n\nRoot: d:\\foobarbaz\n\nOptions: noallwrite noclobber compress crlf locked nomodtime\n\nView:\n\t//depot/pd/ttg/... //dmarkley-testit/ttg/...\n\n"; - char foo[] = txt.toCharArray(); - - P4JNI tmpA = new P4JNI(); - P4JNI tmpB = new P4JNI(); - Env myEnv = new Env(); - BufferedReader br; - BufferedWriter bw; - String l; - - myEnv.setPort("localhost:1666"); - myEnv.setUser("vss"); - myEnv.setPassword("Blows"); - myEnv.setClient("vss-dmarkley"); - tmpA.runCommand(tmpB, cmd3, myEnv); - br = tmpB.getReader(); - bw = tmpB.getWriter(); - try { - bw.write(foo, 0, foo.length); - bw.close(); - } catch(IOException ex) { - ex.printStackTrace(); - } - try { - while(null != (l = br.readLine())) { - System.out.println("LINE: " + l); - } - } catch(IOException ex) { - ex.printStackTrace(); - } - } -} diff --git a/src/main/java/com/perforce/api/P4Process.java b/src/main/java/com/perforce/api/P4Process.java deleted file mode 100644 index 1c88fa8..0000000 --- a/src/main/java/com/perforce/api/P4Process.java +++ /dev/null @@ -1,585 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; -import java.text.DateFormat; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Handles the execution of all perforce commands. This class can be used - * directly, but the preferred use of this API is through the - * {@link com.perforce.api.SourceControlObject SourceControlObject} subclasses. - *

- * Example Usage: - * - *

- * String l;
- * Env env = new Env();
- * String[] cmd = { "p4", "branches" };
- * try {
- * 	P4Process p = new P4Process(env);
- * 	p.exec(cmd);
- * 	while(null != (l = p.readLine())) {
- * 		// Parse the output.
- * 	}
- * 	p.close();
- * } catch(Exception ex) {
- * 	throw new PerforceException(ex.getMessage());
- * }
- * 
- * - * @author David Markley - * @version $Date: 2002/01/15 $ $Revision: #3 $ - * @see Env - * @see SourceControlObject - * @see Thread - */ -public class P4Process { - private static P4Process base = null; - - private P4JNI jni_proc = null; - - private boolean using_native = false; - - private Env environ = null; - - private Runtime rt = Runtime.getRuntime(); - - private Process p; - - private BufferedReader in, err; - - private Writer out; - - private int exit_code = 0; - - private EventLog log; - - private String P4_ERROR = null; - - private String[] new_cmd; - - private long threshold = 10000; // The default is 10 seconds; - - private boolean raw = false; - - /** - * Default no-argument constructor. If the runtime has not been established, - * this constructor will set it up. No environment is specified, so the base - * environment will be used if it exists. - * - * @see #getBase() - */ - public P4Process() { - this(null); - } - - /** - * Constructor that specifies the source control environment. - * - * @param e - * Source control environment to use. - */ - public P4Process(Env e) { - super(); - if(null == rt) { - rt = Runtime.getRuntime(); - } - if(null == e) { - if(null == base) { - base = this; - this.environ = new Env(); - } else { - this.environ = new Env(base.getEnv()); - } - } else { - this.environ = e; - } - if(null != environ) - this.threshold = environ.getServerTimeout(); - } - - /** - * Sets the environment to use. - * - * @param e - * Source control environment. - */ - public void setEnv(Env e) { - this.environ = e; - if(null != environ) - this.threshold = environ.getServerTimeout(); - } - - /** - * Returns the environment in use by this process. - * - * @return Source control environment. - */ - public Env getEnv() { - return this.environ; - } - - /** - * Returns the base process for this class. The base process is set when - * this class is first instantiated. The base process is used when other - * P4Process are instantiated to share settings, including - * the {@link com.perforce.api.Env source control environment}. - * - * @see Env - * @return Source control environment. - */ - public static P4Process getBase() { - if(null != base) { - return base; - } else { - return new P4Process(); - } - } - - /** - * Sets the base process to be used when new processes are instantiated. - * - * @see #getBase() - */ - public static void setBase(P4Process b) { - if(null != b) { - base = b; - } - } - - public Writer getWriter() { - return out; - } - - /** - * Returns the exit code returned when the underlying process exits. - * - * @return Typical UNIX style return code. - */ - public int getExitCode() { - return exit_code; - } - - /** - * In raw mode, the process will return the prefix added by the "-s" command - * line option. The default is false. - */ - public void setRawMode(boolean raw) { - this.raw = raw; - } - - /** - * Returns the status of raw mode for this process. - */ - public boolean getRawMode() { - return this.raw; - } - - /** - * Executes a p4 command. This uses the class environment information to - * execute the p4 command specified in the String array. This array contains - * all the command line arguments that will be specified for execution, - * including "p4" in the first position. - * - * @param cmd - * Array of command line arguments ("p4" must be first). - */ - public synchronized void exec(String[] cmd) throws IOException { - String[] pre_cmds = new String[12]; - int i = 0; - pre_cmds[i++] = cmd[0]; - pre_cmds[i++] = "-s";// Forces all commands to use stdout for message - // reporting, no longer read stderr - if(!getEnv().getPort().trim().equals("")) { - pre_cmds[i++] = "-p"; - pre_cmds[i++] = getEnv().getPort(); - } - if(!getEnv().getUser().trim().equals("")) { - pre_cmds[i++] = "-u"; - pre_cmds[i++] = getEnv().getUser(); - } - if(!getEnv().getClient().trim().equals("")) { - pre_cmds[i++] = "-c"; - pre_cmds[i++] = getEnv().getClient(); - } - if(!getEnv().getPassword().trim().equals("")) { - pre_cmds[i++] = "-P"; - pre_cmds[i++] = getEnv().getPassword(); - } - if(cmd[1].equals("-x")) { - pre_cmds[i++] = "-x"; - pre_cmds[i++] = cmd[2]; - } - new_cmd = new String[(i + cmd.length) - 1]; - for(int j = 0; j < (i + cmd.length) - 1; j++) { - if(j < i) { - new_cmd[j] = pre_cmds[j]; - } else { - new_cmd[j] = cmd[(j - i) + 1]; - } - } - Debug.verbose("P4Process.exec: ", new_cmd); - if(P4JNI.isValid()) { - native_exec(new_cmd); - using_native = true; - } else { - pure_exec(new_cmd); - using_native = false; - } - } - - /** - * Executes the command utilizing the P4API. This method will be used only - * if the supporting Java Native Interface library could be loaded. - */ - private synchronized void native_exec(String[] cmd) throws IOException { - jni_proc = new P4JNI(); - // P4JNI tmp = new P4JNI(); - jni_proc.runCommand(jni_proc, cmd, environ); - in = jni_proc.getReader(); - err = in; - out = jni_proc.getWriter(); - } - - /** - * Executes the command through a system 'exec'. This method will be used - * only if the supporting Java Native Interface library could not be loaded. - */ - private synchronized void pure_exec(String[] cmd) throws IOException { - if(null != this.environ.getExecutable()) { - cmd[0] = this.environ.getExecutable(); - } - p = rt.exec(cmd, this.environ.getEnvp()); - InputStream is = p.getInputStream(); - Debug.verbose("P4Process.exec().is: " + is); - InputStreamReader isr = new InputStreamReader(is); - Debug.verbose("P4Process.exec().isr: " + isr); - in = new BufferedReader(isr); - InputStream es = p.getErrorStream(); - Debug.verbose("P4Process.exec().es: " + es); - InputStreamReader esr = new InputStreamReader(es); - Debug.verbose("P4Process.exec().esr: " + esr); - err = new BufferedReader(esr); - - OutputStream os = p.getOutputStream(); - Debug.verbose("P4Process.exec().os: " + os); - OutputStreamWriter osw = new OutputStreamWriter(os); - Debug.verbose("P4Process.exec().osw: " + osw); - out = new FilterWriter(new BufferedWriter(osw)) { - public void write(String str) throws IOException { - super.write(str); - System.out.print("P4DebugOutput: " + str); - } - - }; - } - - /** - * Sets the event log. Any events that should be logged will be logged - * through the EventLog specified here. - * - * @param log - * Log for all events. - */ - public synchronized void setEventLog(EventLog log) { - this.log = log; - } - - /** - * Logs the event message to the output stream. - * - * @param out - * Stream to which the message is logged. - * @param event - * Message to be logged. - */ - private void log(PrintStream out, String event) { - if(null == log) { - out.println(event); - out.flush(); - } else { - log.log(event); - } - } - - /** - * Writes line to the standard input of the process. - * - * @param line - * Line to be written. - */ - public synchronized void print(String line) throws IOException { - out.write(line); - } - - /** - * Writes line to the standard input of the process. A - * newline is appended to the output. - * - * @param line - * Line to be written. - */ - public synchronized void println(String line) throws IOException { - out.write(line + "\n"); - } - - /** - * Flushes the output stream to the process. - */ - public synchronized void flush() throws IOException { - out.flush(); - } - - /** - * Flushes and closes the output stream to the process. - */ - public synchronized void outClose() throws IOException { - out.flush(); - out.close(); - } - - /** - * Returns the next line from the process, or null if the command has - * completed its execution. - */ - public synchronized String readLine() { - if(using_native && null != jni_proc && jni_proc.isPiped()) { - return native_readLine(); - } else { - return pure_readLine(); - } - } - - /** - * Reads the next line from the process. This method will be used only if - * the supporting Java Native Interface library could be loaded. - */ - private synchronized String native_readLine() { - try { - return in.readLine(); - } catch(IOException ex) { - return null; - } - } - - /** - * Reads the next line from the process. This method will be used only if - * the supporting Java Native Interface library could not be loaded. - */ - private synchronized String pure_readLine() { - String line; - long current, timeout = ((new Date()).getTime()) + threshold; - - if(null == p || null == in || null == err) - return null; - // Debug.verbose("P4Process.readLine()"); - try { - for(;;) { - if(null == p || null == in || null == err) { - Debug.error("P4Process.readLine(): Something went null"); - return null; - } - - current = (new Date()).getTime(); - if(current >= timeout) { - Debug.error("P4Process.readLine(): Timeout"); - // If this was generating a new object from stdin, return an - // empty string. Otherwise, return null. - for(int i = 0; i < new_cmd.length; i++) { - if(new_cmd[i].equals("-i")) - return ""; - } - return null; - } - - // Debug.verbose("P4Process.readLine().in: "+in); - try { - /** - * If there's something coming in from stdin, return it. We - * assume that the p4 command was called with -s which sends - * all messages to standard out pre-pended with a string - * that indicates what kind of messsage it is error warning - * text info exit - */ - // Some errors still come in on Standard error - while(err.ready()) { - line = err.readLine(); - if(null != line) { - addP4Error(line + "\n"); - } - } - - if(in.ready()) { - line = in.readLine(); - Debug.verbose("From P4:" + line); - if(line.startsWith("error")) { - if(!line.trim().equals("") && (-1 == line.indexOf("up-to-date")) - && (-1 == line.indexOf("no file(s) to resolve"))) { - addP4Error(line); - } - } else if(line.startsWith("warning")) { - } else if(line.startsWith("text")) { - } else if(line.startsWith("info")) { - } else if(line.startsWith("exit")) { - int exit_code = new Integer(line.substring(line.indexOf(" ") + 1, line.length())) - .intValue(); - if(0 == exit_code) { - Debug.verbose("P4 Exec Complete."); - } else { - Debug.error("P4 exited with an Error!"); - } - return null; - } - if(!raw) - line = line.substring(line.indexOf(":") + 1).trim(); - Debug.verbose("P4Process.readLine(): " + line); - return line; - } - } catch(NullPointerException ne) { - } - // If there's nothing on stdin or stderr, check to see if the - // process has exited. If it has, return null. - try { - exit_code = p.exitValue(); - return null; - } catch(IllegalThreadStateException ie) { - Debug.verbose("P4Process: Thread is not done yet."); - } - // Sleep for a second, so this thread can't become a CPU hog. - try { - Debug.verbose("P4Process: Sleeping..."); - Thread.sleep(100); // Sleep for 1/10th of a second. - } catch(InterruptedException ie) { - } - } - } catch(IOException ex) { - return null; - } - } - - /** - * Waits for the process to exit and closes out the process. This method - * should be called after the {@link #exec(java.lang.String[]) exec} method - * in order to close things down properly. - * - * @param out - * The stream to which any errors should be sent. - * @return The exit value of the underlying process. - */ - public synchronized int close(PrintStream out) throws IOException { - if(using_native && null != jni_proc && jni_proc.isPiped()) { - native_close(out); - } else { - pure_close(out); - } - /* - * if (0 != exit_code) { throw new IOException("P4Process ERROR: p4 sync - * exited with error ("+ exit_code+")"); } - */ - if(null != P4_ERROR) { - throw new IOException(P4_ERROR); - } - return exit_code; - } - - /** - * Closes down connections to the underlying process. This method will be - * used only if the supporting Java Native Interface library could be - * loaded. - */ - private synchronized void native_close(PrintStream out) { - try { - in.close(); - out.flush(); - out.close(); - } catch(IOException ioe) { - } - } - - /** - * Closes down connections to the underlying process. This method will be - * used only if the supporting Java Native Interface library could not be - * loaded. - */ - private synchronized void pure_close(PrintStream out) { - /* - * Try to close this process for at least 30 seconds. - */ - for(int i = 0; i < 30; i++) { - try { - in.close(); - err.close(); - out.flush(); - out.close(); - } catch(IOException ioe) { - } - try { - exit_code = p.waitFor(); - p.destroy(); - break; - } catch(InterruptedException ie) { - } - try { - Thread.sleep(1000); - } catch(InterruptedException ie) { - } - } - } - - /** - * Waits for the underlying process to exit and closes it down. This method - * should be called after the {@link #exec(java.lang.String[]) exec} method - * in order to close things out properly. Errors are sent to System.err. - * - * @see System - * @return The exit value of the underlying process. - */ - public int close() throws IOException { - return close(System.err); - } - - /** Set the server timeout threshold. */ - public void setServerTimeout(long threshold) { - this.threshold = threshold; - } - - /** Return the server timeout threshold. */ - public long getServerTimeout() { - return threshold; - } - - public String toString() { - return this.environ.toString(); - } - - private void addP4Error(String message) { - if(null == P4_ERROR) { - P4_ERROR = message; - } else { - P4_ERROR += message; - } - } -} diff --git a/src/main/java/com/perforce/api/PerforceException.java b/src/main/java/com/perforce/api/PerforceException.java deleted file mode 100644 index 0f37915..0000000 --- a/src/main/java/com/perforce/api/PerforceException.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.perforce.api; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Signals that a general exception occurred when working with Perforce. - * - * @author David Markley - * @version $Date: 2001/11/05 $ $Revision: #1 $ - */ -public class PerforceException extends Exception { - - public PerforceException(String msg) { - super(msg); - } -} diff --git a/src/main/java/com/perforce/api/RobotMessage.java b/src/main/java/com/perforce/api/RobotMessage.java deleted file mode 100644 index f44883f..0000000 --- a/src/main/java/com/perforce/api/RobotMessage.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Container class for messages to and from the P4Robot. This message is sent to - * the robot by the P4ReviewerService and any other application that wants to - * instruct the P4Robot to synchronize with the P4 depot in a particular way. - *

- * The key to this is the views that are a part of this. Each view will be used - * in executing "p4 sync" on the P4Robot. If the SYNC_FORCE flag is specified, - * then the views are all executed with "p4 sync -f". If the SYNC_ALL flag is - * specified, the views are ignored and one "p4 sync //..." is executed (with - * the -f flag, if that is also specified). - * - * @author David Markley - * @version $Date: 2001/11/05 $ $Revision: #1 $ - * @deprecated This shoud be a part of the P4WebPublisher package. - */ -public class RobotMessage implements Serializable { - /** Indicates that the "p4 sync" should be run with the -f option */ - public final static int SYNC_FORCE = 1; - - /** Indicates that the views should be ignored and "p4 sync //..." is run */ - public final static int SYNC_ALL = 2; - - /** @serial */ - private Vector views = new Vector(); - - /** @serial */ - private String label = ""; - - /** @serial */ - private int change = -1; - - /** @serial */ - private int flags = 0; - - /** - * Default no-argument constructor. - */ - public RobotMessage() { - } - - /** - * Constructs a RobotMessage using the specified Change. What this does is - * load the views for this with the files that were affected by the Change. - * This allows for a more focused sync on the robot side. - * - * @param change - * Change to be used in constructing this. - */ - public RobotMessage(Change change) { - this(); - - views = change.getFiles(); - } - - /** - * Add a view. The view will be appended to a "p4 sync" executed by the - * robot. Thus, any valid file specification that is valid with "p4 sync" - * can be used: file[revRange] - * - * @param view - * Single view to be added. - */ - public void addView(String view) { - views.addElement(view); - } - - /** - * Clear all view information. This is useful, if the RobotMessage instance - * is to be reused in another send to a robot. - */ - public void clearViews() { - views.removeAllElements(); - } - - /** - * Returns the number of views in this. - */ - public int getViewCount() { - return views.size(); - } - - /** - * Returns an enumeration of the views. This is most useful on the robot end - * of things. - */ - public Enumeration getViews() { - return views.elements(); - } - - /** - * Sets the flags. - * - * @see #SYNC_FORCE - * @see #SYNC_ALL - * @param flags - * New value for the flags - */ - public void setFlags(int flags) { - this.flags = flags; - } - - /** - * Returns the flags that are set. - * - * @see #SYNC_FORCE - * @see #SYNC_ALL - */ - public int getFlags() { - return flags; - } - - private void writeObject(ObjectOutputStream out) throws IOException { - if(null == views) { - views = new Vector(); - } - out.writeObject(views); - out.writeObject(label); - out.writeInt(change); - out.writeInt(flags); - } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - views = (Vector) in.readObject(); - label = (String) in.readObject(); - change = in.readInt(); - flags = in.readInt(); - } - -} diff --git a/src/main/java/com/perforce/api/SourceControlObject.java b/src/main/java/com/perforce/api/SourceControlObject.java deleted file mode 100644 index 66cf735..0000000 --- a/src/main/java/com/perforce/api/SourceControlObject.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * An abstract base class for all source control objects. - * - * @author David Markley - * @version $Date: 2002/01/15 $ $Revision: #2 $ - */ -public abstract class SourceControlObject implements Cacheable { - private long update_time = 0; - - private long sync_time = 0; - - private Env environ; - - /** Default, no-argument constructor. */ - public SourceControlObject() { - update_time = 0; - sync_time = 0; - } - - /** - * Constructor that takes an environment for this object to use. - * - * @param env - * source control environement to use. - */ - public SourceControlObject(Env env) { - this(); - setEnv(env); - } - - /** - * Sets the P4 environment to be used when working with this object. This - * environment is required to store, sync, or otherwise work with the P4 - * depot. It is passed to the P4Process used in each of these transactions. - * - * @see Env - * @see P4Process - * @param env - * user environment to use. - */ - public void setEnv(Env env) { - this.environ = env; - } - - /** - * Returns the P4 environment associated with this instance. - * - * @return P4 environment. - */ - public Env getEnv() { - return this.environ; - } - - /** Returns the time, in milliseconds, for this object's last update. */ - public synchronized long getUpdateTime() { - return update_time; - } - - /** Sets the update time for this object to the current time. */ - public synchronized void refreshUpdateTime() { - update_time = (new Date()).getTime(); - } - - /** Returns the time, in milliseconds, that this object was synchronized. */ - public synchronized long getSyncTime() { - return sync_time; - } - - /** - * Tests this object to see if it is out of sync. Checks to see if the - * expiration time is within the specified number of milliseconds. - * - * @param threshold - * Number of milliseconds. - * @return True if the object will be out of sync within the threshold. - */ - public synchronized boolean outOfSync(long threshold) { - return (threshold < ((new Date()).getTime() - sync_time)); - } - - /** Invalidates this object. */ - public synchronized void invalidate() { - sync_time = 0; - } - - /** Marks this object as being in in sync or valid. */ - public synchronized void inSync() { - sync_time = (new Date()).getTime(); - } - - /** Removes any cached objects. */ - public void clearCache() { - getCache().clear(); - } - - /** Returns the HashDecay instance for this class */ - public abstract HashDecay getCache(); - - /** - * Stores this object back into Perforce, creating it if it didn't already - * exist. - */ - public abstract void commit() throws CommitException; - - /** - * Brings this object back into sync with Perforce. This also sets the sets - * the update and sync time for this object. - */ - public abstract void sync() throws PerforceException; - - /** - * Returns a string containing the object in XML form. - */ - public abstract String toXML(); -} diff --git a/src/main/java/com/perforce/api/SubmitException.java b/src/main/java/com/perforce/api/SubmitException.java deleted file mode 100644 index 762e3c4..0000000 --- a/src/main/java/com/perforce/api/SubmitException.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.perforce.api; - -import java.io.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Signals that an exception occurred during a submit to Perforce. - * - * @author David Markley - * @version $Date: 2001/11/05 $ $Revision: #1 $ - */ -public final class SubmitException extends PerforceException { - - public SubmitException(String msg) { - super(msg); - } -} diff --git a/src/main/java/com/perforce/api/User.java b/src/main/java/com/perforce/api/User.java deleted file mode 100644 index f318bc7..0000000 --- a/src/main/java/com/perforce/api/User.java +++ /dev/null @@ -1,336 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Representation of a source control user. Each instance can store one p4 - * user's information. The class methods can be used to get a particular user. If that user - * has been gotten before, their user information will not be reloaded from P4. - * It is instead loaded from an internal HashDecay. - *

- * If the user information must be up to date, then the sync() - * method must be called. - *

- * TBD: The current implementation does NOT handle the "reviews" information for - * each user. Should User extend Mapping? - * - * @see HashDecay - * @author David Markley - * @version $Date: 2002/05/16 $ $Revision: #2 $ - */ -public final class User extends SourceControlObject { - private String id = ""; - - private String email = ""; - - private String fullname = ""; - - private static HashDecay users = null; - - /** - * Default no-argument constructor. - */ - public User() { - super(); - getCache(); - } - - /** - * Constructor that accepts the id of the user. This simply creates an - * instance that has the id set. No other information in the class will be - * present until the sync() method is called. - * - * @param id - * Id for the user. - */ - public User(String id) { - this(); - this.id = id; - } - - private static HashDecay setCache() { - if(null == users) { - users = new HashDecay(600000); - users.start(); - } - return users; - } - - public HashDecay getCache() { - return setCache(); - } - - /** - * Sets the id for this user. - * - * @param id - * Id for the user. - */ - public void setId(String id) { - this.id = id; - } - - /** - * Returns an Enumeration of all User objects. - */ - public static synchronized Enumeration getUsers() { - return getUsers(null); - } - - /** - * Returns an Enumeration of all User objects. - */ - public static synchronized Enumeration getUsers(Env env) { - String l; - User u; - String[] cmd = { "p4", "users" }; - - try { - P4Process p = new P4Process(env); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("#")) { - continue; - } - u = getUser(l); - u.setEnv(env); - } - p.close(); - } catch(IOException ex) { - } - - return setCache().elements(); - } - - /** - * Gets the user information for the specified user. If that user has been - * gotten before, their user information will not be reloaded from P4. It is - * instead loaded from an internal HashDecay. - *

- * If the user information must be up to date, then the sync() method must be called. - * - * @deprecated Use method with Env parameter. - * @param uid - * User id that is requested. - */ - public static synchronized User getUser(String uid) { - return getUser(null, uid); - } - - /** - * Gets the user information for the specified user. If that user has been - * gotten before, their user information will not be reloaded from P4. It is - * instead loaded from an internal HashDecay. - *

- * If the user information must be up to date, then the sync() method must be called. - * - * @param env - * Source control environment to use. - * @param uid - * The user id of the user information to get from p4. - */ - public static synchronized User getUser(Env env, String uid) { - if(null == uid) { - return null; - } - if(uid.trim().equals("")) { - return null; - } - - String tid; - int i, left = 0; - uid = uid.trim(); - if(-1 == (left = uid.indexOf("<"))) { - tid = uid; - } else { - tid = uid.substring(0, left - 1).trim(); - } - User u = (User) setCache().get(uid); - if(null != u) { - return u; - } else { - u = new User(tid); - } - u.setEmail(tid); - u.setFullName(tid); - if(-1 != left) { - uid = uid.substring(left + 1); - char[] ch = uid.toCharArray(); - left = 0; - for(i = 0; i < ch.length; i++) { - switch(ch[i]) { - case '>': - u.setEmail(new String(ch, left, i - left)); - break; - case '(': - left = i + 1; - break; - case ')': - u.setFullName(new String(ch, left, i - left)); - break; - } - } - } - u.setEnv(env); - users.put(tid, u); - return u; - } - - /** - * Returns the id for this user. - * - * @return Id for the user. - */ - public String getId() { - return id; - } - - /** - * Sets the e-mail address for this user. - * - * @param email - * Email address for the user. - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * Returns the e-mail address for this user. - * - * @return Email address for the user. - */ - public String getEmail() { - return email; - } - - /** - * Sets the full name of this user. - * - * @param fullname - * The full name for the user. - */ - public void setFullName(String fullname) { - this.fullname = fullname; - } - - /** - * Returns the full name of this user. - * - * @return The full name for the user. - */ - public String getFullName() { - return fullname; - } - - /** - * TBD: The commit method is not working yet. - */ - public void commit() { - } - - /** - * Synchronizes the user information with P4. This method must be called to - * ensure that this contains the latest information from p4. This form of - * the method can be used to change the user Id in at the same time. - * - * @param id - * The user id for this to synchronize from p4. - */ - public void sync(String id) { - this.id = id; - sync(); - } - - /** - * Synchronizes the user information with P4. This method must be called to - * ensure that this contains the latest information from p4. - */ - public void sync() { - if(!outOfSync(300000)) - return; - String l; - String[] cmd = { "p4", "user", "-o", "id" }; - cmd[3] = id; - - try { - P4Process p = new P4Process(getEnv()); - p.exec(cmd); - while(null != (l = p.readLine())) { - if(l.startsWith("#")) { - continue; - } - if(l.startsWith("User:")) { - id = l.substring(6).trim(); - } else if(l.startsWith("Email:")) { - email = l.substring(7).trim(); - } else if(l.startsWith("FullName:")) { - fullname = l.substring(10).trim(); - } - } - p.close(); - inSync(); - } catch(IOException ex) { - } - } - - public String toString() { - return id; - } - - public String toXML() { - StringBuffer sb = new StringBuffer(""); - return sb.toString(); - } - - /** - * Used for testing. - * - * @deprecated Actually in use, but this keeps it out of the docs. - */ - public static void main(String[] argv) { - User u; - Env env = new Env(); - Debug.setDebugLevel(Debug.NOTICE); - env.setUser("robot"); - env.setPort("perforce.ma.lycos.com:1666"); - Enumeration en = User.getUsers(env); - while(en.hasMoreElements()) { - u = (User) en.nextElement(); - System.out.println("USER: " + u.getId()); - } - } -} diff --git a/src/main/java/com/perforce/api/Utils.java b/src/main/java/com/perforce/api/Utils.java deleted file mode 100644 index 5950403..0000000 --- a/src/main/java/com/perforce/api/Utils.java +++ /dev/null @@ -1,325 +0,0 @@ -package com.perforce.api; - -import java.io.*; -import java.util.*; -import java.text.*; -import java.net.*; - -/* - * Copyright (c) 2001, Perforce Software, All rights reserved. - * - * 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. - */ - -/** - * Class that contains static utility methods. - * - * @see HashDecay - * @author David Markley - * @version $Date: 2002/08/12 $ $Revision: #6 $ - */ -public final class Utils { - - /** - * Initializes the package, in order to avoid some arbitrary JVM problems - * that have been encountered. This is a hack and should not have to be done - * if certain overbearing empires starting with the letter M built a fully - * compliant JVM. - */ - public static void initPackage() { - (new Branch()).getCache(); - (new Change()).getCache(); - (new Client()).getCache(); - (new DirEntry()).getCache(); - (new FileEntry()).getCache(); - (new Job()).getCache(); - (new Label()).getCache(); - (new User()).getCache(); - Properties props = System.getProperties(); - } - - /** - * Check to see if the current Java Virtual Machine is made by Microsoft - * - * @return boolean true if the java.vendor property comtains the word - * 'Microsoft' - */ - public static boolean isMSJVM() { - return (System.getProperty("java.vendor").indexOf("Microsoft") != -1); - } - - /** - * Check to see if the current operating system is a Windows OS - * - * @return boolean true if the os.name property comtains the word 'Windows' - */ - public static boolean isWindows() { - return (System.getProperty("os.name").indexOf("Windows") != -1); - } - - /** - * Returns true if the path matches the wildpath. - * Only perforce wildcards are considered in the wildpath. - */ - public static boolean wildPathMatch(String wildpath, String path) { - // System.out.println("Matching: "+wildpath+" to "+path); - wildpath = wildpath.trim(); - path = path.trim(); - boolean match = true; - boolean in_dots = false; - int i, j, plen = path.length(), wplen = wildpath.length(); - char wc, pc; - for(j = 0, i = 0; i < wplen && j < plen; i++) { - if('%' == (wc = wildpath.charAt(i))) { - wc = wildpath.charAt(++i); - if('0' > wc || '9' < wc) { - match = false; - break; - } - while('/' != path.charAt(j) && j < plen) { - j++; - } - continue; - } else if('*' == wc) { - while('/' != path.charAt(j) && j < plen) { - j++; - } - continue; - } - if('.' == wc && wildpath.regionMatches(i, "...", 0, 3)) { - i += 2; - in_dots = true; - continue; - } - if(path.charAt(j++) != wc) { - if(!in_dots) { - match = false; - break; - } else { - i--; - } - } else if(in_dots) { - String wpath2 = wildpath.substring(i); - String path2 = path.substring(j - 1); - if(wildPathMatch(wpath2, path2)) { - return true; - } else { - i--; - } - } - } - if(j < plen) - return in_dots; - if(i < wplen) - return false; - return match; - } - - /** - * Returns the string encoded for HTML use. - *

> becomes > and < becomes < - */ - public static String HTMLEncode(String str) { - if(null == str) - return "null"; - StringBuffer strbuf = new StringBuffer(str.length()); - char tmp; - for(int i = 0; i < str.length(); i++) { - tmp = str.charAt(i); - if('<' == tmp) { - strbuf.append("<"); - } else if('>' == tmp) { - strbuf.append(">"); - } else { - strbuf.append(tmp); - } - } - return strbuf.toString(); - } - - /** - * Returns common prefix for a Vector of strings. This is very useful for - * determining a commong prefix for a set of paths. - */ - public static String commonPrefix(Vector v) { - return commonPrefix(v.elements()); - } - - /** - * Returns common prefix for an Enumeration of strings. - */ - public static String commonPrefix(Enumeration en) { - if(null == en || !en.hasMoreElements()) - return ""; - String common = (String) en.nextElement(); - String str = null; - int i, len; - char[] ar1, ar2; - - ar1 = common.toCharArray(); - while(en.hasMoreElements()) { - str = (String) en.nextElement(); - ar2 = str.toCharArray(); - if(str.startsWith(common)) - continue; - len = common.length(); - if(len > str.length()) - len = str.length(); - for(i = 0; i < len; i++) { - if(ar1[i] != ar2[i]) - break; - } - if(0 == i) - return ""; - common = common.substring(0, i); - ar1 = common.toCharArray(); - } - if(-1 != (i = common.indexOf('#'))) - common = common.substring(0, i); - if(-1 != (i = common.indexOf('@'))) - common = common.substring(0, i); - return common; - } - - /** - * Returns the change number portion of a depot path, if there is a valid - * one found. Otherwise, it returns -1. - */ - public final static int getChangeFromPath(String path) { - int i = path.indexOf('@'); - if(0 > i) - return -1; - try { - return Integer.valueOf(path.substring(i + 1)).intValue(); - } catch(NumberFormatException ex) { - return -1; - } - } - - /** - * Cleans up after the package has been used. This stops any running threads - * and releases any objects for garbage collection. - */ - public static void cleanUp() { - HashDecay.stopAll(); - System.gc(); - } - - /** - * Breaks up a depot path and formats each level. Each format string takes - * two arguments. The first is set to the full path to a particular element. - * The second is set to the short name for the element. - *

- * This is extremely useful for setting up links from each component of a - * path. - * - * @param path - * The path to be formatted. - * @param pathfmt - * The format to be used for path elements. - * @param filefmt - * The format to be used for the file element. - * @param revfmt - * The format to be used for the rev component. - * @param urlencode - * Determines if paths are encoded. - * @see URLEncoder - */ - public static StringBuffer formatDepotPath(String path, String pathfmt, String filefmt, String revfmt, - boolean urlencode) throws PerforceException { - StringBuffer sb = new StringBuffer("//"); - Object[] args = { "path", "part" }; - int p1 = 1, p2 = 0; - - if(null == path || (!path.startsWith("//"))) { - throw new PerforceException(path + " is not a depot path."); - } - - // Don't bother parsing anything if all the formats are null. - if(null == pathfmt && null == filefmt && null == revfmt) { - return new StringBuffer(path); - } - - if(null == pathfmt) { - p1 = path.lastIndexOf("/"); - sb.append(path.substring(2, p1 + 1)); - } else { - while(-1 != (p2 = path.indexOf("/", p1 + 1))) { - args[0] = path.substring(0, p2); - if(urlencode) - args[0] = URLEncoder.encode((String) args[0]); - args[1] = path.substring(p1 + 1, p2); - sb.append(MessageFormat.format(pathfmt, args)); - sb.append('/'); - p1 = p2; - } - } - - String rev = null; - if(-1 == (p2 = path.indexOf("#", p1 + 1))) { - p2 = path.length(); - } else { - rev = path.substring(p2 + 1); - } - args[0] = path.substring(0, p2); - if(urlencode) - args[0] = URLEncoder.encode((String) args[0]); - String fname = path.substring(p1 + 1, p2); - args[1] = fname; - if(null == filefmt) { - sb.append(args[1]); - } else { - sb.append(MessageFormat.format(filefmt, args)); - } - - if(null != rev) { - sb.append('#'); - args[0] = path; - if(urlencode) - args[0] = URLEncoder.encode((String) args[0]); - args[1] = rev; - if(null == revfmt) { - sb.append(args[1]); - } else { - sb.append(MessageFormat.format(revfmt, args)); - } - } - return sb; - } - - public static Enumeration getEnumeration(Iterator i) { - Vector v = new Vector(); - while(i.hasNext()) - v.addElement(i.next()); - return v.elements(); - } - - /** - * @deprecated Useful for testing, but should not be documented. - */ - public static void main(String[] argv) { - Vector v = new Vector(argv.length); - for(int i = 0; i < argv.length; i++) { - v.addElement(argv[i]); - System.out.println(argv[i] + ": " + getChangeFromPath(argv[i])); - } - System.out.println("Common: " + commonPrefix(v)); - } -} diff --git a/src/main/java/com/perforce/api/package.html b/src/main/java/com/perforce/api/package.html deleted file mode 100644 index e7ea559..0000000 --- a/src/main/java/com/perforce/api/package.html +++ /dev/null @@ -1,21 +0,0 @@ - - - -com.tek42.perforce package - - - - -

-Provides legacy perforce.com API classes. These classes can be used as a backup if -the new API does not provide a particular need for you. The new API contains the -Depot object which has support for generating a legacy Env object. You can use this -for all legacy API calls that require an Env parameter. -

- - - diff --git a/src/main/java/com/tek42/perforce/Depot.java b/src/main/java/com/tek42/perforce/Depot.java deleted file mode 100644 index b21a8a1..0000000 --- a/src/main/java/com/tek42/perforce/Depot.java +++ /dev/null @@ -1,539 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce; - -import java.util.HashMap; -import java.util.StringTokenizer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.perforce.api.Env; -import com.tek42.perforce.parse.*; -import com.tek42.perforce.process.DefaultExecutorFactory; -import com.tek42.perforce.process.Executor; -import com.tek42.perforce.process.ExecutorFactory; - -/** - * Represents the root object from which to interact with a Perforce server. - *

- * As an example of usage:
- * - *

- *  
- * // Setup
- * Depot depot = new Depot();
- * depot.setPort("perforce.com:1666");
- * depot.setUser("username");
- * depot.setPassword("password");
- * depot.setWorkspace("workspace");
- * 
- * // Test
- * depot.isValid()  // returns true if so 
- * 
- * // Look at the last change for a project...
- * List<Changelist> changes = depot.getChanges().getChangelists("//depot/ProjectName/...", -1, 1);
- * System.out.println(Last Change is: " + changes.get(0));
- * 
- * - * @author Mike Wille - */ -public class Depot { - private static Depot depot; - private final Logger logger = LoggerFactory.getLogger("perforce"); - private HashMap settings; - private String pathSep; - private String fileSep; - private boolean validEnvp; - private String p4exe; - private long threshold; - private String p4Ticket; - - ExecutorFactory execFactory; - - private Changes changes; - private Workspaces workspaces; - private Users users; - private Labels labels; - private Status status; - private Groups groups; - private Counters counters; - /** - * If not using this in a Dependancy Injection environment, use this method to get ahold of the depot. - * - * @return - */ - public static Depot getInstance() { - if(depot == null) { - depot = new Depot(); - } - - return depot; - } - - public Depot() { - this(new DefaultExecutorFactory()); - } - - public Depot(ExecutorFactory factory) { - settings = new HashMap(); - settings.put("P4USER", "robot"); - settings.put("P4CLIENT", "robot-client"); - settings.put("P4PORT", "localhost:1666"); - settings.put("P4PASSWD", ""); - settings.put("PATH", "C:\\Program Files\\Perforce"); - settings.put("CLASSPATH", "/usr/share/java/p4.jar"); - setSystemDrive("C:"); - setSystemRoot("C:\\WINDOWS"); - setExecutable("p4"); - setServerTimeout(10000); - - String os = System.getProperty("os.name"); - - if(os == null) { - return; - } - - if(os.startsWith("Windows")) { - settings.put("PATHEXT", ".COM;.EXE;.BAT;.CMD"); - String windir = System.getProperty("com.ms.windir"); - if(windir != null) { - appendPath(windir.substring(0, 1) + "\\Program Files\\Perforce"); - setSystemDrive(windir.substring(0, 1)); - setSystemRoot(windir); - } - } - execFactory = factory; - execFactory.setEnv(settings); - } - - /** - * Ensures that the latest settings are reflected in the ExecutorFactory before it is used. - * - * @return - */ - public ExecutorFactory getExecFactory() { - if(!validEnvp) { - execFactory.setEnv(settings); - } - return execFactory; - } - - public Logger getLogger() { - return logger; - } - - /** - * Obtain a legacy perforce Env object for using legacy API. Useful if you need to leverage a feature not present in - * com.tek42.perforce but one that does exist in com.perforce.api. - * - * @return {@link com.perforce.api.Env} object - */ - public Env getPerforceEnv() { - Env env = new Env(); - env.setClient(getClient()); - env.setExecutable(getExecutable()); - env.setPassword(getPassword()); - env.setUser(getUser()); - env.setPort(getPort()); - env.setSystemDrive(getSystemDrive()); - env.setSystemRoot(getSystemRoot()); - - return env; - } - - /** - * Retrieves the Changes object for interacting with this depot's changelists - * - * @return Changes object - */ - public Changes getChanges() { - if(changes == null) - changes = new Changes(this); - return changes; - } - - /** - * Retrieves the Workspaces object for interacting with this depot's workspaces - * - * @return Workspaces object - */ - public Workspaces getWorkspaces() { - if(workspaces == null) - workspaces = new Workspaces(this); - return workspaces; - } - - /** - * Retrieves the Users object for interacting with this depot's users. - * - * @return Users object - */ - public Users getUsers() { - if(users == null) - users = new Users(this); - return users; - } - - /** - * Retrieves the labels object for interacting with this depot's labels. - * - * @return Labels object - */ - public Labels getLabels() { - if(labels == null) - labels = new Labels(this); - return labels; - } - - /** - * Retrieves the Groups object for interacting with this depot's groups. - * - * @return Groups object - */ - public Groups getGroups() { - if(groups == null) - groups = new Groups(this); - return groups; - } - - /** * Retrieves the {@link Counters} object for interacting with this depot's counters. * * @return Counters object */ public Counters getCounters() { if(counters == null) counters = new Counters(this); return counters; } /** - * Retrieves the status object for interacting with the depot's status. - *

- * E.g., depot.getStatus().isValid() for checking if the settings are correct. - * - * @return Status object - */ - public Status getStatus() { - if(status == null) - status = new Status(this); - return status; - } - - /** - * Returns the output created by "p4 info" - * - * @return The string output of p4 info - */ - public String info() throws Exception { - Executor p4 = getExecFactory().newExecutor(); - String cmd[] = { "p4", "info" }; - p4.exec(cmd); - StringBuilder sb = new StringBuilder(); - String line; - while((line = p4.getReader().readLine()) != null) { - sb.append(line + "\n"); - } - return sb.toString(); - } - - /** - * Gets a property specified by key - * - * @param key - * @return - */ - public String getProperty(String key) { - return settings.get(key); - } - - /** - * Gets a value specified by key. If the value is empty, it will return the specified default. - * - * @param key - * @param def - * @return - */ - public String getProperty(String key, String def) { - String value = getProperty(key); - if(value == null || value.equals("")) - return def; - return value; - } - - /** - * Sets the P4USER in the class information. - * - * @param user - * P4USER value. - */ - public void setUser(String user) { - if(null == user) - return; - settings.put("P4USER", user); - validEnvp = false; - } - - /** - * Returns the P4USER. - * - * @return - */ - public String getUser() { - return settings.get("P4USER"); - } - - /** - * Sets the P4CLIENT in the class information. - * - * @param user - * P4CLIENT value. - */ - public void setClient(String client) { - if(null == client) - return; - settings.put("P4CLIENT", client); - validEnvp = false; - } - - /** - * Returns the P4CLIENT. - * - * @return - */ - public String getClient() { - return settings.get("P4CLIENT"); - } - - /** - * Sets the P4PORT in the class information. - * - * @param user - * P4PORT value. - */ - public void setPort(String port) { - if(null == port) - return; - settings.put("P4PORT", port); - validEnvp = false; - } - - /** - * Returns the P4PORT. - * - * @return - */ - public String getPort() { - return settings.get("P4PORT"); - } - - /** - * Sets the P4PASSWD in the class information. - * - * @param user - * P4PASSWD value. - */ - public void setPassword(String password) { - if(null == password) - return; - settings.put("P4PASSWD", password); - validEnvp = false; - } - - /** - * Returns the P4PASSWORD. - * - * @return - */ - public String getPassword() { - return settings.get("P4PASSWD"); - } - - /** - * Sets the PATH in the class information. - * - * @param path - * PATH value. - */ - public void setPath(String path) { - if(null == path) - return; - settings.put("PATH", path); - validEnvp = false; - } - - /** - * Append the path element to the existing path. If the path element given is already in the path, no change is - * made. - * - * @param path - * the path element to be appended. - */ - public void appendPath(String path) { - String tok; - if(null == path) - return; - String origPath = getProperty("PATH"); - if(null == pathSep || null == origPath) { - setPath(path); - return; - } - StringTokenizer st = new StringTokenizer(origPath, pathSep); - StringBuffer sb = new StringBuffer(); - while(st.hasMoreTokens()) { - tok = st.nextToken(); - if(tok.equals(path)) - return; - sb.append(tok); - sb.append(pathSep); - } - sb.append(path); - setPath(path); - } - - /** - * Returns the path - * - * @return - */ - public String getPath() { - return settings.get("PATH"); - } - - /** - * Sets the SystemDrive in the class information. This is only meaningful under Windows. - * - * @param user - * SystemDrive value. - */ - public void setSystemDrive(String drive) { - if(null == drive) - return; - settings.put("SystemDrive", drive); - validEnvp = false; - } - - /** - * Returns the system drive - * - * @return - */ - public String getSystemDrive() { - return settings.get("SystemDrive"); - } - - /** - * Sets the SystemRoot in the class information. This is only meaningful under Windows. - * - * @param user - * SystemRoot value. - */ - public void setSystemRoot(String root) { - if(null == root) - return; - settings.put("SystemRoot", root); - validEnvp = false; - } - - /** - * Returns the system root. - * - * @return - */ - public String getSystemRoot() { - return settings.get("SystemRoot"); - } - - /** - * Sets up the path to reach the p4 executable. The full path passed in must contain the executable or at least end - * in the system's file separator character. This gotten from the file.separator property. For example: - * - *

-	 * p4.executable=/usr/bin/p4   # This will work
-	 * p4.executable=/usr/bin/     # This will work
-	 * <font color=Red>p4.executable=/usr/bin      # This won't work</font>
-	 * 
- * - * @param exe - * Full path to the p4 executable. - */ - public void setExecutable(String exe) { - int pos; - if(null == exe) - return; - p4exe = exe; - if(null == fileSep) { - fileSep = System.getProperties().getProperty("file.separator", "\\"); - } - if(-1 == (pos = exe.lastIndexOf(fileSep))) - return; - if(null == pathSep) { - pathSep = System.getProperties().getProperty("path.separator", ";"); - } - appendPath(exe.substring(0, pos)); - validEnvp = false; - } - - /** - * Returns the path to the executable. - * - * @return - */ - public String getExecutable() { - return p4exe; - } - - /** - * Set the server timeout threshold. - * - * @param threshold - */ - public void setServerTimeout(long threshold) { - this.threshold = threshold; - } - - /** - * Return the server timeout threshold. - * - * @return - */ - public long getServerTimeout() { - return threshold; - } - - /** - * Returns the ticket value for this depot's user. - * - * @return the p4Ticket - */ - public String getP4Ticket() { - return p4Ticket; - } - - /** - * If using tickets, set the value of the ticket for this depot's user. Example value would be: - * 875477B92937E4AF7B20C5234C8905E2 - * - * @param ticket - * the p4Ticket to set - */ - public void setP4Ticket(String ticket) { - p4Ticket = ticket; - } - -} diff --git a/src/main/java/com/tek42/perforce/PerforceException.java b/src/main/java/com/tek42/perforce/PerforceException.java deleted file mode 100644 index 80b3373..0000000 --- a/src/main/java/com/tek42/perforce/PerforceException.java +++ /dev/null @@ -1 +0,0 @@ -package com.tek42.perforce; /* * Copyright (c) 2001, Perforce Software, All rights reserved. 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. */ /** * Signals that a general exception occurred when working with Perforce. * * @author David Markley * @version $Date: 2001/11/05 $ $Revision: #1 $ */ public class PerforceException extends Exception { private static final long serialVersionUID = 1L; public PerforceException(String mesg) { super(mesg); } public PerforceException(String mesg, Throwable cause) { super(mesg, cause); } } \ No newline at end of file diff --git a/src/main/java/com/tek42/perforce/model/AbstractViewsSupport.java b/src/main/java/com/tek42/perforce/model/AbstractViewsSupport.java deleted file mode 100644 index d27b2af..0000000 --- a/src/main/java/com/tek42/perforce/model/AbstractViewsSupport.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.model; - -import java.util.List; -import java.util.ArrayList; - -/** - * Provide base support for views. - * - * @author Mike Wille - */ -public abstract class AbstractViewsSupport implements java.io.Serializable { - protected List views; - - public AbstractViewsSupport() { - views = new ArrayList(); - } - - /** - * @return the view - */ - public List getViews() { - return views; - } - - /** - * Returns the list of views concatenated together with \n as delimeters. - * - * @return - */ - public String getViewsAsString() { - StringBuilder sb = new StringBuilder(); - for(String view : views) { - sb.append(view + "\n"); - } - return sb.toString(); - } - - /** - * @param view - * the view to set - */ - public void addView(String view) { - this.views.add(view); - } - - /** - * Removes all views from this client. - */ - public void clearViews() { - this.views.clear(); - } -} diff --git a/src/main/java/com/tek42/perforce/model/Changelist.java b/src/main/java/com/tek42/perforce/model/Changelist.java deleted file mode 100644 index 3c71dcd..0000000 --- a/src/main/java/com/tek42/perforce/model/Changelist.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.model; - -import java.util.Date; -import java.util.List; -import java.util.ArrayList; - -/** - * Represents a changelist in Perforce. - *

- * Again Perforce fails us with an imcomplete API. Their change object does not contain a record of files or jobs - * attached to the change. Grr... I'm forced to create one that is more complete. - *

- * This class maps the output of p4 describe [ChangeNumber]. However, it does not contain the diffs ouput by that - * command. If you want those, get them yourself. - * - * @author Mike Wille - */ -public class Changelist implements java.io.Serializable { - int changeNumber; - String workspace; - Date date; - String user; - String description; - List files; - List jobs; - boolean pending; - - public Changelist() { - files = new ArrayList(0); - jobs = new ArrayList(0); - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Change]: " + changeNumber + "\n"); - sb.append("by " + user + "@" + workspace + "\n"); - sb.append("on " + date + "\n"); - sb.append("Description:\n" + description + "\n"); - if(jobs.size() > 0) { - sb.append("Jobs: \n"); - for(JobEntry job : jobs) { - sb.append(job + "\n"); - } - } - if(files.size() > 0) { - sb.append("Files: \n"); - for(FileEntry file : files) { - sb.append(file + "\n"); - } - } - - return sb.toString(); - } - - /** - * Perforce has multiple files per change. This class represents a single file within a change which includes the - * action, filename, and revision. - * - * @author Mike Wille - */ - public static class FileEntry implements java.io.Serializable { - public static enum Action { - ADD, EDIT, DELETE, INTEGRATE, BRANCH, PURGE - } - - Action action; - String filename; - String revision; - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(action + " '" + filename + "' #" + revision + "."); - return sb.toString(); - } - - /** - * @return the action - */ - public Action getAction() { - return action; - } - - /** - * @param action - * the action to set - */ - public void setAction(Action action) { - this.action = action; - } - - /** - * @return the filename - */ - public String getFilename() { - return filename; - } - - /** - * @param filename - * the filename to set - */ - public void setFilename(String filename) { - this.filename = filename; - } - - /** - * @return the revision - */ - public String getRevision() { - return revision; - } - - /** - * @param revision - * the revision to set - */ - public void setRevision(String revision) { - this.revision = revision; - } - } - - /** - * Perforce links issues to changes via jobs. This represents a job attached to a change. - * - * @author Mike Wille - */ - public static class JobEntry implements java.io.Serializable { - String status; - String job; - String description; - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(job + " " + status + " " + description); - return sb.toString(); - } - - /** - * @return the status - */ - public String getStatus() { - return status; - } - - /** - * @param status - * the status to set - */ - public void setStatus(String status) { - this.status = status; - } - - /** - * @return the job - */ - public String getJob() { - return job; - } - - /** - * @param job - * the job to set - */ - public void setJob(String job) { - this.job = job; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - */ - public void setDescription(String description) { - this.description = description; - } - } - - /** - * @return the changeNumber - */ - public int getChangeNumber() { - return changeNumber; - } - - /** - * @param changeNumber - * the changeNumber to set - */ - public void setChangeNumber(int changeNumber) { - this.changeNumber = changeNumber; - } - - /** - * @return the workspace - */ - public String getWorkspace() { - return workspace; - } - - /** - * @param workspace - * the workspace to set - */ - public void setWorkspace(String workspace) { - this.workspace = workspace; - } - - /** - * @return the date - */ - public Date getDate() { - return date; - } - - /** - * @param date - * the date to set - */ - public void setDate(Date date) { - this.date = date; - } - - /** - * @return the user - */ - public String getUser() { - return user; - } - - /** - * @param user - * the user to set - */ - public void setUser(String user) { - this.user = user; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the files - */ - public List getFiles() { - return files; - } - - /** - * @param files - * the files to set - */ - public void setFiles(List files) { - this.files = files; - } - - /** - * @return the jobs - */ - public List getJobs() { - return jobs; - } - - /** - * @param jobs - * the jobs to set - */ - public void setJobs(List jobs) { - this.jobs = jobs; - } - - /** - * @return true if this is a pending changelist - */ - public boolean isPending() { - return pending; - } - - /** - * @param pending - */ - public void setPending(boolean pending) { - this.pending = pending; - } -} diff --git a/src/main/java/com/tek42/perforce/model/Counter.java b/src/main/java/com/tek42/perforce/model/Counter.java deleted file mode 100644 index 2bec619..0000000 --- a/src/main/java/com/tek42/perforce/model/Counter.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.tek42.perforce.model; - -/** - * Represents a Perforce counter. - * - * @author Kamlesh Sangani - */ -public class Counter { - - private String name; - private int value = 0; - - /** - * Returns counter name - * - * @return counter name - */ - public String getName() { - return name; - } - - /** - * Sets counter name - * - * @param name - * counter name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns counter value - * - * @return counter value - */ - public int getValue() { - return value; - } - - /** - * Sets counter value - * - * @param value - * counter value - */ - public void setValue(int value) { - this.value = value; - } - - @Override - public String toString() { - return String.format("[Name=%s, Value=%d]", name, value); - } -} diff --git a/src/main/java/com/tek42/perforce/model/Group.java b/src/main/java/com/tek42/perforce/model/Group.java deleted file mode 100644 index 6369e41..0000000 --- a/src/main/java/com/tek42/perforce/model/Group.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.model; - -import java.util.List; -import java.util.ArrayList; - -/** - * Represents a group in perforce. - * - * @author Mike - * Date: Jul 21, 2008 2:42:09 PM - */ -public class Group { - String name; - String maxResults; - String maxScanRows; - String maxLockTime; - Long timeout; - List subgroups; - List owners; - List users; - - public Group() { - maxResults = "unlimited"; - maxScanRows = "unlimited"; - maxLockTime = "unlimited"; - Long timeout = 43200L; - subgroups = new ArrayList(0); - owners = new ArrayList(0); - users = new ArrayList(0); - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - - sb.append("Group: " + name + "\n"); - sb.append("MaxResults: " + maxResults + "\n"); - sb.append("MaxScanRows: " + maxScanRows + "\n"); - sb.append("MaxLockTime: " + maxLockTime + "\n"); - sb.append("Timeout: " + timeout + "\n"); - sb.append("SubGroups:\n" + getSubgroupsAsString() + "\n"); - sb.append("Owners:\n" + getOwnersAsString() + "\n"); - sb.append("Users:\n" + getUsersAsString() + "\n"); - - return sb.toString(); - } - - public String getMaxLockTime() { - return maxLockTime; - } - - public void setMaxLockTime(String maxLockTime) { - this.maxLockTime = maxLockTime; - } - - public String getMaxResults() { - return maxResults; - } - - public void setMaxResults(String maxResults) { - this.maxResults = maxResults; - } - - public String getMaxScanRows() { - return maxScanRows; - } - - public void setMaxScanRows(String maxScanRows) { - this.maxScanRows = maxScanRows; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getOwners() { - return owners; - } - - public String getOwnersAsString() { - StringBuilder sb = new StringBuilder(); - for(String owner : owners) { - sb.append(owner); - sb.append("\n"); - } - return sb.toString(); - - } - - public void setOwners(List owners) { - this.owners = owners; - } - - public List getSubgroups() { - return subgroups; - } - - public String getSubgroupsAsString() { - StringBuilder sb = new StringBuilder(); - for(String s : subgroups) { - sb.append(s); - sb.append("\n"); - } - return sb.toString(); - } - - public void setSubgroups(List subgroups) { - this.subgroups = subgroups; - } - - public Long getTimeout() { - return timeout; - } - - public void setTimeout(Long timeout) { - this.timeout = timeout; - } - - public List getUsers() { - return users; - } - - public String getUsersAsString() { - StringBuilder sb = new StringBuilder(); - for(String s : users) { - sb.append(s); - sb.append("\n"); - } - return sb.toString(); - } - - public void setUsers(List users) { - this.users = users; - } -} diff --git a/src/main/java/com/tek42/perforce/model/Label.java b/src/main/java/com/tek42/perforce/model/Label.java deleted file mode 100644 index 044184f..0000000 --- a/src/main/java/com/tek42/perforce/model/Label.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.model; - -/** - * Represents a Perforce Label. - * - * @author Mike Wille - */ -public class Label extends AbstractViewsSupport implements java.io.Serializable { - String name; - String update; - String access; - String owner; - String description; - String options; - String revision; - - public Label() { - super(); - name = ""; - update = ""; - access = ""; - owner = ""; - description = ""; - options = ""; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the update - */ - public String getUpdate() { - return update; - } - - /** - * @param update - * the update to set - */ - public void setUpdate(String update) { - this.update = update; - } - - /** - * @return the access - */ - public String getAccess() { - return access; - } - - /** - * @param access - * the access to set - */ - public void setAccess(String access) { - this.access = access; - } - - /** - * @return the owner - */ - public String getOwner() { - return owner; - } - - /** - * @param owner - * the owner to set - */ - public void setOwner(String owner) { - this.owner = owner; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the options - */ - public String getOptions() { - return options; - } - - /** - * @param options - * the options to set - */ - public void setOptions(String options) { - this.options = options; - } - - /** - * @return the revision - */ - public String getRevision() { - return revision; - } - - /** - * @param revision - * the revision to set - */ - public void setRevision(String revision) { - this.revision = revision; - } - -} diff --git a/src/main/java/com/tek42/perforce/model/User.java b/src/main/java/com/tek42/perforce/model/User.java deleted file mode 100644 index c8fb572..0000000 --- a/src/main/java/com/tek42/perforce/model/User.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.model; - -/** - * Represents a user in perforce. - * - * @author Mike Wille - */ -public class User implements java.io.Serializable { - - String username; - String email; - String fullName; - String password; - String jobView; - String reviews; - - /** - * @return the username - */ - public String getUsername() { - return username; - } - - /** - * @param username - * the username to set - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * @return the email - */ - public String getEmail() { - return email; - } - - /** - * @param email - * the email to set - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the fullName - */ - public String getFullName() { - return fullName; - } - - /** - * @param fullName - * the fullName to set - */ - public void setFullName(String fullName) { - this.fullName = fullName; - } - - /** - * @return the password - */ - public String getPassword() { - return password; - } - - /** - * @param password - * the password to set - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return the jobView - */ - public String getJobView() { - return jobView; - } - - /** - * @param jobView - * the jobView to set - */ - public void setJobView(String jobView) { - this.jobView = jobView; - } - - /** - * @return the reviews - */ - public String getReviews() { - return reviews; - } - - /** - * @param reviews - * the reviews to set - */ - public void setReviews(String reviews) { - this.reviews = reviews; - } - -} diff --git a/src/main/java/com/tek42/perforce/model/Workspace.java b/src/main/java/com/tek42/perforce/model/Workspace.java deleted file mode 100644 index 58ada0e..0000000 --- a/src/main/java/com/tek42/perforce/model/Workspace.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.model; - -/** - * Represents a Perforce clientspec or workspace. - *

- * This is necessary because the Client class that Perforce provides in their API is not complete. It is missing several - * fields and we cannot extend that class because its final. - * - * @author Mike Wille - */ -public class Workspace extends AbstractViewsSupport implements java.io.Serializable { - String name; - String owner; - String host; - String description; - String root; - String altRoots; - String options; - String lineEnd; - String submitOptions; - String update; - String access; - - public Workspace() { - super(); - this.name = ""; - this.owner = ""; - this.host = ""; - this.description = ""; - this.root = ""; - this.altRoots = ""; - this.options = ""; - this.lineEnd = ""; - this.submitOptions = ""; - this.update = ""; - this.access = ""; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Client]\n"); - sb.append("Name: " + getName() + "\n"); - sb.append("Update: " + getUpdate() + "\n"); - sb.append("Access: " + getAccess() + "\n"); - sb.append("Owner: " + getOwner() + "\n"); - sb.append("Host: " + getHost() + "\n"); - sb.append("Description: " + getDescription() + "\n"); - sb.append("Root: " + getRoot() + "\n"); - sb.append("AltRoot: " + getAltRoots() + "\n"); - sb.append("Options: " + getOptions() + "\n"); - sb.append("SubmitOptions: " + getSubmitOptions() + "\n"); - sb.append("LineEnd: " + getLineEnd() + "\n"); - sb.append("Views: \n"); - for(String view : views) { - sb.append("\t" + view + "\n"); - } - - return sb.toString(); - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the owner - */ - public String getOwner() { - return owner; - } - - /** - * @param owner - * the owner to set - */ - public void setOwner(String owner) { - this.owner = owner; - } - - /** - * @return the host - */ - public String getHost() { - return host; - } - - /** - * @param host - * the host to set - */ - public void setHost(String host) { - this.host = host; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the root - */ - public String getRoot() { - return root; - } - - /** - * @param root - * the root to set - */ - public void setRoot(String root) { - this.root = root; - } - - /** - * @return the altRoots - */ - public String getAltRoots() { - return altRoots; - } - - /** - * @param altRoots - * the altRoots to set - */ - public void setAltRoots(String altRoots) { - this.altRoots = altRoots; - } - - /** - * @return the options - */ - public String getOptions() { - return options; - } - - /** - * @param options - * the options to set - */ - public void setOptions(String options) { - this.options = options; - } - - /** - * @return the lineEnd - */ - public String getLineEnd() { - return lineEnd; - } - - /** - * @param lineEnd - * the lineEnd to set - */ - public void setLineEnd(String lineEnd) { - this.lineEnd = lineEnd; - } - - /** - * @return the submitOptions - */ - public String getSubmitOptions() { - return submitOptions; - } - - /** - * @param submitOptions - * the submitOptions to set - */ - public void setSubmitOptions(String submitOptions) { - this.submitOptions = submitOptions; - } - - /** - * @return the update - */ - public String getUpdate() { - return update; - } - - /** - * @param update - * the update to set - */ - public void setUpdate(String update) { - this.update = update; - } - - /** - * @return the access - */ - public String getAccess() { - return access; - } - - /** - * @param access - * the access to set - */ - public void setAccess(String access) { - this.access = access; - } - -} diff --git a/src/main/java/com/tek42/perforce/model/package.html b/src/main/java/com/tek42/perforce/model/package.html deleted file mode 100644 index 171532b..0000000 --- a/src/main/java/com/tek42/perforce/model/package.html +++ /dev/null @@ -1,22 +0,0 @@ - - - -com.tek42.perforce package - - - - -

-Provides models of perforce objects. -

- -

-All first class objects of perforce are provided here. -

- - - diff --git a/src/main/java/com/tek42/perforce/package.html b/src/main/java/com/tek42/perforce/package.html deleted file mode 100644 index ca37736..0000000 --- a/src/main/java/com/tek42/perforce/package.html +++ /dev/null @@ -1,37 +0,0 @@ - - - -com.tek42.perforce package - - - - -

-Provides a java API for interacting with Perforce SCM. -

- -

-Example Usage:
-

- // Setup
- Depot depot = new Depot();
- depot.setPort("perforce.com:1666");
- depot.setUser("username");
- depot.setPassword("password");
- depot.setWorkspace("workspace");
- 
- // Test
- depot.getStatus().isValid()  // returns true if so 
- 
- // Look at the last change for a project...
- List changes = depot.getChanges().getChangelists("//depot/ProjectName/...", -1, 1);
- System.out.println(Last Change is: " + changes.get(0));	
-
-

- - - diff --git a/src/main/java/com/tek42/perforce/parse/AbstractFormBuilder.java b/src/main/java/com/tek42/perforce/parse/AbstractFormBuilder.java deleted file mode 100644 index 0d6d6fc..0000000 --- a/src/main/java/com/tek42/perforce/parse/AbstractFormBuilder.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ -package com.tek42.perforce.parse; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tek42.perforce.PerforceException; - -/** - * Abstract class that parses the stringbuilder into key/value pairs and then sends them to a abstract method - * responsible for building the object. If you extend this class, you do NOT override build(StringBuilder) but - * buildForm(Map). - *

- * Useful for all perforce objects that are editable via forms. i.e., User, Workspace, Jobspec, etc. - * - * @author Mike Wille - */ -public abstract class AbstractFormBuilder implements Builder { - private final Logger logger = LoggerFactory.getLogger("perforce"); - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.parse.Builder#build(java.lang.StringBuilder) - */ - public T build(StringBuilder sb) throws PerforceException { - // Allow our regexp to match with only one case and not have to handle the case for the last line - sb.append("Endp:\n"); - logger.debug("Parsing: \n" + sb); - Pattern p = Pattern.compile("^(\\w+):(.*?)(?=\\n\\w{4,}?:)", Pattern.DOTALL | Pattern.MULTILINE); - Matcher m = p.matcher(sb.toString()); - Map fields = new HashMap(); - logger.debug("Parsing response..."); - while(m.find()) { - String key = m.group(1); - String value = m.group(2).trim(); - fields.put(key, value); - logger.debug("Have key: " + key + " = " + value); - } - return buildForm(fields); - } - - /** - * Test for null and returns an empty string if the key is not present. Otherwise, returns the value. - * - * @param key - * @param fields - * @return - */ - protected String getField(String key, Map fields) { - String value = fields.get(key); - if(value == null) - return ""; - - return value; - } - - /** - * Like getField(String, Map) except that it assumes the value of the field is a String containing a - * delimited list of values. It parses the string into a string list. Assumes new line as separator. - * @param key The name of the field. - * @param fields The map of field/value pairs. - * @return A List of strings. - */ - protected List getFieldAsList(String key, Map fields) { - String value = fields.get(key); - if(value == null || value.equals("") || value.equals("\n")) - return new ArrayList(); - - String values[] = value.split("\\n"); - - List list = new ArrayList(values.length); - list.addAll(Arrays.asList(values)); - return list; - } - - /** - * Default implementation for most Perforce operations is to use stdin. This will return true. - * @return True always - */ - public boolean requiresStandardInput() { - return true; - } - - /** - * Should return a new object set with the data from fields. - * - * @param fields - * @return - * @throws PerforceException - */ - public abstract T buildForm(Map fields) throws PerforceException; -} diff --git a/src/main/java/com/tek42/perforce/parse/AbstractPerforceTemplate.java b/src/main/java/com/tek42/perforce/parse/AbstractPerforceTemplate.java deleted file mode 100644 index 27a1a8c..0000000 --- a/src/main/java/com/tek42/perforce/parse/AbstractPerforceTemplate.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.parse; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FilterWriter; -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import org.slf4j.Logger; - -import com.tek42.perforce.Depot; -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.process.Executor; - -/** - * Provides default functionality for interacting with Perforce using the template design pattern. - * - * @author Mike Wille - */ -public abstract class AbstractPerforceTemplate { - Depot depot; - Logger logger; - final String errors[] = new String[] { - "Connect to server failed; check $P4PORT", - "Perforce password (P4PASSWD) invalid or unset.", - "Password not allowed at this server security level, use 'p4 login'", - "Can't create a new user - over license quota.", - "Client '*' can only be used from host '*'", - "Access for user '", - "Your session has expired, please login again." - }; - - final String maxError = "Request too large"; - - public AbstractPerforceTemplate(Depot depot) { - this.depot = depot; - this.logger = depot.getLogger(); - } - - /** - * Parses lines of formatted text for a list of values. Tokenizes each line into columns and adds the column - * specified by index to the list. - * - * @param response The response from perforce to parse - * @param index The column index to add to the list - * @return A List of strings parsed from the response - */ - protected List parseList(StringBuilder response, int index) { - StringTokenizer lines = new StringTokenizer(response.toString(), "\n\r"); - List list = new ArrayList(100); - while(lines.hasMoreElements()) { - StringTokenizer columns = new StringTokenizer(lines.nextToken()); - for(int column = 0; column < index; column++) { - columns.nextToken(); - } - list.add(columns.nextToken()); - } - return list; - - } - - /** - * Check to see if the perforce request resulted in a "too many results" error. If so, special handling needs - * to happen. - * - * @param response The response from perforce - * @return True if the limit was reached, false otherwise. - */ - protected boolean hitMax(StringBuilder response) { - return response.toString().startsWith(maxError); - } - - /** - * Adds any extra parameters that need to be applied to all perforce commands. For example, adding the login ticket - * to authenticate with. - * - * @param cmd - * String array that will be executed - * @return A (possibly) modified string array to be executed in place of the original. - */ - protected String[] getExtraParams(String cmd[]) { - String ticket = depot.getP4Ticket(); - - if(ticket != null) { - // Insert the ticket for the password if tickets are being used... - String newCmds[] = new String[cmd.length + 2]; - newCmds[0] = "p4"; - newCmds[1] = "-P"; - newCmds[2] = ticket; - for(int i = 3; (i - 2) < cmd.length; i++) { - newCmds[i] = cmd[i - 2]; - } - cmd = newCmds; - } - return cmd; - } - - /** - * Handles the IO for opening a process, writing to it, flushing, closing, and then handling any errors. - * - * @param object The perforce object to save - * @param builder The builder responsible for saving the object - * @throws PerforceException If there is any errors thrown from perforce - */ - @SuppressWarnings("unchecked") - protected StringBuilder saveToPerforce(Object object, Builder builder) throws PerforceException { - boolean loop = false; - boolean attemptLogin = true; - - StringBuilder response = new StringBuilder(); - do { - int mesgIndex = -1, i;//, count = 0; - Executor p4 = depot.getExecFactory().newExecutor(); - String debugCmd = ""; - try { - String cmds[] = getExtraParams(builder.getSaveCmd(object)); - - // for exception reporting... - for(String cm : cmds) { - debugCmd += cm + " "; - } - - // back to our regularly scheduled programming... - p4.exec(cmds); - BufferedReader reader = p4.getReader(); - - // Maintain a log of what was sent to p4 on std input - final StringBuilder log = new StringBuilder(); - - // Conditional use of std input for saving the perforce entity - if(builder.requiresStandardInput()) { - BufferedWriter writer = p4.getWriter(); - Writer fwriter = new FilterWriter(writer) { - public void write(String str) throws IOException { - log.append(str); - out.write(str); - } - }; - builder.save(object, fwriter); - fwriter.flush(); - fwriter.close(); - } - - String line; - String error = ""; - int exitCode = 0; - - while((line = reader.readLine()) != null) { - logger.debug("LineIn -> " + line); - - // Check for authentication errors... - for(i = 0; i < errors.length; i++) { - if(line.indexOf(errors[i]) != -1) - mesgIndex = i; - - } - - if(line.startsWith("error")) { - if(!line.trim().equals("") && (line.indexOf("up-to-date") < 0) && (line.indexOf("no file(s) to resolve") < 0)) { - error += line.substring(6); - } - - } else if(line.startsWith("exit")) { - exitCode = Integer.parseInt(line.substring(line.indexOf(" ") + 1, line.length())); - - } else { - if(line.indexOf(":") > -1) - response.append(line.substring(line.indexOf(":"))); - else - response.append(line); - } - } - reader.close(); - - loop = false; - // If we failed to execute because of an authentication issue, try a p4 login. - if(attemptLogin && (mesgIndex == 1 || mesgIndex == 2 || mesgIndex == 6)) { - // password is unset means that perforce isn't using the environment var P4PASSWD - // Instead it is using tickets. We must attempt to login via p4 login, then - // retry this cmd. - p4.close(); - login(); - loop = true; - attemptLogin = false; - continue; - } - - if(exitCode != 0) { - if(!error.equals("")) - throw new PerforceException(error + "\nFor Command: " + debugCmd + "\nWith Data:\n===================\n" + log.toString() + "===================\n"); - throw new PerforceException(response.toString()); - } - - logger.debug("Wrote to " + debugCmd + ":\n" + log.toString()); - logger.info(response.toString()); - - } catch(IOException e) { - throw new PerforceException("Failed to open connection to perforce", e); - } finally { - p4.close(); - } - } while(loop); - - return response; - } - - /** - * Executes a perforce command and returns the output as a StringBuilder. - * - * @param cmd The perforce commands to execute. Each command and argument is it's own array element - * @return The response from perforce as a stringbuilder - * @throws PerforceException If perforce throws any errors - */ - protected StringBuilder getPerforceResponse(String cmd[]) throws PerforceException { - // TODO: Create a way to wildcard portions of the error checking. Add method to check for these errors. - boolean loop = false; - boolean attemptLogin = true; - - StringBuilder response = new StringBuilder(); - do { - int mesgIndex = -1, i, count = 0; - Executor p4 = depot.getExecFactory().newExecutor(); - String debugCmd = ""; - try { - // get entire cmd to execute - cmd = getExtraParams(cmd); - - // setup information for logging... - for(String cm : cmd) { - debugCmd += cm + " "; - } - - // Performe execution and IO - p4.exec(cmd); - BufferedReader reader = p4.getReader(); - String line; - response = new StringBuilder(); - while((line = reader.readLine()) != null) { - count++; - for(i = 0; i < errors.length; i++) { - if(line.indexOf(errors[i]) != -1) - mesgIndex = i; - } - response.append(line); - response.append("\n"); - } - loop = false; - // If we failed to execute because of an authentication issue, try a p4 login. - if(attemptLogin && (mesgIndex == 1 || mesgIndex == 2 || mesgIndex == 6)) { - // password is unset means that perforce isn't using the environment var P4PASSWD - // Instead it is using tickets. We must attempt to login via p4 login, then - // retry this cmd. - p4.close(); - login(); - loop = true; - attemptLogin = false; - continue; - } - - // We aren't using the exact message because we want to add the username for more info - if(mesgIndex == 4) - throw new PerforceException("Access for user '" + depot.getUser() + "' has not been enabled by 'p4 protect'"); - if(mesgIndex != -1) - throw new PerforceException(errors[mesgIndex]); - if(count == 0) - throw new PerforceException("No output for: " + debugCmd); - - } catch(IOException e) { - throw new PerforceException("Failed to communicate with p4", e); - } finally { - p4.close(); - } - } while(loop); - - return response; - } - - /** - * Tries to perform a p4 login if the security level on the server is set to level 3 and no ticket was set via - * depot.setP4Ticket(). - *

- * Unfortunately, this likely doesn't work on windows. - * - * @throws PerforceException If perforce throws any errors - */ - protected void login() throws PerforceException { - // Unfortunately, the simple way of doing this: echo password | p4 login - // Doesn't work on windows! So we have to try and write directly, but - // that doesn't seem to work either. The code is left here, but probably is - // not going to work. If you are facing this problem, use depot.setTicket() with a ticket - // that has an expiration significantly far ahead in time to work as a permanent login. - String sep = System.getProperty("file.separator"); - if(sep.equals("\\")) { - Executor login = depot.getExecFactory().newExecutor(); - login.exec(new String[] { "p4", "login" }); - try { - Thread.sleep(250); - } catch(InterruptedException e) { - // nothing to do - } - try { - login.getWriter().write(depot.getPassword() + "\n"); - } catch(IOException e) { - throw new PerforceException("Failed to communicate with p4 when logging in to server."); - } - login.close(); - } else { // for everything not windows... - Executor login = depot.getExecFactory().newExecutor(); - // The -p parameter outputs the ticket to stdout. - final String[] args = {"/bin/sh", "-c", depot.getExecutable() + " login -p"}; - logger.info("Running " + Arrays.toString(args)); - login.exec(null, args); - String ticket = null; - try { - login.getWriter().write(depot.getPassword()==null ? "" : depot.getPassword()); - login.getWriter().newLine(); - login.getWriter().flush(); - BufferedReader reader = login.getReader(); - String line; - - // The last line output from p4 login will be the ticket - while((line = reader.readLine()) != null) { - ticket = line; - } - - } catch(IOException e) { - throw new PerforceException("Unable to login via p4 login due to IOException: " + e.getMessage()); - } - // if we obtained a ticket, save it for later use. Our environment setup by Depot can't usually - // see the .p4tickets file. - if(ticket != null) { - ticket = ticket.trim(); - if(ticket.contains(" ")) { - throw new PerforceException("Failed to login: " + ticket); - } - logger.warn("Using p4 issued ticket."); - depot.setP4Ticket(ticket); - } - - login.close(); - } - } -} diff --git a/src/main/java/com/tek42/perforce/parse/Builder.java b/src/main/java/com/tek42/perforce/parse/Builder.java deleted file mode 100644 index 2adafc1..0000000 --- a/src/main/java/com/tek42/perforce/parse/Builder.java +++ /dev/null @@ -1 +0,0 @@ -/* * P4Java - java integration with Perforce SCM * Copyright (C) 2007-, Mike Wille, Tek42 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * You can contact the author at: * * Web: http://tek42.com * Email: mike@tek42.com * Mail: 755 W Big Beaver Road * Suite 1110 * Troy, MI 48084 */ package com.tek42.perforce.parse; import java.io.Writer; import com.tek42.perforce.PerforceException; /** * Interface for parsing perforce output into a concrete object and also for saving the object back to perforce. *

* The pattern for using this template to build an object is: *

    *
  1. Retrieve commands to execute via {@link #getBuildCmd(String)}
  2. *
  3. Execute those commands and capture the output.
  4. *
  5. Pass the output to {@link #build(StringBuilder)}
  6. *
*

And conversely for saving: *

    *
  1. Retrieve commands to execute via {@link Builder#getSaveCmd(Object)}
  2. *
  3. Execute those commands and retrieve a Writer for I/O
  4. *
  5. Pass the writer and the object to save to {@link #save(Object, Writer)}
  6. *
* * @author Mike Wille */ public interface Builder { /** * This should return the command line tokens to execute for retrieving an object from Perforce. For example: * String[] { "p4", "user", "-o", "mwille" } * * @param id * The ID or Name of the object we are working on. In the case of a changelist, the changelist number. In * the case of a user, the username. * @return A 1D string array of tokens to execute. */ public String[] getBuildCmd(String id); /** * This should assemble an object from a string value. Format of the string is dependent on the object we are * building and is unspecified. * * @param sb * The StringBuilder containing the string value. * @return The resulting object * @throws PerforceException * If the format is invalid or other errors occur. */ public T build(StringBuilder sb) throws PerforceException; /** * The converse of {@link #getBuildCmd(String)} this should return the command line tokens to execute for saving an * object to Perforce. For example: String[] { "p4", "user", "-i", "mwille" } *

* Note, although the object being saved is passed to this method, this method does not need to do anything with it. * * @return A 1D string array of tokens to execute * @param obj The object that is being saved, useful if propert(ies) are needed for the save command to be generated. */ public String[] getSaveCmd(T obj); /** * Tells the AbstractPerforceTemplate whether or not this builder will write data on Standard Input to the perforce * command specified in getSaveCmd(). Currently, this only applies to saving as their is no writing required for * building. * * @return True if standard input should be opened and this builder's save() method called. False otherwise. */ public boolean requiresStandardInput(); /** * The converse of {@link #build(StringBuilder)} this should take an object and disassemble it for writing to the * Perforce server. The specification of what is written to the Writer is dependant on the object being saved. * * @param obj * The object to be saved * @param writer * The Writer to write the string representation to * @throws PerforceException * If the object is invalid or there is an issue with writing */ public void save(T obj, Writer writer) throws PerforceException; } \ No newline at end of file diff --git a/src/main/java/com/tek42/perforce/parse/ChangelistBuilder.java b/src/main/java/com/tek42/perforce/parse/ChangelistBuilder.java deleted file mode 100644 index 622a558..0000000 --- a/src/main/java/com/tek42/perforce/parse/ChangelistBuilder.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ -package com.tek42.perforce.parse; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Locale; -import java.util.StringTokenizer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Changelist; - -/** - * Responsible for building and saving changelists. - * - * @author Mike Wille - */ -public class ChangelistBuilder implements Builder { - private final Logger logger = LoggerFactory.getLogger("perforce"); - - public String[] getBuildCmd(String id) { - return new String[] { "p4", "describe", "-s", id }; - } - - /* - * (non-Javadoc) - * @see com.tek42.perforce.parse.Builder#build(java.lang.StringBuilder) - */ - public Changelist build(StringBuilder sb) throws PerforceException { - Changelist change = null; - StringTokenizer lines = new StringTokenizer(sb.toString(), "\t\n\r"); - try { - while(lines.hasMoreElements()) { - String line = lines.nextToken(); - logger.debug("Line: " + line); - - if(line.startsWith("Change")) { - logger.debug("New changelist."); - - change = new Changelist(); - // Line looks like: - // Change XXXX by user@client on YYYY/MM/DD HH:MM:SS - StringTokenizer details = new StringTokenizer(line); - details.nextToken(); // client - change.setChangeNumber(new Integer(details.nextToken())); - details.nextToken(); // by - String user = details.nextToken(); - change.setUser(user.substring(0, user.indexOf("@"))); - change.setWorkspace(user.substring(user.indexOf("@") + 1)); - details.nextToken(); // on - - String date = details.nextToken(); - String time = details.nextToken(); - - change.setDate(parseDate(date + " " + time)); - - if (details.hasMoreTokens() && details.nextToken().equals("*pending*")) { - change.setPending(true); - } - - // the lines immediately following is the description - StringBuilder desc = new StringBuilder(); - line = lines.nextToken(); - while(line != null && !line.startsWith("Affected files") && !line.startsWith("Jobs fixed")) { - logger.debug("Description Line: " + line); - desc.append(line + "\n"); - line = lines.nextToken(); - } - change.setDescription(desc.toString().trim()); - - } - - if(line.startsWith("Jobs fixed")) { - logger.debug("Has jobs."); - List jobs = new ArrayList(); - boolean getDesc = false; - Changelist.JobEntry job = new Changelist.JobEntry(); - String description = null; - do { - line = lines.nextToken(); - logger.debug("Job Line: " + line); - if(!getDesc) { - // Line looks like: - // EXT-84 on 2007/09/25 by mwille *closed* - StringTokenizer details = new StringTokenizer(line); - job = new Changelist.JobEntry(); - job.setJob(details.nextToken()); - details.nextToken(); // on - details.nextToken(); // date - details.nextToken(); // by - details.nextToken(); // user - job.setStatus(details.nextToken()); - description = ""; - getDesc = true; - } else { - while(!line.startsWith("Affected files")) { - description += line; - if(!lines.hasMoreElements()) - break; - description += "\n"; - line = lines.nextToken(); - } - job.setDescription(description.trim()); - jobs.add(job); - getDesc = false; - } - - } while(!line.startsWith("Affected files")); - - change.setJobs(jobs); - - } - - if(line.startsWith("Affected files")) { - logger.debug("reading files..."); - List files = new ArrayList(); - - while(lines.hasMoreElements()) { - String entry = lines.nextToken(); - logger.warn("File Line: " + entry); - // if(!entry.startsWith("...")) - // break; - // line looks lie: - // ... //depot/path/to/file/file.ext#1 edit - - int revStart = entry.indexOf("#"); - if(revStart < 0) - continue; - String filename = entry.substring(4, revStart); - String rev = entry.substring(revStart + 1, entry.indexOf(" ", revStart)); - String action = entry.substring(entry.indexOf(" ", revStart) + 1); - Changelist.FileEntry file = new Changelist.FileEntry(); - file.setFilename(filename); - file.setRevision(rev); - file.setAction(Changelist.FileEntry.Action.valueOf(action.toUpperCase(Locale.US))); - files.add(file); - } - - change.setFiles(files); - - } - } - } catch(Exception e) { - logger.error("Exception: " + e.getMessage()); - throw new PerforceException("Failed to retrieve changelist.", e); - } - return change; - } - - public String[] getSaveCmd(Changelist obj) { - return new String[] { "p4", "change", "-i" }; - } - - public boolean requiresStandardInput() { - return true; - } - - /* - * (non-Javadoc) - * @see com.tek42.perforce.parse.Builder#save(java.lang.Object) - */ - public void save(Changelist obj, Writer out) throws PerforceException { - try { - out.write("Change: new \n"); - out.write("Description:\n\t" + obj.getDescription() + "\n"); - out.write("\n"); - } catch(IOException e) { - throw new PerforceException("Failed to save changelist", e); - } - } - - /** - * Returns a java.util.Date object set to the time specified in newDate. The format expected is the format of: - * YYYY-MM-DD HH:MM:SS - * - * @param newDate - * the string date to convert - * @return A java.util.Date based off of the string format. - */ - public static java.util.Date parseDate(String newDate) { - // when we have a null from the database, give it zeros first. - if(newDate == null || newDate.equals("")) { - return null; - } - - String parts[] = newDate.split(" "); - String date[] = parts[0].split("/"); - String time[] = null; - - if(parts.length > 1) { - time = parts[1].split(":"); - time[2] = time[2].replaceAll("\\.0", ""); - } else { - time = "00:00:00".split(":"); - } - - GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); - cal.clear(); - - cal.set(new Integer(date[0]).intValue(), (new Integer(date[1]).intValue() - 1), new Integer(date[2]).intValue(), new Integer( - time[0]).intValue(), new Integer(time[1]).intValue(), new Integer(time[2]).intValue()); - - return cal.getTime(); - } -} diff --git a/src/main/java/com/tek42/perforce/parse/Changes.java b/src/main/java/com/tek42/perforce/parse/Changes.java deleted file mode 100644 index 328853c..0000000 --- a/src/main/java/com/tek42/perforce/parse/Changes.java +++ /dev/null @@ -1,384 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ -package com.tek42.perforce.parse; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.StringTokenizer; - -import com.tek42.perforce.Depot; -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Changelist; - -/** - * Base API object for interacting with changelists. - * - * @author Mike Wille - * @author Brian Westrich - */ -public class Changes extends AbstractPerforceTemplate { - - public Changes(Depot depot) { - super(depot); - } - - /** - * Returns a single changelist specified by its number. - * - * @param number - * @return - * @throws PerforceException - */ - public Changelist getChangelist(int number) throws PerforceException { - ChangelistBuilder builder = new ChangelistBuilder(); - Changelist change = builder.build(getPerforceResponse(builder.getBuildCmd(Integer.toString(number)))); - if(change == null) - throw new PerforceException("Failed to retrieve changelist " + number); - return change; - } - - /** - * Returns a list of changelists that match the parameters - * - * @param path - * What point in the depot to show changes for? - * @param lastChange - * The last changelist number to start from - * @param limit - * The maximum changes to return if less than 1, will return everything - * @return - * @throws PerforceException - */ - public List getChangelists(String path, int lastChange, int limit) throws PerforceException { - path = normalizePath(path); - if(lastChange > 0) - path += "@" + lastChange; - - String cmd[]; - - if(limit > 0) - cmd = new String[] { "p4", "changes", "-m", Integer.toString(limit), path }; - else - cmd = new String[] { "p4", "changes", path }; - - StringBuilder response = getPerforceResponse(cmd); - List ids = parseList(response, 1); - - List changes = new ArrayList(); - for(String id : ids) { - changes.add(getChangelist(new Integer(id))); - } - return changes; - } - - /** - * A lightweight call to return changelist numbers for a given path. - *

- * To get the latest change in the depot for the project, you can use: - * - *

-	 * depot.getChangeNumbers("//project/...", -1, 1)
-	 * 
- *

- * Note: this method follows perforce in that it starts at the highest number and works backwards. So this might not - * be what you want. (It certainly isn't for Hudson) - * - * @param path - * Path to filter on - * @param start - * The number of the change to start from - * @param limit - * The number of changes to return - * @return - * @throws PerforceException - */ - public List getChangeNumbers(String path, int start, int limit) throws PerforceException { - path = normalizePath(path); - if(start > 0) - path += "@" + start; - - String cmd[]; - - if(limit > 0) - cmd = new String[] { "p4", "changes", "-m", Integer.toString(limit), path }; - else - cmd = new String[] { "p4", "changes", path }; - - StringBuilder response = getPerforceResponse(cmd); - List ids = parseList(response, 1); - List numbers = new ArrayList(ids.size()); - for(String id : ids) { - numbers.add(new Integer(id)); - } - return numbers; - } - - /** - * Returns a list of changenumbers that start with the most recent change and work back to the specified change. - * - * @param path - * @param untilChange - * @return - */ - public List getChangeNumbersTo(String path, int untilChange) throws PerforceException { - - return getChangeNumbersTo(null, path, untilChange); - - } - - /** - * Returns a list of changenumbers that start with the most recent change and work back to the specified change. - * - * @param workspace - * @param path - * one or more paths, e.g. "//testproject/... //testfw/...". Paths are assumed to be delimited by a - * single space. - * @param untilChange - * @return - */ - public List getChangeNumbersTo(String workspace, String path, int untilChange) throws PerforceException { - String DELIM = " "; - - // maximum number of paths per command supported by perforce - // note that command line perforce supports up to three, but p4java only - // supports one. - int MAX_PATHS_SUPPORTED_PER_COMMAND = 1; - - // Ccheck our path variable to see if we have multiple paths separated by space. Add those to the list - StringTokenizer allPaths = new StringTokenizer(path, DELIM); - List supportedPaths = new ArrayList(); - StringBuilder currentPaths = new StringBuilder(""); - int numberOfPathsInCurrentPaths = 0; - while(true) { - if(!allPaths.hasMoreTokens()) { - if(currentPaths.length() > 0) { - supportedPaths.add(currentPaths.toString().trim()); - } - break; - } - String nextPath = allPaths.nextToken(); - currentPaths.append(nextPath + " "); - numberOfPathsInCurrentPaths++; - if(numberOfPathsInCurrentPaths == MAX_PATHS_SUPPORTED_PER_COMMAND) { - supportedPaths.add(currentPaths.toString().trim()); - currentPaths.setLength(0); - numberOfPathsInCurrentPaths = 0; - } - } - - // For each of those paths found, load the change list numbers for it. Store them in a set. - Set uniqueIds = new HashSet(); - for(String pathToUse : supportedPaths) { - List ids = getChangeNumbersToForSinglePath(workspace, pathToUse, untilChange); - uniqueIds.addAll(ids); - } - - // Sort and return - List sortedIds = new ArrayList(uniqueIds); - Collections.sort(sortedIds, Collections.reverseOrder()); - return sortedIds; - } - - /** - * Returns a list of changenumbers that start with the most recent change and work back to the specified change. - * - * @param workspace - * @param path - * a single path, e.g. //testproject/... - * @param untilChange - * @return - */ - private List getChangeNumbersToForSinglePath(String workspace, String path, int untilChange) throws PerforceException { - List numbers = new ArrayList(); - recurseGetChangeNumbersTo(workspace, path, untilChange, numbers); - return numbers; - } - - /** - * Internal method that will handle a Perforce MaxResults when looking for changelists that return too many results. - * If the error is encountered, it will call p4 dirs path/* to find a list of top level directories beneath the - * desired path. It will then iterate over that list and call itself on each directory. This gets beyond the - * MaxResults issue. See: https://hudson.dev.java.net/issues/show_bug.cgi?id=1939 - * - * @param workspace - * @param path - * @param untilChange - * @param numbers - * @throws PerforceException - */ - private void recurseGetChangeNumbersTo(String workspace, String path, int untilChange, List numbers) throws PerforceException { - path = normalizePath(path); - - List cmdList = new ArrayList(); - - addCommand(cmdList, "p4", "changes", "-m", "25"); - addCommandWorkspace(cmdList, workspace); - addCommand(cmdList, path); - - String lastChange; - while(true) { - // System.out.println("Looping: " + counter++); - StringBuilder response; - try { - // getPerforceResponse will throw an exception if a command it executes - // returns nothing from perforce. If we are moving back through a list and have - // less change lists in the history then what was specified, we will hit this - // exception - response = getPerforceResponse(cmdList.toArray(new String[cmdList.size()])); - if(hitMax(response)) { - String newPaths[] = getTopLevelDirectoriesForPath(workspace, path); - for(String newPath : newPaths) { - recurseGetChangeNumbersTo(workspace, newPath, untilChange, numbers); - } - break; - } - } catch(PerforceException e) { - if(e.getMessage().startsWith("No output for")) - break; - throw e; - } - List temp = parseList(response, 1); - if(temp.size() == 0) - break; - for(String num : temp) { - if(new Integer(num) >= untilChange) - numbers.add(new Integer(num)); - else - break; - } - lastChange = temp.get(temp.size() - 1); - int next = new Integer(lastChange) - 1; - cmdList.clear(); - addCommand(cmdList, "p4", "changes", "-m", "25"); - addCommandWorkspace(cmdList, workspace); - addCommand(cmdList, path + "@" + next); - } - } - - /** - * Executes: p4 dirs -C workspacename //depot/path/* to find a list of top level directories beneath the path. - * - * @param workspace - * The optional workspace to limit search to. Null if not used. - * @param path - * The path to search - * @return A string array of paths. - * @throws PerforceException - * If there are problems communicating with perforce. - */ - private String[] getTopLevelDirectoriesForPath(String workspace, String path) throws PerforceException { - - if(path.endsWith("...")) - path = path.replaceAll("\\.\\.\\.", "\\*"); - - List cmdList = new ArrayList(); - addCommand(cmdList, "p4", "dirs"); - addCommandWorkspace(cmdList, workspace); - addCommand(cmdList, path); - - StringBuilder response = getPerforceResponse(cmdList.toArray(new String[cmdList.size()])); - List list = parseList(response, 0); - - return list.toArray(new String[list.size()]); - } - - /** - * Add workspace to the command. - * - * @param cmdList - * @param workspace - */ - private void addCommandWorkspace(List cmdList, String workspace) { - if(workspace != null) { - addCommand(cmdList, "-c", workspace); - } - } - - /** - * translate the path into a p4 acceptable format. - * - * @param path - * the path - * @return the normalized path - */ - private String normalizePath(String path) { - if(path == null || path.equals("")) - path = "//..."; - return path; - } - - /** - * add one or more parameters to a command - * - * @param list - * the command - * @param args - * the parameters to add - */ - private void addCommand(List list, String... args) { - for(String command : args) { - list.add(command); - } - } - - /** - * Converts a list of numbers to a list of changes. - * - * @param numbers - * @return - * @throws PerforceException - */ - public List getChangelistsFromNumbers(List numbers) throws PerforceException { - List changes = new ArrayList(); - for(Integer id : numbers) { - changes.add(getChangelist(id)); - } - return changes; - } - - /** - * Creates a new changelist. - * - * @param changelist - * @throws PerforceException - */ - public void createChangelist(Changelist changelist) throws PerforceException { - StringBuilder builder = saveToPerforce(changelist, new ChangelistBuilder()); - // Response is "Changelist 1234 created." - String changelistNumber = builder.substring(builder.indexOf(" ") + 1, builder.lastIndexOf(" ")); - // get the changelist and populate rest of the fields - Changelist savedChangelist = getChangelist(Integer.parseInt(changelistNumber)); - changelist.setChangeNumber(savedChangelist.getChangeNumber()); - changelist.setDate(savedChangelist.getDate()); - changelist.setUser(savedChangelist.getUser()); - changelist.setWorkspace(savedChangelist.getWorkspace()); - changelist.setPending(savedChangelist.isPending()); - } -} diff --git a/src/main/java/com/tek42/perforce/parse/CounterBuilder.java b/src/main/java/com/tek42/perforce/parse/CounterBuilder.java deleted file mode 100644 index d9c3859..0000000 --- a/src/main/java/com/tek42/perforce/parse/CounterBuilder.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.tek42.perforce.parse; - -import java.io.Writer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Counter; - -/** - * Responsible for building and saving counters. - * - * @author Kamlesh Sangani - */ -public class CounterBuilder implements Builder { - - /* - * (non-Javadoc) - * @see com.tek42.perforce.parse.Builder#getBuildCmd(java.lang.String) - */ - public String[] getBuildCmd(String id) { - return new String[] { "p4", "counter", id }; - } - - /* - * (non-Javadoc) - * @see com.tek42.perforce.parse.Builder#getSaveCmd() - */ - public String[] getSaveCmd(Counter obj) { - return new String[] { "p4", "counter", obj.getName(), String.valueOf(obj.getValue()) }; - } - - /* - * (non-Javadoc) - * @see com.tek42.perforce.parse.Builder#build(java.lang.StringBuilder) - */ - public Counter build(StringBuilder sb) throws PerforceException { - final Pattern p = Pattern.compile("^([0-9])*", Pattern.DOTALL | Pattern.MULTILINE); - final Matcher m = p.matcher(sb.toString()); - final Counter counter = new Counter(); - counter.setName(""); - if(m.find()) { - counter.setValue(Integer.parseInt(m.group(0).trim())); - } - return counter; - } - - /* - * (non-Javadoc) - * @see com.tek42.perforce.parse.Builder#save(java.lang.Object, java.io.Writer) - */ - public void save(Counter counter, Writer writer) throws PerforceException {} - - /* - * (non-Javadoc) - * @see com.tek42.perforce.parse.Builder#getSaveCmd(T obj) - */ - public boolean requiresStandardInput() { - return false; - } -} diff --git a/src/main/java/com/tek42/perforce/parse/Counters.java b/src/main/java/com/tek42/perforce/parse/Counters.java deleted file mode 100644 index d9d0e3a..0000000 --- a/src/main/java/com/tek42/perforce/parse/Counters.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.tek42.perforce.parse; - -import java.util.ArrayList; -import java.util.List; - -import com.tek42.perforce.Depot; -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Counter; - -/** - * Base API object for interacting with counters. - * - * @author Kamlesh Sangani - */ -public class Counters extends AbstractPerforceTemplate { - - public Counters(Depot depot) { - super(depot); - } - - /** - * Saves the given counter. Creates new if one does not exist. - * - * @param counter - */ - public void saveCounter(Counter counter) throws PerforceException { - saveToPerforce(counter, new CounterBuilder()); - } - - /** - * Returns a list of counters in the system. - * - * @return a list of counters in the system - * @throws PerforceException - */ - public List getCounters() throws PerforceException { - final String cmd[] = new String[] { "p4", "counters" }; - final List counters = new ArrayList(); - - final StringBuilder response = getPerforceResponse(cmd); - final List names = parseList(response, 0); - - for(final String name : names) { - counters.add(getCounter(name)); - } - - return counters; - } - - /** - * Returns a counter specified by name. - * - * @param name - * counter name - * @return a counter specified by name - * @throws PerforceException - */ - public Counter getCounter(String name) throws PerforceException { - final CounterBuilder builder = new CounterBuilder(); - final Counter counter = builder.build(getPerforceResponse(builder.getBuildCmd(name))); - counter.setName(name); - return counter; - } -} diff --git a/src/main/java/com/tek42/perforce/parse/GroupBuilder.java b/src/main/java/com/tek42/perforce/parse/GroupBuilder.java deleted file mode 100644 index 4f26885..0000000 --- a/src/main/java/com/tek42/perforce/parse/GroupBuilder.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.parse; - -import java.util.Map; -import java.io.Writer; -import java.io.IOException; - -import com.tek42.perforce.model.Group; -import com.tek42.perforce.PerforceException; - -/** - * @author Mike - * Date: Jul 21, 2008 2:44:07 PM - */ -public class GroupBuilder extends AbstractFormBuilder { - public Group buildForm(Map fields) throws PerforceException { - Group group = new Group(); - group.setName(getField("Group", fields)); - group.setMaxLockTime(getField("MaxLockTime", fields)); - group.setMaxResults(getField("MaxResults", fields)); - group.setMaxScanRows(getField("MaxScanRows", fields)); - - String value = getField("Timeout", fields); - if(value.equals("")) - value = "0"; - - group.setTimeout(Long.parseLong(value)); - group.setUsers(getFieldAsList("Users", fields)); - group.setSubgroups(getFieldAsList("Subgroups", fields)); - group.setOwners(getFieldAsList("Owners", fields)); - - return group; - } - - public String[] getBuildCmd(String id) { - return new String[] { "p4", "group", "-o", id }; - } - - public String[] getSaveCmd(Group obj) { - return new String[] { "p4", "-s", "group", "-i" }; - } - - public void save(Group group, Writer out) throws PerforceException { - // A bit of validation to make sure we are correct. Perforce does NOT freaking tell us about this during the save... - if(group.getOwnersAsString().equals("")) { - throw new IllegalArgumentException("Group owner is a required field."); - } - /* form looks like: - Group: tekdev - - MaxResults: unlimited - - MaxScanRows: unlimited - - MaxLockTime: unlimited - - Timeout: 43200 - - Subgroups: - - Owners: - - Users: - anil - mwille - */ - try { - out.write("Group: " + group.getName() + "\n"); - out.write("MaxResults: " + group.getMaxResults() + "\n"); - out.write("MaxScanRows: " + group.getMaxScanRows() + "\n"); - out.write("MaxLockTime: " + group.getMaxLockTime() + "\n"); - out.write("Timeout: " + group.getTimeout() + "\n"); - out.write("Subgroups:\n"); - for(String s : group.getSubgroups()) { - out.write(" " + s + "\n"); - } - out.write("Owners:\n"); - for(String s : group.getOwners()) { - out.write(" " + s + "\n"); - } - out.write("Users:\n"); - for(String s : group.getUsers()) { - out.write(" " + s + "\n"); - } - - } catch(IOException e) { - throw new PerforceException("Failed to save group: " + group.getName(), e); - } - } -} diff --git a/src/main/java/com/tek42/perforce/parse/Groups.java b/src/main/java/com/tek42/perforce/parse/Groups.java deleted file mode 100644 index 94f6b7c..0000000 --- a/src/main/java/com/tek42/perforce/parse/Groups.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.parse; - -import java.util.List; -import java.util.ArrayList; - -import com.tek42.perforce.Depot; -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Group; -import com.tek42.perforce.model.Workspace; -import com.tek42.perforce.model.Changelist; - -/** - * Object for working with perforce groups. - * - * @author Mike - * Date: Jul 21, 2008 3:38:25 PM - */ -public class Groups extends AbstractPerforceTemplate { - public Groups(Depot depot) { - super(depot); - } - - /** - * Retrieves a single group specified by name. - * - * @param name The name of the group to retrieve. - * @return A valid perforce group. - * @throws PerforceException If there is a problem or the group was not found. - */ - public Group getGroup(String name) throws PerforceException { - GroupBuilder builder = new GroupBuilder(); - Group group = builder.build(getPerforceResponse(builder.getBuildCmd(name))); - if(group == null) - throw new PerforceException("Failed to retrieve group: " + name); - - return group; - } - - /** - * Saves changes to an existing group, or creates a new one. - * - * @param group The group to save. - * @throws PerforceException When there is a problem. - */ - public void saveGroup(Group group) throws PerforceException { - GroupBuilder builder = new GroupBuilder(); - saveToPerforce(group, builder); - } - - /** - * Retrieves all groups in the perforce server. - * - * @return A List of groups - * @throws PerforceException when there is a problem. - */ - public List getGroups() throws PerforceException { - String cmd[] = new String[] { "p4", "groups" }; - StringBuilder response = getPerforceResponse(cmd); - List names = parseList(response, 0); - - List groups = new ArrayList(); - for(String name : names) { - groups.add(getGroup(name)); - } - - return groups; - } -} diff --git a/src/main/java/com/tek42/perforce/parse/LabelBuilder.java b/src/main/java/com/tek42/perforce/parse/LabelBuilder.java deleted file mode 100644 index d51ac50..0000000 --- a/src/main/java/com/tek42/perforce/parse/LabelBuilder.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.parse; - -import java.io.IOException; -import java.io.Writer; -import java.util.Map; - -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Label; - -/** - * Responsible for building and saving labels. - * - * @author Mike Wille - */ -public class LabelBuilder extends AbstractFormBuilder

- * If the environment is valid, this method will return true. Otherwise, it will throw a - * PerforceException with a message regarding the failure. - */ - public boolean isValid() throws PerforceException { - getPerforceResponse(new String[] { "p4", "user", "-o" }); - return true; - } - - /** - * Checks the specified path to see if it exists in the depot. This may take a bit of time the first time it is - * called. It seems perforce takes a bit to wake up. - *

- * The path must end with the perforce wildcard: /... Otherwise it will return no results. - *

- * Note: this method may move once the API is more complete. - * - * @param path - * Path to check, example: //depot/MyProject/... - * @return True if it exists, false if not. - * @throws PerforceException - */ - public boolean exists(String path) throws PerforceException { - StringBuilder sb = getPerforceResponse(new String[] { "p4", "fstat", "-m", "1", path }); - if(sb.indexOf("no such file(s).") > 0) - return false; - return true; - } -} diff --git a/src/main/java/com/tek42/perforce/parse/UserBuilder.java b/src/main/java/com/tek42/perforce/parse/UserBuilder.java deleted file mode 100644 index 389e04f..0000000 --- a/src/main/java/com/tek42/perforce/parse/UserBuilder.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.parse; - -import java.io.Writer; -import java.util.Map; - -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.User; - -/** - * Responsible for building and saving user objects. - * - * @author Mike Wille - */ -public class UserBuilder extends AbstractFormBuilder { - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.parse.AbstractFormBuilder#buildForm(java.util.Map) - */ - @Override - public User buildForm(Map fields) throws PerforceException { - User user = new User(); - user.setUsername(getField("User", fields)); - user.setEmail(getField("Email", fields)); - user.setFullName(getField("FullName", fields)); - user.setPassword(getField("Password", fields)); - user.setJobView(getField("JobView", fields)); - user.setReviews(getField("Review", fields)); - return user; - } - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.parse.Builder#getBuildCmd(java.lang.String) - */ - public String[] getBuildCmd(String id) { - return new String[] { "p4", "user", "-o", id }; - } - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.parse.Builder#getSaveCmd() - */ - public String[] getSaveCmd(User obj) { - // TODO Auto-generated method stub - return null; - } - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.parse.Builder#save(java.lang.Object, java.io.Writer) - */ - public void save(User obj, Writer writer) throws PerforceException { - // TODO Auto-generated method stub - } - -} diff --git a/src/main/java/com/tek42/perforce/parse/Users.java b/src/main/java/com/tek42/perforce/parse/Users.java deleted file mode 100644 index 3fc3ccf..0000000 --- a/src/main/java/com/tek42/perforce/parse/Users.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.parse; - -import com.tek42.perforce.Depot; -import com.tek42.perforce.model.User; - -/** - * Base API object for interacting with users. - * - * @author Mike Wille - */ -public class Users extends AbstractPerforceTemplate { - public Users(Depot depot) { - super(depot); - } - - /** - * Returns the user specified by username. - * - * @param name - * @return - * @throws Exception - */ - public User getUser(String name) throws Exception { - UserBuilder builder = new UserBuilder(); - User user = builder.build(getPerforceResponse(builder.getBuildCmd(name))); - return user; - } -} diff --git a/src/main/java/com/tek42/perforce/parse/WorkspaceBuilder.java b/src/main/java/com/tek42/perforce/parse/WorkspaceBuilder.java deleted file mode 100644 index a2633be..0000000 --- a/src/main/java/com/tek42/perforce/parse/WorkspaceBuilder.java +++ /dev/null @@ -1 +0,0 @@ -/* * P4Java - java integration with Perforce SCM * Copyright (C) 2007-, Mike Wille, Tek42 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * You can contact the author at: * * Web: http://tek42.com * Email: mike@tek42.com * Mail: 755 W Big Beaver Road * Suite 1110 * Troy, MI 48084 */ package com.tek42.perforce.parse; import java.io.*; import java.util.*; import com.tek42.perforce.model.*; import com.tek42.perforce.PerforceException; /** * Responsible for building and saving workspaces. * * @author Mike Wille */ public class WorkspaceBuilder extends AbstractFormBuilder { /* * (non-Javadoc) * * @see com.tek42.perforce.parse.Builder#build(java.lang.StringBuilder) */ public Workspace buildForm(Map fields) throws PerforceException { Workspace workspace = new Workspace(); workspace.setName(getField("Client", fields)); workspace.setOwner(getField("Owner", fields)); workspace.setHost(getField("Host", fields)); workspace.setRoot(getField("Root", fields)); workspace.setOptions(getField("Options", fields)); workspace.setSubmitOptions(getField("SubmitOptions", fields)); workspace.setLineEnd(getField("LineEnd", fields)); workspace.setAltRoots(getField("AltRoots", fields)); workspace.setDescription(getField("Description", fields)); workspace.setUpdate(getField("Update", fields)); workspace.setAccess(getField("Access", fields)); for(String line : getField("View", fields).split("\\n")) { workspace.addView(line); } return workspace; } /* * (non-Javadoc) * * @see com.tek42.perforce.parse.Builder#getBuildCmd(java.lang.String) */ public String[] getBuildCmd(String id) { return new String[] { "p4", "workspace", "-o", id }; } /* * (non-Javadoc) * * @see com.tek42.perforce.parse.Builder#getSaveCmd() */ public String[] getSaveCmd(Workspace obj) { return new String[] { "p4", "-s", "client", "-i" }; } /* * (non-Javadoc) * * @see com.tek42.perforce.parse.Builder#save(java.lang.Object) */ public void save(Workspace workspace, Writer out) throws PerforceException { try { out.write("Client: " + workspace.getName() + "\n"); if(!workspace.getOwner().equals("")) out.write("Owner: " + workspace.getOwner() + "\n"); if(!workspace.getHost().equals("")) out.write("Host: " + workspace.getHost() + "\n"); out.write("Description: " + workspace.getDescription() + "\n"); out.write("Root: " + workspace.getRoot() + "\n"); if(!workspace.getAltRoots().equals("")) out.write("AltRoots: " + workspace.getAltRoots() + "\n"); out.write("Options: " + workspace.getOptions() + "\n"); if(!workspace.getSubmitOptions().equals("")) out.write("SubmitOptions: " + workspace.getSubmitOptions() + "\n"); out.write("LineEnd: " + workspace.getLineEnd() + "\n"); out.write("View:\n"); out.write(" " + workspace.getViewsAsString() + "\n"); } catch(IOException e) { throw new PerforceException("Failed to save workspace", e); } } } \ No newline at end of file diff --git a/src/main/java/com/tek42/perforce/parse/Workspaces.java b/src/main/java/com/tek42/perforce/parse/Workspaces.java deleted file mode 100644 index 0b6a145..0000000 --- a/src/main/java/com/tek42/perforce/parse/Workspaces.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.parse; - -import com.tek42.perforce.Depot; -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Workspace; - -/** - * Base API object for interacting with workspaces. - * - * @author Mike Wille - */ -public class Workspaces extends AbstractPerforceTemplate { - public Workspaces(Depot depot) { - super(depot); - } - - /** - * Returns a workspace specified by name. - * - * @param name - * @return - * @throws PerforceException - */ - public Workspace getWorkspace(String name) throws PerforceException { - WorkspaceBuilder builder = new WorkspaceBuilder(); - Workspace workspace = builder.build(getPerforceResponse(builder.getBuildCmd(name))); - if(workspace == null) - throw new PerforceException("Failed to retrieve workspace: " + name); - - return workspace; - } - - /** - * Saves changes to an existing workspace, or creates a new one. - * - * @param workspace - * @throws PerforceException - */ - public void saveWorkspace(Workspace workspace) throws PerforceException { - WorkspaceBuilder builder = new WorkspaceBuilder(); - saveToPerforce(workspace, builder); - } - - /** - * Synchronizes to the latest change for the specified path. Convenience function - * for {@see syncTo(String, boolean)} - * - * @param path - * @return - * @throws PerforceException - */ - public StringBuilder syncToHead(String path) throws PerforceException { - return syncToHead(path, false); - } - - /** - * Synchronizes to the latest change for the specified path. Allows a force sync to be performed by passing true to - * forceSync parameter. - * - * @param path - * The depot path to sync to - * @param forceSync - * True to force sync and overwrite local files - * @return StringBuilder containing output of p4 response. - * @throws PerforceException - */ - public StringBuilder syncToHead(String path, boolean forceSync) throws PerforceException { - if(!path.endsWith("#head")) { - path += "#head"; - } - return syncTo(path, forceSync); - } - - /** - * Provides method to sync to a depot path and allows for any revision, changelist, label, etc. - * to be appended to the path. - *

- * A force sync can be specified by passing true to forceSync. - * - * @param path - * The depot path to sync to. Perforce suffix for [revRange] is allowed. - * @param forceSync - * Should we force a sync to grab all files regardless of version on disk? - * @return - * A StringBuilder that contains the output of the p4 execution. - * @throws PerforceException - */ - public StringBuilder syncTo(String path, boolean forceSync) throws PerforceException { - if(forceSync) - return getPerforceResponse(new String[] { "p4", "sync", "-f", path }); - else - return getPerforceResponse(new String[] { "p4", "sync", path }); - } -} diff --git a/src/main/java/com/tek42/perforce/parse/package.html b/src/main/java/com/tek42/perforce/parse/package.html deleted file mode 100644 index 4fed433..0000000 --- a/src/main/java/com/tek42/perforce/parse/package.html +++ /dev/null @@ -1,18 +0,0 @@ - - - -com.tek42.perforce package - - - - -

-Provides a the classes necessary for parsing p4 output and for writing to p4. -

- - - diff --git a/src/main/java/com/tek42/perforce/process/CmdLineExecutor.java b/src/main/java/com/tek42/perforce/process/CmdLineExecutor.java deleted file mode 100644 index 2848bb6..0000000 --- a/src/main/java/com/tek42/perforce/process/CmdLineExecutor.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.process; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tek42.perforce.PerforceException; - -/** - * Executes on the command line. This is not thread safe. - * - * @author Mike Wille - */ -public class CmdLineExecutor implements Executor { - ProcessBuilder builder; - Process currentProcess; - List args; - BufferedWriter writer; - BufferedReader reader; - private final Logger logger = LoggerFactory.getLogger("perforce"); - - /** - * Requires a map of environment variables (P4USER, P4CLIENT, P4PORT, etc) - * - * @param environment - */ - public CmdLineExecutor(Map environment) { - args = new ArrayList(); - builder = new ProcessBuilder(args); - Map env = builder.environment(); - for(Map.Entry entry : environment.entrySet()) { - // if(key.equals("P4PASSWD")) - // continue; - // logger.warn("Settin env: " + key + " = " + environment.get(key)); - env.put(entry.getKey(), entry.getValue()); - } - } - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.process.P4Executor#exec(java.lang.String[]) - */ - public void exec(String[] args) throws PerforceException { - this.args.clear(); - StringBuilder debug = new StringBuilder(); - for(String arg : args) { - debug.append(arg + " "); - this.args.add(arg); - } - logger.info("Executing: " + debug); - builder.redirectErrorStream(true); - try { - currentProcess = builder.start(); - reader = new BufferedReader(new InputStreamReader(currentProcess.getInputStream())); - writer = new BufferedWriter(new OutputStreamWriter(currentProcess.getOutputStream())); - - } catch(IOException e) { - throw new PerforceException("Failed to open connection to: " + args[0], e); - } - } - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.process.P4Executor#getReader() - */ - public BufferedReader getReader() { - return reader; - } - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.process.P4Executor#getWriter() - */ - public BufferedWriter getWriter() { - return writer; - } - - /* - * (non-Javadoc) - * - * @see com.tek42.perforce.process.P4Executor#close() - */ - public void close() { - try { - if(reader != null) { - reader.close(); - } - reader = null; - } catch(IOException e) { - } - - try { - if(writer != null) { - writer.close(); - } - writer = null; - } catch(IOException e) { - } - } - - /** - * Useful for things like process.waitFor(). - * - * @return - */ - public Process getProcess() { - return currentProcess; - } - -} diff --git a/src/main/java/com/tek42/perforce/process/DefaultExecutorFactory.java b/src/main/java/com/tek42/perforce/process/DefaultExecutorFactory.java deleted file mode 100644 index e503a20..0000000 --- a/src/main/java/com/tek42/perforce/process/DefaultExecutorFactory.java +++ /dev/null @@ -1 +0,0 @@ -/* * P4Java - java integration with Perforce SCM * Copyright (C) 2007-, Mike Wille, Tek42 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * You can contact the author at: * * Web: http://tek42.com * Email: mike@tek42.com * Mail: 755 W Big Beaver Road * Suite 1110 * Troy, MI 48084 */ package com.tek42.perforce.process; import java.util.Map; import java.util.HashMap; /** * Default @{link ExecutorFactory} that handles creating new {@link CmdLineExecutor}s * * @author Mike Wille */ public class DefaultExecutorFactory implements ExecutorFactory { Map env; /* * (non-Javadoc) * * @see com.tek42.perforce.process.ExecutorFactory#newExecutor() */ public Executor newExecutor() { return new CmdLineExecutor(env); } /* * (non-Javadoc) * * @see com.tek42.perforce.process.ExecutorFactory#setEnv(java.util.Map) */ public void setEnv(Map env) { this.env = new HashMap(); for(Map.Entry entry : env.entrySet()) { this.env.put(entry.getKey(), entry.getValue()); } } } \ No newline at end of file diff --git a/src/main/java/com/tek42/perforce/process/Executor.java b/src/main/java/com/tek42/perforce/process/Executor.java deleted file mode 100644 index d519536..0000000 --- a/src/main/java/com/tek42/perforce/process/Executor.java +++ /dev/null @@ -1 +0,0 @@ -/* * P4Java - java integration with Perforce SCM * Copyright (C) 2007-, Mike Wille, Tek42 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * You can contact the author at: * * Web: http://tek42.com * Email: mike@tek42.com * Mail: 755 W Big Beaver Road * Suite 1110 * Troy, MI 48084 */ package com.tek42.perforce.process; import java.io.*; import com.tek42.perforce.*; /** * A simplified interface for interacting with another process. * * @author Mike Wille */ public interface Executor { /** * Execute the specified command and its arguments * * @param args * @throws PerforceException */ public void exec(String args[]) throws PerforceException; /** * Returns a BufferedWriter for writing to the stdin of this process * * @return */ public BufferedWriter getWriter(); /** * Returns a BufferedReader for reading from the stdout/stderr of this process * * @return */ public BufferedReader getReader(); /** * Close down all open resources */ public void close(); } \ No newline at end of file diff --git a/src/main/java/com/tek42/perforce/process/ExecutorFactory.java b/src/main/java/com/tek42/perforce/process/ExecutorFactory.java deleted file mode 100644 index f62c3ef..0000000 --- a/src/main/java/com/tek42/perforce/process/ExecutorFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * P4Java - java integration with Perforce SCM - * Copyright (C) 2007-, Mike Wille, Tek42 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * You can contact the author at: - * - * Web: http://tek42.com - * Email: mike@tek42.com - * Mail: 755 W Big Beaver Road - * Suite 1110 - * Troy, MI 48084 - */ - -package com.tek42.perforce.process; - -import java.util.*; - -/** - * Parent interface to handle creation of new {@link Executor} objects. - * - * @author Mike Wille - */ -public interface ExecutorFactory { - /** - * Sets a the environment variables for processes to be run. - * - * @param env - */ - public void setEnv(Map env); - - /** - * Creates a new executor for running a process. - * - * @return - */ - public Executor newExecutor(); -} diff --git a/src/main/java/com/tek42/perforce/process/package.html b/src/main/java/com/tek42/perforce/process/package.html deleted file mode 100644 index e1580e1..0000000 --- a/src/main/java/com/tek42/perforce/process/package.html +++ /dev/null @@ -1,39 +0,0 @@ - - - -com.tek42.perforce package - - - - - -

Provides objects for interacting with processes. All of our - interaction with perforce happens through the command line client: p4. -

-

-This package provides methods for simplifying the interaction with system calls. Additionally, -it abstracts this interaction so that other methods could be used. For example, the perforce native -DLL for windows. -

-

-@{link ExecutorFactory} provides an interface for an object that is responsible for holding on to the -system environment passed to the child process. It has a method to obtain a new child process wrapper. -

-

-@{link Executor} provides an interface that represents the basic functionality needed for working with -a child process. This boils down to 4 methods: -

    -
  • Execution - @{link Executor#exec}
  • -
  • Reading from process - @{link Executor#getReader}
  • -
  • Writing to process - @{link Executor#getWriter}
  • -
  • Closing the process - @{link Executor#close}
  • -
-Currently there is an executor implementation for command line interaction. If the native libraries for -p4 where used, we would need a dll implementation. -

- - diff --git a/src/main/resources/README b/src/main/resources/README deleted file mode 100644 index 728b166..0000000 --- a/src/main/resources/README +++ /dev/null @@ -1,24 +0,0 @@ -P4Java - java integration with Perforce SCM -Copyright (C) 2007-2008 Mike Wille, Tek42 - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Contact the author at: - -Web: http://tek42.com -Email: mike@tek42.com -Mail: 755 W Big Beaver Road - Suite 1110 - Troy, MI 48084 \ No newline at end of file diff --git a/src/main/resources/license.txt b/src/main/resources/license.txt deleted file mode 100644 index 3f9959f..0000000 --- a/src/main/resources/license.txt +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. \ No newline at end of file diff --git a/src/test/java/com/tek42/perforce/ChangelistTest.java b/src/test/java/com/tek42/perforce/ChangelistTest.java deleted file mode 100644 index 81f51f0..0000000 --- a/src/test/java/com/tek42/perforce/ChangelistTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.tek42.perforce; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -import com.tek42.perforce.model.Changelist; - -/** - * @author mwille - */ -public class ChangelistTest extends PropertySupport { - Depot depot; - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - depot = new Depot(); - depot.setPort(getProperty("p4.port")); - depot.setUser(getProperty("p4.user")); - depot.setPassword(getProperty("p4.passwd")); - depot.setClient(getProperty("p4.client")); - } - - /** - * Test method for {@link com.tek42.perforce.Depot#getEnvp()}. - */ - @Test - public void testGetChangelist() throws Exception { - int id = new Integer(getProperty("changelist.middlechange")); - Changelist change = depot.getChanges().getChangelist(id); - System.out.println("\nRetrieved Changelist:\n" + change.toString()); - } - - /** - * Test method for {@link com.tek42.perforce.Depot#getChangelists(java.lang.String, int, int)}. - */ - @Test - public void testGetLimitedChangelists() throws Exception { - List changes = depot.getChanges().getChangelists(getProperty("changelist.project"), -1, 5); - assertNotNull(changes); - assertEquals(4, changes.size()); - - String ids[] = getProperties("changelist.numbers"); - int i = 0; - for(Changelist change : changes) { - assertEquals(new Integer(ids[i++]).intValue(), change.getChangeNumber()); - } - } - - @Test - public void testGetAllChangelists() throws Exception { - List changes = depot.getChanges().getChangelists(getProperty("changelist.project"), 0, -1); - assertNotNull(changes); - assertTrue(changes.size() > 0); - - String ids[] = getProperties("changelist.numbers"); - assertEquals(ids.length, changes.size()); - int i = 0; - for(Changelist change : changes) { - assertEquals(new Integer(ids[i++]).intValue(), change.getChangeNumber()); - } - } - - @Test - public void testGetLastestChange() throws Exception { - int change = new Integer(getProperty("changelist.lastchange")); - List changes = depot.getChanges().getChangelists(getProperty("changelist.project"), -1, 1); - assertNotNull(changes); - assertEquals(1, changes.size()); - assertEquals(change, changes.get(0).getChangeNumber()); - } - - @Test - public void testGetChangeNumbers() throws Exception { - List numbers = depot.getChanges().getChangeNumbers(getProperty("changelist.project"), -1, 5); - for(int num : numbers) { - System.out.println("Found change: " + num); - } - } - - @Test - public void testGetRange() throws Exception { - int number = new Integer(getProperty("changelist.firstchange")); - List numbers = depot.getChanges().getChangeNumbersTo(getProperty("changelist.project"), number); - String ids[] = getProperties("changelist.numbers"); - assertEquals(ids.length, numbers.size()); - - assertEquals(new Integer(getProperty("changelist.lastchange")), numbers.get(0)); - assertEquals(new Integer(getProperty("changelist.firstchange")), numbers.get(numbers.size() - 1)); - } - - @Test - public void testGetChangeNumbersNotInclusive() throws Exception { - int change = new Integer(getProperty("changelist.lastchange")); - System.out.println("Last change listed in config: " + change); - List changes = depot.getChanges().getChangelistsFromNumbers( - depot.getChanges().getChangeNumbersTo(getProperty("changelist.project"), change + 1)); - assertEquals(0, changes.size()); - - changes = depot.getChanges().getChangelists(getProperty("changelist.project"), -1, 1); - assertEquals(change, changes.get(0).getChangeNumber()); - System.out.println("Latest change in depot is: " + changes.get(0).getChangeNumber()); - } - - // @Test - public void testCreateChangeList() throws Exception { - Changelist changelist = new Changelist(); - changelist.setDescription("desc"); - - Depot.getInstance().getChanges().createChangelist(changelist); - assertNotNull(changelist.getChangeNumber()); - assertTrue(changelist.isPending()); - assertNotNull(depot.getChanges().getChangelist(changelist.getChangeNumber())); - } - -} diff --git a/src/test/java/com/tek42/perforce/CounterTest.java b/src/test/java/com/tek42/perforce/CounterTest.java deleted file mode 100644 index e421110..0000000 --- a/src/test/java/com/tek42/perforce/CounterTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.tek42.perforce; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -import com.tek42.perforce.model.Counter; - -/** - * @author Kamlesh Sangani - */ -public class CounterTest extends PropertySupport { - - private Depot depot; - - /** - * @throws com.tek42.perforce.PerforceException - */ - @Before - public void setUp() throws PerforceException { - this.depot = new Depot(); - this.depot.setPort(getProperty("p4.port")); - this.depot.setUser(getProperty("p4.user")); - this.depot.setPassword(getProperty("p4.passwd")); - this.depot.setClient(getProperty("p4.client")); - } - - @Test - public void testGetCounter() throws PerforceException { - final Counter counter = this.depot.getCounters().getCounter("change"); - assertEquals("Counter names should be equal", "change", counter.getName()); - assertTrue("Counter value should be >= 0", counter.getValue() >= 0); - } - - @Test - public void testGetCounters() throws PerforceException { - final List counters = this.depot.getCounters().getCounters(); - for(final Counter counter : counters) { - assertNotNull("Counter name should not be null", counter.getName()); - assertTrue("Counter value should be >= 0", counter.getValue() >= 0); - } - } - - @Test - public void testSaveCounter() throws PerforceException { - final Counter counter = new Counter(); - counter.setName("test"); - counter.setValue(101); - - this.depot.getCounters().saveCounter(counter); - - final Counter actualCounter = this.depot.getCounters().getCounter(counter.getName()); - assertEquals("Counter names should be equal", counter.getName(), actualCounter.getName()); - assertEquals("Counter value should be equal", counter.getValue(), actualCounter.getValue()); - } -} diff --git a/src/test/java/com/tek42/perforce/DepotTest.java b/src/test/java/com/tek42/perforce/DepotTest.java deleted file mode 100644 index e42e066..0000000 --- a/src/test/java/com/tek42/perforce/DepotTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.tek42.perforce; - -import java.io.*; - -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -/** - * - * @author mwille - * - */ -public class DepotTest extends PropertySupport { - Depot depot; - /** - * - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - depot = new Depot(); - depot.setPort(getProperty("p4.port")); - depot.setUser(getProperty("p4.user")); - depot.setPassword(getProperty("p4.passwd")); - depot.setClient(getProperty("p4.client")); - - String home = System.getProperty("user.home"); - System.out.println("Deleting p4 tickets under: " + home); - new File(home + "/" + ".p4tickets").delete(); - new File(home + "\\" + "p4tickets.txt").delete(); - } - - /** - * - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } - - @Test - public void testServerInfo() throws Exception { - System.out.println("\nPerforce Info:\n" + depot.info()); - } - - /** - * Test method for {@link com.tek42.perforce.Depot#checkValidity()}. - */ - @Test - public void testCheckValidity() throws Exception { - assertTrue(depot.getStatus().isValid()); - } -} diff --git a/src/test/java/com/tek42/perforce/GroupsTest.java b/src/test/java/com/tek42/perforce/GroupsTest.java deleted file mode 100644 index c07bef1..0000000 --- a/src/test/java/com/tek42/perforce/GroupsTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.tek42.perforce; - -import java.util.List; -import java.util.ArrayList; -import java.util.Collections; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import org.junit.Before; -import org.junit.Test; - -import com.tek42.perforce.model.Label; -import com.tek42.perforce.model.Group; - -/** - * @author Mike - * Date: Jul 21, 2008 3:47:46 PM - */ -public class GroupsTest extends PropertySupport { - Depot depot; - static String ticket; - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - depot = new Depot(); - depot.setPort(getProperty("p4.port")); - depot.setUser(getProperty("p4.user")); - depot.setPassword(getProperty("p4.passwd")); - depot.setClient(getProperty("p4.client")); - depot.setP4Ticket(ticket); - } - - /** - * Test method for {@link com.tek42.perforce.parse.Labels#getLabels(java.lang.String)}. - */ - @Test - public void testGetGroups() throws Exception { - List groups = depot.getGroups().getGroups(); - for(Group g : groups) { - System.out.println("Group: " + g.getName()); - } - } - - /** - * Test method for {@link com.tek42.perforce.parse.Labels#getLabel(java.lang.String)}. - */ - @Test - public void testGetGroup() throws Exception { - Group group = depot.getGroups().getGroup(getProperty("group.name")); - assertNotNull(group); - assertEquals(getProperty("group.name"), group.getName()); - assertEquals(Long.parseLong(getProperty("group.timeout")), (long) group.getTimeout()); - } - - /** - * Test method for {@link com.tek42.perforce.parse.Labels#saveLabel(com.tek42.perforce.model.Label)}. - */ - @Test - public void testCreateGroup() throws Exception { - Group group = new Group(); - group.setName(getProperty("group.new.name")); - List users = new ArrayList(); - users.add(getProperty("group.new.user").trim()); - group.setUsers(users); - List owners = new ArrayList(); - owners.add(getProperty("p4.user").trim()); - group.setOwners(owners); - group.setTimeout(Long.parseLong(getProperty("group.new.timeout"))); - - Group copy = group; - - depot.getGroups().saveGroup(group); - - group = depot.getGroups().getGroup(getProperty("group.new.name")); - - assertNotNull(group); - - assertEquals(copy.getName(), group.getName()); - assertEquals(copy.getUsersAsString(), group.getUsersAsString()); - assertEquals(copy.getOwnersAsString(), group.getOwnersAsString()); - assertEquals(copy.getSubgroupsAsString(), group.getSubgroupsAsString()); - assertEquals(copy.getTimeout(), group.getTimeout()); - assertEquals(copy.getMaxLockTime(), group.getMaxLockTime()); - assertEquals(copy.getMaxResults(), group.getMaxResults()); - assertEquals(copy.getMaxScanRows(), group.getMaxScanRows()); - } - - @Test - public void testSaveChanges() throws Exception { - Group group = depot.getGroups().getGroup(getProperty("group.name")); - - group.setTimeout(100L); - - depot.getGroups().saveGroup(group); - - group = depot.getGroups().getGroup(getProperty("group.name")); - - assertNotNull(group); - - assertEquals(100L, (long) group.getTimeout()); - - // Must reset data in perforce... - group.setTimeout(Long.parseLong(getProperty("group.timeout"))); - depot.getGroups().saveGroup(group); - } - - /** - * This guy is here because our main method to test login retries on expired session is to modify the timeout of - * the user's group. - * - * @throws Exception - */ - @Test - public void testLoginExpiration() throws Exception { - System.out.println("p4 info: \n" + depot.info()); - Group group = depot.getGroups().getGroup(getProperty("group.name")); - // long enough that we can change this back when we are done without hitting the timeout... - group.setTimeout(5L); - depot.getGroups().saveGroup(group); - group = depot.getGroups().getGroup(getProperty("group.name")); - assertEquals(5L, (long) group.getTimeout()); - Thread.sleep(7000L); - assertEquals(true, depot.getStatus().isValid()); - // We should get a PerforceException about not being logged in... (But we aren't under my test instance ??!!) - group = depot.getGroups().getGroup(getProperty("group.name")); - group.setTimeout(Long.parseLong(getProperty("group.timeout"))); - depot.getGroups().saveGroup(group); - - } -} diff --git a/src/test/java/com/tek42/perforce/LabelsTest.java b/src/test/java/com/tek42/perforce/LabelsTest.java deleted file mode 100644 index d89c2b9..0000000 --- a/src/test/java/com/tek42/perforce/LabelsTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.tek42.perforce; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import com.tek42.perforce.model.*; - -/** - * - * @author mwille - * - */ -public class LabelsTest extends PropertySupport { - Depot depot; - static String ticket; - /** - * - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - depot = new Depot(); - depot.setPort(getProperty("p4.port")); - depot.setUser(getProperty("p4.user")); - depot.setPassword(getProperty("p4.passwd")); - depot.setClient(getProperty("p4.client")); - depot.setP4Ticket(ticket); - } - - /** - * Test method for {@link com.tek42.perforce.parse.Labels#getLabels(java.lang.String)}. - */ - @Test - public void testGetLabels() throws Exception { - - } - - /** - * Test method for {@link com.tek42.perforce.parse.Labels#getLabel(java.lang.String)}. - */ - @Test - public void testGetLabel() throws Exception { - Label label = depot.getLabels().getLabel(getProperty("label.name")); - assertNotNull(label); - assertEquals(getProperty("label.name"), label.getName()); - ticket = depot.getP4Ticket(); - System.out.println("GetLabel -> Ticket: " + ticket); - } - - /** - * Test method for {@link com.tek42.perforce.parse.Labels#saveLabel(com.tek42.perforce.model.Label)}. - */ - @Test - public void testSaveLabel() throws Exception { - System.out.println("SaveLabel ->Ticket: " + ticket); - Label label = new Label(); - label.setName(getProperty("label.name")); - label.setDescription(getProperty("label.desc")); - label.setOptions(getProperty("label.options")); - label.setOwner(getProperty("label.owner")); - label.setRevision(getProperty("label.revision")); - label.addView(getProperty("label.view")); - - Label copy = label; - - depot.getLabels().saveLabel(label); - - label = depot.getLabels().getLabel(getProperty("label.name")); - - assertNotNull(label); - - assertEquals(copy.getName(), label.getName()); - assertEquals(copy.getDescription(), label.getDescription()); - assertEquals(copy.getOptions(), label.getOptions()); - assertEquals(copy.getOwner(), label.getOwner()); - assertEquals(copy.getRevision(), label.getRevision()); - assertEquals(copy.getViewsAsString(), label.getViewsAsString()); - } -} diff --git a/src/test/java/com/tek42/perforce/PropertySupport.java b/src/test/java/com/tek42/perforce/PropertySupport.java deleted file mode 100644 index 4479444..0000000 --- a/src/test/java/com/tek42/perforce/PropertySupport.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.tek42.perforce; - -import java.io.*; -import java.util.*; - -/** - * Provides support for loading test configuration from a properties file. - * - * @author Mike Wille - * - */ -public abstract class PropertySupport { - protected Properties props; - protected String PROP_FILE = "test"; - - /** - * Looks up a property in the PROP_FILE - * - * @param key - * @return The value if it exists or blank if the key did not exist. - */ - public String getProperty(String key) { - if(props == null) { - try { - // InputStream stream = - // getClass().getClassLoader().getResourceAsStream (PROP_FILE); - String packageName = getClass().getPackage().getName().replaceAll("\\.", "/"); - props = loadProperties(packageName + "/" + PROP_FILE); - } catch(Exception e) { - // file doesn't exist, fail silently... - System.err.println("Failed to load test properties: " + PROP_FILE); - System.err.println(e.getMessage()); - e.printStackTrace(); - return ""; - } - } - String value = props.getProperty(key); - if(value == null) - return ""; - return value.trim(); - } - - /** - * Returns a 1D string array of values for a property that had a delimited list of values. - * - * @param key - * @return - */ - public String[] getProperties(String key) { - return getProperty(key).split(","); - } - - /** - * Looks up a resource named 'name' in the classpath. The resource must map - * to a file with .properties extention. The name is assumed to be absolute - * and can use either "/" or "." for package segment separation with an - * optional leading "/" and optional ".properties" suffix. Thus, the - * following names refer to the same resource: - * - *
-	 * some.pkg.Resource
-	 * some.pkg.Resource.properties
-	 * some/pkg/Resource
-	 * some/pkg/Resource.properties
-	 * /some/pkg/Resource
-	 * /some/pkg/Resource.properties
-	 * 
- * - * @param name - * classpath resource name [may not be null] - * @param loader - * classloader through which to load the resource [null is - * equivalent to the application loader] - * - * @return resource converted to java.util.Properties [may be null if the - * resource was not found and THROW_ON_LOAD_FAILURE is false] - * @throws IllegalArgumentException - * if the resource was not found and THROW_ON_LOAD_FAILURE is - * true - */ - public static Properties loadProperties(String name, ClassLoader loader) { - if(name == null) - throw new IllegalArgumentException("null input: name"); - - if(name.startsWith("/")) - name = name.substring(1); - - if(name.endsWith(SUFFIX)) - name = name.substring(0, name.length() - SUFFIX.length()); - - Properties result = null; - - InputStream in = null; - try { - if(loader == null) - loader = ClassLoader.getSystemClassLoader(); - - if(LOAD_AS_RESOURCE_BUNDLE) { - name = name.replace('/', '.'); - // Throws MissingResourceException on lookup failures: - final ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault(), loader); - - result = new Properties(); - for(Enumeration keys = rb.getKeys(); keys.hasMoreElements();) { - final String key = keys.nextElement(); - final String value = rb.getString(key); - - result.put(key, value); - } - } else { - name = name.replace('.', '/'); - - if(!name.endsWith(SUFFIX)) - name = name.concat(SUFFIX); - - // Returns null on lookup failures: - in = loader.getResourceAsStream(name); - if(in != null) { - result = new Properties(); - result.load(in); // Can throw IOException - } - } - } catch(Exception e) { - result = null; - } finally { - if(in != null) - try { - in.close(); - } catch(Throwable ignore) { - } - } - - if(THROW_ON_LOAD_FAILURE && (result == null)) { - throw new IllegalArgumentException("could not load [" + name + "]" + " as " - + (LOAD_AS_RESOURCE_BUNDLE ? "a resource bundle" : "a classloader resource")); - } - - return result; - } - - /** - * A convenience overload of {@link #loadProperties(String, ClassLoader)} - * that uses the current thread's context classloader. - */ - public static Properties loadProperties(final String name) { - return loadProperties(name, Thread.currentThread().getContextClassLoader()); - } - - private static final boolean THROW_ON_LOAD_FAILURE = true; - - private static final boolean LOAD_AS_RESOURCE_BUNDLE = false; - - private static final String SUFFIX = ".properties"; -} diff --git a/src/test/java/com/tek42/perforce/UserTest.java b/src/test/java/com/tek42/perforce/UserTest.java deleted file mode 100644 index 61114e9..0000000 --- a/src/test/java/com/tek42/perforce/UserTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.tek42.perforce; - -import static org.junit.Assert.*; -import org.junit.Test; -import org.junit.Before; - -import com.tek42.perforce.model.*; - -/** - * - * @author mwille - * - */ -public class UserTest extends PropertySupport { - Depot depot; - - /** - * - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - depot = new Depot(); - depot.setPort(getProperty("p4.port")); - depot.setUser(getProperty("p4.user")); - depot.setPassword(getProperty("p4.passwd")); - depot.setClient(getProperty("p4.client")); - } - - @Test - public void testGetUser() throws Exception { - User user = depot.getUsers().getUser(getProperty("user.username")); - assertNotNull(user); - assertEquals(getProperty("user.username"), user.getUsername()); - assertEquals(getProperty("user.email"), user.getEmail()); - assertEquals(getProperty("user.fullname"), user.getFullName()); - } - - @Test - public void testSessionExpiredRetry() throws Exception { - - } - - /* - @Test - public void testCreateUser() throws Exception { - - } - - @Test - public void testSaveUser() throws Exception { - - } - */ -} diff --git a/src/test/java/com/tek42/perforce/WorkspaceTest.java b/src/test/java/com/tek42/perforce/WorkspaceTest.java deleted file mode 100644 index af22f58..0000000 --- a/src/test/java/com/tek42/perforce/WorkspaceTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.tek42.perforce; - -import static org.junit.Assert.*; - -import java.io.*; -import java.util.Date; - -import org.junit.Before; -import org.junit.Test; - -import com.tek42.perforce.model.Workspace; - -/** - * - * @author mwille - * - */ -public class WorkspaceTest extends PropertySupport { - Depot depot; - static String ticket; - /** - * - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - depot = new Depot(); - depot.setPort(getProperty("p4.port")); - depot.setUser(getProperty("p4.user")); - depot.setPassword(getProperty("p4.passwd")); - depot.setClient(getProperty("p4.client")); - depot.setP4Ticket(ticket); - } - - /** - * Test method for {@link com.tek42.perforce.parse.Workspaces#getWorkspace(String)}. - */ - @Test - public void testGetWorkspace() throws Exception { - Workspace workspace = depot.getWorkspaces().getWorkspace(getProperty("ws.existingname")); - System.out.println("Have workspace: \n" + workspace); - // work around for saving to depot not authenticating first. I KNOW. I KNOW. - ticket = depot.getP4Ticket(); - } - - @Test - public void testMyCreateWorkspace() throws Exception { - Workspace workspace = new Workspace(); - String name = getProperty("ws.name"); - workspace.setName(name); - workspace.setDescription(getProperty("ws.create.desc") + new Date()); - workspace.setHost(getProperty("ws.create.host")); - workspace.setLineEnd(getProperty("ws.create.lineend")); - workspace.setRoot(getProperty("ws.create.root")); - workspace.setAltRoots(getProperty("ws.create.altroot")); - workspace.setOptions(getProperty("ws.create.options")); - workspace.setOwner(getProperty("ws.create.owner")); - workspace.setSubmitOptions(getProperty("ws.create.submitoptions")); - workspace.addView(getProperty("ws.create.view")); - - Workspace copy = workspace; - - depot.getWorkspaces().saveWorkspace(workspace); - - workspace = depot.getWorkspaces().getWorkspace(name); - - assertNotNull(workspace); - - // For some reason, this doesn't quite work... - //assertEquals(copy, workspace); - assertEquals(copy.getName(), workspace.getName()); - assertEquals(copy.getDescription(), workspace.getDescription()); - assertEquals(copy.getHost(), workspace.getHost()); - assertEquals(copy.getLineEnd(), workspace.getLineEnd()); - assertEquals(copy.getRoot(), workspace.getRoot()); - assertEquals(copy.getAltRoots(), workspace.getAltRoots()); - assertEquals(copy.getOptions(), workspace.getOptions()); - assertEquals(copy.getSubmitOptions(), workspace.getSubmitOptions()); - assertEquals(copy.getOwner(), workspace.getOwner()); - assertEquals(copy.getViewsAsString(), workspace.getViewsAsString()); - } - - @Test - public void testUpdateWorkspace() throws Exception { - Workspace workspace = depot.getWorkspaces().getWorkspace(getProperty("ws.name")); - - workspace.setRoot(getProperty("ws.update.root")); - workspace.clearViews(); - workspace.addView(getProperty("ws.update.view")); - String desc = getProperty("ws.update.desc") + new Date(); - workspace.setDescription(desc); - workspace.setSubmitOptions(getProperty("ws.update.submitoptions")); - - depot.getWorkspaces().saveWorkspace(workspace); - - workspace = depot.getWorkspaces().getWorkspace(getProperty("ws.name")); - assertNotNull(workspace); - assertEquals(getProperty("ws.update.root"), workspace.getRoot()); - assertEquals(getProperty("ws.update.view") + "\n", workspace.getViewsAsString()); - assertEquals(desc, workspace.getDescription()); - - } - - @Test - public void testSyncToLabel() throws Exception { - Workspace workspace = depot.getWorkspaces().getWorkspace(getProperty("p4.client")); - File dir = new File(workspace.getRoot()); - if(!dir.exists()) { - dir.mkdirs(); - } - StringBuilder sb = depot.getWorkspaces().syncTo(getProperty("changelist.project") + "@TestLabel", true); - System.out.println(sb); - File test = new File(dir.getAbsolutePath() + "/" + getProjectFolder(getProperty("changelist.project")) + "/project-file.txt"); - System.out.println("Checking for file: " + test.getAbsolutePath()); - assertTrue("Workspace sync failed, file does not exist.", test.exists()); - } - - /** - * Test properties only has a depot path, we'll fix that here... - * @param depotPath - * @return - */ - private String getProjectFolder(String depotPath) { - depotPath = depotPath.substring(7); - depotPath = depotPath.replaceAll("/\\.\\.\\.", ""); - return depotPath; - - } -} diff --git a/src/test/java/com/tek42/perforce/parse/ChangelistBuilderTest.java b/src/test/java/com/tek42/perforce/parse/ChangelistBuilderTest.java deleted file mode 100644 index fc06ee0..0000000 --- a/src/test/java/com/tek42/perforce/parse/ChangelistBuilderTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.tek42.perforce.parse; - -import java.io.*; - -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Changelist; - -import junit.framework.TestCase; - -public class ChangelistBuilderTest extends TestCase { - - public void testBuild() throws Exception { - //InputStream is = new FileInputStream("ChangelistTest-Issue-1092.txt"); - InputStream is = this.getClass().getResourceAsStream("ChangelistTest-Issue-1092.txt"); - - StringBuilder sb = new StringBuilder(); - byte[] buff = new byte[10*1024*1024]; - int read = 0; - while( (read = is.read(buff)) != -1 ) { - String line = new String(buff, 0, read); - sb.append(line); - - } - - ChangelistBuilder b = new ChangelistBuilder(); - Changelist c = b.build(sb); - System.out.println("Changelist: " + c); - } - - public void testBuildChangelistContainsOthers() throws Exception { - InputStream is = this.getClass().getResourceAsStream("ChangelistTest-Issue-1821.txt"); - - StringBuilder sb = new StringBuilder(); - byte[] buff = new byte[10*1024*1024]; - int read = 0; - while( (read = is.read(buff)) != -1 ) { - String line = new String(buff, 0, read); - sb.append(line); - - } - - ChangelistBuilder b = new ChangelistBuilder(); - Changelist c = b.build(sb); - System.out.println("Changelist: " + c); - } - -} diff --git a/src/test/java/com/tek42/perforce/parse/CounterBuilderTest.java b/src/test/java/com/tek42/perforce/parse/CounterBuilderTest.java deleted file mode 100644 index 86c79d0..0000000 --- a/src/test/java/com/tek42/perforce/parse/CounterBuilderTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.tek42.perforce.parse; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Counter; - -/** - * @author Kamlesh Sangani - */ -public class CounterBuilderTest { - - @Test - public void testBuild() throws PerforceException { - final int counterValue = 456456; - final StringBuilder sb = new StringBuilder(); - sb.append(String.valueOf(counterValue)); - sb.append("\r\n"); - sb.append("\r\n"); - final CounterBuilder counterBuilder = new CounterBuilder(); - final Counter counter = counterBuilder.build(sb); - assertEquals("Counter names should be equal", "", counter.getName()); - assertEquals("Counter value should be equal", counterValue, counter.getValue()); - } - - @Test - public void testGetSaveCmd() throws PerforceException { - final String counterName = "test"; - final int counterValue = 100; - final Counter counter = new Counter(); - counter.setName(counterName); - counter.setValue(counterValue); - - final String[] commands = new CounterBuilder().getSaveCmd(counter); - final String[] expectedCommands = new String[] { "p4", "counter", counterName, String.valueOf(counterValue) }; - - assertEquals("Commands length should be equal", expectedCommands.length, commands.length); - - for(int i = 0; i < expectedCommands.length; i++) { - assertEquals("Command should be equal", expectedCommands[i], commands[i]); - } - } - - @Test - public void testGetBuildCmd() throws PerforceException { - final String counterName = "test"; - final CounterBuilder counterBuilder = new CounterBuilder(); - final String[] commands = counterBuilder.getBuildCmd(counterName); - final String[] expectedCommands = new String[] { "p4", "counter", counterName }; - - assertEquals("Commands length should be equal", expectedCommands.length, commands.length); - - for(int i = 0; i < expectedCommands.length; i++) { - assertEquals("Command should be equal", expectedCommands[i], commands[i]); - } - } - -} diff --git a/src/test/java/com/tek42/perforce/parse/GroupBuilderTest.java b/src/test/java/com/tek42/perforce/parse/GroupBuilderTest.java deleted file mode 100644 index 2d6709a..0000000 --- a/src/test/java/com/tek42/perforce/parse/GroupBuilderTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.tek42.perforce.parse; - -import java.io.InputStream; -import java.io.OutputStreamWriter; - -import com.tek42.perforce.model.Group; -import junit.framework.TestCase; - -/** - * @author Mike - * Date: Jul 21, 2008 3:20:53 PM - */ -public class GroupBuilderTest extends TestCase { - - public void testBuild() throws Exception { - System.out.println("GroupBuilderTest.testBuild() >>>>>>>>>>>"); - InputStream is = this.getClass().getResourceAsStream("GroupTest.txt"); - - StringBuilder sb = new StringBuilder(); - byte[] buff = new byte[10*1024*1024]; - int read = 0; - while( (read = is.read(buff)) != -1 ) { - String line = new String(buff, 0, read); - sb.append(line); - - } - - GroupBuilder b = new GroupBuilder(); - Group g = b.build(sb); - System.out.println("New Group:\n" + g); - } - - public void testSave() throws Exception { - System.out.println("GroupBuilderTest.testSave() >>>>>>>>>>>"); - InputStream is = this.getClass().getResourceAsStream("GroupTest.txt"); - - StringBuilder sb = new StringBuilder(); - byte[] buff = new byte[10*1024*1024]; - int read = 0; - while( (read = is.read(buff)) != -1 ) { - String line = new String(buff, 0, read); - sb.append(line); - - } - - GroupBuilder b = new GroupBuilder(); - Group g = b.build(sb); - - OutputStreamWriter osw = new OutputStreamWriter(System.out); - b.save(g, osw); - osw.flush(); - } -} diff --git a/src/test/java/com/tek42/perforce/parse/WorkspaceBuilderTest.java b/src/test/java/com/tek42/perforce/parse/WorkspaceBuilderTest.java deleted file mode 100644 index e18752d..0000000 --- a/src/test/java/com/tek42/perforce/parse/WorkspaceBuilderTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.tek42.perforce.parse; - -import java.io.*; - -import com.tek42.perforce.PerforceException; -import com.tek42.perforce.model.Changelist; -import com.tek42.perforce.model.Workspace; - -import junit.framework.TestCase; - -public class WorkspaceBuilderTest extends TestCase { - - public void testBuild() throws Exception { - InputStream is = this.getClass().getResourceAsStream("Clientspec-Serverv2003-Issue-1070.txt"); - - StringBuilder sb = new StringBuilder(); - byte[] buff = new byte[10*1024*1024]; - int read = 0; - while( (read = is.read(buff)) != -1 ) { - String line = new String(buff, 0, read); - sb.append(line); - - } - - WorkspaceBuilder wb = new WorkspaceBuilder(); - Workspace w = wb.build(sb); - System.out.println("Changelist: " + w); - } - -} diff --git a/src/test/resources/com/tek42/perforce/README-test.properties b/src/test/resources/com/tek42/perforce/README-test.properties deleted file mode 100644 index a12be9a..0000000 --- a/src/test/resources/com/tek42/perforce/README-test.properties +++ /dev/null @@ -1,74 +0,0 @@ -######################################################## -# This file contains the configuration and some test -# data for the perforce tests. If you wish to run these -# tests, you will need to change some values to suit -# your installation of perforce. -# -# When you have added good data, you will need to rename this -# file to test.properties. -# -# MODIFY CONNECTION DETAILS... -p4.user=username -p4.passwd=password -p4.port=hostname.com:1666 -p4.client=clientname - -# -# For Changelist tests -# You will need to provide a path and list of changes -# that exist on your perforce installation. -changelist.project=//depot/ProjectName/... -# below from most recent to earliest... -# (this needs all changes for a particular project. Obviously, -# a real project might not be the best match here.) -changelist.numbers=8,7,6,5,4,3,2,1 -changelist.lastchange=8 -changelist.secondtolastchange=7 -changelist.firstchange=1 -changelist.middlechange=4 - -# For User tests -# Provide a user that exists. -user.username=username -user.fullname=Full Name -user.email=email@hostname.com - -# For Workspace tests -# You'll need an existing workspace. -ws.existingname=workspace -ws.name=test-workspace - -ws.create.desc=Testing workspace creation. -ws.create.host=workstation -ws.create.root=c:/dev -ws.create.altroot=/Users/username/dev -ws.create.options=noallwrite noclobber compress unlocked nomodtime normdir -ws.create.owner=username -ws.create.lineend=unix -ws.create.submitoptions=revertunchanged -ws.create.view=//depot/... //test-workspace/... - -ws.update.desc=Testing workspace update. -ws.update.host=workstation2 -ws.update.root=c:/dev2 -ws.update.altroot=/Users/username/dev2 -ws.update.options=allwrite clobber compress locked modtime rmdir -ws.update.owner=anybody -ws.update.lineend=unix -ws.update.submitoptions=submitunchanged -ws.update.view=//depot/... //test-workspace/2/... - -label.name=TestLabel -label.desc=label for testing -label.options=unlocked -label.owner=username -label.revision="#1" -label.view=//... - -group.name=TestGroup -group.timeout=43200 - -group.new.name=NewTestGroup -group.new.user=username -group.new.timeout=5 -group.new.maxresults=1000 diff --git a/src/test/resources/com/tek42/perforce/parse/ChangelistTest-Issue-1092.txt b/src/test/resources/com/tek42/perforce/parse/ChangelistTest-Issue-1092.txt deleted file mode 100644 index 18a3bee..0000000 --- a/src/test/resources/com/tek42/perforce/parse/ChangelistTest-Issue-1092.txt +++ /dev/null @@ -1,15 +0,0 @@ -Change 166289 by aaa@bbb on 2007/10/12 15:04:45 - - Change 166281 by aaa@bbb on 2007/10/12 13:36:25 - - Some dummy description here - - Responsibles: John - - - Affected files ... - -Affected files ... - -... //something/file.java#2 edit - diff --git a/src/test/resources/com/tek42/perforce/parse/ChangelistTest-Issue-1821.txt b/src/test/resources/com/tek42/perforce/parse/ChangelistTest-Issue-1821.txt deleted file mode 100644 index 5fb6366..0000000 --- a/src/test/resources/com/tek42/perforce/parse/ChangelistTest-Issue-1821.txt +++ /dev/null @@ -1,20 +0,0 @@ -Change 208013 by garyd@GARYD on 2007/03/26 15:00:23 - - Integrate the following Changelist: - - 3/26/2007 2:54:07 PM - garyd: - Change 208010 by garyd@GARYD on 2007/03/26 14:53:42 - - CR66913: Missing TxnFileLoader.sh to run TxnFileLoader Utility - - Adding the properties and shell script needed to kick off the - TxnFileLoader utility. - - This has been tested by formal test but requires these properties and - script for operations to run it. - -Affected files ... - -... //bds/main/development/bmcagent/WEB-INF/classes/brewcustom.properties#2 integrate -... //bds/main/development/bmcagent/runtxnfileloader.sh#1 branch - diff --git a/src/test/resources/com/tek42/perforce/parse/Clientspec-Serverv2003-Issue-1070.txt b/src/test/resources/com/tek42/perforce/parse/Clientspec-Serverv2003-Issue-1070.txt deleted file mode 100644 index fbb76d5..0000000 --- a/src/test/resources/com/tek42/perforce/parse/Clientspec-Serverv2003-Issue-1070.txt +++ /dev/null @@ -1,37 +0,0 @@ -# A Perforce Client Specification. -# -# Client: The client name. -# Update: The date this specification was last modified. -# Access: The date this client was last used in any way. -# Owner: The user who created this client. -# Host: If set, restricts access to the named host. -# Description: A short description of the client (optional). -# Root: The base directory of the client workspace. -# AltRoots: Up to two alternate client workspace roots. -# Options: Client options: -# [no]allwrite [no]clobber [no]compress -# [un]locked [no]modtime [no]rmdir -# LineEnd: Text file line endings on client: local/unix/mac/win/share. -# View: Lines to map depot files into the client workspace. -# -# Use 'p4 help client' to see more about client views and options. - -Client: Azrail - -Update: 2006/08/21 09:25:32 - -Access: 2008/01/24 15:30:26 - -Owner: edawid - -Description: - Created by edawid. - -Root: /Users/edawid/Projects - -Options: noallwrite noclobber nocompress unlocked nomodtime normdir - -LineEnd: share - -View: - //depot/... //Azrail/... diff --git a/src/test/resources/com/tek42/perforce/parse/GroupTest.txt b/src/test/resources/com/tek42/perforce/parse/GroupTest.txt deleted file mode 100644 index 1f9aefe..0000000 --- a/src/test/resources/com/tek42/perforce/parse/GroupTest.txt +++ /dev/null @@ -1,36 +0,0 @@ -# A Perforce Group Specification. -# -# Group: The name of the group. -# MaxResults: Limits the rows (or 'unlimited') any one operation can -# return to the client. See 'p4 help maxresults'. -# MaxScanRows: Limits the rows (or 'unlimited') any one operation can scan -# from any one database table. See 'p4 help maxresults'. -# MaxLockTime: Limits the time (in milliseconds, or 'unlimited') any one -# operation can lock any database table when scanning data. -# See 'p4 help maxresults'. -# Timeout: A time (in seconds) which determines how long a 'p4 login' -# session ticket remains valid (default is 12 hours). -# Subgroups: Other groups automatically included in this group. -# Owners: Users allowed to change this group without requiring super -# access permission. -# Users: The users in the group. One per line. - -Group: tekdev - -MaxResults: unlimited - -MaxScanRows: unlimited - -MaxLockTime: unlimited - -Timeout: 43200 - -Subgroups: - -Owners: - mwille - tuba - -Users: - anil - mwille