Example usage for java.net InetSocketAddress getAddress

List of usage examples for java.net InetSocketAddress getAddress

Introduction

In this page you can find the example usage for java.net InetSocketAddress getAddress.

Prototype

public final InetAddress getAddress() 

Source Link

Document

Gets the InetAddress .

Usage

From source file:org.apache.hadoop.ipc.TestSaslRPC.java

public void testDigestAuthMethod(boolean useIp) throws Exception {
    setTokenServiceUseIp(useIp);//from   w w  w  .j  a v a  2s  .  c  om

    TestTokenSecretManager sm = new TestTokenSecretManager();
    Server server = RPC.getServer(new TestSaslImpl(), ADDRESS, 0, 5, true, conf, sm);
    server.start();

    final UserGroupInformation current = UserGroupInformation.getCurrentUser();
    final InetSocketAddress addr = NetUtils.getConnectAddress(server);
    TestTokenIdentifier tokenId = new TestTokenIdentifier(new Text(current.getUserName()));
    Token<TestTokenIdentifier> token = new Token<TestTokenIdentifier>(tokenId, sm);
    SecurityUtil.setTokenService(token, addr);
    LOG.info("Service IP address for token is " + token.getService());

    InetSocketAddress tokenAddr = SecurityUtil.getTokenServiceAddr(token);
    String expectedHost, gotHost;
    if (useIp) {
        expectedHost = addr.getAddress().getHostAddress();
        gotHost = tokenAddr.getAddress().getHostAddress();
    } else {
        gotHost = tokenAddr.getHostName();
        expectedHost = ADDRESS;
    }
    Assert.assertEquals(expectedHost, gotHost);
    Assert.assertEquals(expectedHost + ":" + addr.getPort(), token.getService().toString());

    current.addToken(token);

    current.doAs(new PrivilegedExceptionAction<Object>() {
        public Object run() throws IOException {
            TestSaslProtocol proxy = null;
            try {
                proxy = (TestSaslProtocol) RPC.getProxy(TestSaslProtocol.class, TestSaslProtocol.versionID,
                        addr, conf);
                Assert.assertEquals(AuthenticationMethod.TOKEN, proxy.getAuthMethod());
            } finally {
                if (proxy != null) {
                    RPC.stopProxy(proxy);
                }
            }
            return null;
        }
    });
    server.stop();
}

From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java

@Test
public void testAPop() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;//from w ww . j av  a2 s  . co m
    try {
        TestApopCmdHandler handler = new TestApopCmdHandler();
        server = createServer(createProtocol(handler), address);
        server.bind();

        POP3Client client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        String welcomeMessage = client.getReplyString();

        // check for valid syntax that include all info needed for APOP
        assertThat(welcomeMessage.trim()).matches(Pattern.compile("\\+OK \\<-?\\d+\\.\\d+@.+\\> .+"));

        assertThat(client.sendCommand("APOP invalid invalid")).isEqualTo(POP3Reply.ERROR);

        handler.add("valid", new MockMailbox("id"));
        assertThat(client.sendCommand("APOP valid valid")).isEqualTo(POP3Reply.OK);

        assertThat(client.logout()).isTrue();

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.hadoop.hdfs.server.hightidenode.HighTideNode.java

private void initialize(Configuration conf) throws IOException, SAXException, InterruptedException,
        HighTideConfigurationException, ClassNotFoundException, ParserConfigurationException {
    this.conf = conf;
    InetSocketAddress socAddr = HighTideNode.getAddress(conf);
    int handlerCount = conf.getInt("fs.hightidenodenode.handler.count", 10);

    // read in the configuration
    configMgr = new ConfigManager(conf);
    configMgr.reloadConfigsIfNecessary();
    configMgr.startReload();//from www  .j av  a2  s. c o  m

    // create Metrics object
    myMetrics = new HighTideNodeMetrics(conf, this);

    // create rpc server
    this.server = RPC.getServer(this, socAddr.getAddress().getHostAddress(), socAddr.getPort(), handlerCount,
            false, conf);

    // The rpc-server port can be ephemeral... ensure we have the correct info
    this.serverAddress = this.server.getListenerAddress();
    LOG.info("HighTideNode up at: " + this.serverAddress);

    initialized = true;
    running = true;
    this.server.start(); // start RPC server

    this.fileFixer = new FileFixer(conf);
    this.fileFixerThread = new Daemon(this.fileFixer);
    fileFixer.setPolicyInfo(configMgr.getAllPolicies());
    this.fileFixerThread.start();

    // start the deamon thread to resync if needed
    this.triggerThread = new Daemon(new TriggerMonitor());
    this.triggerThread.start();
}

From source file:org.cloudata.core.commitlog.ServerLocationManager.java

void removeCommitLogServer(String hostAddrStr) throws IOException {
    InetSocketAddress hostAddr = new InetSocketAddress(InetAddress.getByName(getHost(hostAddrStr)),
            getPort(hostAddrStr));/*from  w w w. j ava 2  s .  c  o m*/

    addrSet.remove(hostAddr);

    if (hostAddr.getAddress().equals(InetAddress.getLocalHost())) {
        localCommitLogServerAddress = null;
    }
}

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Returns the HttpClient through which the REST call is made. Uses an
 * unsafe TrustStrategy in case the user specified a HTTPS URL and
 * set the ignoreUnverifiedSSLPeer flag.
 *
 * @param logger    the logger to log messages to
 * @param build/*w w w .j  ava2  s.co  m*/
 * @return         the HttpClient
 */
private HttpClient getHttpClient(PrintStream logger, AbstractBuild<?, ?> build) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String bitbucketServer = bitbucketServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();

    // Determine if we are using the local or global settings
    String credentialsId = getCredentialsId();
    if (StringUtils.isBlank(credentialsId)) {
        credentialsId = descriptor.getCredentialsId();
    }

    Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider
            .lookupCredentials(CertificateCredentials.class, Jenkins.getInstance(), ACL.SYSTEM),
            CredentialsMatchers.withId(credentialsId));

    if ("".equals(bitbucketServer) || bitbucketServer == null) {
        bitbucketServer = descriptor.getBitbucketRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
        ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(bitbucketServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https")
            && (ignoreUnverifiedSSL || credentials instanceof CertificateCredentials)) {
        // add unsafe trust manager to avoid thrown
        // SSLPeerUnverifiedException
        try {
            SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(
                    buildSslContext(ignoreUnverifiedSSL, credentials),
                    ignoreUnverifiedSSL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : null);
            builder.setSSLSocketFactory(sslConnSocketFactory);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnSocketFactory).build();

            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

            builder.setConnectionManager(ccm);
        } catch (NoSuchAlgorithmException nsae) {
            logger.println("Couldn't establish SSL context:");
            nsae.printStackTrace(logger);
        } catch (KeyManagementException kme) {
            logger.println("Couldn't initialize SSL context:");
            kme.printStackTrace(logger);
        } catch (KeyStoreException kse) {
            logger.println("Couldn't initialize SSL context:");
            kse.printStackTrace(logger);
        }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
        Proxy proxy = proxyConfig.createProxy(url.getHost());
        if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
            SocketAddress addr = proxy.address();
            if (addr != null && addr instanceof InetSocketAddress) {
                InetSocketAddress proxyAddr = (InetSocketAddress) addr;
                HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
                builder = builder.setProxy(proxyHost);

                String proxyUser = proxyConfig.getUserName();
                if (proxyUser != null) {
                    String proxyPass = proxyConfig.getPassword();
                    BasicCredentialsProvider cred = new BasicCredentialsProvider();
                    cred.setCredentials(new AuthScope(proxyHost),
                            new UsernamePasswordCredentials(proxyUser, proxyPass));
                    builder = builder.setDefaultCredentialsProvider(cred)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        }
    }

    return builder.build();
}

From source file:org.sipfoundry.sipxrelay.DataShuffler.java

/**
 * Send method to send a packet received from a datagram channel to all the active legs of a
 * bridge.//from w  ww.  j  av  a 2 s  .c o  m
 * 
 * <pre>
 * send(bridge,datagramChannel, addressWherePacketCameFrom) :
 *    for each sym in bridge do :
 *       if sym.receiver.datagramChannel == datagramChannel &amp;&amp; sym.isAutoLearn
 *           sym.receiver.farEnd = addressWherePacketCameFrom
 *       else if sym.transmitter.state == RUNNING :
 *          sym.transmitter.send(byteBuffer)
 * </pre>
 * 
 * @param bridge -- the bridge to forward through.
 * @param datagramChannel -- datagramChannel on which packet was received.
 * @param remoteAddress -- remote address to send to.
 * @throws UnknownHostException -- if there was a problem with the specified remote address.
 */
public static void send(Bridge bridge, DatagramChannel datagramChannel, InetSocketAddress remoteAddress,
        long stamp, boolean selfRouted) throws UnknownHostException {
    try {

        if (logger.isTraceEnabled()) {
            logger.trace("DataShuffler.send(): BridgeSize = " + bridge.sessions.size());
        }
        /* xx-5907 sipxrelay needs to guard against stray media streams. */
        Sym receivedOn = bridge.getReceiverSym(datagramChannel);
        if (logger.isTraceEnabled()) {
            logger.trace("DataShuffler : received packet on symId " + receivedOn.getId());
        }
        if (!selfRouted && receivedOn == null) {
            logger.error("Could not find bridge on which packet was received. Dropping packet");
            return;
        }
        if (remoteAddress == null) {
            logger.warn("remoteAddress is null cannot send. Dropping packet.");
            return;
        }
        if (SymmitronServer.filterStrayPackets) {
            if (!selfRouted && receivedOn.getTransmitter() != null
                    && receivedOn.getTransmitter().getAutoDiscoveryFlag() == AutoDiscoveryFlag.NO_AUTO_DISCOVERY
                    && receivedOn.getTransmitter().getInetAddress() != null
                    && (!receivedOn.getTransmitter().getInetAddress().equals(remoteAddress.getAddress())
                            || receivedOn.getTransmitter().getPort() != remoteAddress.getPort())) {
                if (logger.isTraceEnabled()) {
                    logger.trace(String.format(
                            "Discarding packet - remote endpoint  does not match transmitter endpoint %s %s %d %d ",
                            receivedOn.getTransmitter().getInetAddress(), remoteAddress.getAddress(),
                            receivedOn.getTransmitter().getPort(), remoteAddress.getPort()));

                }
                receivedOn.recordStrayPacket(remoteAddress.getAddress().getHostAddress());
                return;
            } else if (!selfRouted && receivedOn.getTransmitter() != null
                    && receivedOn.getTransmitter().getAutoDiscoveryFlag() == AutoDiscoveryFlag.PORT_ONLY
                    && receivedOn.getTransmitter().getInetAddress() != null
                    && !receivedOn.getTransmitter().getInetAddress().equals(remoteAddress.getAddress())) {
                if (logger.isTraceEnabled()) {
                    logger.trace(String.format(
                            "Discarding packet - remote endpoint  does not match transmitter endpoint %s %s ",
                            receivedOn.getTransmitter().getInetAddress(), remoteAddress.getAddress()));
                }
                receivedOn.recordStrayPacket(remoteAddress.getAddress().getHostAddress());
                return;
            } else if (logger.isTraceEnabled() && receivedOn != null && receivedOn.getTransmitter() != null) {
                if (logger.isTraceEnabled()) {
                    logger.trace("receivedOn : " + receivedOn.getTransmitter().getInetAddress());
                }
            } else if (logger.isTraceEnabled()) {
                logger.trace("receivedOn : transmitter == null ");
            }
        }

        for (Sym sym : bridge.sessions) {
            if (sym.getReceiver() != null && datagramChannel == sym.getReceiver().getDatagramChannel()) {
                if (logger.isTraceEnabled() && remoteAddress != null) {
                    logger.trace("remoteIpAddressAndPort : " + remoteAddress.getAddress().getHostAddress() + ":"
                            + remoteAddress.getPort());

                }
                sym.lastPacketTime = System.currentTimeMillis();
                sym.packetsReceived++;

                bridge.setLastPacketTime(sym.lastPacketTime);

                /*
                 * Set the remote port of the transmitter side of the connection. This allows
                 * for NAT reboots ( port can change while in progress. This is not relevant
                 * for the LAN side.
                 */
                if (sym.getTransmitter() != null) {
                    AutoDiscoveryFlag autoDiscoveryFlag = sym.getTransmitter().getAutoDiscoveryFlag();
                    if (autoDiscoveryFlag != AutoDiscoveryFlag.NO_AUTO_DISCOVERY) {
                        if (remoteAddress != null) {
                            // This packet was self routed.       
                            if (selfRouted) {
                                if (sym.getTransmitter().getIpAddress() != null) {
                                    continue;
                                } else {
                                    String remoteHostAddress = remoteAddress.getAddress().getHostAddress();
                                    int remotePort = remoteAddress.getPort();
                                    /* This search is done just once on the first auto address discovery for a self
                                    * routed packet. Hence the loop is not too alarming subsequently, you dont ever have to look again.
                                    * However, there is probably a better way to do this.
                                    */
                                    for (Sym tsym : SymmitronServer.getSyms()) {
                                        if (tsym.getTransmitter() != null
                                                && tsym.getTransmitter().getIpAddress() != null
                                                && tsym.getTransmitter().getIpAddress()
                                                        .equals(remoteHostAddress)
                                                && tsym.getTransmitter().getPort() == remotePort) {
                                            logger.debug("linking syms for self routed packet ");
                                            sym.getTransmitter().setIpAddressAndPort(
                                                    tsym.getReceiver().getIpAddress(),
                                                    tsym.getReceiver().getPort());
                                            break;
                                        }
                                    }
                                    if (logger.isTraceEnabled()) {
                                        for (Bridge br : SymmitronServer.getBridges()) {
                                            logger.trace(br.toString());
                                        }
                                    }
                                }
                            } else {
                                if (autoDiscoveryFlag == AutoDiscoveryFlag.IP_ADDRESS_AND_PORT) {
                                    if (logger.isTraceEnabled()) {
                                        logger.trace(
                                                "autoDiscovery : setting Ip addess and port : autoDiscovery flag "
                                                        + autoDiscoveryFlag);
                                    }
                                    sym.getTransmitter().setIpAddressAndPort(
                                            remoteAddress.getAddress().getHostAddress(),
                                            remoteAddress.getPort());
                                } else if (autoDiscoveryFlag == AutoDiscoveryFlag.PORT_ONLY) {
                                    // Only update the remote port when the IP address matches. OR if the address is not yet set.  
                                    if (logger.isTraceEnabled()) {
                                        logger.trace("autoDiscovery : setting port : autoDiscovery flag "
                                                + autoDiscoveryFlag);
                                    }
                                    sym.getTransmitter().setPort(remoteAddress.getPort());
                                }
                            }
                        }
                    }

                }
                continue;
            }
            SymTransmitterEndpoint writeChannel = sym.getTransmitter();
            if (writeChannel == null) {
                continue;
            }

            try {

                /*
                 * No need for header rewrite. Just duplicate, flip and push out. Important:
                 * We cannot do this outside the loop. See XECS-2425.
                 */
                if (!writeChannel.isOnHold()) {
                    if (!sym.isVisited(stamp)) {
                        sym.setVisited(stamp);
                        ByteBuffer bufferToSend = readBuffer.duplicate();
                        bufferToSend.flip();
                        writeChannel.send((ByteBuffer) bufferToSend, stamp);
                        bridge.packetsSent++;
                        writeChannel.packetsSent++;
                    } else {
                        if (logger.isTraceEnabled()) {
                            logger.trace("sym " + sym + " Routing Loop detected!");
                        }
                    }
                } else {
                    if (logger.isTraceEnabled()) {
                        logger.trace("WriteChannel on hold." + writeChannel.getIpAddress() + ":"
                                + writeChannel.getPort() + " Not forwarding");
                    }
                }

            } catch (Exception ex) {
                logger.error("Unexpected error shuffling bytes", ex);
                SymmitronServer.printBridges();
            }
        }
    } finally {

    }

}

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();/*from  ww  w  .  ja v a 2 s .  c o m*/

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

From source file:org.apache.hadoop.mapred.TaskRunner.java

/**
 * @param taskid//from  w  ww . j av  a 2 s  . com
 * @param workDir
 * @param classPaths
 * @param logSize
 * @return
 * @throws IOException
 */
private Vector<String> getVMArgs(TaskAttemptID taskid, File workDir, List<String> classPaths, long logSize)
        throws IOException {
    Vector<String> vargs = new Vector<String>(8);
    File jvm = // use same jvm as parent
            new File(new File(System.getProperty("java.home"), "bin"), "java");

    vargs.add(jvm.toString());

    // Add child (task) java-vm options.
    //
    // The following symbols if present in mapred.{map|reduce}.child.java.opts 
    // value are replaced:
    // + @taskid@ is interpolated with value of TaskID.
    // Other occurrences of @ will not be altered.
    //
    // Example with multiple arguments and substitutions, showing
    // jvm GC logging, and start of a passwordless JVM JMX agent so can
    // connect with jconsole and the likes to watch child memory, threads
    // and get thread dumps.
    //
    //  <property>
    //    <name>mapred.map.child.java.opts</name>
    //    <value>-Xmx 512M -verbose:gc -Xloggc:/tmp/@taskid@.gc \
    //           -Dcom.sun.management.jmxremote.authenticate=false \
    //           -Dcom.sun.management.jmxremote.ssl=false \
    //    </value>
    //  </property>
    //
    //  <property>
    //    <name>mapred.reduce.child.java.opts</name>
    //    <value>-Xmx 1024M -verbose:gc -Xloggc:/tmp/@taskid@.gc \
    //           -Dcom.sun.management.jmxremote.authenticate=false \
    //           -Dcom.sun.management.jmxremote.ssl=false \
    //    </value>
    //  </property>
    //
    String javaOpts = getChildJavaOpts(conf, JobConf.DEFAULT_MAPRED_TASK_JAVA_OPTS);
    javaOpts = javaOpts.replace("@taskid@", taskid.toString());
    String[] javaOptsSplit = javaOpts.split(" ");

    // Add java.library.path; necessary for loading native libraries.
    //
    // 1. To support native-hadoop library i.e. libhadoop.so, we add the 
    //    parent processes' java.library.path to the child. 
    // 2. We also add the 'cwd' of the task to it's java.library.path to help 
    //    users distribute native libraries via the DistributedCache.
    // 3. The user can also specify extra paths to be added to the 
    //    java.library.path via mapred.{map|reduce}.child.java.opts.
    //
    String libraryPath = System.getProperty("java.library.path");
    if (libraryPath == null) {
        libraryPath = workDir.getAbsolutePath();
    } else {
        libraryPath += SYSTEM_PATH_SEPARATOR + workDir;
    }
    boolean hasUserLDPath = false;
    for (int i = 0; i < javaOptsSplit.length; i++) {
        if (javaOptsSplit[i].startsWith("-Djava.library.path=")) {
            javaOptsSplit[i] += SYSTEM_PATH_SEPARATOR + libraryPath;
            hasUserLDPath = true;
            break;
        }
    }
    if (!hasUserLDPath) {
        vargs.add("-Djava.library.path=" + libraryPath);
    }
    for (int i = 0; i < javaOptsSplit.length; i++) {
        vargs.add(javaOptsSplit[i]);
    }

    Path childTmpDir = createChildTmpDir(workDir, conf, false);
    vargs.add("-Djava.io.tmpdir=" + childTmpDir);

    // Add classpath.
    vargs.add("-classpath");
    String classPath = StringUtils.join(SYSTEM_PATH_SEPARATOR, classPaths);
    vargs.add(classPath);

    // Setup the log4j prop
    setupLog4jProperties(vargs, taskid, logSize);

    if (conf.getProfileEnabled()) {
        if (conf.getProfileTaskRange(t.isMapTask()).isIncluded(t.getPartition())) {
            File prof = TaskLog.getTaskLogFile(taskid, t.isTaskCleanupTask(), TaskLog.LogName.PROFILE);
            vargs.add(String.format(conf.getProfileParams(), prof.toString()));
        }
    }

    // Add main class and its arguments 
    vargs.add(Child.class.getName()); // main of Child
    // pass umbilical address
    InetSocketAddress address = tracker.getTaskTrackerReportAddress();
    vargs.add(address.getAddress().getHostAddress());
    vargs.add(Integer.toString(address.getPort()));
    vargs.add(taskid.toString()); // pass task identifier
    // pass task log location
    vargs.add(TaskLog.getAttemptDir(taskid, t.isTaskCleanupTask()).toString());
    return vargs;
}

From source file:org.ScripterRon.JavaBitcoin.RpcHandler.java

/**
 * Handle an HTTP request/*from  www  .ja  va  2s . co m*/
 *
 * @param       exchange            HTTP exchange
 * @throws      IOException         Error detected while handling the request
 */
@Override
public void handle(HttpExchange exchange) throws IOException {
    try {
        int responseCode;
        String responseBody;
        //
        // Get the HTTP request
        //
        InetSocketAddress requestAddress = exchange.getRemoteAddress();
        String requestMethod = exchange.getRequestMethod();
        Headers requestHeaders = exchange.getRequestHeaders();
        String contentType = requestHeaders.getFirst("Content-Type");
        Headers responseHeaders = exchange.getResponseHeaders();
        log.debug(String.format("%s request received from %s", requestMethod, requestAddress.getAddress()));
        if (!rpcAllowIp.contains(requestAddress.getAddress())) {
            responseCode = HttpURLConnection.HTTP_UNAUTHORIZED;
            responseBody = "Your IP address is not authorized to access this server";
            responseHeaders.set("Content-Type", "text/plain");
        } else if (!exchange.getRequestMethod().equals("POST")) {
            responseCode = HttpURLConnection.HTTP_BAD_METHOD;
            responseBody = String.format("%s requests are not supported", exchange.getRequestMethod());
            responseHeaders.set("Content-Type", "text/plain");
        } else if (contentType == null || !contentType.equals("application/json-rpc")) {
            responseCode = HttpURLConnection.HTTP_BAD_REQUEST;
            responseBody = "Content type must be application/json-rpc";
            responseHeaders.set("Content-Type", "text/plain");
        } else {
            responseBody = processRequest(exchange);
            responseCode = HttpURLConnection.HTTP_OK;
            responseHeaders.set("Content-Type", "application/json-rpc");
        }
        //
        // Return the HTTP response
        //
        responseHeaders.set("Cache-Control", "no-cache, no-store, must-revalidate, private");
        responseHeaders.set("Server", "JavaBitcoin");
        byte[] responseBytes = responseBody.getBytes("UTF-8");
        exchange.sendResponseHeaders(responseCode, responseBytes.length);
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(responseBytes);
        }
        log.debug(String.format("RPC request from %s completed", requestAddress.getAddress()));
    } catch (IOException exc) {
        log.error("Unable to process RPC request", exc);
        throw exc;
    }
}

From source file:org.apache.bookkeeper.client.TestRegionAwareEnsemblePlacementPolicy.java

@Test(timeout = 60000)
public void testReplaceBookieWithEnoughBookiesInSameRegion() throws Exception {
    InetSocketAddress addr1 = new InetSocketAddress("127.0.0.2", 3181);
    InetSocketAddress addr2 = new InetSocketAddress("127.0.0.3", 3181);
    InetSocketAddress addr3 = new InetSocketAddress("127.0.0.4", 3181);
    InetSocketAddress addr4 = new InetSocketAddress("127.0.0.5", 3181);
    // update dns mapping
    StaticDNSResolver.addNodeToRack(addr1.getAddress().getHostAddress(), NetworkTopology.DEFAULT_RACK);
    StaticDNSResolver.addNodeToRack(addr2.getAddress().getHostAddress(), "/region1/r1");
    StaticDNSResolver.addNodeToRack(addr3.getAddress().getHostAddress(), "/region1/r2");
    StaticDNSResolver.addNodeToRack(addr4.getAddress().getHostAddress(), "/default-region/r3");
    // Update cluster
    Set<InetSocketAddress> addrs = new HashSet<InetSocketAddress>();
    addrs.add(addr1);//from w ww  .java2 s.c o m
    addrs.add(addr2);
    addrs.add(addr3);
    addrs.add(addr4);
    repp.onClusterChanged(addrs, new HashSet<InetSocketAddress>());
    // replace node under r2
    InetSocketAddress replacedBookie = repp.replaceBookie(addr2, new HashSet<InetSocketAddress>());
    assertEquals(addr3, replacedBookie);
}