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.maxmind.geoip.LookupService.java

public Location getLocation(InetAddress addr) {
    return getLocation(bytesToLong(addr.getAddress()));
}

From source file:com.maxmind.geoip.LookupService.java

/**
 * Returns the country the IP address is in.
 *
 * @param ipAddress the IP address.//w w w. j  a  v  a2  s  .  c  om
 * @return the country the IP address is from.
 */
public synchronized Country getCountry(InetAddress ipAddress) {
    return getCountry(bytesToLong(ipAddress.getAddress()));
}

From source file:org.apache.cassandra.service.StorageProxy.java

/**
 * for each datacenter, send a message to one node to relay the write to other replicas
 *//*from  w w  w  .  j  a v  a  2 s  .  co  m*/
private static void sendMessages(String localDataCenter, Map<String, Multimap<Message, InetAddress>> dcMessages,
        IWriteResponseHandler handler) throws IOException {
    for (Map.Entry<String, Multimap<Message, InetAddress>> entry : dcMessages.entrySet()) {
        String dataCenter = entry.getKey();

        // send the messages corresponding to this datacenter
        for (Map.Entry<Message, Collection<InetAddress>> messages : entry.getValue().asMap().entrySet()) {
            Message message = messages.getKey();
            // a single message object is used for unhinted writes, so clean out any forwards
            // from previous loop iterations
            message.removeHeader(RowMutation.FORWARD_HEADER);

            if (dataCenter.equals(localDataCenter) || StorageService.instance.useEfficientCrossDCWrites()) {
                // direct writes to local DC or old Cassadra versions
                for (InetAddress destination : messages.getValue())
                    MessagingService.instance().sendRR(message, destination, handler);
            } else {
                // Non-local DC. First endpoint in list is the destination for this group
                Iterator<InetAddress> iter = messages.getValue().iterator();
                InetAddress target = iter.next();
                // Add all the other destinations of the same message as a header in the primary message.
                while (iter.hasNext()) {
                    InetAddress destination = iter.next();
                    // group all nodes in this DC as forward headers on the primary message
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    DataOutputStream dos = new DataOutputStream(bos);

                    // append to older addresses
                    byte[] previousHints = message.getHeader(RowMutation.FORWARD_HEADER);
                    if (previousHints != null)
                        dos.write(previousHints);

                    dos.write(destination.getAddress());
                    message.setHeader(RowMutation.FORWARD_HEADER, bos.toByteArray());
                }
                // send the combined message + forward headers
                MessagingService.instance().sendRR(message, target, handler);
            }
        }
    }
}

From source file:com.maxmind.geoip.LookupService.java

/**
 * Finds the country index value given an IPv6 address.
 *
 * @param addr the ip address to find in long format.
 * @return the country index.//from   w  w  w.  ja va 2  s .  com
 */
private synchronized int seekCountryV6(InetAddress addr) {
    byte[] v6vec = addr.getAddress();
    byte[] buf = new byte[2 * MAX_RECORD_LENGTH];
    int[] x = new int[2];
    int offset = 0;
    _check_mtime();
    for (int depth = 127; depth >= 0; depth--) {
        if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
            //read from memory
            for (int i = 0; i < 2 * MAX_RECORD_LENGTH; i++) {
                buf[i] = dbbuffer[(2 * recordLength * offset) + i];
            }
        } else if ((dboptions & GEOIP_INDEX_CACHE) != 0) {
            //read from index cache
            for (int i = 0; i < 2 * MAX_RECORD_LENGTH; i++) {
                buf[i] = index_cache[(2 * recordLength * offset) + i];
            }
        } else {
            //read from disk 
            try {
                file.seek(2 * recordLength * offset);
                file.readFully(buf);
            } catch (IOException e) {
                System.out.println("IO Exception");
            }
        }
        for (int i = 0; i < 2; i++) {
            x[i] = 0;
            for (int j = 0; j < recordLength; j++) {
                int y = buf[i * recordLength + j];
                if (y < 0) {
                    y += 256;
                }
                x[i] += (y << (j * 8));
            }
        }

        int bnum = 127 - depth;
        int idx = bnum >> 3;
        int b_mask = 1 << (bnum & 7 ^ 7);
        if ((v6vec[idx] & b_mask) > 0) {
            if (x[1] >= databaseSegments[0]) {
                last_netmask = 128 - depth;
                return x[1];
            }
            offset = x[1];
        } else {
            if (x[0] >= databaseSegments[0]) {
                last_netmask = 128 - depth;
                return x[0];
            }
            offset = x[0];
        }
    }

    // shouldn't reach here
    System.err.println("Error seeking country while seeking " + addr.getHostAddress());
    return 0;
}

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

@Override
public List<IaPrefix> findUnusedIaPrefixes(final InetAddress startAddr, final InetAddress endAddr) {
    final long offerExpiration = new Date().getTime() - 12000; // 2 min = 120 sec = 12000 ms
    List<DhcpLease> leases = getJdbcTemplate().query(
            "select * from dhcplease" + " where ((state=" + IaPrefix.ADVERTISED + " and starttime <= ?)"
                    + " or (state=" + IaPrefix.EXPIRED + " or state=" + IaPrefix.RELEASED + "))"
                    + " and ipaddress >= ? and ipaddress <= ?" + " order by state, validendtime, ipaddress",
            new PreparedStatementSetter() {
                @Override// w w  w  . j a va  2 s  .c o  m
                public void setValues(PreparedStatement ps) throws SQLException {
                    java.sql.Timestamp ts = new java.sql.Timestamp(offerExpiration);
                    ps.setTimestamp(1, ts);
                    ps.setBytes(2, startAddr.getAddress());
                    ps.setBytes(3, endAddr.getAddress());
                }
            }, new DhcpLeaseRowMapper());
    return toIaPrefixes(leases);
}

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

/**
 * This method sends the job into the distributed infrastructure using
 * the GridEngine methods//  w  w  w.j a  va 2s.c  o m
 * 
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void submitJob(AppInput appInput) {
    //
    // Initialize the GridEngine Multi Infrastructure Job Submission object
    //
    MultiInfrastructureJobSubmission miJobSubmission = new MultiInfrastructureJobSubmission();

    // Assigns all enabled infrastructures
    InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures();
    for (int i = 0; i < infrastructuresInfo.length; i++) {
        _log.info("Adding infrastructure #" + (i + 1) + " - Name: '" + infrastructuresInfo[i].getName() + "'"
                + LS);
        miJobSubmission.addInfrastructure(infrastructuresInfo[i]);
    }

    // Check the enabled infrastructures
    if (infrastructuresInfo.length > 0) {
        // 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 = "" + ipAddr[0] + ":" + ipAddr[1] + ":" + ipAddr[2] + ":" + ipAddr[3];
        } catch (Exception e) {
            _log.error("Unable to get the portal IP address");
        }

        // Job details
        String executable = "/bin/sh"; // Application executable
        String arguments = appPreferences.getPilotScript(); // executable' arguments 
        String outputPath = "/tmp/"; // Output Path
        String outputFile = "g-hmmer-Output.txt"; // Distributed application standard output
        String errorFile = "g-hmmer-Error.txt"; // Distrubuted application standard error
        String appFile = "g-hmmer-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.inputSandbox_inputFile // input file
                       ;  
                */

        String inputSandbox = appServerPath + "/WEB-INF/job/pilot_script.sh ," + appServerPath
                + "/WEB-INF/job/hmmer-2.3.2.tar.gz ," + appServerPath + "/WEB-INF/job/secuencia.fasta ,"
                + appServerPath + "/WEB-INF/job/secuenciah.hmm";

        // 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
        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

        // Other job initialization settings
        miJobSubmission.setExecutable(executable); // Specify the executeable
        miJobSubmission.setArguments(arguments); // Specify the application' arguments
        miJobSubmission.setOutputPath(outputPath); // Specify the output directory 
        miJobSubmission.setOutputFiles(outputSandbox); // Setup output files (OutputSandbox)
        miJobSubmission.setJobOutput(outputFile); // Specify the std-outputr file
        miJobSubmission.setJobError(errorFile); // Specify the std-error file
        if (null != inputSandbox // Setup input files (InputSandbox) avoiding empty inputSandboxes
                && inputSandbox.length() > 0)
            miJobSubmission.setInputFiles(inputSandbox);
        if (numRequirements > 0) // Setup the JDL requirements
            miJobSubmission.setJDLRequirements(jdlRequirements);

        // Submit Job
        miJobSubmission.submitJobAsync(appInput.username, portalIPAddress, applicationId,
                appInput.jobIdentifier);

        // 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        

    } // numInfra > 0
    else {
        _log.warn(LS + "There are no enough enabled infrastructures!" + LS + "It is impossible to send any job"
                + LS + "Configure the application preferences in order to setup" + LS
                + "or enable at least one infrastructure." + LS);
    } // numInfra == 0                    
}

From source file:hudson.plugins.dimensionsscm.DimensionsSCM.java

@Override
public boolean checkout(final AbstractBuild build, final Launcher launcher, final FilePath workspace,
        final BuildListener listener, final File changelogFile) throws IOException, InterruptedException {
    boolean bRet = false;

    if (!isCanJobUpdate()) {
        Logger.Debug("Skipping checkout - " + this.getClass().getName());
    }/* w w  w  .  j ava  2s.c  o  m*/

    Logger.Debug("Invoking checkout - " + this.getClass().getName());

    try {
        // Load other Dimensions plugins if set
        DimensionsBuildWrapper.DescriptorImpl bwplugin = (DimensionsBuildWrapper.DescriptorImpl) Hudson
                .getInstance().getDescriptor(DimensionsBuildWrapper.class);
        DimensionsBuildNotifier.DescriptorImpl bnplugin = (DimensionsBuildNotifier.DescriptorImpl) Hudson
                .getInstance().getDescriptor(DimensionsBuildNotifier.class);

        if (DimensionsChecker.isValidPluginCombination(build, listener)) {
            Logger.Debug("Plugins are ok");
        } else {
            listener.fatalError("\n[DIMENSIONS] The plugin combinations you have selected are not valid.");
            listener.fatalError("\n[DIMENSIONS] Please review online help to determine valid plugin uses.");
            return false;
        }

        if (isCanJobUpdate()) {
            int version = 2009;
            long key = dmSCM.login(getJobUserName(), getJobPasswd(), getJobDatabase(), getJobServer());

            if (key > 0) {
                // Get the server version
                Logger.Debug("Login worked.");
                version = dmSCM.getDmVersion();
                if (version == 0) {
                    version = 2009;
                }
                dmSCM.logout(key);
            }

            // Get the details of the master
            InetAddress netAddr = InetAddress.getLocalHost();
            byte[] ipAddr = netAddr.getAddress();
            String hostname = netAddr.getHostName();

            boolean master = false;
            GetHostDetailsTask buildHost = new GetHostDetailsTask(hostname);
            master = workspace.act(buildHost);

            if (master) {
                // Running on master...
                listener.getLogger().println("[DIMENSIONS] Running checkout on master...");
                listener.getLogger().flush();

                // Using Java API because this allows the plugin to work on platforms
                // where Dimensions has not been ported, e.g. MAC OS, which is what
                // I use
                CheckOutAPITask task = new CheckOutAPITask(build, this, workspace, listener, version);
                bRet = workspace.act(task);
            } else {
                // Running on slave... Have to use the command line as Java API will not
                // work on remote hosts. Cannot serialise it...

                {
                    // VariableResolver does not appear to be serialisable either, so...
                    VariableResolver<String> myResolver = build.getBuildVariableResolver();

                    String baseline = myResolver.resolve("DM_BASELINE");
                    String requests = myResolver.resolve("DM_REQUEST");

                    listener.getLogger().println("[DIMENSIONS] Running checkout on slave...");
                    listener.getLogger().flush();

                    CheckOutCmdTask task = new CheckOutCmdTask(getJobUserName(), getJobPasswd(),
                            getJobDatabase(), getJobServer(), getProject(), baseline, requests,
                            isCanJobDelete(), isCanJobRevert(), isCanJobForce(), isCanJobExpand(),
                            isCanJobNoMetadata(), (build.getPreviousBuild() == null), getFolders(), version,
                            permissions, workspace, listener);
                    bRet = workspace.act(task);
                }
            }
        } else {
            bRet = true;
        }

        if (bRet) {
            bRet = generateChangeSet(build, listener, changelogFile);
        }
    } catch (Exception e) {
        String errMsg = e.getMessage();
        if (errMsg == null) {
            errMsg = "An unknown error occurred. Please try the operation again.";
        }
        listener.fatalError("Unable to run checkout callout - " + errMsg);
        // e.printStackTrace();
        //throw new IOException("Unable to run checkout callout - " + e.getMessage());
        bRet = false;
    }
    return bRet;
}

From source file:com.maxmind.geoip.LookupService.java

public int getID(String ipAddress) {
    InetAddress addr;
    try {/*  w  ww  .j  ava 2s .com*/
        addr = InetAddress.getByName(ipAddress);
    } catch (UnknownHostException e) {
        return 0;
    }
    return getID(bytesToLong(addr.getAddress()));
}

From source file:com.maxmind.geoip.LookupService.java

public synchronized Region getRegion(String str) {
    InetAddress addr;
    try {//from   w  ww  .  ja v a2s .  c o m
        addr = InetAddress.getByName(str);
    } catch (UnknownHostException e) {
        return null;
    }

    return getRegion(bytesToLong(addr.getAddress()));
}

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

/**
 * This method sends the job into the distributed infrastructure using
 * the GridEngine methods//from  ww w .  ja v a 2s . co  m
 * 
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void submitJob(AppInput appInput) {
    //
    // Initialize the GridEngine Multi Infrastructure Job Submission object
    //
    MultiInfrastructureJobSubmission miJobSubmission = new MultiInfrastructureJobSubmission();

    // Assigns all enabled infrastructures
    InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures();
    for (int i = 0; i < infrastructuresInfo.length; i++) {
        _log.info("Adding infrastructure #" + (i + 1) + " - Name: '" + infrastructuresInfo[i].getName() + "'"
                + LS);
        miJobSubmission.addInfrastructure(infrastructuresInfo[i]);
    }

    // Check the enabled infrastructures
    if (infrastructuresInfo.length > 0) {
        // 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 = "" + ipAddr[0] + ":" + ipAddr[1] + ":" + ipAddr[2] + ":" + ipAddr[3];
        } catch (Exception e) {
            _log.error("Unable to get the portal IP address");
        }

        // Job details
        String executable = "/bin/sh"; // Application executable
        String arguments = appPreferences.getPilotScript() // executable' arguments: pilot_script.sh
                + " '" + appInput.jobIdentifier + "'" // User job description
                + " '" + appInput.username + "'" // User name
        ;
        String outputPath = "/tmp/"; // Output Path
        String outputFile = ".octave-Output.txt"; // Distributed application standard output
        String errorFile = ".octave-Error.txt"; // Distrubuted application standard error
        String appFile = "octave-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.inputSandbox_inputFile // input file
        ;
        // OutputSandbox (string with comma separated list of file names)
        String outputSandbox = appFile + ",README.txt"; // Output file

        // Take care of job requirements
        // More requirements can be specified in the preference value 'jobRequirements'
        // separating each requirement by the ';' character
        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

        // Other job initialization settings
        miJobSubmission.setExecutable(executable); // Specify the executeable
        miJobSubmission.setArguments(arguments); // Specify the application' arguments
        miJobSubmission.setOutputPath(outputPath); // Specify the output directory 
        miJobSubmission.setOutputFiles(outputSandbox); // Setup output files (OutputSandbox)
        miJobSubmission.setJobOutput(outputFile); // Specify the std-outputr file
        miJobSubmission.setJobError(errorFile); // Specify the std-error file
        if (null != inputSandbox // Setup input files (InputSandbox) avoiding empty inputSandboxes
                && inputSandbox.length() > 0)
            miJobSubmission.setInputFiles(inputSandbox);
        if (numRequirements > 0) // Setup the JDL requirements
            miJobSubmission.setJDLRequirements(jdlRequirements);

        // Submit Job
        miJobSubmission.submitJobAsync(appInput.username, portalIPAddress, applicationId,
                appInput.jobIdentifier);

        // 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        

    } // numInfra > 0
    else {
        _log.warn(LS + "There are no enough enabled infrastructures!" + LS + "It is impossible to send any job"
                + LS + "Configure the application preferences in order to setup" + LS
                + "or enable at least one infrastructure." + LS);
    } // numInfra == 0                    
}