package com.perforce.p4camel;
import java.net.URISyntaxException;
import java.util.Properties;
import com.perforce.p4java.PropertyDefs;
import com.perforce.p4java.exception.ConfigException;
import com.perforce.p4java.exception.ConnectionException;
import com.perforce.p4java.exception.NoSuchObjectException;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.exception.ResourceException;
import com.perforce.p4java.impl.mapbased.rpc.RpcPropertyDefs;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.ServerFactory;
public class ConnectionFactory {
public static IOptionsServer getConnection(P4Endpoint endpoint)
throws ConnectionException, NoSuchObjectException, ConfigException,
ResourceException, URISyntaxException {
String address = endpoint.getHost() + ":" + endpoint.getPort();
if (endpoint.isSsl()) {
return getConnection("p4javassl://" + address);
} else {
return getConnection("p4java://" + address);
}
}
private static IOptionsServer getConnection(String uri)
throws ConnectionException, NoSuchObjectException, ConfigException,
ResourceException, URISyntaxException {
Properties props = System.getProperties();
ConnectionConfig config = new ConnectionConfig();
// Identify ourselves in server log files.
props.put(PropertyDefs.PROG_NAME_KEY, config.getProduct());
props.put(PropertyDefs.PROG_VERSION_KEY, config.getVersion());
// Allow p4 admin commands.
props.put(RpcPropertyDefs.RPC_RELAX_CMD_NAME_CHECKS_NICK, "true");
// disable timeout for slow servers / large db lock times
props.put(RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK, "0");
// Get a server connection
IOptionsServer iserver = null;
iserver = ServerFactory.getOptionsServer(uri, props);
return iserver;
}
public static void login(IOptionsServer p4, P4Endpoint endpoint)
throws P4JavaException {
p4.setUserName(endpoint.getUsername());
// CHARSET is not defined (only for client access)
if (p4.getServerInfo().isUnicodeEnabled()) {
p4.setCharsetName("utf8");
}
if (!isLogin(p4)) {
String pass = endpoint.getPassword();
p4.login(pass);
}
}
public static void logout(IOptionsServer p4) throws P4JavaException {
if (isLogin(p4)) {
p4.logout();
}
}
private static boolean isLogin(IOptionsServer p4) throws P4JavaException {
String status = p4.getLoginStatus();
if (status.contains("not necessary")) {
return true;
}
if (status.contains("ticket expires in")) {
return true;
}
// If there is a broker or something else that swallows the message
if (status.isEmpty()) {
return true;
}
return false;
}
}