Example usage for java.net InetAddress getAddress

List of usage examples for java.net InetAddress getAddress

Introduction

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

Prototype

public byte[] getAddress() 

Source Link

Document

Returns the raw IP address of this InetAddress object.

Usage

From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java

@Override
public List<InetAddress> findExistingIPs(final InetAddress startAddr, final InetAddress endAddr) {
    return getJdbcTemplate().query("select ipaddress from dhcplease"
            + " where ipaddress >= ? and ipaddress <= ?" + " order by ipaddress",
            new PreparedStatementSetter() {
                @Override/* ww w  . j  a  v  a2s.c om*/
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setBytes(1, startAddr.getAddress());
                    ps.setBytes(2, endAddr.getAddress());
                }
            }, new RowMapper<InetAddress>() {
                @Override
                public InetAddress mapRow(ResultSet rs, int rowNum) throws SQLException {
                    InetAddress inetAddr = null;
                    try {
                        inetAddr = InetAddress.getByAddress(rs.getBytes("ipaddress"));
                    } catch (UnknownHostException e) {
                        // re-throw as SQLException
                        throw new SQLException("Unable to map ipaddress", e);
                    }
                    return inetAddr;
                }
            });
}

From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java

/**
 * Update ia options./*from w ww.  j a  v  a  2s. co  m*/
 */
protected void updateIaOptions(final InetAddress inetAddr, final Collection<DhcpOption> iaOptions) {
    getJdbcTemplate().update("update dhcplease" + " set ia_options=?" + " where ipaddress=?",
            new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setBytes(1, encodeOptions(iaOptions));
                    ps.setBytes(2, inetAddr.getAddress());
                }
            });
}

From source file:com.netxforge.oss2.config.DiscoveryConfigFactory.java

/**
 * <p>isExcluded</p>/*  w w  w.j ava 2 s. com*/
 *
 * @param address a {@link java.net.InetAddress} object.
 * @return a boolean.
 */
public boolean isExcluded(final InetAddress address) {
    getReadLock().lock();

    try {
        final List<ExcludeRange> excludeRange = getConfiguration().getExcludeRangeCollection();
        if (excludeRange != null) {
            final byte[] laddr = address.getAddress();

            for (final ExcludeRange range : excludeRange) {
                if (InetAddressUtils.isInetAddressInRange(laddr, range.getBegin(), range.getEnd())) {
                    return true;
                }
            }
        }
        return false;
    } finally {
        getReadLock().unlock();
    }
}

From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java

/**
 * Update ipaddr options.//from w w w . j  a  v a  2s .c  om
 */
protected void updateIpAddrOptions(final InetAddress inetAddr, final Collection<DhcpOption> ipAddrOptions) {
    getJdbcTemplate().update("update dhcplease" + " set ipaddr_options=?" + " where ipaddress=?",
            new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setBytes(1, encodeOptions(ipAddrOptions));
                    ps.setBytes(2, inetAddr.getAddress());
                }
            });
}

From source file:org.opennms.netmgt.config.DiscoveryConfigFactory.java

/**
 * <p>isExcluded</p>//from   w  ww .ja  v  a  2 s.c  o m
 *
 * @param address a {@link java.net.InetAddress} object.
 * @return a boolean.
 */
@Override
public boolean isExcluded(final InetAddress address) {
    getReadLock().lock();
    try {
        final List<ExcludeRange> excludeRange = getConfiguration().getExcludeRangeCollection();
        if (excludeRange != null) {
            final byte[] laddr = address.getAddress();

            for (final ExcludeRange range : excludeRange) {
                if (InetAddressUtils.isInetAddressInRange(laddr, range.getBegin(), range.getEnd())) {
                    return true;
                }
            }
        }
        return false;
    } finally {
        getReadLock().unlock();
    }
}

From source file:it.dfa.unict.CodeRadePortlet.java

private void submitJob(String appServerPath, AppInput appInput, InfrastructureInfo[] enabledInfrastructures) {

    // Job details
    String executable = "/bin/sh"; // Application executable
    String arguments = appPreferences.getPilotScript(); // executable' arguments
    String outputPath = "/tmp/"; // Output Path
    String outputFile = "code-rade-Output.txt"; // Distributed application standard output
    String errorFile = "code-rade-Error.txt"; // Distributed application standard error
    String appFile = "code-rade-Files.tar.gz"; // Hostname output files (created by the pilot script)

    // InputSandbox (string with comma separated list of file names)
    String inputSandbox = appServerPath + "WEB-INF/job/" //
            + appPreferences.getPilotScript() // pilot script
            + "," + appInput.getInputSandbox() // input file
    ;/*from  w w w .j a  va  2  s.c o  m*/

    // OutputSandbox (string with comma separated list of file names)
    String outputSandbox = appFile; // Output file

    // Take care of job requirements
    // More requirements can be specified in the preference value 'jobRequirements'
    // separating each requirement by the ';' character
    // The loop prepares a string array with GridEngine/JSAGA compliant requirements
    String jdlRequirements[] = appPreferences.getJobRequirements().split(";");
    int numRequirements = 0;
    for (int i = 0; i < jdlRequirements.length; i++) {
        if (!jdlRequirements[i].equals("")) {
            jdlRequirements[numRequirements] = "JDLRequirements=(" + jdlRequirements[i] + ")";
            numRequirements++;
            _log.info("Requirement[" + i + "]='" + jdlRequirements[i] + "'");
        }
    } // for each jobRequirement

    // Prepare the GridEngine job description
    GEJobDescription jobDesc = new GEJobDescription();
    jobDesc.setExecutable(executable); // Specify the executeable
    jobDesc.setArguments(arguments); // Specify the application' arguments
    jobDesc.setOutputPath(outputPath); // Specify the output directory
    jobDesc.setOutput(outputFile); // Specify the std-output file
    jobDesc.setError(errorFile); // Specify the std-error file
    jobDesc.setOutputFiles(outputSandbox); // Setup output files (OutputSandbox) (*)
    jobDesc.setInputFiles(inputSandbox); // Setut input files (InputSandbox)

    // GridEngine' MultiInfrastructure job submission object
    MultiInfrastructureJobSubmission miJobSubmission = null;

    // Initialize the GridEngine Multi Infrastructure Job Submission object
    //
    //  GridEngine uses two different kind of constructors. The constructor
    //  taking no database arguments is used for production environments, while
    //  the constructor taking SciGwyUserTrackingDB parameters is normally used
    //  for development purposes. In order to switch-on the production constructor
    //  just set to empty strings the following portlet init parameters or form
    //  the portlet preferences:
    //      sciGwyUserTrackingDB_Hostname
    //      sciGwyUserTrackingDB_Username
    //      sciGwyUserTrackingDB_Password
    //      sciGwyUserTrackingDB_Database
    //
    if (!appPreferences.isProductionEnviroment()) {
        String DBNM = "jdbc:mysql://" + appPreferences.getSciGwyUserTrackingDB_Hostname() + "/"
                + appPreferences.getSciGwyUserTrackingDB_Database();
        String DBUS = appPreferences.getSciGwyUserTrackingDB_Username();
        String DBPW = appPreferences.getSciGwyUserTrackingDB_Password();
        miJobSubmission = new MultiInfrastructureJobSubmission(DBNM, DBUS, DBPW, jobDesc);
        _log.info("MultiInfrastructureJobSubmission [DEVEL]\n" + LS + "    DBNM: '" + DBNM + "'" + LS
                + "    DBUS: '" + DBUS + "'" + LS + "    DBPW: '" + DBPW + "'");
    }

    else {
        miJobSubmission = new MultiInfrastructureJobSubmission(jobDesc);
        _log.info("MultiInfrastructureJobSubmission [PROD]");
    }

    for (int i = 0; i < enabledInfrastructures.length; i++) {
        _log.info("Adding infrastructure #" + (i + 1) + " - Name: '" + enabledInfrastructures[i].getName() + "'"
                + LS);
        miJobSubmission.addInfrastructure(enabledInfrastructures[i]);
    }

    // GridOperations' Application Id
    int applicationId = Integer.parseInt(appPreferences.getGridOperationId());

    // Grid Engine' UserTraking needs the portal IP address
    String portalIPAddress = "";
    try {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        portalIPAddress = "" + (short) (ipAddr[0] & 0xff) + ":" + (short) (ipAddr[1] & 0xff) + ":"
                + (short) (ipAddr[2] & 0xff) + ":" + (short) (ipAddr[3] & 0xff);
    } catch (Exception e) {
        _log.error("Unable to get the portal IP address");
    }

    // Setup job requirements
    if (numRequirements > 0)
        miJobSubmission.setJDLRequirements(jdlRequirements);

    // Ready now to submit the Job
    miJobSubmission.submitJobAsync(appInput.getUsername(), portalIPAddress, applicationId,
            appInput.getJobIdentifier());

    // Show log
    // View jobSubmission details in the log
    _log.info(LS + "JobSent" + LS + "-------" + LS + "Portal address: '" + portalIPAddress + "'" + LS
            + "Executable    : '" + executable + "'" + LS + "Arguments     : '" + arguments + "'" + LS
            + "Output path   : '" + outputPath + "'" + LS + "Output sandbox: '" + outputSandbox + "'" + LS
            + "Ouput file    : '" + outputFile + "'" + LS + "Error file    : '" + errorFile + "'" + LS
            + "Input sandbox : '" + inputSandbox + "'" + LS); // _log.info
}

From source file:org.htrace.impl.ZipkinSpanReceiver.java

/**
 * Set up the HTrace to Zipkin converter.
 *//* w ww .  ja  v  a  2  s . com*/
private void initConverter() {
    InetAddress tracedServiceHostname = null;
    // Try and get the hostname.  If it's not configured try and get the local hostname.
    try {
        String host = conf.get("zipkin.traced-service-hostname", InetAddress.getLocalHost().getHostAddress());

        tracedServiceHostname = InetAddress.getByName(host);
    } catch (UnknownHostException e) {
        LOG.error("Couldn't get the localHost address", e);
    }
    short tracedServicePort = (short) conf.getInt("zipkin.traced-service-port", -1);
    byte[] address = tracedServiceHostname != null ? tracedServiceHostname.getAddress()
            : DEFAULT_COLLECTOR_HOSTNAME.getBytes();
    int ipv4 = ByteBuffer.wrap(address).getInt();
    this.converter = new HTraceToZipkinConverter(ipv4, tracedServicePort);
}

From source file:org.commoncrawl.service.crawler.CrawlTarget.java

public void cacheOriginalRequestData(NIOHttpConnection connection) {
    InetAddress address = connection.getResolvedAddress();
    int ipAddress = 0;
    if (address == null || address.getAddress() == null) {
        if (address == null) {
            LOG.error("### BUG resolved Adddress is null in cacheOriginalRequest! for Target:"
                    + getOriginalURL());
        } else {//from   w  w w.  ja  v a 2s  .  co m
            LOG.error("### BUG resolved Adddress.getAddress returned null in cacheOriginalRequest! for Target:"
                    + getOriginalURL());
        }
    } else {
        ipAddress = IPAddressUtils.IPV4AddressToInteger(address.getAddress());
    }

    _originalRequestData = new CrawlTarget.HTTPData(connection.getResponseHeaders().toString(),
            (short) connection.getHttpResponseCode(), ipAddress, connection.getResolvedAddressTTL());
}

From source file:org.commoncrawl.service.crawler.CrawlTarget.java

public void fetchSucceeded(NIOHttpConnection connection, NIOHttpHeaders httpHeaders,
        NIOBufferList nioContentBuffer) {

    boolean failure = false;
    int failureReason = CrawlURL.FailureReason.UNKNOWN;
    Exception failureException = null;
    String failureDescription = "";

    // revalidate ip address here ...
    if (getRedirectCount() == 0) {
        // check to see if ip address go reresolved ...
        if (connection.getResolvedAddress() != null) {

            InetAddress address = connection.getResolvedAddress();

            int ipAddress = 0;

            if (address.getAddress() != null) {
                // if so, update url data information ...
                ipAddress = IPAddressUtils.IPV4AddressToInteger(address.getAddress());
            } else {
                LOG.error("### BUG int Address getAddress returned Null for target:" + getActiveURL());
            }/*  ww  w.j  a v a  2  s. c  o m*/

            // LOG.info("IP Address for URL:" + getActiveURL() + " is:" + ipAddress
            // + " ttl is:" + connection.getResolvedAddressTTL());
            setServerIP(ipAddress);
            setServerIPTTL(connection.getResolvedAddressTTL());
        }
    }

    Buffer contentBuffer = new Buffer();
    byte data[] = new byte[nioContentBuffer.available()];

    int responseCode = -1;

    try {
        responseCode = NIOHttpConnection.getHttpResponseCode(httpHeaders);

        if (!isAcceptableSuccessResponseCode(responseCode)) {
            failure = true;
            failureReason = CrawlURL.FailureReason.InvalidResponseCode;
            failureDescription = "URL:" + getOriginalURL() + " returned invalid responseCode:" + responseCode;
        }
    } catch (Exception e) {
        failure = true;
        failureReason = CrawlURL.FailureReason.RuntimeError;
        failureException = e;
        failureDescription = "getHTTPResponse Threw:" + StringUtils.stringifyException(e) + " for URL:"
                + getOriginalURL();
    }

    if (!failure) {
        // populate a conventional buffer object with content data ...

        try {
            // read data from nio buffer into byte array
            nioContentBuffer.read(data);
            // and reset source buffer .... (releasing memory )...
            nioContentBuffer.reset();
            // set byte buffer into buffer object ...
            contentBuffer.set(data);

        } catch (IOException e) {

            failure = true;
            failureReason = CrawlURL.FailureReason.IOException;
            failureException = e;
            failureDescription = "Unable to read Content Buffer from successfull Fetch for URL:"
                    + getOriginalURL();
        }
    }

    if (!failure) {
        // populate crawl url data
        _activeRequestHeaders = httpHeaders.toString();
        _activeRequestResultCode = (short) NIOHttpConnection.getHttpResponseCode(httpHeaders);
        ;
    }

    if (failure) {
        if (failureException != null) {
            if (Environment.detailLogEnabled())
                LOG.error(StringUtils.stringifyException(failureException));
        }
        fetchFailed(failureReason, failureDescription);
    } else {

        // call host ...
        _sourceList.fetchSucceeded(this, connection.getDownloadTime(), httpHeaders, contentBuffer);

        // Add to CrawlLog for both content gets and robots gets
        // create a crawl url object
        CrawlURL urlData = createCrawlURLObject(CrawlURL.CrawlResult.SUCCESS, contentBuffer);
        // set truncation flag if content truncation during download
        if (connection.isContentTruncated()) {
            urlData.setFlags(urlData.getFlags() | CrawlURL.Flags.TruncatedDuringDownload);
        }
        // and update segment progress logs ...
        getEngine().crawlComplete(connection, urlData, this, true);

        /*
         * if ((getFlags() & CrawlURL.Flags.IsRobotsURL) != 0) {
         * getEngine().logSuccessfulRobotsGET(connection, this); }
         */
    }
}

From source file:it.infn.ct.GridEngineInterface.java

/**
 * Setup machine IP address, needed by job submission.
 *///from   w w w . ja v a2s .  c om
private void getIP() {
    try {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        int i = 0;
        gedIPAddress = "" + (short) (ipAddr[i++] & FF_BITMASK) + ":" + (short) (ipAddr[i++] & FF_BITMASK) + ":"
                + (short) (ipAddr[i++] & FF_BITMASK) + ":" + (short) (ipAddr[i++] & FF_BITMASK);
    } catch (Exception e) {
        gedIPAddress = "";
        LOG.fatal("Unable to get the portal IP address");
    }
}