Example usage for java.net UnknownHostException printStackTrace

List of usage examples for java.net UnknownHostException printStackTrace

Introduction

In this page you can find the example usage for java.net UnknownHostException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.speechforge.zanzibar.sip.SipServer.java

public void startup() {
    _logger.info("Starting sip Server!");

    try {//from w ww .j  a  v a  2s. c  o  m
        if (zanzibarHostName == null)
            zanzibarHostName = CairoUtil.getLocalHost().getHostAddress();

        if (cairoSipHostName == null)
            cairoSipHostName = CairoUtil.getLocalHost().getHostAddress();
    } catch (SocketException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (UnknownHostException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    try {
        _sipAgent = new SipAgent(this, mySipAddress, stackName, zanzibarHostName, null, port, transport);
    } catch (SipException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    waitingList = new HashMap<String, SessionPair>();
    _logger.info("Returned from call to Start sip Server!");

    if (mode.equals("cloud")) {
        try {
            _replicatorPool = RTPStreamReplicatorFactory.createObjectPool(baseReceiverRtpPort, maxConnects,
                    InetAddress.getByName(zanzibarHostName));
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        _portPairPool = new PortPairPool(baseXmitRtpPort, maxConnects);
    }

}

From source file:org.speechforge.zanzibar.sip.SipServer.java

public SdpMessage processInviteRequest(SdpMessage request, SipSession session)
        throws SdpException, ResourceUnavailableException, RemoteException {

    //TODO: Check the callee registry here.  But then do ai need to check for all requests
    //TODO: Investigate Pushing the check down to sipAgent/Listener?

    //get the rtp channels from the invitation
    Vector pbxFormats = null;/*from   ww  w .j av  a 2  s  .  c o  m*/
    int pbxRtpPort = 0;
    String pbxHost = request.getSessionDescription().getConnection().getAddress();
    String pbxSessionName = request.getSessionDescription().getSessionName().getValue();
    SdpMessage pbxResponse = null;
    SipSession internalSession = null;

    _logger.info("Got an invite request");
    try {
        for (MediaDescription md : request.getRtpChannels()) {
            pbxRtpPort = md.getMedia().getMediaPort();
            pbxFormats = md.getMedia().getMediaFormats(true);
            //_logger.debug("Individual Media connection address: "+ md.getConnection().getAddress());
        }
    } catch (SdpException e) {
        _logger.debug(e, e);
        throw e;
    }
    if (_logger.isDebugEnabled()) {
        for (int i = 0; i < pbxFormats.size(); i++) {
            _logger.debug("pbx format # " + i + " is: " + pbxFormats.get(i).toString());
        }
    }

    if (mode.equals("cloud")) {

        RTPStreamReplicator rtpReplicator = null;
        try {
            rtpReplicator = (RTPStreamReplicator) _replicatorPool.borrowObject();
            AudioFormats af = AudioFormats.constructWithSdpVector(pbxFormats);
            _logger.info("Audio Format " + af);
            Vector supportedFormats = af.filterOutUnSupportedFormatsInOffer();
            if (_logger.isDebugEnabled()) {
                for (int i = 0; i < supportedFormats.size(); i++) {
                    //_logger.debug(i+" format type is: "+supportedFormats.get(i).getClass().getCanonicalName());
                    _logger.debug("Supported format # " + i + " is: " + supportedFormats.get(i).toString());
                }
            }

            pbxResponse = constructInviteResponseToPbx(rtpReplicator.getPort(), zanzibarHostName,
                    supportedFormats);
            _sipAgent.sendResponse(session, pbxResponse);

            InetAddress address = InetAddress.getByName(pbxHost);
            int localPort = _portPairPool.borrowPort();
            RtpTransmitter rtpTransmitter = new RtpTransmitter(localPort, address, pbxRtpPort, af);

            dialogService.startNewCloudDialog(session, rtpReplicator, rtpTransmitter);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else if (mode.equals("mrcpv2")) {

        //construct the invite request and send it to the cairo resource server to get the resources for the session
        //TODO: check which resource needed in the original invite (from pbx).  the construct method below blindly gets a tts and recog resoruce
        SdpMessage message = null;
        SdpMessage inviteResponse = null;
        try {
            message = constructInviteRequestToCairo(pbxRtpPort, pbxHost, pbxSessionName, pbxFormats);
            internalSession = _sipAgent.sendInviteWithoutProxy(cairoSipAddress, message, cairoSipHostName,
                    cairoSipPort);
        } catch (UnknownHostException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SipException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //these sessions are linked
        //the forward attribute is not good enough (one side is the backwrds lookup)
        //TODO: Session rediesign.  It has become a bucket of things that are sometmes needed in the client and sometimes in teh server
        // and the proxy relationship is messy with the single reference "forward"
        session.setForward(internalSession);
        internalSession.setForward(session);
        SessionPair sessionPair = new SessionPair(internalSession, session);
        //_logger.debug(":::: ADDING  Internal "+internalSession.getId()+" :::::::");
        //_logger.debug(":::: AND THE External "+session.getId()+" :::::::");
        waitingList.put(internalSession.getCtx().toString(), sessionPair);
    } else {
        _logger.warn("Unrecognized SipServer mode, " + mode);
    }
    return null;
}

From source file:org.speechforge.zanzibar.sip.SipServer.java

public synchronized SdpMessage processInviteResponse(boolean ok, SdpMessage response, SipSession session) {
    _logger.debug("Gotta invite response, ok is: " + ok);
    SdpMessage pbxResponse = null;//www .  j a va2s  .  c o m
    if (ok) {
        //_logger.debug(":::: "+session.getId()+" :::::::");
        SessionPair pair = waitingList.get(session.getCtx().toString());
        waitingList.remove(session.getCtx().toString());

        if (pair != null) {
            // Get the MRCP media channels (need the port number and the channelID that are sent
            // back from the server in the response in order to setup the MRCP channel)
            String remoteHostName = null;
            InetAddress remoteHostAdress = null;
            try {
                remoteHostName = response.getSessionDescription().getConnection().getAddress();
                remoteHostAdress = InetAddress.getByName(remoteHostName);

                List<MediaDescription> xmitterChans = response.getMrcpTransmitterChannels();
                int xmitterPort = xmitterChans.get(0).getMedia().getMediaPort();
                String xmitterChannelId = xmitterChans.get(0).getAttribute(SdpMessage.SDP_CHANNEL_ATTR_NAME);

                List<MediaDescription> receiverChans = response.getMrcpReceiverChannels();
                MediaDescription controlChan = receiverChans.get(0);
                int receiverPort = controlChan.getMedia().getMediaPort();
                String receiverChannelId = receiverChans.get(0).getAttribute(SdpMessage.SDP_CHANNEL_ATTR_NAME);

                List<MediaDescription> rtpChans = response.getAudioChansForThisControlChan(controlChan);
                int remoteRtpPort = -1;
                Vector supportedFormats = null;
                if (rtpChans.size() > 0) {
                    //TODO: What if there is more than 1 media channels?
                    //TODO: check if there is an override for the host attribute in the m block
                    //InetAddress remoteHost = InetAddress.getByName(rtpmd.get(1).getAttribute();
                    remoteRtpPort = rtpChans.get(0).getMedia().getMediaPort();
                    //rtpmd.get(1).getMedia().setMediaPort(localPort);
                    supportedFormats = rtpChans.get(0).getMedia().getMediaFormats(true);
                } else {
                    _logger.warn("No Media channel specified in the invite request");
                    //TODO:  handle no media channel in the response corresponding tp the mrcp channel (sip/sdp error)
                }

                //Construct the MRCP Channels
                String protocol = MrcpProvider.PROTOCOL_TCP_MRCPv2;
                MrcpFactory factory = MrcpFactory.newInstance();
                MrcpProvider provider = factory.createProvider();

                _logger.debug("New Xmitter chan: " + xmitterChannelId + " " + remoteHostAdress + " "
                        + xmitterPort + " " + protocol);
                _logger.debug("New Receiver chan: " + receiverChannelId + " " + remoteHostAdress + " "
                        + receiverPort + " " + protocol);

                MrcpChannel ttsChannel = provider.createChannel(xmitterChannelId, remoteHostAdress, xmitterPort,
                        protocol);
                MrcpChannel recogChannel = provider.createChannel(receiverChannelId, remoteHostAdress,
                        receiverPort, protocol);
                session.setTtsChannel(ttsChannel);
                session.setRecogChannel(recogChannel);

                pbxResponse = startupSpeechlet(remoteHostName, remoteRtpPort, supportedFormats,
                        pair.getMrcpSession(), pair.getPbxSession());

                //_logger.debug(">>>>Here is the invite response:");
                //_logger.debug(pbxResponse.getSessionDescription().toString());

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SdpParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalValueException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SdpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // TODO:  Need to keep track of the "forwarded" Session.  the one that wa created to get the resourses for MRCPv2.  The original
            // Session came from the pbx
            //session.setForward(forward);

        } else {
            _logger.info("Could not find corresponding external request in waiting list");
        }
    } else {
        _logger.info("Invite Response not ok");
    }

    return pbxResponse;
}

From source file:edu.ku.brc.specify.toycode.RegPivot.java

/**
 * @param tblName/* www .  j a  va  2s .  co  m*/
 * @param keyName
 */
public void fillCountryCity(final String tblName, final String keyName) {
    Statement stmt = null;
    try {
        stmt = connection.createStatement();

        BasicSQLUtils.setDBConnection(connection);

        HTTPGetter httpGetter = new HTTPGetter();

        String sql = String.format("SELECT %s, IP, Lookup, Country, City FROM %s WHERE Country IS NULL",
                keyName, tblName);
        PreparedStatement pStmt = connection.prepareStatement(
                String.format("UPDATE %s SET lookup=?, Country=?, City=? WHERE %s = ?", tblName, keyName));

        HashMap<String, String> ipHash = new HashMap<String, String>();
        HashMap<String, Pair<String, String>> ccHash = new HashMap<String, Pair<String, String>>();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            int regId = rs.getInt(1);
            String ip = rs.getString(2);
            String lookup = rs.getString(3);
            String country = rs.getString(4);
            String city = rs.getString(5);

            boolean allEmpty = StringUtils.isEmpty(lookup) && StringUtils.isEmpty(country)
                    && StringUtils.isEmpty(city);

            String hostName = ipHash.get(ip);

            if (allEmpty && hostName == null) {
                String rvStr = new String(
                        httpGetter.doHTTPRequest("http://api.hostip.info/get_html.php?ip=" + ip));
                country = parse(rvStr, "Country:");
                city = parse(rvStr, "City:");
                System.out.println(rvStr + "[" + country + "][" + city + "]");

                try {
                    InetAddress addr = InetAddress.getByName(ip);
                    hostName = addr.getHostName();
                    ipHash.put(ip, hostName);
                    ccHash.put(ip, new Pair<String, String>(country, city));

                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            } else {
                Pair<String, String> p = ccHash.get(ip);
                if (p != null) {
                    country = p.first;
                    city = p.second;
                }
            }

            pStmt.setString(1, hostName);
            pStmt.setString(2, country);
            pStmt.setString(3, city);
            pStmt.setInt(4, regId);
            pStmt.executeUpdate();
        }
        pStmt.close();

        stmt.close();
        colDBConn.close();

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

    System.out.println("Done.");
}

From source file:org.jboss.tools.tycho.sitegenerator.GenerateRepositoryFacadeMojo.java

/**
 * @param outputRepository//from   w w w .java  2 s . co m
 * @throws MojoFailureException
 * @throws MojoExecutionException
 */
private void createBuildInfo(File outputRepository, File buildinfoFolder)
        throws MojoFailureException, MojoExecutionException {
    ModelNode jsonProperties = new ModelNode();
    jsonProperties.get("timestamp").set(System.currentTimeMillis()); // TODO get it from build metadata

    try {
        jsonProperties.get("revision").set(createRevisionObject());
    } catch (FileNotFoundException ex) {
        getLog().error("Could not add revision to " + BUILDINFO_JSON + ": not a Git repository", ex);
    } catch (Exception ex) {
        throw new MojoFailureException("Could not add revision to " + BUILDINFO_JSON, ex);
    }

    // get hostname and load into HOSTNAME
    java.net.InetAddress localMachine;
    try {
        localMachine = java.net.InetAddress.getLocalHost();
        System.setProperty("HOSTNAME", localMachine.getHostName());
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    // if WORKSPACE is null, use current directory
    if (System.getProperty("WORKSPACE") == null || System.getProperty("WORKSPACE").equals("")) {
        System.setProperty("WORKSPACE", Paths.get("").toAbsolutePath().toString());
    }

    ModelNode sysProps = new ModelNode();
    for (String propertyName : this.systemProperties) {
        sysProps.get(propertyName).set(String.valueOf(System.getProperty(propertyName)));
    }

    jsonProperties.get("properties").set(sysProps);

    try {
        jsonProperties.get(UPSTREAM_ELEMENT).set(aggregateUpstreamMetadata(buildinfoFolder));
    } catch (Exception ex) {
        throw new MojoExecutionException("Could not get upstream metadata", ex);
    }

    try {
        // put buildinfo.json inside the target/buildinfo/ folder
        FileUtils.fileWrite(new File(buildinfoFolder, BUILDINFO_JSON), jsonProperties.toJSONString(false));
        // put a copy inside the target/repository/ folder (and site zip)
        FileUtils.fileWrite(new File(outputRepository, BUILDINFO_JSON), jsonProperties.toJSONString(false));
    } catch (Exception ex) {
        throw new MojoFailureException("Could not generate properties file", ex);
    }
}

From source file:com.radicaldynamic.groupinform.services.DatabaseService.java

synchronized public ReplicationStatus replicate(String db, int mode) {
    final String tt = t + "replicate(): ";

    if (Collect.Log.DEBUG)
        Log.d(Collect.LOGTAG, tt + "about to replicate " + db);

    // Will not replicate unless signed in
    if (!Collect.getInstance().getIoService().isSignedIn()) {
        if (Collect.Log.DEBUG)
            Log.d(Collect.LOGTAG, tt + "aborting replication: not signed in");
        return null;
    }/*  w  w  w  .ja  v  a 2 s. c  o  m*/

    if (Collect.getInstance().getInformOnlineState().isOfflineModeEnabled()) {
        if (Collect.Log.DEBUG)
            Log.d(Collect.LOGTAG, tt + "aborting replication: offline mode is enabled");
        return null;
    }

    /*
     * Lookup master cluster by IP.  Do this instead of relying on Erlang's internal resolver 
     * (and thus Google's public DNS).  Our builds of Erlang for Android do not yet use 
     * Android's native DNS resolver.
     */
    String masterClusterIP = null;

    try {
        InetAddress[] clusterInetAddresses = InetAddress
                .getAllByName(getString(R.string.tf_default_ionline_server));
        masterClusterIP = clusterInetAddresses[new Random().nextInt(clusterInetAddresses.length)]
                .getHostAddress();
    } catch (UnknownHostException e) {
        if (Collect.Log.ERROR)
            Log.e(Collect.LOGTAG, tt + "unable to lookup master cluster IP addresses: " + e.toString());
        e.printStackTrace();
    }

    // Create local instance of database
    boolean dbCreated = false;

    // User may not have connected to local database yet - start up the connection for them
    try {
        if (mLocalDbInstance == null) {
            connectToLocalServer();
        }
    } catch (DbUnavailableException e) {
        if (Collect.Log.ERROR)
            Log.e(Collect.LOGTAG, tt + "cannot connect to local database server");
        e.printStackTrace();
    }

    if (mLocalDbInstance.getAllDatabases().indexOf("db_" + db) == -1) {
        switch (mode) {
        case REPLICATE_PULL:
            if (Collect.Log.INFO)
                Log.i(Collect.LOGTAG, tt + "creating local database " + db);
            mLocalDbInstance.createDatabase("db_" + db);
            dbCreated = true;
            break;

        case REPLICATE_PUSH:
            // If the database does not exist client side then there is no point in continuing
            if (Collect.Log.WARN)
                Log.w(Collect.LOGTAG, tt + "cannot find local database " + db + " to push");
            return null;
        }
    }

    // Configure replication direction
    String source = null;
    String target = null;

    String deviceId = Collect.getInstance().getInformOnlineState().getDeviceId();
    String deviceKey = Collect.getInstance().getInformOnlineState().getDeviceKey();

    String localServer = "http://" + mLocalHost + ":" + mLocalPort + "/db_" + db;
    String remoteServer = "http://" + deviceId + ":" + deviceKey + "@" + masterClusterIP + ":5984/db_" + db;

    // Should we use encrypted transfers?
    SharedPreferences settings = PreferenceManager
            .getDefaultSharedPreferences(Collect.getInstance().getBaseContext());

    if (settings.getBoolean(PreferencesActivity.KEY_ENCRYPT_SYNCHRONIZATION, true)) {
        remoteServer = "https://" + deviceId + ":" + deviceKey + "@" + masterClusterIP + ":6984/db_" + db;
    }

    switch (mode) {
    case REPLICATE_PUSH:
        source = localServer;
        target = remoteServer;
        break;

    case REPLICATE_PULL:
        source = remoteServer;
        target = localServer;
        break;
    }

    ReplicationCommand cmd = new ReplicationCommand.Builder().source(source).target(target).build();
    ReplicationStatus status = null;

    try {
        status = mLocalDbInstance.replicate(cmd);
    } catch (Exception e) {
        // Remove a recently created DB if the replication failed
        if (dbCreated) {
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "replication exception: " + e.toString());
            e.printStackTrace();

            mLocalDbInstance.deleteDatabase("db_" + db);
        }
    }

    return status;
}

From source file:com.vangent.hieos.logbrowser.servlets.AuthenticationServlet.java

/**
 * //from  ww  w .  j a  v  a  2s .c om
 *  Entry point of the servlet
 */
public void doPost(HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("text/xml");
    HttpSession session = req.getSession(true);
    String passwordInput = req.getParameter("password");
    String newPassword = req.getParameter("chgPassword");
    String getIsAdmin = req.getParameter("isAdmin");
    String logout = req.getParameter("logout");
    String ipFrom = req.getRemoteAddr();
    String company = null;
    try {
        InetAddress address = InetAddress.getByName(ipFrom);
        if (address instanceof Inet6Address) {
            if (address.isLoopbackAddress()) {
                ipFrom = "127.0.0.1";
            } else {
                ipFrom = "null";
            }
        }
    } catch (UnknownHostException e) {
    }

    if (ipFrom != null && !ipFrom.equals("null")) {
        Log log = new Log();
        try {
            PreparedStatement selectCompanyName = null;
            Connection con = log.getConnection();
            selectCompanyName = con.prepareStatement("SELECT company_name,email FROM ip where ip = ? ; ");
            selectCompanyName.setString(1, ipFrom);
            ResultSet result = selectCompanyName.executeQuery();
            if (result.next()) {
                company = result.getString(1).replaceAll("'", "&quot;");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (LoggerException e) {
            e.printStackTrace();
        } finally {
            try {
                log.closeConnection();
            } catch (LoggerException ex) {
                Logger.getLogger(AuthenticationServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    String pageNumber = (String) session.getAttribute("page");
    String numberResultsByPage = (String) session.getAttribute("numberResultsByPage");
    session.setAttribute("isAdmin", true); // BHT (HACK).

    // DISABLED (BHT)
    // readFile();
    if (passwordInput != null) {
        try {
            if (passwordRead.equals(passwordInput)) {
                session.setAttribute("isAdmin", true);
                if (newPassword != null) {
                    FileWriter fstream;
                    try {
                        fstream = new FileWriter(passwordFile);
                        BufferedWriter out = new BufferedWriter(fstream);
                        out.write(newPassword);
                        out.close();
                        res.getWriter()
                                .write("<response isChanged='true' isAuthenticated='true' page ='" + pageNumber
                                        + "' numberResultByPage='" + numberResultsByPage + "'></response>");

                    } catch (IOException e) {
                        try {
                            res.getWriter().write("<response isChanged='false' page ='" + pageNumber
                                    + "' numberResultByPage='" + numberResultsByPage + "' ip='" + ipFrom + "' +"
                                    + " company='" + company + "' > " + e.getMessage() + "</response>");
                        } catch (IOException e1) {
                        }
                    }

                } else {
                    res.getWriter().write("<response isAuthenticated='true' page ='" + pageNumber
                            + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                }
            } else {
                res.getWriter().write("<response isAuthenticated='false' ip='" + ipFrom + "' page ='"
                        + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
            }
        } catch (Exception e) {
        }
    } else if (getIsAdmin != null && getIsAdmin.equals("get")) {
        try {
            Boolean isAuthenticated = (Boolean) session.getAttribute("isAdmin");
            String sysType = (String) session.getAttribute("systemType");

            if (sysType == null) {
                sysType = "new";
            }

            if (isAuthenticated != null && isAuthenticated.booleanValue()) {
                res.getWriter().write("<response isAuthenticated='true' systemType='" + sysType + "' page ='"
                        + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                /*} else if (authorizedIPs.contains(ipFrom)) {
                res.getWriter().write(
                "<response isAuthenticated='true'" + " page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>");
                session.setAttribute("isAdmin", true);
                }*/
            } else {
                res.getWriter()
                        .write("<response isAuthenticated='false' ip='" + ipFrom + "' systemType ='" + sysType
                                + "' company    ='" + company + "' page       ='" + pageNumber
                                + "' numberResultByPage='" + numberResultsByPage + "'></response>");
            }
        } catch (IOException e) {
        }
    } else if (logout != null && logout.equals("yes")) {
        session.invalidate();
        try {
            res.getWriter().write("<response/>");
        } catch (IOException e) {
        }
    }
}

From source file:de.fhg.fokus.diameter.DiameterPeer.DiameterPeer.java

/**
 * Configure a DiameterPeer based on a configuration file or string. Path && isFile==true is equivalent to DiameterPeer(Path).
 * /*from  w w  w. j a  v  a2s .com*/
 * @param xml
 *            XML configuration payload.
 * @param isFile
 *            Set to true if string is a path/uri, false if raw xml.
 */
public void configure(String xml, boolean isFile) {
    Acceptor acc;
    NodeList nl;
    Node n, nv;
    int port, app_id, vendor_id;
    InetAddress addr;

    Application app;

    this.eventListeners = new Vector<EventListener>();

    java.util.Random rand = new java.util.Random();
    this.hopbyhop_id = rand.nextInt();
    this.endtoend_id = ((int) (System.currentTimeMillis() & 0xFFF)) << 20;
    this.endtoend_id |= rand.nextInt() & 0xFFFFF;

    if (isFile) {
        /* parse the config */
        if (!readConfigFile(xml)) {
            log.error("DiameterPeer: Error parsing config file");
            return;
        }
    } else {
        /* parse the config */
        if (!readConfigString(xml)) {
            log.error("DiameterPeer: Error parsing config String");
            return;
        }
    }

    this.FQDN = this.config.getDocumentElement().getAttribute("FQDN");
    this.Realm = this.config.getDocumentElement().getAttribute("Realm");
    this.Vendor_Id = Integer.parseInt(this.config.getDocumentElement().getAttribute("Vendor_Id"));
    this.Product_Name = this.config.getDocumentElement().getAttribute("Product_Name");
    this.AcceptUnknownPeers = Integer
            .parseInt(this.config.getDocumentElement().getAttribute("AcceptUnknownPeers")) != 0;
    this.DropUnknownOnDisconnect = Integer
            .parseInt(this.config.getDocumentElement().getAttribute("DropUnknownOnDisconnect")) != 0;
    this.Tc = Integer.parseInt(this.config.getDocumentElement().getAttribute("Tc"));
    this.workerCount = Integer.parseInt(this.config.getDocumentElement().getAttribute("Workers"));
    this.queueLength = Integer.parseInt(this.config.getDocumentElement().getAttribute("QueueLength"));
    this.queueTasks = new ArrayBlockingQueue<DiameterTask>(this.queueLength, true);
    this.reqTimeout = Long.parseLong(this.config.getDocumentElement().getAttribute("ReqTimeout"));

    log.info("FQDN: " + this.FQDN);
    log.info("Realm: " + this.Realm);
    log.info("Vendor_ID : " + this.Vendor_Id);
    log.info("Product Name: " + this.Product_Name);
    log.info("AcceptUnknwonPeers: " + this.AcceptUnknownPeers);
    log.info("DropUnknownOnDisconnect: " + this.DropUnknownOnDisconnect);
    log.info("ReqTimeout: " + this.reqTimeout);

    startWorkers();

    /* Read Supported Application ids */
    this.AuthApp = new Vector<Application>();
    this.AcctApp = new Vector<Application>();
    this.hostIpAdds = new Vector<String>();
    // get auth data from DiameterPeerHSS.xml.env-vm
    nl = this.config.getDocumentElement().getElementsByTagName("Auth");
    for (int i = 0; i < nl.getLength(); i++) {
        n = nl.item(i);
        app_id = 0;
        app_id = Integer.parseInt(n.getAttributes().getNamedItem("id").getNodeValue());
        vendor_id = 0;
        if (n.getAttributes().getNamedItem("vendor") != null)
            vendor_id = Integer.parseInt(n.getAttributes().getNamedItem("vendor").getNodeValue());

        app = new Application(app_id, vendor_id, Application.Auth);
        this.AuthApp.add(app);
    }
    // get acct data from DiameterPeerHSS.xml.env-vm
    nl = this.config.getDocumentElement().getElementsByTagName("Acct");
    for (int i = 0; i < nl.getLength(); i++) {
        n = nl.item(i);
        app_id = 0;
        app_id = Integer.parseInt(n.getAttributes().getNamedItem("id").getNodeValue());
        vendor_id = 0;
        if (n.getAttributes().getNamedItem("vendor") != null)
            vendor_id = Integer.parseInt(n.getAttributes().getNamedItem("vendor").getNodeValue());

        app = new Application(app_id, vendor_id, Application.Acct);
        this.AcctApp.add(app);
    }

    /* Initialize the Peer Manager */
    this.peerManager = new PeerManager(this);

    /* Read the peers from the configuration file */
    nl = this.config.getDocumentElement().getElementsByTagName("Peer");
    for (int i = 0; i < nl.getLength(); i++) {
        n = nl.item(i);

        String localIp = n.getAttributes().getNamedItem("LocalIp").getNodeValue();

        int localPort = Integer.parseInt(n.getAttributes().getNamedItem("LocalPort").getNodeValue());

        this.peerFQDN = n.getAttributes().getNamedItem("FQDN").getNodeValue();

        this.peerRealm = n.getAttributes().getNamedItem("Realm").getNodeValue();

        port = 3868;
        nv = n.getAttributes().getNamedItem("port");
        if (nv == null) {
            port = 3868;
        } else {
            port = Integer.parseInt(nv.getNodeValue());
        }

        this.peerManager.configurePeer(localIp, localPort, this.peerFQDN, this.peerRealm, "", port);
    }

    /* Create & start connection acceptors */
    this.acceptors = new Vector<Acceptor>();
    nl = this.config.getDocumentElement().getElementsByTagName("Acceptor");
    for (int i = 0; i < nl.getLength(); i++) {
        n = nl.item(i);

        nv = n.getAttributes().getNamedItem("port");
        if (nv != null) {
            this.bindPort = Integer.parseInt(nv.getNodeValue());
        }

        addr = null;
        nv = n.getAttributes().getNamedItem("bind");
        if (nv != null && nv.getNodeValue().length() != 0)
            try {
                this.bindIp = nv.getNodeValue();
                this.hostIpAdds.add(this.bindIp);
                addr = InetAddress.getByName(this.bindIp);
            } catch (UnknownHostException e) {
                log.error("DiameterPeer: Can not resolve " + this.bindIp);
                e.printStackTrace();
                continue;
            }
        acc = new Acceptor(bindPort, addr, this);
        acc.startAccepting();
        this.acceptors.add(acc);
    }

    // get host ip address data from DiameterPeerHSS.xml.env-vm
    nl = this.config.getDocumentElement().getElementsByTagName("HostIpAdd");
    for (int i = 0; i < nl.getLength(); i++) {
        n = nl.item(i);
        String hostIpAddress = null;
        hostIpAddress = n.getAttributes().getNamedItem("ip").getNodeValue();
        this.hostIpAdds.add(hostIpAddress);
    }

    initRoutingTable(this.config);

    this.peerManager.start();

}

From source file:com.chiorichan.http.HttpRequestWrapper.java

/**
 * Similar to {@link #getInetAddr(boolean)}
 *
 * @param detectCDN/* ww  w  .  j  a  v a 2 s.c  o m*/
 *             Try to detect the use of CDNs, e.g., CloudFlare, IP headers when set to false.
 * @return
 *         the remote connections IP address
 */
public InetAddress getInetAddr(boolean detectCDN) {
    if (detectCDN && http.headers().contains("CF-Connecting-IP"))
        try {
            return InetAddress.getByName(http.headers().getAndConvert("CF-Connecting-IP"));
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }

    return ((InetSocketAddress) channel.remoteAddress()).getAddress();
}

From source file:iZiggiClient.java

private JSONObject doAction(String cmd, String val) {
    String actUrl = requestUrl + api + "?id=" + userId + "&pwd=" + userPass + "&command=" + cmd;
    if (!val.equals(""))
        actUrl += "&value=" + val;
    URL url = null;/*from   w  w  w .  j a  v  a 2  s.c o m*/
    BufferedReader reader = null;
    StringBuilder stringBuilder;
    JSONObject json = null;
    String extraMessage = "";
    try {
        // create the HttpURLConnection
        url = new URL(actUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // just want to do an HTTP GET here
        connection.setRequestMethod("GET");

        // give it 15 seconds to respond
        connection.setReadTimeout(15 * 1000);
        connection.connect();

        // read the output from the server
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        stringBuilder = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }

        json = new JSONObject(stringBuilder.toString());
    } catch (UnknownHostException e) {
        try {
            json = new JSONObject("{Status:5}");
            extraMessage = " - host name error";
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    } catch (ConnectException e) {
        try {
            json = new JSONObject("{Status:5}");
            extraMessage = " - connect error";
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    } catch (NullPointerException e) {
        try {
            json = new JSONObject("{Status:5}");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
    try {
        json.put("Message", getMessage(json.getInt("Status")) + extraMessage);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return json;
}