Example usage for java.net UnknownHostException getMessage

List of usage examples for java.net UnknownHostException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:Default.YTDownloadThread.java

public boolean downloadOne(String url) throws IOException {

    boolean rc = false;
    boolean rc204 = false;
    boolean rc302 = false;

    this.recursionCount++;

    // stop recursion
    try {//from  ww w .j  ava  2s.  co  m
        if (url.equals("")) {
            return (false);
        }
    } catch (NullPointerException npe) {
        return (false);
    }
    //      if (JFCMainClient.getQuitRequested()) {
    //         return(false); // try to get information about application shutdown
    //      }

    outputDebugMessage("start.");

    // TODO GUI option for proxy?
    // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube
    // using local squid to save download time for tests

    try {

        this.request = new HttpGet(url);
        this.request.setConfig(this.config);
        this.httpClient = HttpClients.createDefault();

    } catch (Exception e) {
        outputDebugMessage(e.getMessage());
    }
    outputDebugMessage("executing request: ".concat(this.request.getRequestLine().toString()));
    outputDebugMessage("uri: ".concat(this.request.getURI().toString()));
    outputDebugMessage("using proxy: ".concat(this.getProxy()));

    try {
        this.response = this.httpClient.execute(this.request);
    } catch (ClientProtocolException cpe) {
        outputDebugMessage(cpe.getMessage());
    } catch (UnknownHostException uhe) {
        output(("error connecting to: ").concat(uhe.getMessage()));
        outputDebugMessage(uhe.getMessage());
    } catch (IOException ioe) {
        outputDebugMessage(ioe.getMessage());
    } catch (IllegalStateException ise) {
        outputDebugMessage(ise.getMessage());
    }

    try {
        outputDebugMessage("HTTP response status line:".concat(this.response.getStatusLine().toString()));

        // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL?
        if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)"))
                & !(rc204 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)204(.*)"))
                & !(rc302 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)302(.*)"))) {
            outputDebugMessage(this.response.getStatusLine().toString().concat(" ").concat(url));
            output(this.response.getStatusLine().toString().concat(" \"").concat(this.title).concat("\""));
            return (rc & rc204 & rc302);
        }
        if (rc204) {
            rc = downloadOne(this.nextVideoUrl.get(0).getUrl());
            return (rc);
        }
        if (rc302) {
            outputDebugMessage(
                    "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString()));
        }

    } catch (NullPointerException npe) {
        // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because
        // response.getStatusLine() == null
        this.videoUrl = null;
    }

    HttpEntity entity = null;
    try {
        entity = this.response.getEntity();
    } catch (NullPointerException npe) {
        //TODO catch must not be empty
    }

    // try to read HTTP response body
    if (entity != null) {
        try {
            if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase()
                    .matches("^text/html(.*)")) {
                this.textReader = new BufferedReader(new InputStreamReader(entity.getContent()));
            } else {
                this.binaryReader = new BufferedInputStream(entity.getContent());
            }
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            // test if we got a webpage
            this.contentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase();
            if (this.contentType.matches("^text/html(.*)")) {
                rc = saveTextData();
                // test if we got the binary content
            } else if (this.contentType.matches("(audio|video)/(.*)|application/octet-stream")) {

                // add audio stream URL if necessary
                if (this.recursionCount == 1) {
                    outputDebugMessage(("last response code==true - download: ")
                            .concat(this.nextVideoUrl.get(0).getYoutubeId()));
                    if (this.nextVideoUrl.get(0).getAudioStreamUrl().equals("")) {
                        outputDebugMessage("download audio stream? no");
                    } else {
                        // FIXME audio stream has no filename if we add the direct URL to the GUI url list - we should add YTURL objects, not Strings!
                        outputDebugMessage("download audio stream? yes - "
                                .concat(this.nextVideoUrl.get(0).getAudioStreamUrl()));
                        this.youtubeUrl.setTitle(this.getTitle());
                        //JFCMainClient.addYoutubeUrlToList(this.nextVideoUrl.get(0).getAudioStreamUrl(),this.getTitle(),"AUDIO");
                    }
                }
                //                  if (JFCMainClient.getNoDownload())
                //                    reportHeaderInfo();
                //                  else
                saveBinaryData();
            } else { // content-type is not video/
                rc = false;
                this.videoUrl = null;
            }
        } catch (IOException ex) {
            try {
                throw ex;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (RuntimeException ex) {
            try {
                throw ex;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } //if (entity != null)

    this.httpClient.close();

    outputDebugMessage("done: ".concat(url));
    if (this.videoUrl == null) {
        this.videoUrl = ""; // to prevent NPE
    }
    if (this.videoUrl.matches(URL_REGEX)) {
        // enter recursion - download video resource
        outputDebugMessage("try to download video from URL: ".concat(this.videoUrl));
        rc = downloadOne(this.videoUrl);
    } else {
        // no more recursion - html source hase been read
        // rc==false if video could not downloaded because of some error (like wrong protocol or country restriction)
        if (!rc) {
            outputDebugMessage("cannot download video - URL does not seem to be valid or could not be found: "
                    .concat(this.url));
            output("there was a problem getting the video URL! perhaps not allowed in your country?!");
            output(("consider reporting the URL to author! - ").concat(this.url));
            this.videoUrl = null;
        }
    }

    this.videoUrl = null;

    return (rc);
}

From source file:org.mule.module.mongo.MongoCloudConnector.java

/**
 * Method invoked when a {@link MongoSession} needs to be created.
 * // w  w w . ja  va2s  .co m
 * @param username the username to use for authentication. NOTE: Please use a dummy user if you
 *            have disabled Mongo authentication
 * @param password the password to use for authentication. NOTE: Please use a dummy password if
 *            you have disabled Mongo authentication
 * @param database Name of the database
 * @return the newly created {@link MongoSession}
 * @throws org.mule.api.ConnectionException
 */
@Connect
public void connect(@ConnectionKey final String username, @Password final String password,
        @Optional @Default("test") final String database) throws ConnectionException {
    DB db = null;
    try {
        final MongoOptions options = new MongoOptions();

        if (connectionsPerHost != null) {
            options.connectionsPerHost = connectionsPerHost;
        }
        if (threadsAllowedToBlockForConnectionMultiplier != null) {
            options.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
        }
        if (maxWaitTime != null) {
            options.maxWaitTime = maxWaitTime;
        }
        if (connectTimeout != null) {
            options.connectTimeout = connectTimeout;
        }
        if (socketTimeout != null) {
            options.socketTimeout = socketTimeout;
        }
        if (autoConnectRetry != null) {
            options.autoConnectRetry = autoConnectRetry;
        }
        if (slaveOk != null) {
            options.slaveOk = slaveOk;
        }
        if (safe != null) {
            options.safe = safe;
        }
        if (w != null) {
            options.w = w;
        }
        if (wtimeout != null) {
            options.wtimeout = wtimeout;
        }
        if (fsync != null) {
            options.fsync = fsync;
        }
        if (database != null) {
            this.database = database;
        }

        final String[] hosts = host.split(",\\s?");
        if (hosts.length == 1) {
            mongo = new Mongo(new ServerAddress(host, port), options);
        } else {
            final List<ServerAddress> servers = new ArrayList<ServerAddress>();
            for (final String host : hosts) {
                servers.add(new ServerAddress(host, port));
            }
            mongo = new Mongo(servers, options);
        }
        db = getDatabase(mongo, username, password, database);
    } catch (final MongoException me) {
        throw new ConnectionException(ConnectionExceptionCode.UNKNOWN, null, me.getMessage());
    } catch (final UnknownHostException e) {
        throw new ConnectionException(ConnectionExceptionCode.UNKNOWN_HOST, null, e.getMessage());
    }
    this.client = new MongoClientImpl(db);
}

From source file:org.rhq.storage.installer.StorageInstaller.java

private InstallerInfo upgrade(File upgradeFromDir) throws StorageInstallerException {
    DeploymentOptionsFactory factory = new DeploymentOptionsFactory();
    DeploymentOptions deploymentOptions = factory.newDeploymentOptions();
    InstallerInfo installerInfo = new InstallerInfo();

    File existingStorageDir = null;

    if (!upgradeFromDir.isDirectory()) {
        log.error("The value passed to the upgrade option is not a directory. The value must be a valid "
                + "path that points to the base directory of an existing RHQ server installation.");
        throw new StorageInstallerException(
                "The upgrade cannot proceed. The value passed to the upgrade option " + "is invalid.",
                STATUS_INVALID_UPGRADE);
    }/*from   w w w.j  a  v  a  2  s .com*/
    existingStorageDir = new File(upgradeFromDir, "rhq-storage");
    if (!(existingStorageDir.exists() && existingStorageDir.isDirectory())) {
        log.error(existingStorageDir + " does not appear to be an existing RHQ storage node installation. "
                + "Check the value that was passed to the upgrade option and make sure it specifies the base "
                + "directory of an existing RHQ server installation.");
        throw new StorageInstallerException("The upgrade cannot proceed. " + existingStorageDir + " is not an "
                + "existing RHQ storage node installation", STATUS_INVALID_UPGRADE);
    }

    try {
        File oldConfDir = new File(existingStorageDir, "conf");
        File oldYamlFile = new File(oldConfDir, "cassandra.yaml");
        File newConfDir = new File(storageBasedir, "conf");
        File newYamlFile = new File(newConfDir, "cassandra.yaml");
        File cassandraEnvFile = new File(oldConfDir, "cassandra-env.sh");
        File cassandraJvmPropsFile = new File(newConfDir, "cassandra-jvm.properties");

        installerInfo.basedir = storageBasedir;

        boolean isRHQ48Install;
        if (cassandraEnvFile.exists()) {
            isRHQ48Install = true;
            installerInfo.jmxPort = parseJmxPortFromCassandrEnv(cassandraEnvFile);
        } else {
            isRHQ48Install = false;
            installerInfo.jmxPort = parseJmxPort(new File(oldConfDir, "cassandra-jvm.properties"));
        }

        deploymentOptions.setBasedir(storageBasedir.getAbsolutePath());
        deploymentOptions.setLogFileName(installerInfo.logFile);
        deploymentOptions.setLoggingLevel("INFO");
        deploymentOptions.setJmxPort(installerInfo.jmxPort);
        deploymentOptions.setHeapSize(defaultHeapSize);
        deploymentOptions.setHeapNewSize(defaultHeapNewSize);

        deploymentOptions.load();

        Deployer deployer = new Deployer();
        deployer.setDeploymentOptions(deploymentOptions);
        storageBasedir.mkdirs();
        deployer.unzipDistro();
        deployer.applyConfigChanges();
        deployer.updateFilePerms();

        ConfigEditor oldYamlEditor = new ConfigEditor(oldYamlFile);
        oldYamlEditor.load();
        ConfigEditor newYamlEditor = new ConfigEditor(newYamlFile);
        newYamlEditor.load();

        installerInfo.hostname = oldYamlEditor.getListenAddress();
        newYamlEditor.setListenAddress(installerInfo.hostname);
        newYamlEditor.setRpcAddress(installerInfo.hostname);

        installerInfo.cqlPort = oldYamlEditor.getNativeTransportPort();
        newYamlEditor.setNativeTransportPort(installerInfo.cqlPort);

        installerInfo.gossipPort = oldYamlEditor.getStoragePort();
        newYamlEditor.setStoragePort(installerInfo.gossipPort);

        newYamlEditor.setCommitLogDirectory(oldYamlEditor.getCommitLogDirectory());
        newYamlEditor.setSavedCachesDirectory(oldYamlEditor.getSavedCachesDirectory());
        newYamlEditor.setDataFileDirectories(oldYamlEditor.getDataFileDirectories());
        newYamlEditor.setSeeds(installerInfo.hostname);

        newYamlEditor.save();

        if (isRHQ48Install) {
            Properties jvmProps = new Properties();
            jvmProps.load(new FileInputStream(cassandraJvmPropsFile));
            PropertiesFileUpdate propertiesUpdater = new PropertiesFileUpdate(
                    cassandraJvmPropsFile.getAbsolutePath());
            jvmProps.setProperty("jmx_port", Integer.toString(installerInfo.jmxPort));

            propertiesUpdater.update(jvmProps);

            deployer.updateStorageAuthConf(asSet(installerInfo.hostname));
        } else {
            File oldStorageAuthConfFile = new File(oldConfDir, "rhq-storage-auth.conf");
            File newStorageAuthConfFile = new File(newConfDir, "rhq-storage-auth.conf");
            StreamUtil.copy(new FileInputStream(oldStorageAuthConfFile),
                    new FileOutputStream(newStorageAuthConfFile));
        }

        return installerInfo;

    } catch (UnknownHostException unknownHostException) {
        throw new StorageInstallerException(
                "Failed to resolve requested binding address. Please check the installation instructions and host DNS settings"
                        + (isWindows() ? "." : " also make sure the hostname alias is set in /etc/hosts.")
                        + " Unknown host " + unknownHostException.getMessage(),
                unknownHostException, STATUS_UNKNOWN_HOST);
    } catch (IOException e) {
        throw new StorageInstallerError("The upgrade cannot proceed. An unexpected I/O error occurred", e,
                STATUS_IO_ERROR);
    } catch (DeploymentException e) {
        throw new StorageInstallerException(
                "THe upgrade cannot proceed. An error occurred during the storage " + "node deployment", e,
                STATUS_DEPLOYMENT_ERROR);
    }
}

From source file:org.opennms.netmgt.provision.service.vmware.VmwareRequisitionUrlConnection.java

/**
 * Creates a requisition node for the given managed entity and type.
 *
 * @param ipAddresses   the set of Ip addresses
 * @param managedEntity the managed entity
 * @return the generated requisition node
 *//*from  w w  w  .j  a v  a2s. c  o  m*/
private RequisitionNode createRequisitionNode(Set<String> ipAddresses, ManagedEntity managedEntity,
        int apiVersion, VmwareViJavaAccess vmwareViJavaAccess) {
    RequisitionNode requisitionNode = new RequisitionNode();

    // Setting the node label
    requisitionNode.setNodeLabel(managedEntity.getName());

    // Foreign Id consisting of managed entity Id
    requisitionNode.setForeignId(managedEntity.getMOR().getVal());

    /*
     * Original version:
     *
     * Foreign Id consisting of VMware management server's hostname and managed entity id
     *
     * requisitionNode.setForeignId(m_hostname + "/" + managedEntity.getMOR().getVal());
     */

    if (managedEntity instanceof VirtualMachine) {
        boolean firstInterface = true;

        // add all given interfaces
        for (String ipAddress : ipAddresses) {

            try {
                if ((m_persistIPv4 && InetAddressUtils.isIPv4Address(ipAddress))
                        || (m_persistIPv6 && InetAddressUtils.isIPv6Address(ipAddress))) {
                    InetAddress inetAddress = InetAddress.getByName(ipAddress);

                    if (!inetAddress.isLoopbackAddress()) {
                        RequisitionInterface requisitionInterface = new RequisitionInterface();
                        requisitionInterface.setIpAddr(ipAddress);

                        //  the first one will be primary
                        if (firstInterface) {
                            requisitionInterface.setSnmpPrimary(PrimaryType.PRIMARY);
                            for (String service : m_virtualMachineServices) {
                                requisitionInterface.insertMonitoredService(
                                        new RequisitionMonitoredService(service.trim()));
                            }
                            firstInterface = false;
                        } else {
                            requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY);
                        }

                        requisitionInterface.setManaged(Boolean.TRUE);
                        requisitionInterface.setStatus(Integer.valueOf(1));
                        requisitionNode.putInterface(requisitionInterface);
                    }
                }
            } catch (UnknownHostException unknownHostException) {
                logger.warn("Invalid IP address '{}'", unknownHostException.getMessage());
            }
        }
    } else {
        if (managedEntity instanceof HostSystem) {
            boolean reachableInterfaceFound = false, firstInterface = true;
            List<RequisitionInterface> requisitionInterfaceList = new ArrayList<RequisitionInterface>();
            RequisitionInterface primaryInterfaceCandidate = null;

            // add all given interfaces
            for (String ipAddress : ipAddresses) {

                try {
                    if ((m_persistIPv4 && InetAddressUtils.isIPv4Address(ipAddress))
                            || (m_persistIPv6 && InetAddressUtils.isIPv6Address(ipAddress))) {
                        InetAddress inetAddress = InetAddress.getByName(ipAddress);

                        if (!inetAddress.isLoopbackAddress()) {
                            RequisitionInterface requisitionInterface = new RequisitionInterface();
                            requisitionInterface.setIpAddr(ipAddress);

                            if (firstInterface) {
                                primaryInterfaceCandidate = requisitionInterface;
                                firstInterface = false;
                            }

                            if (!reachableInterfaceFound && reachableCimService(vmwareViJavaAccess,
                                    (HostSystem) managedEntity, ipAddress)) {
                                primaryInterfaceCandidate = requisitionInterface;
                                reachableInterfaceFound = true;
                            }

                            requisitionInterface.setManaged(Boolean.TRUE);
                            requisitionInterface.setStatus(Integer.valueOf(1));
                            requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY);
                            requisitionInterfaceList.add(requisitionInterface);
                        }
                    }

                } catch (UnknownHostException unknownHostException) {
                    logger.warn("Invalid IP address '{}'", unknownHostException.getMessage());
                }
            }

            if (primaryInterfaceCandidate != null) {
                if (reachableInterfaceFound) {
                    logger.warn("Found reachable primary interface '{}'",
                            primaryInterfaceCandidate.getIpAddr());
                } else {
                    logger.warn(
                            "Only non-reachable interfaces found, using first one for primary interface '{}'",
                            primaryInterfaceCandidate.getIpAddr());
                }
                primaryInterfaceCandidate.setSnmpPrimary(PrimaryType.PRIMARY);

                for (String service : m_hostSystemServices) {
                    if (reachableInterfaceFound || !"VMwareCim-HostSystem".equals(service)) {
                        primaryInterfaceCandidate
                                .insertMonitoredService(new RequisitionMonitoredService(service.trim()));
                    }
                }
            } else {
                logger.warn("No primary interface found");
            }

            for (RequisitionInterface requisitionInterface : requisitionInterfaceList) {
                requisitionNode.putInterface(requisitionInterface);
            }

        } else {
            logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType());
            return null;
        }
    }

    /*
     * For now we use displaycategory, notifycategory and pollercategory for storing
     * the vcenter Ip address, the username and the password
     */

    String powerState = "unknown";
    StringBuffer vmwareTopologyInfo = new StringBuffer();

    // putting parents to topology information
    ManagedEntity parentEntity = managedEntity.getParent();

    do {
        if (vmwareTopologyInfo.length() > 0) {
            vmwareTopologyInfo.append(", ");
        }
        try {
            if (parentEntity != null && parentEntity.getMOR() != null) {
                vmwareTopologyInfo.append(parentEntity.getMOR().getVal() + "/"
                        + URLEncoder.encode(parentEntity.getName(), "UTF-8"));
            } else {
                logger.warn(
                        "Can't add topologyInformation because either the parentEntity or the MOR is null for "
                                + managedEntity.getName());
            }
        } catch (UnsupportedEncodingException e) {
            logger.warn("Unsupported encoding '{}'", e.getMessage());
        }
        parentEntity = parentEntity == null ? null : parentEntity.getParent();
    } while (parentEntity != null);

    if (managedEntity instanceof HostSystem) {

        HostSystem hostSystem = (HostSystem) managedEntity;

        HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();

        if (hostRuntimeInfo == null) {
            logger.debug("hostRuntimeInfo=null");
        } else {
            HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
            if (hostSystemPowerState == null) {
                logger.debug("hostSystemPowerState=null");
            } else {
                powerState = hostSystemPowerState.toString();
            }
        }

        try {
            if (m_topologyDatastores) {
                for (Datastore datastore : hostSystem.getDatastores()) {
                    if (vmwareTopologyInfo.length() > 0) {
                        vmwareTopologyInfo.append(", ");
                    }
                    try {
                        vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/"
                                + URLEncoder.encode(datastore.getSummary().getName(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        logger.warn("Unsupported encoding '{}'", e.getMessage());
                    }
                }
            }
        } catch (RemoteException e) {
            logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'",
                    managedEntity.getMOR().getVal(), e.getMessage());
        }

        try {
            if (m_topologyNetworks) {
                for (Network network : hostSystem.getNetworks()) {
                    if (vmwareTopologyInfo.length() > 0) {
                        vmwareTopologyInfo.append(", ");
                    }
                    try {
                        if (network instanceof DistributedVirtualPortgroup ? m_topologyPortGroups : true) {
                            vmwareTopologyInfo.append(network.getMOR().getVal() + "/"
                                    + URLEncoder.encode(network.getSummary().getName(), "UTF-8"));
                        }
                    } catch (UnsupportedEncodingException e) {
                        logger.warn("Unsupported encoding '{}'", e.getMessage());
                    }
                }
            }
        } catch (RemoteException e) {
            logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'",
                    managedEntity.getMOR().getVal(), e.getMessage());
        }
    } else {

        if (managedEntity instanceof VirtualMachine) {
            VirtualMachine virtualMachine = (VirtualMachine) managedEntity;

            VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime();

            if (virtualMachineRuntimeInfo == null) {
                logger.debug("virtualMachineRuntimeInfo=null");
            } else {
                VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState();
                if (virtualMachinePowerState == null) {
                    logger.debug("virtualMachinePowerState=null");
                } else {
                    powerState = virtualMachinePowerState.toString();
                }
            }

            try {
                if (m_topologyDatastores) {
                    for (Datastore datastore : virtualMachine.getDatastores()) {
                        if (vmwareTopologyInfo.length() > 0) {
                            vmwareTopologyInfo.append(", ");
                        }
                        try {
                            vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/"
                                    + URLEncoder.encode(datastore.getSummary().getName(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            logger.warn("Unsupported encoding '{}'", e.getMessage());
                        }
                    }
                }
            } catch (RemoteException e) {
                logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'",
                        managedEntity.getMOR().getVal(), e.getMessage());
            }
            try {
                if (m_topologyNetworks) {
                    for (Network network : virtualMachine.getNetworks()) {
                        if (vmwareTopologyInfo.length() > 0) {
                            vmwareTopologyInfo.append(", ");
                        }
                        try {
                            if (network instanceof DistributedVirtualPortgroup ? m_topologyPortGroups : true) {
                                vmwareTopologyInfo.append(network.getMOR().getVal() + "/"
                                        + URLEncoder.encode(network.getSummary().getName(), "UTF-8"));
                            }
                        } catch (UnsupportedEncodingException e) {
                            logger.warn("Unsupported encoding '{}'", e.getMessage());
                        }
                    }
                }
            } catch (RemoteException e) {
                logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'",
                        managedEntity.getMOR().getVal(), e.getMessage());
            }

            if (vmwareTopologyInfo.length() > 0) {
                vmwareTopologyInfo.append(", ");
            }

            try {
                vmwareTopologyInfo.append(virtualMachine.getRuntime().getHost().getVal() + "/" + URLEncoder
                        .encode(m_hostSystemMap.get(virtualMachine.getRuntime().getHost().getVal()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.warn("Unsupported encoding '{}'", e.getMessage());
            }
        } else {
            logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType());

            return null;
        }
    }

    RequisitionAsset requisitionAssetHostname = new RequisitionAsset("vmwareManagementServer", m_hostname);
    requisitionNode.putAsset(requisitionAssetHostname);

    RequisitionAsset requisitionAssetType = new RequisitionAsset("vmwareManagedEntityType",
            (managedEntity instanceof HostSystem ? "HostSystem" : "VirtualMachine"));
    requisitionNode.putAsset(requisitionAssetType);

    RequisitionAsset requisitionAssetId = new RequisitionAsset("vmwareManagedObjectId",
            managedEntity.getMOR().getVal());
    requisitionNode.putAsset(requisitionAssetId);

    RequisitionAsset requisitionAssetTopologyInfo = new RequisitionAsset("vmwareTopologyInfo",
            vmwareTopologyInfo.toString());
    requisitionNode.putAsset(requisitionAssetTopologyInfo);

    RequisitionAsset requisitionAssetState = new RequisitionAsset("vmwareState", powerState);
    requisitionNode.putAsset(requisitionAssetState);

    requisitionNode.putCategory(new RequisitionCategory("VMware" + apiVersion));

    return requisitionNode;
}

From source file:org.rhq.storage.installer.StorageInstaller.java

private InstallerInfo install(CommandLine cmdLine) throws StorageInstallerException {
    DeploymentOptionsFactory factory = new DeploymentOptionsFactory();
    DeploymentOptions deploymentOptions = factory.newDeploymentOptions();
    InstallerInfo installerInfo = new InstallerInfo();

    if (cmdLine.hasOption("dir")) {
        installerInfo.basedir = new File(cmdLine.getOptionValue("dir"));
        deploymentOptions.setBasedir(installerInfo.basedir.getAbsolutePath());
    } else {/* w w w .ja  v  a2s.  c  o m*/
        installerInfo.basedir = new File(serverBasedir, "rhq-storage");
        deploymentOptions.setBasedir(installerInfo.basedir.getAbsolutePath());
    }

    try {
        if (cmdLine.hasOption("n")) {
            installerInfo.hostname = cmdLine.getOptionValue("n");
            // Make sure it is a reachable address
            InetAddress.getByName(installerInfo.hostname);
        } else {
            installerInfo.hostname = InetAddress.getLocalHost().getHostName();
        }

        if (InetAddress.getByName(installerInfo.hostname).isLoopbackAddress()) {
            log.warn("This Storage Node is bound to the loopback address " + installerInfo.hostname + " . "
                    + "It will not be able to communicate with Storage Nodes on other machines,"
                    + " and it can only receive client requests from this machine.");
        }

        deploymentOptions.setListenAddress(installerInfo.hostname);
        deploymentOptions.setRpcAddress(installerInfo.hostname);

        String seeds = cmdLine.getOptionValue(StorageProperty.SEEDS.property(), installerInfo.hostname);
        deploymentOptions.setSeeds(seeds);

        String commitlogDir = cmdLine.getOptionValue(StorageProperty.COMMITLOG.property(),
                getDefaultCommitLogDir());
        String dataDir = cmdLine.getOptionValue(StorageProperty.DATA.property(), getDefaultDataDir());
        String savedCachesDir = cmdLine.getOptionValue(StorageProperty.SAVED_CACHES.property(),
                getDefaultSavedCachesDir());

        File commitLogDirFile = new File(commitlogDir);
        File dataDirFile = new File(dataDir);
        File savedCachesDirFile = new File(savedCachesDir);

        boolean verifyDataDirsEmpty = Boolean
                .valueOf(cmdLine.getOptionValue(StorageProperty.VERIFY_DATA_DIRS_EMPTY.property(), "true"));
        if (verifyDataDirsEmpty) {
            // validate the three data directories are empty - if they are not, we are probably stepping on
            // another storage node
            if (!isDirectoryEmpty(commitLogDirFile)) {
                log.error("Commitlog directory is not empty. It should not exist for a new Storage Node ["
                        + commitLogDirFile.getAbsolutePath() + "]");
                throw new StorageInstallerException("Installation cannot proceed. The commit log directory "
                        + commitLogDirFile + " is not empty", STATUS_DATA_DIR_NOT_EMPTY);
            }
            if (!isDirectoryEmpty(dataDirFile)) {
                log.error("Data directory is not empty. It should not exist for a new Storage Node ["
                        + dataDirFile.getAbsolutePath() + "]");
                throw new StorageInstallerException(
                        "Installation cannot proceed. The data directory " + dataDirFile + " is not empty",
                        STATUS_DATA_DIR_NOT_EMPTY);
            }
            if (!isDirectoryEmpty(savedCachesDirFile)) {
                log.error("Saved caches directory is not empty. It should not exist for a new Storage Node ["
                        + savedCachesDirFile.getAbsolutePath() + "]");
                throw new StorageInstallerException("Installation cannot proceed. The saved caches directory "
                        + savedCachesDirFile + " is not empty", STATUS_DATA_DIR_NOT_EMPTY);
            }
        }

        verifyPortStatus(cmdLine, installerInfo);

        deploymentOptions.setCommitLogDir(commitlogDir);
        // TODO add support for specifying multiple dirs
        deploymentOptions.setDataDir(dataDirFile.getPath());
        deploymentOptions.setSavedCachesDir(savedCachesDir);

        deploymentOptions.setLogFileName(installerInfo.logFile);
        deploymentOptions.setLoggingLevel("INFO");

        deploymentOptions.setRpcPort(rpcPort);
        deploymentOptions.setCqlPort(installerInfo.cqlPort);
        deploymentOptions.setGossipPort(installerInfo.gossipPort);
        deploymentOptions.setJmxPort(installerInfo.jmxPort);

        deploymentOptions
                .setHeapSize(cmdLine.getOptionValue(StorageProperty.HEAP_SIZE.property(), defaultHeapSize));
        deploymentOptions.setHeapNewSize(
                cmdLine.getOptionValue(StorageProperty.HEAP_NEW_SIZE.property(), defaultHeapNewSize));
        if (cmdLine.hasOption(StorageProperty.STACK_SIZE.property())) {
            deploymentOptions.setStackSize(cmdLine.getOptionValue(StorageProperty.STACK_SIZE.property()));
        }

        // The out of box default for native_transport_max_threads is 128. We default
        // to 64 for dev/test environments so we need to update it here.
        deploymentOptions.setNativeTransportMaxThreads(128);

        deploymentOptions.load();

        List<String> errors = new ArrayList<String>();
        checkPerms(options.getOption(StorageProperty.SAVED_CACHES.property()), savedCachesDir, errors);
        checkPerms(options.getOption(StorageProperty.COMMITLOG.property()), commitlogDir, errors);
        checkPerms(options.getOption(StorageProperty.DATA.property()), dataDir, errors);

        if (!errors.isEmpty()) {
            log.error("Problems have been detected with one or more of the directories in which the storage "
                    + "node will need to store data");
            for (String error : errors) {
                log.error(error);
            }
            throw new StorageInstallerException(
                    "Installation cannot proceed. There are problems with one or more of "
                            + "the storage data directories.",
                    STATUS_INVALID_FILE_PERMISSIONS);
        }

        Deployer deployer = getDeployer();
        deployer.setDeploymentOptions(deploymentOptions);
        storageBasedir.mkdirs();
        deployer.unzipDistro();
        deployer.applyConfigChanges();
        deployer.updateFilePerms();

        deployer.updateStorageAuthConf(asSet(installerInfo.hostname));

        return installerInfo;
    } catch (UnknownHostException unknownHostException) {
        throw new StorageInstallerException(
                "Failed to resolve requested binding address. Please check the installation instructions and host DNS settings"
                        + (isWindows() ? "." : " also make sure the hostname alias is set in /etc/hosts.")
                        + " Unknown host " + unknownHostException.getMessage(),
                unknownHostException, STATUS_UNKNOWN_HOST);
    } catch (IOException e) {
        throw new StorageInstallerError("The upgrade cannot proceed. An unexpected I/O error occurred", e,
                STATUS_IO_ERROR);
    } catch (DeploymentException e) {
        throw new StorageInstallerException(
                "The installation cannot proceed. An error occurred during storage " + "node deployment.", e,
                STATUS_DEPLOYMENT_ERROR);
    }
}

From source file:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java

/**
 * common.agent.discovery.pingport ????????IP??
 *  ?TCP???????true?/*ww w.  jav a2  s  . c om*/
 *  ?????????false?
 *
 * @param facilityId
 * @return
 * @throws UnknownHostException
 * @throws IOException
 */
public static boolean sendManagerDiscoveryInfo(String facilityId) throws UnknownHostException, IOException {
    String managerIpAddr = "";
    boolean successFlag = true;
    String agentIpAddr = "";
    int pingPort;

    // ???????????????????
    pingPort = HinemosPropertyUtil.getHinemosPropertyNum("common.agent.discovery.pingport", Long.valueOf(24005))
            .intValue();
    if (pingPort < 1 || pingPort > 65535) {
        return false;
    }
    // ???????IP?
    try {
        // DNS????(agent.connection.dnsname??) Hinemos ver 4.0.2?
        managerIpAddr = HinemosPropertyUtil.getHinemosPropertyStr("agent.connection.dnsname", "");

        // IP??(agent.connection.dnsname?)
        if (managerIpAddr == null || "".equals(managerIpAddr)) {
            managerIpAddr = HinemosPropertyUtil.getHinemosPropertyStr("agent.connection.ipaddres",
                    InetAddress.getLocalHost().getHostAddress());
        }
    } catch (UnknownHostException e) {
        throw e;
    }

    // FIXME ??????????????????????????????
    Socket socket = null;
    InputStream is = null;
    try {
        String sendDataStr = "managerIp=" + managerIpAddr + ",agentFacilityId=" + facilityId;
        byte[] data = sendDataStr.getBytes();
        byte[] msg = new byte[data.length];
        agentIpAddr = NodeProperty.getProperty(facilityId).getAvailableIpAddress();

        m_log.info("trying to establish connection to hinemos agent server at " + agentIpAddr + ":" + pingPort);

        socket = new Socket(agentIpAddr, pingPort);

        m_log.info("established the connection to the hinemos agent server at " + agentIpAddr);

        is = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        out.write(data);

        m_log.info("sent the message " + new String(data));

        // ???
        int totalBytesRcvd = 0;
        int bytesRcvd;

        while (totalBytesRcvd < data.length) {
            if ((bytesRcvd = is.read(msg, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) {
                continue;
            }
            totalBytesRcvd += bytesRcvd;
        }
        m_log.info("received the message: " + new String(msg));
    } catch (Exception e) {
        successFlag = false;
        m_log.warn("facilityId: " + facilityId + ", " + e.getMessage());
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            throw e;
        }
    }

    return successFlag;
}

From source file:esg.gateway.service.ESGGatewayServiceImpl.java

public void register(ESGRemoteEvent evt) {
    log.trace("Gateway service got \"register\" call from datanode with event: [" + evt + "]");

    //Triage incoming revent...
    if (evt.getMessageType() != ESGRemoteEvent.REGISTER) {
        log.trace("Registration called with wrong event type... dropping on floor...");
        return;/*from w  ww  .j  a va 2 s . com*/
    }

    //Create the string for *our* callback address...
    String myLocation = null;
    try {
        myLocation = "http://" + InetAddress.getLocalHost().getCanonicalHostName() + "/esg-node/gateway";
    } catch (java.net.UnknownHostException ex) {
        log.error("Could not build proper location string for myself", ex);
    }

    //Create proxy endpoint for data node service that sent us this event.
    try {
        datanodeService = (ESGDataNodeService) factory.create(ESGDataNodeService.class, evt.getSource());
    } catch (MalformedURLException ex) {
        log.warn("Could not connect to serviceURL [" + evt.getSource() + "]", ex);
    }

    //Assemble info to create an event and send it to data node in response to this 'register' call.
    try {
        ESGRemoteEvent registrationResponseEvent = new ESGRemoteEvent(myLocation, ESGRemoteEvent.REGISTER,
                Utils.nextSeq());
        log.trace("Completing Registration By Making Remote Call to \"notify\" method, sending: "
                + registrationResponseEvent);
        //Since no longer as of 2011-04-25 supporting notify method on the datanode service... 
        //if(datanodeService.notify(registrationResponseEvent))
        //log.trace("Registration Request Successfully Submitted...");
        //else
        log.trace("Registration Request Rejected");
    } catch (HessianRuntimeException ex) {
        log.error("Problem calling \"register\" on [" + evt.getSource() + "] " + ex.getMessage());
    }
}

From source file:com.adito.security.DefaultLogonController.java

private void refreshLogonTicket(HttpServletRequest request, HttpServletResponse response, String logonTicket)
        throws SecurityErrorException {
    if (log.isInfoEnabled())
        log.info("Refreshing logon ticket " + logonTicket);
    User user = getUser(request, logonTicket);
    request.getSession().setAttribute(Constants.USER, user);
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    SessionInfo info = (SessionInfo) logons.get(logonTicket);
    if (info == null) {
        InetAddress address;/*www  .jav a2 s .c o m*/
        try {
            address = InetAddress.getByName(request.getRemoteAddr());
        } catch (UnknownHostException uhe) {
            throw new SecurityErrorException(SecurityErrorException.ERR_INVALID_TICKET,
                    "Could not refresh logon ticket. " + uhe.getMessage());
        }
        String userAgent = request.getHeader("User-Agent");
        info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, SessionInfo.UI,
                userAgent);
    } else {
        moveSessionTimeoutBlocks(info.getHttpSession(), request.getSession());
        info.setSession(request.getSession());
    }
    request.getSession().setAttribute(Constants.SESSION_INFO, info);

    /**
     * LDP - Allow for the session info to be looked up using the session
     * id.
     */
    try {
        String sessionIdentifier = SystemProperties.get("adito.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    addSession(logonTicket, info, request, response);
    try {
        if (Property.getPropertyBoolean(new SystemConfigKey("security.session.lockSessionOnBrowserClose"))) {
            if (log.isInfoEnabled())
                log.info("New session - will force the user to authenticate again");
            request.getSession().setAttribute(Constants.SESSION_LOCKED, user);
        } else {
            ResourceUtil.setAvailableProfiles(info);
        }
    } catch (Exception e) {
        log.warn("Failed to set session lock.", e);
    }
}

From source file:com.sslexplorer.security.DefaultLogonController.java

private void refreshLogonTicket(HttpServletRequest request, HttpServletResponse response, String logonTicket)
        throws SecurityErrorException {
    if (log.isInfoEnabled())
        log.info("Refreshing logon ticket " + logonTicket);
    User user = getUser(request, logonTicket);
    request.getSession().setAttribute(Constants.USER, user);
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    SessionInfo info = (SessionInfo) logons.get(logonTicket);
    if (info == null) {
        InetAddress address;/* w  w w  . j a va2s  . co  m*/
        try {
            address = InetAddress.getByName(request.getRemoteAddr());
        } catch (UnknownHostException uhe) {
            throw new SecurityErrorException(SecurityErrorException.ERR_INVALID_TICKET,
                    "Could not refresh logon ticket. " + uhe.getMessage());
        }
        String userAgent = request.getHeader("User-Agent");
        info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, SessionInfo.UI,
                userAgent);
    } else {
        moveSessionTimeoutBlocks(info.getHttpSession(), request.getSession());
        info.setSession(request.getSession());
    }
    request.getSession().setAttribute(Constants.SESSION_INFO, info);

    /**
     * LDP - Allow for the session info to be looked up using the session
     * id.
     */
    try {
        String sessionIdentifier = SystemProperties.get("sslexplorer.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    addSession(logonTicket, info, request, response);
    try {
        if (Property.getPropertyBoolean(new SystemConfigKey("security.session.lockSessionOnBrowserClose"))) {
            if (log.isInfoEnabled())
                log.info("New session - will force the user to authenticate again");
            request.getSession().setAttribute(Constants.SESSION_LOCKED, user);
        } else {
            ResourceUtil.setAvailableProfiles(info);
        }
    } catch (Exception e) {
        log.warn("Failed to set session lock.", e);
    }
}

From source file:com.waltz3d.common.httpclient.request.AsyncHttpRequest.java

private void makeRequestWithRetries() throws ConnectException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See: https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;/*w w  w.j av  a 2  s. co m*/
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            makeRequest();
            return;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "can't resolve host");
            }
            return;
        } catch (SocketException e) {
            e.printStackTrace();
            // Added to detect host unreachable
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "can't resolve host");
            }
            return;
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "socket time out");
            }
            return;
        } catch (IOException e) {
            e.printStackTrace();
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (NullPointerException e) {
            e.printStackTrace();
            // there's a bug in HttpClient 4.0.x that on some occasions causes
            // DefaultRequestExecutor to throw an NPE, see
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        }
    }

    // no retries left, crap out with exception
    ConnectException ex = new ConnectException();
    ex.initCause(cause);
    throw ex;
}