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

/**
 * Returns the country the IP address is in.
 *
 * @param ipAddress String version of an IP address, i.e. "127.0.0.1"
 * @return the country the IP address is from.
 *//*w w  w . j a va  2 s. c o m*/
public Country getCountry(String ipAddress) {
    InetAddress addr;
    try {
        addr = InetAddress.getByName(ipAddress);
    } catch (UnknownHostException e) {
        return UNKNOWN_COUNTRY;
    }
    return getCountry(bytesToLong(addr.getAddress()));
}

From source file:it.infn.mib.AndreaPortlet.java

/**
 * This method sends the job into the distributed infrastructure using
 * the GridEngine methods/* w w  w  .j a v  a2  s.  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 
        String outputPath = "/tmp/"; // Output Path
        String outputFile = "andrea-Output.txt"; // Distributed application standard output
        String errorFile = "andrea-Output.txt"; // Distrubuted application standard error
        String appFile = "andrea-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; // 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

        // Setup input files (InputSandbox) avoiding empty inputSandboxes
        if (null != inputSandbox && inputSandbox.length() > 0)
            miJobSubmission.setInputFiles(inputSandbox);
        // Setup the JDL requirements
        if (numRequirements > 0)
            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:org.opennms.ng.services.capsdconfig.CapsdConfigManager.java

/**
 * Utility method which compares two InetAddress objects based on the
 * provided method (MIN/MAX) and returns the InetAddress which is to be
 * considered the primary interface.//from   w w w  . j  a v a  2  s  .  co  m
 * <p/>
 * NOTE: In order for an interface to be considered primary, if strict is
 * true, it must be included by a Collectd package which supports the
 * specified service. This method will return null if the 'oldPrimary'
 * address is null and the 'currentIf' address does not pass the Collectd
 * package check, if strict is true..
 *
 * @param svcName    Service name
 * @param currentIf  Interface with which to compare the 'oldPrimary' address.
 * @param oldPrimary Primary interface to be compared against the 'currentIf'
 *                   address.
 * @param method     Comparison method to be used (either "min" or "max")
 * @param strict     require interface to be part of a Collectd package
 * @return InetAddress object of the primary interface based on the provided
 * method or null if neither address is eligible to be primary.
 */
private InetAddress compareAndSelectPrimaryCollectionInterface(String svcName, InetAddress currentIf,
        InetAddress oldPrimary, String method, boolean strict) {
    InetAddress newPrimary = null;
    CollectdConfigFactory factory = CollectdConfigFactory.getInstance();

    if (oldPrimary == null && strict) {
        if (factory.isServiceCollectionEnabled(InetAddressUtils.str(currentIf), svcName)) {
            return currentIf;
        } else {
            return oldPrimary;
        }
    }

    if (oldPrimary == null) {
        return currentIf;
    }

    int comparison = new ByteArrayComparator().compare(currentIf.getAddress(), oldPrimary.getAddress());

    if (method.equals(CollectdConfigFactory.SELECT_METHOD_MIN)) {
        // Smallest address wins
        if (comparison < 0) {
            /*
             * Replace the primary interface with the current
            * interface only if the current interface is managed!
             */
            if (strict) {
                if (factory.isServiceCollectionEnabled(InetAddressUtils.str(currentIf), svcName)) {
                    newPrimary = currentIf;
                }
            } else {
                newPrimary = currentIf;
            }
        }
    } else {
        // Largest address wins
        if (comparison > 0) {
            /*
             * Replace the primary interface with the current
            * interface only if the current interface is managed!
             */
            if (strict) {
                if (factory.isServiceCollectionEnabled(InetAddressUtils.str(currentIf), svcName)) {
                    newPrimary = currentIf;
                }
            } else {
                newPrimary = currentIf;
            }
        }
    }

    if (newPrimary != null) {
        return newPrimary;
    } else {
        return oldPrimary;
    }
}

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

@Override
public List<IaAddress> findUnusedIaAddresses(final InetAddress startAddr, final InetAddress endAddr) {
    long offerExpireMillis = DhcpServerPolicies.globalPolicyAsLong(Property.BINDING_MANAGER_OFFER_EXPIRATION);
    final long offerExpiration = new Date().getTime() - offerExpireMillis;
    List<DhcpLease> leases = getJdbcTemplate().query(
            "select * from dhcplease" + " where ((state=" + IaAddress.ADVERTISED + " and starttime <= ?)"
                    + " or (state=" + IaAddress.EXPIRED + " or state=" + IaAddress.RELEASED + "))"
                    + " and ipaddress >= ? and ipaddress <= ?" + " order by state, validendtime, ipaddress",
            new PreparedStatementSetter() {
                @Override/*from  ww  w. ja v  a  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 toIaAddresses(leases);
}

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

/**
 * This method sends the job into the distributed infrastructure using the
 * GridEngine methods/*w  ww.  ja v  a 2  s.  com*/
 *
 * @param appInput AppInput instance storing the jobSubmission data
 */
void submitJob(AppInput appInput) {

    ArrayList<GEJobDescription> descriptions = new ArrayList<GEJobDescription>();

    for (int i = 0; i < Integer.parseInt(appInput.taskNumber); i++) {
        GEJobDescription description = new GEJobDescription();
        switch (CollectionType.valueOf(appInput.collectionType)) {
        case JOB_COLLECTION:
        case WORKFLOW_N1:
            if (!appInput.executables.get(i).contains("/bin/")) {
                String tmp = "/bin/";
                tmp += appInput.executables.remove(i);
                appInput.executables.add(i, tmp);
            }
            description.setExecutable(appInput.executables.get(i));
            description.setInputFiles("");
            break;
        case JOB_PARAMETRIC:
            if (!appInput.executable.contains("/bin/")) {
                String tmp = "/bin/";
                tmp += appInput.executable;
                appInput.executable = tmp;
            }
            description.setExecutable(appInput.executable);
            description.setInputFiles(appServerPath + "WEB-INF/job/pilot_script.sh");
            break;
        }

        description.setArguments(appInput.arguments.get(i));

        description.setOutputPath("/tmp");

        description.setOutput("myOutput-" + i + ".txt");

        description.setError("myError-" + i + ".txt");

        descriptions.add(description);
    }

    // GridEngine' JobCollectionSubmission job submission object
    JobCollectionSubmission tmpJobCollectionSubmission = null;

    JobCollection collection = null;

    switch (CollectionType.valueOf(appInput.collectionType)) {
    case JOB_COLLECTION:
        collection = new JobCollection(appInput.username, appInput.jobIdentifier, "/tmp", descriptions);
        break;
    case WORKFLOW_N1:
        GEJobDescription finalJobDescription = new GEJobDescription();

        if (!appInput.finalJobExecutable.contains("/bin/")) {
            appInput.finalJobExecutable = "/bin/" + appInput.finalJobExecutable;
        }

        finalJobDescription.setExecutable(appInput.finalJobExecutable);
        finalJobDescription.setArguments(appInput.finalJobArgument);

        String tmp = "";
        for (int i = 0; i < descriptions.size(); i++) {
            if (tmp.equals("")) {
                tmp = descriptions.get(i).getOutput();
            } else {
                tmp += "," + descriptions.get(i).getOutput();
            }
        }

        finalJobDescription.setInputFiles(tmp);
        finalJobDescription.setOutputPath("/tmp");
        finalJobDescription.setOutput("myOutput-FinalJob.txt");
        finalJobDescription.setError("myError-FinalJob.txt");

        collection = new WorkflowN1(appInput.username, appInput.jobIdentifier, "/tmp", descriptions,
                finalJobDescription);
        break;
    case JOB_PARAMETRIC:
        collection = new JobParametric(appInput.username, appInput.jobIdentifier, "/tmp", descriptions,
                appInput.executable);
        break;
    }

    //
    // Initialize the GridEngine Multi Infrastructure Job Submission object
    //
    //  GridEngine uses two different kind of constructors. The constructor
    //  taking void type as argument 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:
    //      sciGwyUserTrackingDB_Hostname
    //      sciGwyUserTrackingDB_Username
    //      sciGwyUserTrackingDB_Password
    //      sciGwyUserTrackingDB_Database
    //
    if (null != appPreferences.getSciGwyUserTrackingDB_Hostname()
            && !appPreferences.getSciGwyUserTrackingDB_Hostname().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Username()
            && !appPreferences.getSciGwyUserTrackingDB_Username().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Password()
            && !appPreferences.getSciGwyUserTrackingDB_Password().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Database()
            && !appPreferences.getSciGwyUserTrackingDB_Database().equals("")) {
        String arg1 = "jdbc:mysql://" + appPreferences.getSciGwyUserTrackingDB_Hostname() + "/"
                + appPreferences.getSciGwyUserTrackingDB_Database();
        String arg2 = appPreferences.getSciGwyUserTrackingDB_Username();
        String arg3 = appPreferences.getSciGwyUserTrackingDB_Password();
        _log.info("JobCollectionSubmission [DEVEL]\n" + LS + "    Arg1: '" + arg1 + "'" + LS + "    Arg2: '"
                + arg2 + "'" + LS + "    Arg3: '" + arg3 + "'");
        tmpJobCollectionSubmission = new JobCollectionSubmission(arg1, arg2, arg3, collection);
    } else {
        tmpJobCollectionSubmission = new JobCollectionSubmission(collection);
        _log.info("JobCollectionSubmission [PROD]");
    }

    // Assigns all enabled infrastructures
    InfrastructureInfo[] infrastructuresInfo = appPreferences.getEnabledInfrastructures();

    // 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");
        }

        // Submit Collection
        tmpJobCollectionSubmission.submitJobCollection(infrastructuresInfo, portalIPAddress, applicationId);

        // Show log
        // View jobSubmission details in the log
        _log.info(LS + "Job Collection Sent" + LS + "-------" + LS + "Portal address: '" + portalIPAddress + "'"
                + 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:org.opennms.netmgt.config.DiscoveryConfigFactory.java

@Override
public String getForeignSource(InetAddress address) {
    getReadLock().lock();//  w  ww  .  ja v a2  s  .co  m
    try {
        LOG.debug("Looking for matching foreign source specific IP or IP range with address: {}...", address);

        List<Specific> specificCollection = getConfiguration().getSpecificCollection();
        for (Specific specific : specificCollection) {
            String ipAddr = specific.getContent();

            if (ipAddr.equals(InetAddressUtils.str(address))) {

                String foreignSource = specific.getForeignSource();
                LOG.debug("Matched foreign source {} matching address: {} against specific {}.", foreignSource,
                        address, ipAddr);
                return foreignSource;
            }
        }

        final byte[] laddr = address.getAddress();

        List<IncludeRange> includeRangeCollection = getConfiguration().getIncludeRangeCollection();
        for (IncludeRange range : includeRangeCollection) {

            if (InetAddressUtils.isInetAddressInRange(laddr, range.getBegin(), range.getEnd())) {

                String foreignSource = range.getForeignSource();
                LOG.debug("Found foreign source {} with address {} in the range begin: {} and end: {}.",
                        foreignSource, address, range.getBegin(), range.getEnd());
                return foreignSource;
            }
        }

        List<IncludeUrl> includeUrlCollection = getConfiguration().getIncludeUrlCollection();
        for (IncludeUrl includeUrl : includeUrlCollection) {
            String ipAddr = includeUrl.getContent();
            if (ipAddr.equals(InetAddressUtils.str(address))) {

                String foreignSource = includeUrl.getForeignSource();
                LOG.debug("Matched foreign source {} matching address: {} in specified URL.", foreignSource,
                        address);
                return foreignSource;
            }
        }

        return getConfiguration().getForeignSource();
    } finally {
        getReadLock().unlock();
    }
}

From source file:com.eleybourn.bookcatalogue.utils.Utils.java

/**
 * Check if phone can connect to a specific host.
 * Does not work....//from  ww  w  .  ja va 2  s  .  c o  m
 * 
 * ENHANCE: Find a way to make network host checks possible
 * 
 * @return
 */
/*
public static boolean hostIsAvailable(Context ctx, String host) {
   if (!isOnline(ctx))
 return false;
   int addr;
   try {
 addr = lookupHost(host);         
   } catch (Exception e) {
 return false;
   }
    ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
  return cm.requestRouteToHost(ConnectivityManager., addr);          
   } catch (Exception e) {
 return false;
   }
}
*/

public static int lookupHost(String hostname) {
    InetAddress inetAddress;
    try {
        inetAddress = InetAddress.getByName(hostname);
    } catch (UnknownHostException e) {
        return -1;
    }
    byte[] addrBytes;
    int addr;
    addrBytes = inetAddress.getAddress();
    addr = ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8)
            | (addrBytes[0] & 0xff);
    return addr;
}

From source file:com.chiralBehaviors.autoconfigure.AutoConfigure.java

/**
 * @return the host address to bind this service to
 *//*from   w  w w.j  av a  2  s  .  co m*/
protected InetAddress determineHostAddress() {
    NetworkInterface iface = determineNetworkInterface();
    InetAddress raw = null;
    for (Enumeration<InetAddress> interfaceAddresses = iface.getInetAddresses(); interfaceAddresses
            .hasMoreElements();) {
        if (!interfaceAddresses.hasMoreElements()) {
            String msg = String.format("Unable to find any network address for interface[%s] {%s}",
                    iface.getName(), iface.getDisplayName());
            logger.error(msg);
            throw new IllegalStateException(msg);
        }
        raw = interfaceAddresses.nextElement();
        if (config.ipV6) {
            if (raw.getAddress().length == 6) {
                break;
            }
        } else if (raw.getAddress().length == 4) {
            break;
        }
    }
    if (raw == null) {
        String msg = String.format("Unable to find any network address for interface[%s] {%s}", iface.getName(),
                iface.getDisplayName());
        logger.error(msg);
        throw new IllegalStateException(msg);
    }
    InetAddress address;
    try {
        address = InetAddress.getByName(raw.getCanonicalHostName());
    } catch (UnknownHostException e) {
        String msg = String.format("Unable to resolve network address [%s] for interface[%s] {%s}", raw,
                iface.getName(), iface.getDisplayName());
        logger.error(msg, e);
        throw new IllegalStateException(msg, e);
    }
    return address;
}

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

/**
 * -- WARNING -------------------------------------------------------
 * (DEPRECATED) This method will be left only for some future commits
 * ------------------------------------------------------------------
 * This method sends the job into the distributed infrastructure using
 * the GridEngine methods//from  ww  w  .  j  a va2 s  .  c  o  m
 *
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void __submitJob(AppInput appInput) {
    // 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 void type as argument 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:
    //      sciGwyUserTrackingDB_Hostname
    //      sciGwyUserTrackingDB_Username
    //      sciGwyUserTrackingDB_Password
    //      sciGwyUserTrackingDB_Database
    //
    if (null != appPreferences.getSciGwyUserTrackingDB_Hostname()
            && !appPreferences.getSciGwyUserTrackingDB_Hostname().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Username()
            && !appPreferences.getSciGwyUserTrackingDB_Username().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Password()
            && !appPreferences.getSciGwyUserTrackingDB_Password().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Database()
            && !appPreferences.getSciGwyUserTrackingDB_Database().equals("")) {
        String arg1 = "jdbc:mysql://" + appPreferences.getSciGwyUserTrackingDB_Hostname() + "/"
                + appPreferences.getSciGwyUserTrackingDB_Database();
        String arg2 = appPreferences.getSciGwyUserTrackingDB_Username();
        String arg3 = appPreferences.getSciGwyUserTrackingDB_Password();
        miJobSubmission = new MultiInfrastructureJobSubmission(arg1, arg2, arg3);
        _log.info("MultiInfrastructureJobSubmission [DEVEL]\n" + LS + "    Arg1: '" + arg1 + "'" + LS
                + "    Arg2: '" + arg2 + "'" + LS + "    Arg3: '" + arg3 + "'");
    } else {
        miJobSubmission = new MultiInfrastructureJobSubmission();
        _log.info("MultiInfrastructureJobSubmission [PROD]");
    }

    // 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 = "" + (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");
        }

        // 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"; // Distrubuted 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.inputSandbox_inputFile // input file
        ;
        // 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:it.infn.ct.mi_hostname_portlet.java

/**
 * -- WARNING -------------------------------------------------------
 * (DEPRECATED) This method will be left only for some future commits
 * ------------------------------------------------------------------
 * This method sends the job into the distributed infrastructure using
 * the GridEngine methods/*  w w w.  java  2 s  .co m*/
 *
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void __submitJob(AppInput appInput) {
    // 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 void type as argument 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:
    //      sciGwyUserTrackingDB_Hostname
    //      sciGwyUserTrackingDB_Username
    //      sciGwyUserTrackingDB_Password
    //      sciGwyUserTrackingDB_Database
    //
    if (null != appPreferences.getSciGwyUserTrackingDB_Hostname()
            && !appPreferences.getSciGwyUserTrackingDB_Hostname().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Username()
            && !appPreferences.getSciGwyUserTrackingDB_Username().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Password()
            && !appPreferences.getSciGwyUserTrackingDB_Password().equals("")
            && null != appPreferences.getSciGwyUserTrackingDB_Database()
            && !appPreferences.getSciGwyUserTrackingDB_Database().equals("")) {
        String arg1 = "jdbc:mysql://" + appPreferences.getSciGwyUserTrackingDB_Hostname() + "/"
                + appPreferences.getSciGwyUserTrackingDB_Database();
        String arg2 = appPreferences.getSciGwyUserTrackingDB_Username();
        String arg3 = appPreferences.getSciGwyUserTrackingDB_Password();
        miJobSubmission = new MultiInfrastructureJobSubmission(arg1, arg2, arg3);
        _log.info("MultiInfrastructureJobSubmission [DEVEL]\n" + LS + "    Arg1: '" + arg1 + "'" + LS
                + "    Arg2: '" + arg2 + "'" + LS + "    Arg3: '" + arg3 + "'");
    } else {
        miJobSubmission = new MultiInfrastructureJobSubmission();
        _log.info("MultiInfrastructureJobSubmission [PROD]");
    }

    // 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 = "" + (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");
        }

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