Example usage for java.net InetAddress getByName

List of usage examples for java.net InetAddress getByName

Introduction

In this page you can find the example usage for java.net InetAddress getByName.

Prototype

public static InetAddress getByName(String host) throws UnknownHostException 

Source Link

Document

Determines the IP address of a host, given the host's name.

Usage

From source file:com.basho.riak.pbc.RiakClient.java

public RiakClient(String host, int port) throws IOException {
    this(InetAddress.getByName(host), port);
}

From source file:net.darkmist.clf.LogParserTest.java

public void testURIWithDoubleQuote() throws Exception {
    String in = "1.2.3.4 Ident User [" + LOG_TIME_AS_STR + "] \"GET http://localhost:80/\" HTTP/1.1\" 200 2";
    LogEntry entry = parser.parse(in);//  w  ww.  j a  va  2 s. co m

    assertEquals(InetAddress.getByName("1.2.3.4"), entry.getIP());
    assertEquals("Ident", entry.getIdent());
    assertEquals("User", entry.getUser());
    assertEquals(LOG_TIME_AS_DATE, entry.getDate());
    assertEquals("GET", entry.getMethod());
    assertEquals("http://localhost:80/\"", entry.getURI());
    assertEquals("HTTP/1.1", entry.getProtocol());
    assertEquals(200, entry.getStatus());
    assertEquals(2, entry.getSize());
}

From source file:net.majorkernelpanic.streaming.rtsp.UriParser.java

/**
 * Configures a Session according to the given URI.
 * Here are some examples of URIs that can be used to configure a Session:
 * <ul><li>rtsp://xxx.xxx.xxx.xxx:8086?h264&flash=on</li>
 * <li>rtsp://xxx.xxx.xxx.xxx:8086?h263&camera=front&flash=on</li>
 * <li>rtsp://xxx.xxx.xxx.xxx:8086?h264=200-20-320-240</li>
 * <li>rtsp://xxx.xxx.xxx.xxx:8086?aac</li></ul>
 * @param uri The URI/*  ww  w.j  av  a 2  s  . c om*/
 * @throws IllegalStateException
 * @throws IOException
 * @return A Session configured according to the URI
 */
public static Session parse(String uri) throws IllegalStateException, IOException {
    SessionBuilder builder = SessionBuilder.getInstance().clone();

    List<NameValuePair> params = URLEncodedUtils.parse(URI.create(uri), "UTF-8");
    if (params.size() > 0) {

        builder.setAudioEncoder(AUDIO_NONE).setVideoEncoder(VIDEO_NONE);

        // Those parameters must be parsed first or else they won't necessarily be taken into account
        for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) {
            NameValuePair param = it.next();

            // FLASH ON/OFF
            if (param.getName().equalsIgnoreCase("flash")) {
                if (param.getValue().equalsIgnoreCase("on"))
                    builder.setFlashEnabled(true);
                else
                    builder.setFlashEnabled(false);
            }

            // CAMERA -> the client can choose between the front facing camera and the back facing camera
            else if (param.getName().equalsIgnoreCase("camera")) {
                if (param.getValue().equalsIgnoreCase("back"))
                    builder.setCamera(CameraInfo.CAMERA_FACING_BACK);
                else if (param.getValue().equalsIgnoreCase("front"))
                    builder.setCamera(CameraInfo.CAMERA_FACING_FRONT);
            }

            // MULTICAST -> the stream will be sent to a multicast group
            // The default mutlicast address is 228.5.6.7, but the client can specify another
            else if (param.getName().equalsIgnoreCase("multicast")) {
                if (param.getValue() != null) {
                    try {
                        InetAddress addr = InetAddress.getByName(param.getValue());
                        if (!addr.isMulticastAddress()) {
                            throw new IllegalStateException("Invalid multicast address !");
                        }
                        builder.setDestination(addr);
                    } catch (UnknownHostException e) {
                        throw new IllegalStateException("Invalid multicast address !");
                    }
                } else {
                    // Default multicast address
                    builder.setDestination(InetAddress.getByName("228.5.6.7"));
                }
            }

            // UNICAST -> the client can use this to specify where he wants the stream to be sent
            else if (param.getName().equalsIgnoreCase("unicast")) {
                if (param.getValue() != null) {
                    try {
                        InetAddress addr = InetAddress.getByName(param.getValue());
                        builder.setDestination(addr);
                    } catch (UnknownHostException e) {
                        throw new IllegalStateException("Invalid destination address !");
                    }
                }
            }

            // TTL -> the client can modify the time to live of packets
            // By default ttl=64
            else if (param.getName().equalsIgnoreCase("ttl")) {
                if (param.getValue() != null) {
                    try {
                        int ttl = Integer.parseInt(param.getValue());
                        if (ttl < 0)
                            throw new IllegalStateException();
                        builder.setTimeToLive(ttl);
                    } catch (Exception e) {
                        throw new IllegalStateException("The TTL must be a positive integer !");
                    }
                }
            }

            // H.264
            else if (param.getName().equalsIgnoreCase("h264")) {
                VideoQuality quality = VideoQuality.parseQuality(param.getValue());
                builder.setVideoQuality(quality).setVideoEncoder(VIDEO_H264);
            }

            // H.263
            else if (param.getName().equalsIgnoreCase("h263")) {
                VideoQuality quality = VideoQuality.parseQuality(param.getValue());
                builder.setVideoQuality(quality).setVideoEncoder(VIDEO_H263);
            }

            // AMR
            else if (param.getName().equalsIgnoreCase("amrnb") || param.getName().equalsIgnoreCase("amr")) {
                AudioQuality quality = AudioQuality.parseQuality(param.getValue());
                builder.setAudioQuality(quality).setAudioEncoder(AUDIO_AMRNB);
            }

            // AAC
            else if (param.getName().equalsIgnoreCase("aac")) {
                AudioQuality quality = AudioQuality.parseQuality(param.getValue());
                builder.setAudioQuality(quality).setAudioEncoder(AUDIO_AAC);
            }

        }

    }

    if (builder.getVideoEncoder() == VIDEO_NONE && builder.getAudioEncoder() == AUDIO_NONE) {
        SessionBuilder b = SessionBuilder.getInstance();
        builder.setVideoEncoder(b.getVideoEncoder());
        builder.setAudioEncoder(b.getAudioEncoder());
    }

    return builder.build();

}

From source file:com.adito.tunnels.forms.TunnelForm.java

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errs = super.validate(mapping, request);
    if (isCommiting()) {

        if (!Util.isNullOrTrimmedBlank(sourceInterface)) {
            /**//from   w w w.  ja v  a  2  s . c o  m
             * For remote tunnels, the listening interface must be a valid
             * IP address of a network interface on this server
             */
            if (getTunnelType() == TransportType.REMOTE_TUNNEL_ID) {
                if (!sourceInterface.trim().equals("0.0.0.0") && !sourceInterface.trim().equals("127.0.0.2"))
                    try {
                        InetAddress addr = InetAddress.getByName(sourceInterface);
                        NetworkInterface nif = NetworkInterface.getByInetAddress(addr);
                        if (nif == null) {
                            throw new Exception();
                        }
                    } catch (Exception e) {
                        errs.add(Globals.ERROR_KEY, new ActionMessage(
                                "tunnelWizard.tunnelDetails.error.invalidRemoteSourceInterface"));
                    }
            } else {
                /**
                 * For local tunnels, we do not know what will be a valid IP
                 * address until the client is running so all we can do is
                 * validate that it looks like an IP address
                 */
                if (!IPV4AddressValidator.isIpAddressExpressionValid(sourceInterface)) {
                    errs.add(Globals.ERROR_KEY,
                            new ActionMessage("tunnelWizard.tunnelDetails.error.invalidLocalSourceInterface"));
                }
            }
        }

        try {
            int port = Integer.valueOf(sourcePort).intValue();
            if (port < 0 || port > 65535) {
                throw new IllegalArgumentException();
            }
        } catch (Exception e) {
            errs.add(Globals.ERROR_KEY,
                    new ActionMessage("tunnelWizard.tunnelDetails.error.sourcePortNotInteger"));
        }

        try {
            int port = Integer.valueOf(destinationPort).intValue();
            if (port < 1 || port > 65535) {
                throw new IllegalArgumentException();
            }
            Integer.valueOf(destinationPort).intValue();
        } catch (Exception e) {
            errs.add(Globals.ERROR_KEY,
                    new ActionMessage("tunnelWizard.tunnelDetails.error.destinationPortNotInteger"));
        }

        if (Util.isNullOrTrimmedBlank(destinationHost)) {
            errs.add(Globals.ERROR_KEY,
                    new ActionMessage("tunnelWizard.tunnelDetails.error.noDestinationHost"));
        } else {
            if (!HostnameOrIPAddressWithReplacementsValidator.isValidAsHostOrIp(destinationHost)) {
                errs.add(Globals.ERROR_KEY, new ActionMessage("tunnelWizard.tunnelDetails.error.invalidHost"));
            }
        }

        if (getResourceName().equalsIgnoreCase("default") && (!getEditing()
                || (getEditing() && !getResource().getResourceName().equalsIgnoreCase("default")))) {
            errs.add(Globals.ERROR_KEY, new ActionMessage("error.createNetworkPlace.cantUseNameDefault"));
            setResourceName("");
        }
    }
    return errs;
}

From source file:com.odap.server.audit.AuditServer.java

public static void configServer(Config.Processor cp, String iname) {
    try {/* ww w  .j ava 2 s  .  co  m*/
        TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters();
        params.setKeyStore("keystore.jks", keystore_password);
        TServerSocket serverTransport_config = TSSLTransportFactory.getServerSocket(7912, 10000,
                InetAddress.getByName(iname), params);
        TServer server_config = new TThreadPoolServer(
                new TThreadPoolServer.Args(serverTransport_config).processor(config_processor));

        logger.info("Starting server on port 7912 ...");
        server_config.serve();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.thebigbang.ftpclient.FTPOperation.java

/**
 * will force keep the device turned on for all the operation duration.
 * @param params/*from w  w w . ja  v a  2s.  c o m*/
 * @return 
 */
@SuppressLint("Wakelock")
@SuppressWarnings("deprecation")
@Override
protected Boolean doInBackground(FTPBundle... params) {
    Thread.currentThread().setName("FTPOperationWorker");
    for (final FTPBundle bundle : params) {

        FTPClient ftp = new FTPClient();
        PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
        WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client");
        try {
            // setup ftp connection:
            InetAddress addr = InetAddress.getByName(bundle.FTPServerHost);
            //set here the timeout.
            TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() {
                @Override
                public void Occurred(TimeoutException e) {
                    bundle.Exception = e;
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                    publishProgress(bundle);
                }
            });
            timeout.start();
            ftp.connect(addr, bundle.FTPServerPort);
            int reply = ftp.getReplyCode();
            timeout.Stop();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new IOException("connection refuse");
            }
            ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword);
            if (bundle.OperationType == FTPOperationType.Connect) {
                bundle.OperationStatus = FTPOperationStatus.Succed;
                publishProgress(bundle);
                continue;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();

            w.acquire();
            // then switch between enum of operation types.
            if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.GetData) {
                String finalFPFi = bundle.LocalFilePathName;
                // The remote filename to be downloaded.
                if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") {
                    File f = new File(bundle.LocalWorkingDirectory);
                    f.mkdirs();

                    finalFPFi = bundle.LocalWorkingDirectory + finalFPFi;
                }
                FileOutputStream fos = new FileOutputStream(finalFPFi);

                // Download file from FTP server
                String finalFileN = bundle.RemoteFilePathName;
                if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") {
                    finalFileN = bundle.RemoteWorkingDirectory + finalFileN;
                }
                boolean b = ftp.retrieveFile(finalFileN, fos);
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                fos.close();

            } else if (bundle.OperationType == FTPOperationType.SendData) {
                InputStream istr = new FileInputStream(bundle.LocalFilePathName);
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr);
                istr.close();
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
            } else if (bundle.OperationType == FTPOperationType.DeleteData) {
                throw new IOException("DeleteData is Not yet implemented");
            }

            ftp.disconnect();
            // then finish/return.
            //publishProgress(bundle);
        } catch (IOException e) {
            e.printStackTrace();
            bundle.Exception = e;
            bundle.OperationStatus = FTPOperationStatus.Failed;
        }
        try {
            w.release();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        }
        publishProgress(bundle);
    }
    return true;
}

From source file:com.alliander.osgp.adapter.protocol.iec61850.infra.networking.Iec61850ChannelHandlerServer.java

private void processRegistrationMessage(final RegisterDeviceRequest message, final String correlationId) {

    this.logMessage(message);

    String deviceIdentification = message.getDeviceIdentification();
    String deviceType = Ssld.SSLD_TYPE;
    final IED ied = IED.FLEX_OVL;
    String ipAddress = message.getIpAddress();

    // In case the optional properties 'testDeviceId' and 'testDeviceIp' are
    // set, the values will be used to set an IP address for a device.
    if (this.testDeviceId != null && this.testDeviceId.equals(deviceIdentification)
            && this.testDeviceIp != null) {
        LOGGER.info("Using testDeviceId: {} and testDeviceIp: {}", this.testDeviceId, this.testDeviceIp);
        deviceIdentification = this.testDeviceId;
        deviceType = Ssld.SSLD_TYPE;/*from   w  w w  .  j a v  a2s  .  c  o m*/
        ipAddress = this.testDeviceIp;
    }

    final DeviceRegistrationDataDto deviceRegistrationData = new DeviceRegistrationDataDto(ipAddress,
            deviceType, true);

    final RequestMessage requestMessage = new RequestMessage(correlationId, "no-organisation",
            deviceIdentification, ipAddress, deviceRegistrationData);

    LOGGER.info("Sending register device request to OSGP with correlation ID: " + correlationId);
    this.osgpRequestMessageSender.send(requestMessage, DeviceFunctionDto.REGISTER_DEVICE.name());

    try {
        this.deviceRegistrationService.disableRegistration(deviceIdentification,
                InetAddress.getByName(ipAddress), ied);
        LOGGER.info("Disabled registration for device: {}, at IP address: {}", deviceIdentification, ipAddress);
    } catch (final Exception e) {
        LOGGER.error("Failed to disable registration for device: {}, at IP address: {}", deviceIdentification,
                ipAddress, e);
    }
}

From source file:com.couchbase.client.core.config.DefaultCouchbaseBucketConfig.java

/**
 * Helper method to reference the partition hosts from the raw node list.
 *
 * @param nodeInfos the node infos./*w  ww .j av  a2  s . co  m*/
 * @param partitionInfo the partition info.
 * @return a ordered reference list for the partition hosts.
 */
private static List<NodeInfo> buildPartitionHosts(List<NodeInfo> nodeInfos,
        CouchbasePartitionInfo partitionInfo) {
    List<NodeInfo> partitionHosts = new ArrayList<NodeInfo>();
    for (String rawHost : partitionInfo.partitionHosts()) {
        InetAddress convertedHost;
        try {
            convertedHost = InetAddress.getByName(rawHost);
        } catch (UnknownHostException e) {
            throw new ConfigurationException("Could not resolve " + rawHost + "on config building.");
        }
        for (NodeInfo nodeInfo : nodeInfos) {
            if (nodeInfo.hostname().equals(convertedHost)) {
                partitionHosts.add(nodeInfo);
            }
        }
    }
    if (partitionHosts.size() != partitionInfo.partitionHosts().length) {
        throw new ConfigurationException("Partition size is not equal after conversion, this is a bug.");
    }
    return partitionHosts;
}

From source file:HDFSFileFinder.java

private static void getBlockLocationsFromHdfs() {
    StringBuilder sb = new StringBuilder();
    Configuration conf = new Configuration();
    boolean first = true;

    // make connection to hdfs
    try {/*from  ww w.j  a  va2  s.  com*/
        if (verbose) {
            writer.println("DEBUG: Trying to connect to " + fsName);
        }
        FileSystem fs = FileSystem.get(conf);
        Path file = new Path(fileName);
        FileStatus fStatus = fs.getFileStatus(file);
        status = fStatus;
        bLocations = fs.getFileBlockLocations(status, 0, status.getLen());
        //print out all block locations
        for (BlockLocation aLocation : bLocations) {
            String[] names = aLocation.getHosts();
            for (String name : names) {
                InetAddress addr = InetAddress.getByName(name);
                String host = addr.getHostName();
                int idx = host.indexOf('.');
                String hostname;
                if (0 < idx) {
                    hostname = host.substring(0, host.indexOf('.'));
                } else {
                    hostname = host;
                }
                if (first) {
                    sb.append(hostname);
                    first = false;
                } else {
                    sb.append(",").append(hostname);
                }
            }
        }
        sb.append(NEWLINE);
    } catch (IOException e) {
        writer.println("Error getting block location data from namenode");
        e.printStackTrace();
    }
    writer.print(sb.toString());
    writer.flush();
}

From source file:com.clustercontrol.winservice.util.RequestWinRM.java

/**
 * WinRM????Windows??Running??????// w w w  .  ja v a 2 s . c o  m
 * 
 * @param ipAddress
 * @param user
 * @param userPassword
 * @param port
 * @param protocol
 * @param timeout
 * @param retries
 * @return
 */
public boolean polling(String ipAddress, String user, String userPassword, int port, String protocol,
        int timeout, int retries) throws HinemosUnknown, WsmanException {
    m_log.debug("polling() " + "ipAddress = " + ipAddress + ",user = " + user + ",userPassword = "
            + userPassword + ",port = " + port + ",protocol = " + protocol + ",timeout = " + timeout
            + ",retries = " + retries);

    // XML?TransformerFactory?
    m_log.debug("polling() javax.xml.transform.TransformerFactory = "
            + System.getProperty("javax.xml.transform.TransformerFactory"));
    System.setProperty("javax.xml.transform.TransformerFactory",
            "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");

    // URL??
    try {
        InetAddress address = InetAddress.getByName(ipAddress);
        if (address instanceof Inet6Address) {
            m_url = protocol + "://[" + ipAddress + "]:" + port + "/wsman";
        } else {
            m_url = protocol + "://" + ipAddress + ":" + port + "/wsman";
        }
    } catch (UnknownHostException e) {
        m_log.info("polling() ipAddress is not valid : " + ipAddress + e.getClass().getSimpleName() + ", "
                + e.getMessage());
        throw new HinemosUnknown("ipAddress is not valid : " + ipAddress);
    }
    m_log.debug("polling() url = " + m_url);

    // ????
    m_con = WsmanConnection.createConnection(m_url);
    m_con.setAuthenticationScheme("basic");
    m_con.setUsername(user);
    m_con.setUserpassword(userPassword);
    m_con.setTimeout(timeout);

    boolean sslTrustall = HinemosPropertyUtil.getHinemosPropertyBool("monitor.winservice.ssl.trustall", true);
    if (sslTrustall) {
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
        };

        m_con.setTrustManager(tm);
        m_con.setHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    } else {
        // HTTP???? common-httpclient ? HostnameVerifier ?
        m_con.setHostnameVerifier(SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    }

    // URI?
    ManagedReference ref = m_con.newReference(URI_WIN32_SERVICE);
    ref.addSelector("Name", m_serviceName);

    // 
    int count = 0;
    WsmanException lastException = null;
    while (count < retries) {
        try {
            // 
            ManagedInstance inst = ref.get();
            if (m_log.isDebugEnabled()) {
                m_log.debug(WsmanUtils.getXML(inst));
            }

            // ??
            Object stateObj = inst.getProperty("State");
            if (stateObj != null) {
                m_state = stateObj.toString();
            } else {
                count++;
                continue;
            }

            // ?
            if (STATE_RUNNING.equalsIgnoreCase(m_state)) {

                // [OK]
                m_message = m_serviceName + " Service is " + STATE_RUNNING;
                m_messageOrg = m_serviceName + " Service is " + STATE_RUNNING;
                m_date = HinemosTime.currentTimeMillis();

                break;
            } else {
                // [NG]
                m_message = m_serviceName + " Service is not " + STATE_RUNNING;
                m_messageOrg = m_serviceName + " Service is another state : " + m_state;
                m_date = HinemosTime.currentTimeMillis();

                return false;
            }

        } catch (WsmanException e) {
            m_log.debug("polling() url=" + m_url + ", count=" + count + " " + e.getMessage() + ", "
                    + e.getReason());

            lastException = e; // ??
            count++;
            continue;

        } finally {

            if (m_con != null) {
                m_con = null;
            }
        }
    }

    // ???NG
    if (count == retries) {

        // ?
        m_message = "WinRM Access Error . ";
        m_messageOrg = "WinRM Access Error . ";
        if (lastException != null) {
            m_messageOrg = m_messageOrg + " : " + lastException.getMessage();
        }
        m_date = HinemosTime.currentTimeMillis();

        if (lastException != null) {
            m_log.info("winservice url=" + m_url + ", message=" + lastException.getMessage() + ", reason="
                    + lastException.getReason());
            if (lastException.getMessage() == null) {
                throw new HinemosUnknown(
                        MessageConstant.MESSAGE_WINSERVICE_NAME_NOT_EXIST_OR_NOT_REFERENCE_AUTHORITY_TO_WINRM
                                .getMessage() + " : " + lastException.getReason());
            } else {
                if (lastException.getMessage().indexOf("HTTP response code: 401") != -1) {
                    throw new HinemosUnknown(
                            MessageConstant.MESSAGE_FAIL_AT_WINRM_ID_OR_PASSWORD_OR_LOGINAUTH_ERR.getMessage());
                }
            }
            throw lastException;
        } else {
            // ??????????
            throw new HinemosUnknown("winservice unknown");
        }
    }

    // [OK]?????
    return true;
}