Java Code Examples for java.net.UnknownHostException

The following are top voted examples for showing how to use java.net.UnknownHostException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: Trivial4b   File: TrivialAPI.java View source code 9 votes vote down vote up
private static DB conectar() {
	MongoClient mongoClient = null;
	MongoCredential mongoCredential = MongoCredential
			.createMongoCRCredential("trivialuser", "trivial",
					"4btrivialmongouser".toCharArray());
	try {
		mongoClient = new MongoClient(new ServerAddress(
				"ds062797.mongolab.com", 62797),
				Arrays.asList(mongoCredential));
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}

	DB db = mongoClient.getDB("trivial");
	System.out.println("Conexion creada con la base de datos");
	return db;
}
 
Example 2
Project: Torrent-Client   File: UTPPacket.java View source code 8 votes vote down vote up
public UTPPacket(UTPPacket other) {
	this.ver = other.ver;
	this.type = other.type;
	this.extension = other.extension;
	this.connection_id = other.connection_id;
	this.connection_id_recv = other.connection_id_recv;
	this.connection_id_send = other.connection_id_send;
	this.timestamp_difference_microseconds = other.timestamp_difference_microseconds;
	this.timestamp_microseconds = other.timestamp_microseconds;
	this.wnd_size = other.wnd_size;
	this.seq_nr = other.seq_nr;
	this.ack_nr = other.ack_nr;
	this.size = other.size;
	for (int i = 0; i < extra.length; i++) 
		this.extra[i] = other.extra[i];
	
	try {
		this.inet = InetAddress.getByAddress(other.inet.getAddress());
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	this.port = other.port;
}
 
Example 3
Project: usc   File: UscDtoUtilsTest.java View source code 8 votes vote down vote up
@Test
public void uscRemoteChannelEquals() {
    InetAddress address1 = null;
    InetAddress address2 = null;
    try {
        address1 = InetAddress.getByName("192.168.56.102");
        address2 = InetAddress.getByName("192.168.56.102");
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    UscDeviceMountTable table = UscDeviceMountTable.getInstance();
    UscRemoteChannelIdentifier remoteChannel1 = new UscRemoteChannelIdentifier(address1, ChannelType.TLS);
    UscRemoteChannelIdentifier remoteChannel2 = new UscRemoteChannelIdentifier(address2, ChannelType.TLS);
    table.addEntry(remoteChannel1, null);
    Assert.assertEquals(remoteChannel1, remoteChannel2);
    // Assert.assertTrue(table.existRemoteChannel(remoteChannel2, null));
}
 
Example 4
Project: balerocms-enterprise   File: UserAuthenticationErrorHandler.java View source code 7 votes vote down vote up
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
    try {
        InetAddress ip = InetAddress.getLocalHost();
        Object userName = event.getAuthentication().getPrincipal();
        Object credentials = event.getAuthentication().getCredentials();
        log.warn("Failed login using USERNAME " +
                userName + " and PASSWORD " + credentials + " from " + ip.getHostAddress());
        blacklistService.addIpToBlacklist(ip.getHostAddress());

    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: SecurePhoto   File: ConnectionHandler.java View source code 7 votes vote down vote up
public ConnectionHandler(SecureServer server, Socket clientSocket) {
    this.clientSocket = clientSocket;
    this.server = server;

    name = "";
    address = "";

    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        address = Arrays.toString(inetAddress.getAddress());
        name = inetAddress.getHostName();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}
 
Example 6
Project: TinyRadius   File: TestProxy.java View source code 7 votes vote down vote up
public RadiusEndpoint getProxyServer(RadiusPacket packet,
		RadiusEndpoint client) {
	// always proxy
	try {
		InetAddress address = InetAddress.getByAddress(new byte[]{127,0,0,1});
		int port = 10000;
		if (packet instanceof AccountingRequest)
			port = 10001;
		return new RadiusEndpoint(new InetSocketAddress(address, port), "testing123");
	} catch (UnknownHostException uhe) {
		uhe.printStackTrace();
		return null;
	}
}
 
Example 7
Project: hadoop_ekg   File: NICParser.java View source code 7 votes vote down vote up
/**
 * Invokes query() to do the parsing and handles parsing errors for 
 * each one of the NICs specified in the configuration. 
 * 
 * @return an array of EventRecords that holds one element that represents
 * the current state of network interfaces.
 */
public EventRecord[] monitor() {
  ArrayList<EventRecord> recs = new ArrayList<EventRecord>();

  for (String nic : nics) {
    try {
      recs.add(query(nic));
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }

  EventRecord[] T = new EventRecord[recs.size()];

  return recs.toArray(T);
}
 
Example 8
Project: R5A   File: Peer2PeerConnection.java View source code 7 votes vote down vote up
@Override
public String connect(OnReceiveHandler handler) {
	if (peerID.equals("")) {
		this.manager = getManager();
		this.sender = new Sender(this.manager);
		this.receiver = new Receiver(this.manager, handler);
		this.receiver.start();
	}

	String uniqueID = sender.getPeerID();
	try {
		uniqueID += InetAddress.getLocalHost().getHostAddress();
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
	return uniqueID;
}
 
Example 9
Project: WS171-frameworks-base   File: DomainNameChecker.java View source code 7 votes vote down vote up
/**
 * @return True iff the domain name is specified as an IP address
 */
private static boolean isIpAddress(String domain) {
    boolean rval = (domain != null && domain.length() != 0);
    if (rval) {
        try {
            // do a quick-dirty IP match first to avoid DNS lookup
            rval = QUICK_IP_PATTERN.matcher(domain).matches();
            if (rval) {
                rval = domain.equals(
                    InetAddress.getByName(domain).getHostAddress());
            }
        } catch (UnknownHostException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
              errorMessage = "unknown host exception";
            }

            if (HttpLog.LOGV) {
                HttpLog.v("DomainNameChecker.isIpAddress(): " + errorMessage);
            }

            rval = false;
        }
    }

    return rval;
}
 
Example 10
Project: Leads-QueryProcessorM   File: WP3Configuration.java View source code 6 votes vote down vote up
public static void initialize() {

        properties = getProperties();
        if (!loadPropertiesFile("processor.properties"))
            loadDefaultWP3Values();
        if (!loadPropertiesFile("config.properties"))
            loadDefaultCrawlerValues();
        if (!properties.containsKey(StringConstants.CLUSTER_NAME_KEY)) {
            properties.setProperty(StringConstants.CLUSTER_NAME_KEY, StringConstants.DEFAULT_CLUSTER_NAME);
        }
        if (!properties.containsKey(StringConstants.NODE_NAME_KEY)) {
            properties.setProperty(StringConstants.NODE_NAME_KEY, StringConstants.DEFAULT_NODE_NAME);
        }
        if(!properties.containsKey("crawlerCache"))
            properties.setProperty("crawlerCache", "preprocessingMap");
        String hostname = "";
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        properties.setProperty("hostname", hostname);


    }
 
Example 11
Project: RelaxFactory   File: ProxyDaemon.java View source code 6 votes vote down vote up
public ProxyDaemon(ProxyTask... proxyTask) {
  this.proxyTask = proxyTask.length > 0 ? proxyTask[0] : new ProxyTask();

  if (PROXY_PORT != 0)
    try {
      preallocAddr = new InetSocketAddress(InetAddress.getByName(PROXY_HOST), PROXY_PORT);
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
}
 
Example 12
Project: keycloak   File: HostUtils.java View source code 6 votes vote down vote up
private static String getHostNameImpl() {
    // Return bind address if available
    String bindAddr = System.getProperty("jboss.bind.address");
    if (bindAddr != null && !bindAddr.trim().equals("0.0.0.0")) {
        return bindAddr;
    }

    // Fallback to qualified name
    String qualifiedHostName = System.getProperty("jboss.qualified.host.name");
    if (qualifiedHostName != null) {
        return qualifiedHostName;
    }

    // If not on jboss env, let's try other possible fallbacks
    // POSIX-like OSes including Mac should have this set
    qualifiedHostName = System.getenv("HOSTNAME");
    if (qualifiedHostName != null) {
        return qualifiedHostName;
    }

    // Certain versions of Windows
    qualifiedHostName = System.getenv("COMPUTERNAME");
    if (qualifiedHostName != null) {
        return qualifiedHostName;
    }

    try {
        return NetworkUtils.canonize(getLocalHost().getHostName());
    } catch (UnknownHostException uhe) {
        uhe.printStackTrace();
        return "unknown-host.unknown-domain";
    }
}
 
Example 13
Project: BlockServer   File: ServerBuilder.java View source code 6 votes vote down vote up
public ServerBuilder(){
	try{
		address = InetAddress.getByName("localhost");
	}catch(UnknownHostException e){
		e.printStackTrace();
	}
}
 
Example 14
Project: bigpetstore   File: NICParser.java View source code 6 votes vote down vote up
/**
 * Invokes query() to do the parsing and handles parsing errors for 
 * each one of the NICs specified in the configuration. 
 * 
 * @return an array of EventRecords that holds one element that represents
 * the current state of network interfaces.
 */
public EventRecord[] monitor() {
  ArrayList<EventRecord> recs = new ArrayList<EventRecord>();

  for (String nic : nics) {
    try {
      recs.add(query(nic));
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }

  EventRecord[] T = new EventRecord[recs.size()];

  return recs.toArray(T);
}
 
Example 15
Project: ecologylabFundamental   File: NetTools.java View source code 6 votes vote down vote up
/**
 * local host address (parse out only IP address)
 * 
 * @return
 */
public static String localHost()
{
	String localHost1 = NetTools.localHost;
	if (localHost1 == null)
	{
		try
		{
			localHost1 = InetAddress.getLocalHost().toString();
			// localHost = localHost.replace('/','_');
			localHost1 = localHost1.substring(localHost1.indexOf('/') + 1);
			NetTools.localHost = localHost1;
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}
	}
	return localHost1;
}
 
Example 16
Project: vivarium   File: Server.java View source code 6 votes vote down vote up
public static void main(String[] args)
{
    System.out.println("SERVER: Running Vivarium Research Server.");
    try
    {
        Server server = new Server();
        server.start();
    }
    catch (UnknownHostException e)
    {
        e.printStackTrace();
    }
}
 
Example 17
Project: voms-api-java   File: TestACValidator.java View source code 6 votes vote down vote up
@Test
public void testTargetValidationSuccess() throws Exception {

  VOMSAA aa = Utils.getVOMSAA();

  String localhostName;

  try {

    localhostName = InetAddress.getLocalHost().getCanonicalHostName();

  } catch (UnknownHostException e) {
    throw new VOMSError("Error resolving local hostname: " + e.getMessage(),
      e);
  }

  VOMSACValidator validator = Utils.getVOMSValidator();
  ProxyCertificate proxy = aa.createVOMSProxy(Utils.getTestUserCredential(),
    Arrays.asList("/test.vo"), null, Arrays.asList(localhostName));

  List<VOMSValidationResult> results = validator.validateWithResult(proxy
    .getCertificateChain());
  Assert.assertEquals(1, results.size());
  VOMSValidationResult r = results.get(0);

  Assert.assertTrue(r.isValid());
}
 
Example 18
Project: turmeric-security   File: CloneableSubjectType.java View source code 6 votes vote down vote up
private int convertIPFromStringToInt(String ip) {
	try {
		InetAddress ia = InetAddress.getByName(ip); 
		 byte[] b = ia.getAddress(); 
		 return ((b[0] << 24) & 0xFF000000) + ((b[1] << 16) & 0x00FF0000) 
		 		+ ((b[2] << 8) & 0x0000FF00) + ((b[3] << 0) & 0x000000FF);
	} catch (UnknownHostException e) {
		throw new IllegalArgumentException("Invalid IP :" + ip + ": " + e.getMessage());
	} 
}
 
Example 19
Project: iqrfsdk   File: UDPNetworkLayerMultinet.java View source code 6 votes vote down vote up
/**
 * Creates new UDP client network layer object.
 * @param connectionStorage storage of network UDP connections
 * @param localHostName local host name, or [email protected] null} for the loopback address
 * @param localPort local port number
 * @param maxRecvPacketSize maximal size of received packets [in bytes].
 * @param receptionTimeout timeout [in ms] of blocking waiting for reception 
 *                        of packet from the socket. [email protected] 0} means infinity
 *                        waiting.
 */
public UDPNetworkLayerMultinet(
        NetworkConnectionStorage connectionStorage,
        String localHostName, 
        int localPort, 
        int maxRecvPacketSize, 
        int receptionTimeout
 ) {
    super(checkStorage(connectionStorage));
    try {
        this.localAddress = InetAddress.getByName(localHostName);
    } catch (UnknownHostException ex) {
        throw new IllegalArgumentException("Hostname not valid: " + ex.getMessage());
    }
    this.localPort = localPort;
    
    this.maxRecvPacketSize = checkMaxRecvPacketSize(maxRecvPacketSize);
    this.receptionTimeout = checkReceptionTimeout(receptionTimeout);
}
 
Example 20
Project: jubatus-msgpack-rpc   File: IPAddress.java View source code 6 votes vote down vote up
public InetSocketAddress getInetSocketAddress() {
    try {
        return new InetSocketAddress(InetAddress.getByAddress(address),
                port);
    } catch (UnknownHostException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 21
Project: fitNevis   File: CommandRunningFitClient.java View source code 6 votes vote down vote up
public CommandRunningFitClient(TestSystemListener listener, String command, int port, Map<String, String> environmentVariables, SocketDealer dealer, boolean fastTest) {
  super(listener);
  this.fastTest = fastTest;
  ticketNumber = dealer.seekingSocket(this);
  String hostName;
  try {
    hostName = java.net.InetAddress.getLocalHost().getHostName();
  } catch (UnknownHostException e) {
    throw new RuntimeException(e.getMessage(), e);
  }
  String fitArguments = hostName + SPACE + port + SPACE + ticketNumber;
  String commandLine = command + SPACE + fitArguments;
  if (fastTest) {
    commandRunner = new MockCommandRunner();
    createFitServer("-x " + fitArguments);
  } else
    commandRunner = new CommandRunner(commandLine, "", environmentVariables);
}
 
Example 22
Project: groundhog-reader   File: DomainNameChecker.java View source code 6 votes vote down vote up
/**
 * @return True iff the domain name is specified as an IP address
 */
private static boolean isIpAddress(String domain) {
    boolean rval = (domain != null && domain.length() != 0);
    if (rval) {
        try {
            // do a quick-dirty IP match first to avoid DNS lookup
            rval = QUICK_IP_PATTERN.matcher(domain).matches();
            if (rval) {
                rval = domain.equals(
                    InetAddress.getByName(domain).getHostAddress());
            }
        } catch (UnknownHostException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
              errorMessage = "unknown host exception";
            }

            rval = false;
        }
    }

    return rval;
}
 
Example 23
Project: werval   File: FreePortFinder.java View source code 6 votes vote down vote up
public static int findRandomOnInterfaceByName( String host )
{
    try
    {
        return findOnInterfaceWithPreference( InetAddress.getByName( host ), -1 );
    }
    catch( UnknownHostException ex )
    {
        throw new UncheckedIOException( "Unable to find free port: " + ex.getMessage(), ex );
    }
}
 
Example 24
Project: msgpack-rpc-java   File: IPAddress.java View source code 6 votes vote down vote up
public InetSocketAddress getInetSocketAddress() {
    try {
        return new InetSocketAddress(InetAddress.getByAddress(address),
                port);
    } catch (UnknownHostException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 25
Project: funambol-client-sdk   File: HttpConnectionAdapter.java View source code 6 votes vote down vote up
/**
 * Open the output stream. The ownership of the stream is transferred to the
 * caller which is responsbile to close and release the resource once it is
 * no longer used. This method shall be called only once per connection.
 *
 * @throws IOException if the output stream cannot be opened.
 */
public OutputStream openOutputStream() throws IOException {
    if (conn == null) {
        throw new IOException("Cannot open output stream on non opened connection");
    }
    try {
        return conn.getOutputStream();
    } catch (UnknownHostException ue) {
        // Translate this exception into a platform independent one
        throw new ConnectionNotFoundException(ue.getMessage());
    }
}
 
Example 26
Project: HDP-2.2-Patched   File: ServerWebApp.java View source code 6 votes vote down vote up
/**
 * Resolves the host & port InetSocketAddress the web server is listening to.
 * <p/>
 * This implementation looks for the following 2 properties:
 * <ul>
 *   <li>#SERVER_NAME#.http.hostname</li>
 *   <li>#SERVER_NAME#.http.port</li>
 * </ul>
 *
 * @return the host & port InetSocketAddress the web server is listening to.
 * @throws ServerException thrown if any of the above 2 properties is not defined.
 */
protected InetSocketAddress resolveAuthority() throws ServerException {
  String hostnameKey = getName() + HTTP_HOSTNAME;
  String portKey = getName() + HTTP_PORT;
  String host = System.getProperty(hostnameKey);
  String port = System.getProperty(portKey);
  if (host == null) {
    throw new ServerException(ServerException.ERROR.S13, hostnameKey);
  }
  if (port == null) {
    throw new ServerException(ServerException.ERROR.S13, portKey);
  }
  try {
    InetAddress add = InetAddress.getByName(host);
    int portNum = Integer.parseInt(port);
    return new InetSocketAddress(add, portNum);
  } catch (UnknownHostException ex) {
    throw new ServerException(ServerException.ERROR.S14, ex.toString(), ex);
  }
}
 
Example 27
Project: SLAMD   File: TFTPClient.java View source code 6 votes vote down vote up
private void initialisePackets() throws TFTPClientException
{
    byte[] buffer = new byte[MAX_BUFFER_SIZE];

    try
    {
        sendPacket = new DatagramPacket(buffer, buffer.length,
                                            InetAddress.getByName(getServerIP()), getRemotePort());
        receivePacket = new DatagramPacket(buffer , buffer.length);
    }
    catch(UnknownHostException unknownHostException)
    {
        throw new TFTPClientException("IP address " + getServerIP()
                                      + " is invalid. The error is "
                                      + unknownHostException.toString());
    }
}
 
Example 28
Project: property-db   File: NetworkUtils.java View source code 6 votes vote down vote up
/**
 * Get InetAddress masked with prefixLength.  Will never return null.
 * @param IP address which will be masked with specified prefixLength
 * @param prefixLength the prefixLength used to mask the IP
 */
public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
    if (address == null) {
        throw new RuntimeException("getNetworkPart doesn't accept null address");
    }

    byte[] array = address.getAddress();

    if (prefixLength < 0 || prefixLength > array.length * 8) {
        throw new RuntimeException("getNetworkPart - bad prefixLength");
    }

    int offset = prefixLength / 8;
    int reminder = prefixLength % 8;
    byte mask = (byte)(0xFF << (8 - reminder));

    if (offset < array.length) array[offset] = (byte)(array[offset] & mask);

    offset++;

    for (; offset < array.length; offset++) {
        array[offset] = 0;
    }

    InetAddress netPart = null;
    try {
        netPart = InetAddress.getByAddress(array);
    } catch (UnknownHostException e) {
        throw new RuntimeException("getNetworkPart error - " + e.toString());
    }
    return netPart;
}
 
Example 29
Project: hadoop-on-lustre2   File: ServerWebApp.java View source code 6 votes vote down vote up
/**
 * Resolves the host & port InetSocketAddress the web server is listening to.
 * <p/>
 * This implementation looks for the following 2 properties:
 * <ul>
 *   <li>#SERVER_NAME#.http.hostname</li>
 *   <li>#SERVER_NAME#.http.port</li>
 * </ul>
 *
 * @return the host & port InetSocketAddress the web server is listening to.
 * @throws ServerException thrown if any of the above 2 properties is not defined.
 */
protected InetSocketAddress resolveAuthority() throws ServerException {
  String hostnameKey = getName() + HTTP_HOSTNAME;
  String portKey = getName() + HTTP_PORT;
  String host = System.getProperty(hostnameKey);
  String port = System.getProperty(portKey);
  if (host == null) {
    throw new ServerException(ServerException.ERROR.S13, hostnameKey);
  }
  if (port == null) {
    throw new ServerException(ServerException.ERROR.S13, portKey);
  }
  try {
    InetAddress add = InetAddress.getByName(host);
    int portNum = Integer.parseInt(port);
    return new InetSocketAddress(add, portNum);
  } catch (UnknownHostException ex) {
    throw new ServerException(ServerException.ERROR.S14, ex.toString(), ex);
  }
}
 
Example 30
Project: cnAndroidDocs   File: NetworkUtils.java View source code 6 votes vote down vote up
/**
 * Get InetAddress masked with prefixLength.  Will never return null.
 * @param IP address which will be masked with specified prefixLength
 * @param prefixLength the prefixLength used to mask the IP
 */
public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
    if (address == null) {
        throw new RuntimeException("getNetworkPart doesn't accept null address");
    }

    byte[] array = address.getAddress();

    if (prefixLength < 0 || prefixLength > array.length * 8) {
        throw new RuntimeException("getNetworkPart - bad prefixLength");
    }

    int offset = prefixLength / 8;
    int reminder = prefixLength % 8;
    byte mask = (byte)(0xFF << (8 - reminder));

    if (offset < array.length) array[offset] = (byte)(array[offset] & mask);

    offset++;

    for (; offset < array.length; offset++) {
        array[offset] = 0;
    }

    InetAddress netPart = null;
    try {
        netPart = InetAddress.getByAddress(array);
    } catch (UnknownHostException e) {
        throw new RuntimeException("getNetworkPart error - " + e.toString());
    }
    return netPart;
}
 
Example 31
Project: ArchStudio5   File: LJMDeployment.java View source code 6 votes vote down vote up
public static int deploy(String objectName, Object o, int port) throws LJMException {
	LJMServer objectServer;
	try {
		objectServer = getObjectServer(port);
	}
	catch (UnknownHostException uhe) {
		throw new LJMException("Couldn't resolve local host: " + uhe.toString());
	}
	catch (IOException ioe) {
		throw new LJMException("Couldn't create object server: " + ioe.toString());
	}

	objectServer.deploy(objectName, o);

	Integer refCountInt = (Integer) refCounts.get(new Integer(port));
	if (refCountInt != null) {
		int refCount = refCountInt.intValue();
		refCount++;
		refCounts.put(new Integer(port), new Integer(refCount));
	}
	else {
		refCounts.put(new Integer(port), new Integer(1));
	}
	return objectServer.getPort();
}
 
Example 32
Project: qksms   File: NetworkUtils.java View source code 6 votes vote down vote up
/**
 * Get InetAddress masked with prefixLength.  Will never return null.
 *
 * @param IP           address which will be masked with specified prefixLength
 * @param prefixLength the prefixLength used to mask the IP
 */
public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
    if (address == null) {
        throw new RuntimeException("getNetworkPart doesn't accept null address");
    }

    byte[] array = address.getAddress();

    if (prefixLength < 0 || prefixLength > array.length * 8) {
        throw new RuntimeException("getNetworkPart - bad prefixLength");
    }

    int offset = prefixLength / 8;
    int reminder = prefixLength % 8;
    byte mask = (byte) (0xFF << (8 - reminder));

    if (offset < array.length) array[offset] = (byte) (array[offset] & mask);

    offset++;

    for (; offset < array.length; offset++) {
        array[offset] = 0;
    }

    InetAddress netPart = null;
    try {
        netPart = InetAddress.getByAddress(array);
    } catch (UnknownHostException e) {
        throw new RuntimeException("getNetworkPart error - " + e.toString());
    }
    return netPart;
}
 
Example 33
Project: hadoop   File: ServerWebApp.java View source code 6 votes vote down vote up
/**
 * Resolves the host and port InetSocketAddress the web server is listening to.
 * <p>
 * This implementation looks for the following 2 properties:
 * <ul>
 *   <li>#SERVER_NAME#.http.hostname</li>
 *   <li>#SERVER_NAME#.http.port</li>
 * </ul>
 *
 * @return the host and port InetSocketAddress the web server is listening to.
 * @throws ServerException thrown if any of the above 2 properties is not defined.
 */
protected InetSocketAddress resolveAuthority() throws ServerException {
  String hostnameKey = getName() + HTTP_HOSTNAME;
  String portKey = getName() + HTTP_PORT;
  String host = System.getProperty(hostnameKey);
  String port = System.getProperty(portKey);
  if (host == null) {
    throw new ServerException(ServerException.ERROR.S13, hostnameKey);
  }
  if (port == null) {
    throw new ServerException(ServerException.ERROR.S13, portKey);
  }
  try {
    InetAddress add = InetAddress.getByName(host);
    int portNum = Integer.parseInt(port);
    return new InetSocketAddress(add, portNum);
  } catch (UnknownHostException ex) {
    throw new ServerException(ServerException.ERROR.S14, ex.toString(), ex);
  }
}
 
Example 34
Project: hadoop-release-2.6.0   File: ServerWebApp.java View source code 6 votes vote down vote up
/**
 * Resolves the host & port InetSocketAddress the web server is listening to.
 * <p/>
 * This implementation looks for the following 2 properties:
 * <ul>
 *   <li>#SERVER_NAME#.http.hostname</li>
 *   <li>#SERVER_NAME#.http.port</li>
 * </ul>
 *
 * @return the host & port InetSocketAddress the web server is listening to.
 * @throws ServerException thrown if any of the above 2 properties is not defined.
 */
protected InetSocketAddress resolveAuthority() throws ServerException {
  String hostnameKey = getName() + HTTP_HOSTNAME;
  String portKey = getName() + HTTP_PORT;
  String host = System.getProperty(hostnameKey);
  String port = System.getProperty(portKey);
  if (host == null) {
    throw new ServerException(ServerException.ERROR.S13, hostnameKey);
  }
  if (port == null) {
    throw new ServerException(ServerException.ERROR.S13, portKey);
  }
  try {
    InetAddress add = InetAddress.getByName(host);
    int portNum = Integer.parseInt(port);
    return new InetSocketAddress(add, portNum);
  } catch (UnknownHostException ex) {
    throw new ServerException(ServerException.ERROR.S14, ex.toString(), ex);
  }
}
 
Example 35
Project: Onosendai   File: SuccessWhaleExceptionTest.java View source code 6 votes vote down vote up
@Test
public void itMakesFriendlyErrorForHostNotFound () throws Exception {
	final UnknownHostException uhe = new UnknownHostException("Unable to resolve host \"successwhale-api.herokuapp.com\": No address associated with hostname");
	final SuccessWhaleException swe = new SuccessWhaleException("Failed to fetch feed 'somefeed' from 'someurl': " + uhe.toString(), uhe);
	assertEquals("Network error: Unable to resolve host \"successwhale-api.herokuapp.com\": No address associated with hostname",
			swe.friendlyMessage());
}
 
Example 36
Project: wildfly-core   File: InetAddressValidator.java View source code 6 votes vote down vote up
/**
 * [email protected]}
 */
@Override
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException {
    super.validateParameter(parameterName, value);
    if (value.isDefined() && value.getType() != ModelType.EXPRESSION) {
        String str = value.asString();
        try {
            //noinspection ResultOfMethodCallIgnored
            InetAddress.getByName(str);
        } catch (UnknownHostException e) {
            throw new OperationFailedException(e.toString());
        }
    }
}
 
Example 37
Project: ftpapi   File: SSLDataConnection.java View source code 6 votes vote down vote up
/**
 * Connects to the specified IP address to the specified port number. This
 * method is called by the FTPClients if they prefer to transfer data in
 * passive mode.
 * 
 * @param ipAddress
 *            IP address of the remote host in xxx.xxx.xxx.xxx format.
 * @param port
 *            Port number to connect to.
 * @exception ConnectionException
 *                if a network or IO error occurs.
 */
@Override
public synchronized void connect(String ipAddress, int port)
		throws ConnectionException {
	try {
		if (client.isPassiveIPSubstitutionEnabled()) {
			connect(client.getRemoteAddress(), port);
		} else {
			connect(InetAddress.getByName(ipAddress), port);
		}
	} catch (UnknownHostException exp) {
		throw new ConnectionException(exp.toString());
	}
}
 
Example 38
Project: android-15   File: NetworkUtils.java View source code 6 votes vote down vote up
/**
 * Get InetAddress masked with prefixLength.  Will never return null.
 * @param IP address which will be masked with specified prefixLength
 * @param prefixLength the prefixLength used to mask the IP
 */
public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
    if (address == null) {
        throw new RuntimeException("getNetworkPart doesn't accept null address");
    }

    byte[] array = address.getAddress();

    if (prefixLength < 0 || prefixLength > array.length * 8) {
        throw new RuntimeException("getNetworkPart - bad prefixLength");
    }

    int offset = prefixLength / 8;
    int reminder = prefixLength % 8;
    byte mask = (byte)(0xFF << (8 - reminder));

    if (offset < array.length) array[offset] = (byte)(array[offset] & mask);

    offset++;

    for (; offset < array.length; offset++) {
        array[offset] = 0;
    }

    InetAddress netPart = null;
    try {
        netPart = InetAddress.getByAddress(array);
    } catch (UnknownHostException e) {
        throw new RuntimeException("getNetworkPart error - " + e.toString());
    }
    return netPart;
}
 
Example 39
Project: mina-ftpserver   File: PASV.java View source code 6 votes vote down vote up
private InetAddress resolveAddress(String host) throws DataConnectionException {
    try {
        return InetAddress.getByName(host);
    } catch (UnknownHostException ex) {
        throw new DataConnectionException(ex.getLocalizedMessage(), ex);
    }
}
 
Example 40
Project: defense4all   File: PO.java View source code 6 votes vote down vote up
public Hashtable<String, Object> toRow() throws IllegalArgumentException {

		/* Change any null value to empty, otherwise Hashtable.put() will throw an exception */
		if(label == null) label = "";
		if(protectionSLA == null) protectionSLA = new ProtectionSLA("");
		if(virtualNetid == null)  virtualNetid = "";
		if(props == null) props = new Properties();
		if(dstAddr == null) {
			try {
				dstAddr = InetAddress.getLocalHost();
			} catch (UnknownHostException e) {
				log.error("Failed to obtain local host. " + e.getLocalizedMessage());
				throw new IllegalArgumentException("Failed to obtain local host. " + e.getLocalizedMessage());
			}
		}

		Hashtable<String, Object> row = new Hashtable<String, Object>();
		row.put(LABEL, label);
		row.put(IP_VERSION, ipVersion.name());
		row.put(DST_ADDR, dstAddr.getHostAddress());
		row.put(DST_ADDR_PREFIX_LEN, dstAddrPrefixLen);
		row.put(PROTECTION_SLA, protectionSLA.toString());
		row.put(PROPS, props);
		row.put(VIRTUAL_NETWORK_ID, virtualNetid);
		
		return row;
	}
 
Example 41
Project: soulissapp   File: UDPHelper.java View source code 6 votes vote down vote up
/**
 * Issue a command to Souliss, at specified coordinates
 * 
 * @param id
 * @param slot
 * @param cmd
 * @return TODO output string
 */
public static String issueSoulissCommand(String id, String slot, SoulissPreferenceHelper prefs,
		String... cmd) {
	InetAddress serverAddr;
	DatagramSocket sender = null;
	DatagramPacket packet;
	try {
		// Log.d(TAG, "Issuing command " + cmd[0]);
		serverAddr = InetAddress.getByName(prefs.getAndSetCachedAddress());

		sender = getSenderSocket(serverAddr);
		ArrayList<Byte> buf;
		if (id.equals(""+it.angelic.soulissclient.Constants.MASSIVE_NODE_ID) ){
			buf = buildVNetFrame(buildMaCaCoMassive(Constants.Net.Souliss_UDP_function_force_massive, slot, cmd),
					prefs.getPrefIPAddress(), prefs.getUserIndex(), prefs.getNodeIndex());
		} else {
			buf = buildVNetFrame(buildMaCaCoForce(Constants.Net.Souliss_UDP_function_force, id, slot, cmd),
					prefs.getPrefIPAddress(), prefs.getUserIndex(), prefs.getNodeIndex());
		}

		byte[] merd = new byte[buf.size()];
		for (int i = 0; i < buf.size(); i++) {
			merd[i] = buf.get(i);
		}
		packet = new DatagramPacket(merd, merd.length, serverAddr, prefs.getUDPPort());

		sender.send(packet);
		Log.i(Constants.Net.TAG, "Command sent to: " + serverAddr);

		return "UDP command OK";
	} catch (UnknownHostException ed) {
		ed.printStackTrace();
		return ed.getLocalizedMessage();
	} catch (SocketException et) {
		et.printStackTrace();
		return et.getLocalizedMessage();
	} catch (Exception e) {
		Log.e(Constants.Net.TAG, "***Fail", e);
		return e.getLocalizedMessage();
	} finally {
		if (sender != null && !sender.isClosed())
			sender.close();
	}
}
 
Example 42
Project: soulissapp   File: UDPHelper.java View source code 6 votes vote down vote up
/**
 * Builds a broadcast command to all typicals of the same type
 * 
 * @param typ
 * @param prefs
 * @param cmd
 *            varargs of commands
 * @return
 */
public static String issueMassiveCommand(String typ, SoulissPreferenceHelper prefs, String... cmd) {
	InetAddress serverAddr;
	DatagramSocket sender = null;
	DatagramPacket packet;
	try {
		// Log.d(TAG, "Issuing command " + cmd[0]);
		serverAddr = InetAddress.getByName(prefs.getAndSetCachedAddress());

		sender = getSenderSocket(serverAddr);
		ArrayList<Byte> buf;
		buf = buildVNetFrame(buildMaCaCoMassive(Constants.Net.Souliss_UDP_function_force_massive, typ, cmd),
				prefs.getPrefIPAddress(), prefs.getUserIndex(), prefs.getNodeIndex());

		byte[] merd = new byte[buf.size()];
		for (int i = 0; i < buf.size(); i++) {
			merd[i] = buf.get(i);
		}
		packet = new DatagramPacket(merd, merd.length, serverAddr,  prefs.getUDPPort());

		sender.send(packet);
		Log.i(Constants.Net.TAG, "Massive Command sent to: " + serverAddr);

		return "UDP massive command OK";
	} catch (UnknownHostException ed) {
		ed.printStackTrace();
		return ed.getLocalizedMessage();
	} catch (SocketException et) {
		et.printStackTrace();
		return et.getLocalizedMessage();
	} catch (Exception e) {
		Log.d(Constants.Net.TAG, "***Fail", e);
		return e.getLocalizedMessage();
	} finally {
		if (sender != null && !sender.isClosed())
			sender.close();
	}
}
 
Example 43
Project: zenoss-zep   File: IpUtils.java View source code 6 votes vote down vote up
/**
 * Parses the string into an InetAddress ensuring that no DNS lookup is performed
 * on the address (it must be specified as a literal IPv4 or IPv6 address).
 * 
 * @param value String IP address.
 * @return InetAddress for the specified address.
 * @throws IllegalArgumentException If the address is invalid.
 */
public static InetAddress parseAddress(String value) throws IllegalArgumentException {
    // Looks for an IPv6 or IPv4 address. Discards anything that looks like a hostname
    // to prevent long running hostname lookups.
    final InetAddress addr;
    if (value.indexOf(':') != -1) {
        if (value.startsWith("[") && value.endsWith("]")) {
            // We expect an IPv6 address
            value = value.substring(1, value.length()-1);
        }
        // Use Guava IPv6 parsing - previous parsing performed DNS lookups
        addr = InetAddresses.forString(value);
    }
    else {
        Matcher matcher = IPV4_PATTERN.matcher(value);
        if (matcher.matches()) {
            final byte[] bytes = new byte[4];
            for (int i = 1; i <= matcher.groupCount(); i++) {
                int octet = Integer.parseInt(matcher.group(i));
                if (octet > 255) {
                    throw new IllegalArgumentException("Invalid IP address: " + value);
                }
                bytes[i-1] = (byte)octet;
            }
            try {
                addr = InetAddress.getByAddress(bytes);
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getLocalizedMessage(), e);
            }
        }
        else {
            throw new IllegalArgumentException("Invalid IP address: " + value); 
        }
    }
    return addr;
}
 
Example 44
Project: zenoss-zep   File: IpUtils.java View source code 6 votes vote down vote up
/**
 * Converts the specified number of prefix bits to a InetAddress representing
 * the netmask.
 * 
 * @param prefixBits The number of prefix bits in the netmask.
 * @param isIPv6 True if the returned netmask should be IPv6, otherwise uses
 *               IPv4.
 * @return An InetAddress representing the netmask.
 * @throws IllegalArgumentException If the prefix bits are out of range.
 */
public static InetAddress prefixBitsToNetmask(int prefixBits, boolean isIPv6) throws IllegalArgumentException {
    if (prefixBits < 0) {
        throw new IllegalArgumentException("Invalid prefix bits");
    }
    final byte[] bytes;
    if (isIPv6) {
        if (prefixBits > 128) {
            throw new IllegalArgumentException("Invalid prefix bits");
        }
        bytes = new byte[16];
    }
    else {
        if (prefixBits > 32) {
            throw new IllegalArgumentException("Invalid prefix bits");
        }
        bytes = new byte[4];
    }
    int byteOffset = 0;
    int bitOffset = 7;
    for (int i = 0; i < prefixBits; i++) {
        bytes[byteOffset] |= (1<<bitOffset);
        --bitOffset;
        if (bitOffset < 0) {
            ++byteOffset;
            bitOffset = 7;
        }
    }
    try {
        return InetAddress.getByAddress(bytes);
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException(e.getLocalizedMessage(), e);
    }
}
 
Example 45
Project: jacclog   File: IpAddressTranslator.java View source code 6 votes vote down vote up
/**
 * Translates an IPv4 address from its Four dimensions byte array representation to an <code>Inet4Address</code>.
 * 
 * @param ipAddress
 *            Four dimensions byte array representation of an IP address
 * @return IP address as <code>Inet4Address</code>
 * @throws IllegalArgumentException
 *             If the given argument is <code>null</code>
 * @throws IllegalArgumentException
 *             If the given byte array does not have four entries
 * @throws InvalidIpAddressException
 *             If the IP address is not valid.
 */
public static Inet4Address toInet4Address(final byte[] ipAddress) {
	if (ipAddress == null) {
		throw new IllegalArgumentException("Argument 'ipAddress' can not be null.");
	}

	if (ipAddress.length != 4) {
		throw new IllegalArgumentException("An IP address as byte array needs 4 entries.");
	}

	try {
		return (Inet4Address) InetAddress.getByAddress(ipAddress);
	} catch (final UnknownHostException e) {
		throw new InvalidIpAddressException("The given IP address is not valid: " + e.getLocalizedMessage(), e);
	}
}
 
Example 46
Project: jetstream   File: OutboundRESTChannel.java View source code 6 votes vote down vote up
public void open() throws EventException {
	LOGGER.info( "Opening Outbound Messaging Channel");

	super.open();
	
	Management.removeBeanOrFolder(getBeanName(), this);
	Management.addBean(getBeanName(), this);
	m_client = new HttpClient();
	m_client.setConfig(getConfig());
	m_client.setKeepAlive(true);
	m_batchPublisher = new EventBatcher(m_client);
	m_batchPublisher.setBatchSize(m_config.getBatchSz());
	m_queueProcessor = new Thread(m_batchPublisher);
	m_queueProcessor.start();
	m_urlList.addAll(m_address.getUriList());
	
	try {
		Iterator<URI> urlIter = m_urlList.iterator();

		while(urlIter.hasNext()) {
			m_client.connect(urlIter.next(), getConfig().getNumConnections());
		}
	}
	catch (UnknownHostException e) {
		m_errors.registerError(e);
		throw new EventException(e.getLocalizedMessage());
	}
}
 
Example 47
Project: RFC4765   File: Address.java View source code 5 votes vote down vote up
/**
	 * Instantiate an address object and set its values.
	 * If the value passed in is a host name and the category indicates and IPV4 or IPV6 address, the name or number
	 * will be resolved to an address and the value stored in the object. If a host name cannot be resolved,
	 * an IllegalArgumentException is thrown. Note that the netmask part is NOT CHECKED for validity in this release
	 * in the case of an address/netmask.
	 * 
	 * @param ident optional:. if null, the ident will be set to the RFC-default of "0"
	 * @param address required per the RFC (and EXPANDING on it), this may be a host name, an IP address, IP address/netmask, or other permitted type. If category is an ipv4 or v6 address, it is looked up and saved in the object
	 * @param category optional type of address represented. if null, this will be set to the RFC-defined default UNKNOWN
	 * @param vlanName optional name of the Virtual LAN to which the address belongs or null if not reporting this
	 * @param vlanNum optional number of the Virtual LAN to which the address belongs or null if not reporting this
x	 * 
	 * @throws IllegalArgumentException if 'address' is not provided, or if 'category' indicates an ipv4 or ipv6 address, but 'address' is not a valid address or if an address/netmask combo cannot be parsed as expected
	 */
	public Address(String ident, String address, Category category, String vlanName, String vlanNum)
	throws IllegalArgumentException {
		if (address == null)
			throw new IllegalArgumentException("Cannot instantiate Address: 'address' is required by the RFC");

		if (ident == null)
			this.ident = "0";
		else
			this.ident = ident;

		if (category == null)
			this.category = Category.UNKNOWN;
		else
			this.category = category;

		this.vlanName = vlanName;
		this.vlanNum = vlanNum;

		// init address to default value ( then overwrite below in the case of an address/netmask ), and set netmask and inetAddress to null as they are only filled if appropriate
		this.address = address.trim();
		this.netmask = null;
		this.inetAddress = null; // is only set if _address is a host name or ip address, null otherwise

		// if this is an address or host name, try to look it up via Java's java.net.getByName() method, which accepts either string-versions of addresses, or host names
		// if the presented address cannot be encoded, then an exception will be thrown and we can reject the proffered address through our own exception
		switch (category) {
		// if it's an address + netmask (separated by a slash), parse them apart
		case IPV4_NET:
		case IPV4_NET_MASK:
		case IPV6_NET:
		case IPV6_NET_MASK:
			String[] splitAddress = address.split("/");
			if (splitAddress.length != 2)
				throw new IllegalArgumentException("Address+netmask "+address+" could not be converted to "+category);
			this.address = splitAddress[0];
			this.netmask = splitAddress[1];
			// if an address+mask were processed, fall through to convert the address into the inetAddress field
			// if it's an address without a mask, then we switch in at this point and just convert the string address/name to an address
		case IPV4_ADDR:
		case IPV4_ADDR_HEX:
		case IPV6_ADDR:
		case IPV6_ADDR_HEX:
			try {
				this.inetAddress = InetAddress.getByName(this.address);
			}
			catch (UnknownHostException uhe) {
				throw new IllegalArgumentException("Address "+address+" could not be converted to "+category+" "+uhe.getMessage());
			}
			break;
		default:
		}
	}
 
Example 48
Project: jSLP   File: SLPDaemonImpl.java View source code 5 votes vote down vote up
/**
 * deregister a service from the SLP framework. Deregisters from all DAs
 * within the scopes and from the local service cache.
 * 
 * @param dereg
 *            the service deregistration.
 * @throws ServiceLocationException
 */
private void deregisterService(final ServiceDeregistration dereg)
		throws ServiceLocationException {

	final String[] scopes = (String[]) registeredServices.keySet().toArray(
			new String[registeredServices.size()]);
	for (int i = 0; i < scopes.length; i++) {
		final List tmp = (List) registeredServices.get(scopes[i]);
		final Service[] services = (Service[]) tmp.toArray(new Service[tmp
				.size()]);

		for (int j = 0; j < services.length; j++) {
			if (dereg.url.matches(services[j].url)) {
				List daList = (List) SLPCore.dAs.get(scopes[i].toLowerCase());
				if (daList != null) {
					for (Iterator daIter = daList.iterator(); daIter
							.hasNext();) {
						try {
							String dA = (String) daIter.next();
							dereg.address = InetAddress.getByName(dA);
							dereg.port = SLPCore.SLP_RESERVED_PORT;
							dereg.xid = SLPCore.nextXid();
							if (SLPCore.CONFIG.getSecurityEnabled()) {
								List spiList = (List) SLPCore.dASPIs
										.get(dA);
								dereg.sign(spiList);
							}
							ReplyMessage reply = SLPCore.sendMessage(dereg,
									true);
							if (reply.errorCode != 0) {
								throw new ServiceLocationException(
										(short) reply.errorCode,
										"Error during deregistration: "
												+ reply.errorCode);
							}
						} catch (UnknownHostException uhe) {
							throw new ServiceLocationException(
									ServiceLocationException.NETWORK_ERROR,
									uhe.getMessage());
						}
					}
				}
				synchronized (registeredServices) {
					SLPUtils.removeValue(registeredServices, scopes[i],
							services[j]);
				}
				break;
			}
		}
	}
}
 
Example 49
Project: defense4all   File: PN.java View source code 5 votes vote down vote up
public Hashtable<String, Object> toRow() throws IllegalArgumentException {

		/* Change any null value to empty, otherwise Hashtable.put() will throw an exception */
		if(label == null) label = "";
		if(protectionSLA == null) protectionSLA = new ProtectionSLA("");
		if(thresholdStr == null)  thresholdStr = "";
		if(averageStr == null)    averageStr = "";
		if(latestRateStr == null) latestRateStr = "";
		if(baselineStr == null)   baselineStr = "";
		if(detectorLabel == null) detectorLabel = "";
		if(virtualNetid == null)  virtualNetid = "";
		if(attackSuspicions == null)  attackSuspicions = "";
		if(amsConfigProps == null) amsConfigProps = new Properties();
		if(props == null) props = new Properties();
		if(dstAddr == null) {
			try {
				dstAddr = InetAddress.getLocalHost();
			} catch (UnknownHostException e) {
				log.error("Failed to obtain local host. " + e.getLocalizedMessage());
				throw new IllegalArgumentException("Failed to obtain local host. " + e.getLocalizedMessage());
			}
		}

		Hashtable<String, Object> row = new Hashtable<String, Object>();
		row.put(LABEL, label);
		row.put(IP_VERSION, ipVersion.name());
		row.put(DST_ADDR, dstAddr.getHostAddress());
		row.put(DST_ADDR_PREFIX_LEN, dstAddrPrefixLen);
		row.put(AMS_CONFIG_PROPS, amsConfigProps);
		row.put(PROTECTION_SLA, protectionSLA.toString());
		row.put(MITIGATION_CONFIRMATION, mitigationConfirmation);
		row.put(DETECTOR_LABEL, detectorLabel);
		row.put(THRESHOLDS, thresholdStr);
		row.put(AVERAGES, averageStr);
		row.put(LATEST_RATES, latestRateStr);
		row.put(BASELINES, baselineStr);
		row.put(LATEST_RATES_TIME, latestRateTime);
		row.put(BASELINES_TIME, baselinesTime);
		row.put(PROPS, props);
		row.put(STATS_COLLECTION_STATUS, statsCollectionStatus.name());
		row.put(OPERATIONAL_STATUS, operationalStatus.name());
		row.put(MITIGATION_SCOPE, mitigationScope.name());
		row.put(ATTACK_SUSPICIONS, attackSuspicions);
		row.put(OF_BASED_DETECTION, ofBasedDetection);
		row.put(SYMMETRIC_DVSN, symmetricDvsn);
		row.put(VIRTUAL_NETWORK_ID, virtualNetid);
		row.put(ANOMALY_RATE_THRESHOLD_PERCENTAGE, anomalyThresholdPercentage);
		for(String trafficFloorKey : trafficFloorKeys)
			row.put(PN.TRAFFIC_FLOOR_KEY_PREFIX + trafficFloorKey, trafficFloorKey);
		for(String netNodeLabel : netNodeLabels)
			row.put(PN.NETNODE_PREFIX + netNodeLabel, netNodeLabel);

		return row;
	}
 
Example 50
Project: p4ic4idea   File: RpcServer.java View source code 5 votes vote down vote up
public ServerStatus init(String host, int port, Properties props, UsageOptions opts, boolean secure)
                        throws ConfigException, ConnectionException {
        super.init(host, port, props, opts, secure);
        try {
    			this.cmdMapArgs = new HashMap<String, Object>();
    			this.cmdMapArgs.put(ProtocolCommand.RPC_ARGNAME_PROTOCOL_ZTAGS, "");
                this.relaxCmdNameValidationChecks = RpcPropertyDefs.getPropertyAsBoolean(props,
                                                        RpcPropertyDefs.RPC_RELAX_CMD_NAME_CHECKS_NICK, false);
                this.applicationName = RpcPropertyDefs.getProperty(props,
                        								RpcPropertyDefs.RPC_APPLICATION_NAME_NICK, null);
                if (this.getUsageOptions().getHostName() != null) {
                        // This had better reflect reality...
                        this.localHostName = this.getUsageOptions().getHostName();
                } else {
                        this.localHostName = java.net.InetAddress.getLocalHost().getHostName();
                }
                if (this.localHostName == null) {
                        throw new NullPointerError("Null client host name in RPC connection init");
                }
                if (!this.useAuthMemoryStore) {
                  // Search properties for ticket file path, fix for job035376
                  this.ticketsFilePath = this.props.getProperty(PropertyDefs.TICKET_PATH_KEY_SHORT_FORM,
                                                       this.props.getProperty(PropertyDefs.TICKET_PATH_KEY));
                  // Search environment variable
                  if (this.ticketsFilePath == null) {
                  		this.ticketsFilePath = PerforceEnvironment.getP4Tickets();
                  }
                  // Search standard OS location
                  if (this.ticketsFilePath == null) {
                  		this.ticketsFilePath = getDefaultP4TicketsFile();
                  }
                  
                  // Search properties for trust file path
                  this.trustFilePath = this.props.getProperty(PropertyDefs.TRUST_PATH_KEY_SHORT_FORM,
                                                     this.props.getProperty(PropertyDefs.TRUST_PATH_KEY));
                  // Search environment variable
                  if (this.trustFilePath == null) {
                          this.trustFilePath = PerforceEnvironment.getP4Trust();

                  }
                  // Search standard OS location
                  if (this.trustFilePath == null) {
                          this.trustFilePath = getDefaultP4TrustFile();
                  }
                }
                this.serverStats = new ServerStats();
        } catch (UnknownHostException uhe) {
                throw new ConfigException("Unable to determine client host name: "
                                + uhe.getLocalizedMessage());
        }

        // Initialize client trust
        clientTrust = new ClientTrust(this);
        
        return status;
}
 
Example 51
Project: p4ic4idea   File: RpcServer.java View source code 5 votes vote down vote up
public ServerStatus init(String host, int port, Properties props, UsageOptions opts, boolean secure)
                        throws ConfigException, ConnectionException {
        super.init(host, port, props, opts, secure);
        try {
    			this.cmdMapArgs = new HashMap<String, Object>();
    			this.cmdMapArgs.put(ProtocolCommand.RPC_ARGNAME_PROTOCOL_ZTAGS, "");
                this.relaxCmdNameValidationChecks = RpcPropertyDefs.getPropertyAsBoolean(props,
                                                        RpcPropertyDefs.RPC_RELAX_CMD_NAME_CHECKS_NICK, false);
                this.applicationName = RpcPropertyDefs.getProperty(props,
                        								RpcPropertyDefs.RPC_APPLICATION_NAME_NICK, null);
                if (this.getUsageOptions().getHostName() != null) {
                        // This had better reflect reality...
                        this.localHostName = this.getUsageOptions().getHostName();
                } else {
                        this.localHostName = java.net.InetAddress.getLocalHost().getHostName();
                }
                if (this.localHostName == null) {
                        throw new NullPointerError("Null client host name in RPC connection init");
                }
                if (!this.useAuthMemoryStore) {
                  // Search properties for ticket file path, fix for job035376
                  this.ticketsFilePath = this.props.getProperty(PropertyDefs.TICKET_PATH_KEY_SHORT_FORM,
                                                       this.props.getProperty(PropertyDefs.TICKET_PATH_KEY));
                  // Search environment variable
                  if (this.ticketsFilePath == null) {
                  		this.ticketsFilePath = PerforceEnvironment.getP4Tickets();
                  }
                  // Search standard OS location
                  if (this.ticketsFilePath == null) {
                  		this.ticketsFilePath = getDefaultP4TicketsFile();
                  }
                  
                  // Search properties for trust file path
                  this.trustFilePath = this.props.getProperty(PropertyDefs.TRUST_PATH_KEY_SHORT_FORM,
                                                     this.props.getProperty(PropertyDefs.TRUST_PATH_KEY));
                  // Search environment variable
                  if (this.trustFilePath == null) {
                          this.trustFilePath = PerforceEnvironment.getP4Trust();

                  }
                  // Search standard OS location
                  if (this.trustFilePath == null) {
                          this.trustFilePath = getDefaultP4TrustFile();
                  }
                }
                this.serverStats = new ServerStats();
        } catch (UnknownHostException uhe) {
                throw new ConfigException("Unable to determine client host name: "
                                + uhe.getLocalizedMessage());
        }

        // Initialize client trust
        clientTrust = new ClientTrust(this);
        
        return status;
}