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:org.commoncrawl.service.crawler.HttpFetcher.java

private boolean fillSlot(int index, CrawlTarget optionalTarget) {

    // dont fill slot in paused state ... 
    if (!isPaused() || optionalTarget != null) {

        if (_active[index] != null) {
            LOG.error("fill Slot Called on Non-Empty Slot:" + index + " With URL:" + _active[index].getURL());
        }/*from  w  w w.  j av a2 s. co  m*/
        // if there are pending urls ...    
        if (optionalTarget != null || _pending.size() != 0) {
            // pop a url off of the queue ... or use the optionally passed in target 
            CrawlTarget crawlTarget = (optionalTarget != null) ? optionalTarget : _pending.removeFirst();

            try {
                URL fetchURL = new URL(crawlTarget.getActiveURL());
                URL originalURL = (crawlTarget.getRedirectCount() == 0) ? fetchURL
                        : new URL(crawlTarget.getOriginalURL());

                // open a new connection and assign it to the available slot ...
                if (_crawlInterfaces != null) {
                    _active[index] = new NIOHttpConnection(fetchURL,
                            _crawlInterfaces[getCrawlInterfaceForCrawlTarget(crawlTarget)], _selector,
                            _resolver, crawlTarget.getCookieStore());
                } else {
                    _active[index] = new NIOHttpConnection(fetchURL, _selector, _resolver,
                            crawlTarget.getCookieStore());
                }

                // LOG.info("### FETCHER Alloc HTTPConnect to:" + fetchURL + " Slot:" + index);

                //TODO: MAJOR HACK
                // disable proxy requests for robots
                if ((crawlTarget.getFlags() & CrawlURL.Flags.IsRobotsURL) == 0) {
                    if (CrawlerServer.getServer().getProxyAddress() != null) {
                        // check to see if we should be using a proxy server 
                        _active[index].setProxyServer(CrawlerServer.getServer().getProxyAddress());
                    }
                }

                // add in special source header
                _active[index].getRequestHeaders().setIfNotSet("x-cc-id", _crawlerName);
                // add in cache tests if present 
                if (crawlTarget.getRedirectCount() == 0) {
                    if (crawlTarget.getLastModifiedTime() != -1) {
                        _active[index].getRequestHeaders().setIfNotSet("If-Modified-Since",
                                http_date_format.format(new Date(crawlTarget.getLastModifiedTime())));

                    }
                    if (crawlTarget.getETag() != null) {
                        _active[index].getRequestHeaders().setIfNotSet("If-None-Match", crawlTarget.getETag());

                    }
                }

                _activeVersions[index] = (short) ((_activeVersions[index] + 1) % 10);

                long currentTime = System.currentTimeMillis();

                if (crawlTarget.getRedirectCount() != 0) {
                    String newHost = fetchURL.getHost();
                    String originalHost = originalURL.getHost();
                    if (newHost != null && originalHost != null && newHost.equalsIgnoreCase(originalHost)) {
                        crawlTarget.getSourceList().populateIPAddressForTarget(fetchURL.getHost(), crawlTarget);
                    }
                }
                // IFF NOT Redirect 
                else {
                    // if the cached ip is still valid based on stored TTL ... 
                    if (crawlTarget.getServerIP() != 0
                            && crawlTarget.getServerIPTTL() >= System.currentTimeMillis()) {
                        // then set the resolved address data members (thus enabling us to bypass dns lookup)
                        _active[index].setResolvedAddress(
                                IPAddressUtils.IntegerToInetAddress(crawlTarget.getServerIP()),
                                crawlTarget.getServerIPTTL(), null);
                    } else {
                        if (Environment.detailLogEnabled()) {
                            if (crawlTarget.getServerIP() == 0)
                                LOG.info("#### IP Address for Host:" + fetchURL.getHost()
                                        + " Not Set. Will require DNS Resolution");
                            else
                                LOG.info("#### TTL of Cached IP Expired for Host:" + fetchURL.getHost()
                                        + ". Will require DNS Resolution");
                        }
                    }
                }

                _active[index].setListener(this);
                _active[index].setContext(new CrawlContext(crawlTarget, index));
                _active[index].setDownloadMax(DOWNLOAD_LIMIT);

                if (!_failConnections) {
                    _active[index].open();
                    //LOG.info("### FETCHER called open on connection to:" + fetchURL + " slot:" + index);
                } else {
                    throw new IOException("Deliberately Skipped Open and FAILED Connection");
                }

                snapShotConnectionCount++;
                connectionCount++;
                if (Environment.detailLogEnabled())
                    LOG.info("Filled SLOT:" + index + " With URL:" + crawlTarget.getActiveURL());

                // inform the target of the status change 
                crawlTarget.fetchStarting(_active[index]);
                // LOG.info("### FETCHER called fetchStarting for:" + fetchURL + " slot:" + index);

                // log it ... 
                logGET(crawlTarget, index);
                // and construct the http request ...

            } catch (UnknownHostException e) {
                //TODO: CLEAR SLOT BEFORE CALLING fetchFailed!!!!
                if (_active[index] != null) {
                    _active[index].setContext(null);
                    _active[index].close();
                }
                _active[index] = null;
                if (Environment.detailLogEnabled())
                    LOG.error("Maformed URL Exception Processing URL:" + crawlTarget.getActiveURL());
                crawlTarget.fetchFailed(CrawlURL.FailureReason.MalformedURL, e.toString());

                failureCount++;
            } catch (MalformedURLException e) {

                //TODO: CLEAR SLOT BEFORE CALLING fetchFailed!!!!
                if (_active[index] != null) {
                    _active[index].setContext(null);
                    _active[index].close();
                }
                _active[index] = null;
                if (Environment.detailLogEnabled())
                    LOG.error("Maformed URL Exception Processing URL:" + crawlTarget.getActiveURL());
                crawlTarget.fetchFailed(CrawlURL.FailureReason.MalformedURL, e.toString());

                failureCount++;
            } catch (IOException e2) {
                if (Environment.detailLogEnabled())
                    LOG.error("IOException Processing URL:" + crawlTarget.getActiveURL() + " Details:"
                            + e2.getMessage());

                //TODO: WATCH IT!!! - always clear slot FIRST because fetchFailed calls back into fillSlot!!!!
                if (_active[index] != null) {
                    _active[index].setContext(null);
                    _active[index].close();
                }
                _active[index] = null;

                // LOG.debug("Fetch FAILED URL:"+ context.getURL().getURL() + " Code:"+ failureCode);
                // notify url of failure ... 
                //TODO: Investigate if it is SANE!!! to call back into fillSlot from fetchFailed !!!
                crawlTarget.fetchFailed(CrawlURL.FailureReason.IOException, e2.getMessage());

                failureCount++;
            } catch (Exception e) {

                LOG.error("Runtime Exception Processing URL:" + crawlTarget.getActiveURL() + " Details:"
                        + e.getMessage());

                //TODO: WATCH IT!!! - always clear slot FIRST because fetchFailed calls back into fillSlot!!!!
                if (_active[index] != null) {
                    _active[index].setContext(null);
                    _active[index].close();
                }
                _active[index] = null;

                // LOG.debug("Fetch FAILED URL:"+ context.getURL().getURL() + " Code:"+ failureCode);
                // notify url of failure ... 
                //TODO: Investigate if it is SANE!!! to call back into fillSlot from fetchFailed !!!
                crawlTarget.fetchFailed(CrawlURL.FailureReason.RuntimeError, e.getMessage());

                failureCount++;

            }
        }
    }
    return _active[index] != null;
}

From source file:org.apache.hadoop.hive.metastore.HiveMetaStoreClientPreCatalog.java

private OpenTxnsResponse openTxnsIntr(String user, int numTxns, String replPolicy, List<Long> srcTxnIds,
        TxnType txnType) throws TException {
    String hostname;/*ww w.  java 2s. co  m*/
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        LOG.error("Unable to resolve my host name " + e.getMessage());
        throw new RuntimeException(e);
    }
    OpenTxnRequest rqst = new OpenTxnRequest(numTxns, user, hostname);
    if (replPolicy != null) {
        assert srcTxnIds != null;
        assert numTxns == srcTxnIds.size();
        // need to set this only for replication tasks
        rqst.setReplPolicy(replPolicy);
        rqst.setReplSrcTxnIds(srcTxnIds);
    } else {
        assert srcTxnIds == null;
    }
    if (txnType != null) {
        rqst.setTxn_type(txnType);
    }
    return client.open_txns(rqst);
}

From source file:act.server.MongoDB.java

private void initDB() {
    try {//from   w ww. j a v a 2s.  c  o m
        mongo = new Mongo(this.hostname, this.port);
        mongoDB = mongo.getDB(this.database);

        // in case the db is protected then we would do the following:
        // boolean auth = db.authenticate(myUserName, myPassword);
        // but right now we do not care.

        this.dbReactions = mongoDB.getCollection("reactions");
        this.dbChemicals = mongoDB.getCollection("chemicals");
        this.dbCofactors = mongoDB.getCollection("cofactors");
        this.dbOrganisms = mongoDB.getCollection("organisms");
        this.dbOrganismNames = mongoDB.getCollection("organismnames");
        this.dbSeq = mongoDB.getCollection("seq");
        this.dbCascades = mongoDB.getCollection("cascades");
        this.dbWaterfalls = mongoDB.getCollection("waterfalls");
        this.dbPubmed = mongoDB.getCollection("pubmed");

        initIndices();
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("Invalid host for Mongo Act server.");
    } catch (MongoException e) {
        throw new IllegalArgumentException(
                String.format("Could not initialize Mongo driver: %s", e.getMessage()));
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * @inheritDoc/*from w  w w .j a  va  2 s .c  o m*/
 */
@Override
protected byte[] getContent(ExchangeSession.Message message) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream contentInputStream;
    try {
        try {
            try {
                contentInputStream = getContentInputStream(message.messageUrl);
            } catch (UnknownHostException e) {
                // failover for misconfigured Exchange server, replace host name in url
                restoreHostName = true;
                contentInputStream = getContentInputStream(message.messageUrl);
            }
        } catch (HttpNotFoundException e) {
            LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl");
            contentInputStream = getContentInputStream(message.permanentUrl);
        }

        try {
            IOUtil.write(contentInputStream, baos);
        } finally {
            contentInputStream.close();
        }

    } catch (LoginTimeoutException e) {
        // throw error on expired session
        LOGGER.warn(e.getMessage());
        throw e;
    } catch (IOException e) {
        LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl
                + ", trying to rebuild from properties");

        try {
            DavPropertyNameSet messageProperties = new DavPropertyNameSet();
            messageProperties.add(Field.getPropertyName("contentclass"));
            messageProperties.add(Field.getPropertyName("message-id"));
            messageProperties.add(Field.getPropertyName("from"));
            messageProperties.add(Field.getPropertyName("to"));
            messageProperties.add(Field.getPropertyName("cc"));
            messageProperties.add(Field.getPropertyName("subject"));
            messageProperties.add(Field.getPropertyName("date"));
            messageProperties.add(Field.getPropertyName("htmldescription"));
            messageProperties.add(Field.getPropertyName("body"));
            PropFindMethod propFindMethod = new PropFindMethod(encodeAndFixUrl(message.permanentUrl),
                    messageProperties, 0);
            DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
            MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus();
            if (responses.getResponses().length > 0) {
                MimeMessage mimeMessage = new MimeMessage((Session) null);

                DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK);
                String propertyValue = getPropertyIfExists(properties, "contentclass");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Content-class", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "date");
                if (propertyValue != null) {
                    mimeMessage.setSentDate(parseDateFromExchange(propertyValue));
                }
                propertyValue = getPropertyIfExists(properties, "from");
                if (propertyValue != null) {
                    mimeMessage.addHeader("From", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "to");
                if (propertyValue != null) {
                    mimeMessage.addHeader("To", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "cc");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Cc", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "subject");
                if (propertyValue != null) {
                    mimeMessage.setSubject(propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "htmldescription");
                if (propertyValue != null) {
                    mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");
                } else {
                    propertyValue = getPropertyIfExists(properties, "body");
                    if (propertyValue != null) {
                        mimeMessage.setText(propertyValue);
                    }
                }
                mimeMessage.writeTo(baos);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
            }
        } catch (IOException e2) {
            LOGGER.warn(e2);
        } catch (DavException e2) {
            LOGGER.warn(e2);
        } catch (MessagingException e2) {
            LOGGER.warn(e2);
        }
        // other exception
        if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) {
            LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: "
                    + message.permanentUrl);
            try {
                message.delete();
            } catch (IOException ioe) {
                LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl);
            }
            throw e;
        }
    }

    return baos.toByteArray();
}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.MeridioConnector.java

/** Set up the session with Meridio */
protected void getSession() throws ManifoldCFException, ServiceInterruption {
    if (meridio_ == null) {
        // Do the first part (which used to be in connect() itself)
        try {//from ww w. ja va2  s  .c om
            /*=================================================================
            * Construct the URL strings from the parameters
            *================================================================*/
            String DMWSProtocol = params.getParameter("DMWSServerProtocol");
            String DMWSPort = params.getParameter("DMWSServerPort");
            if (DMWSPort == null || DMWSPort.length() == 0)
                DMWSPort = "";
            else
                DMWSPort = ":" + DMWSPort;

            String Url = DMWSProtocol + "://" + params.getParameter("DMWSServerName") + DMWSPort
                    + params.getParameter("DMWSLocation");

            Logging.connectors.debug("Meridio: Document Management Web Service (DMWS) URL is [" + Url + "]");
            DmwsURL = new URL(Url);

            String RMWSProtocol = params.getParameter("RMWSServerProtocol");
            String RMWSPort = params.getParameter("RMWSServerPort");
            if (RMWSPort == null || RMWSPort.length() == 0)
                RMWSPort = "";
            else
                RMWSPort = ":" + RMWSPort;

            Url = RMWSProtocol + "://" + params.getParameter("RMWSServerName") + RMWSPort
                    + params.getParameter("RMWSLocation");

            Logging.connectors.debug("Meridio: Record Management Web Service (RMWS) URL is [" + Url + "]");
            RmwsURL = new URL(Url);

            // Set up ssl if indicated
            String keystoreData = params.getParameter("MeridioKeystore");

            if (keystoreData != null)
                mySSLFactory = KeystoreManagerFactory.make("", keystoreData).getSecureSocketFactory();
            else
                mySSLFactory = null;

            // Put together the url base
            String clientProtocol = params.getParameter("MeridioWebClientProtocol");
            String clientPort = params.getParameter("MeridioWebClientServerPort");
            if (clientPort == null || clientPort.length() == 0)
                clientPort = "";
            else
                clientPort = ":" + clientPort;
            urlVersionBase = clientProtocol + "://" + params.getParameter("MeridioWebClientServerName")
                    + clientPort + params.getParameter("MeridioWebClientDocDownloadLocation");
            urlBase = urlVersionBase + "?launchMode=1&launchAs=0&documentId=";

        } catch (MalformedURLException malformedURLException) {
            throw new ManifoldCFException(
                    "Meridio: Could not construct the URL for either " + "the DM or RM Meridio Web Service",
                    malformedURLException, ManifoldCFException.REPOSITORY_CONNECTION_ERROR);
        }

        // Do the second part (where we actually try to connect to the system)
        try {
            /*=================================================================
            * Now try and login to Meridio; the wrapper's constructor can be
            * used as it calls the Meridio login method
            *================================================================*/
            meridio_ = new MeridioWrapper(Logging.connectors, DmwsURL, RmwsURL, null,
                    params.getParameter("DMWSProxyHost"), params.getParameter("DMWSProxyPort"),
                    params.getParameter("RMWSProxyHost"), params.getParameter("RMWSProxyPort"), null,

                    null, params.getParameter("UserName"), params.getObfuscatedParameter("Password"),
                    InetAddress.getLocalHost().getHostName(), mySSLFactory,
                    org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd");
        } catch (NumberFormatException e) {
            throw new ManifoldCFException("Meridio: bad number: " + e.getMessage(), e);
        } catch (UnknownHostException unknownHostException) {
            throw new ManifoldCFException("Meridio: A Unknown Host Exception occurred while "
                    + "connecting - is a network software and hardware configuration: "
                    + unknownHostException.getMessage(), unknownHostException);
        } catch (org.apache.axis.AxisFault e) {
            long currentTime = System.currentTimeMillis();
            if (e.getFaultCode().equals(new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HTTP"))) {
                org.w3c.dom.Element elem = e.lookupFaultDetail(
                        new javax.xml.namespace.QName("http://xml.apache.org/axis/", "HttpErrorCode"));
                if (elem != null) {
                    elem.normalize();
                    String httpErrorCode = elem.getFirstChild().getNodeValue().trim();
                    throw new ManifoldCFException("Unexpected http error code " + httpErrorCode
                            + " accessing Meridio: " + e.getMessage(), e);
                }
                throw new ManifoldCFException("Unknown http error occurred while connecting: " + e.getMessage(),
                        e);
            }
            if (e.getFaultCode().equals(new javax.xml.namespace.QName(
                    "http://schemas.xmlsoap.org/soap/envelope/", "Server.userException"))) {
                String exceptionName = e.getFaultString();
                if (exceptionName.equals("java.lang.InterruptedException"))
                    throw new ManifoldCFException("Interrupted", ManifoldCFException.INTERRUPTED);
            }
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors.debug("Meridio: Got an unknown remote exception connecting - axis fault = "
                        + e.getFaultCode().getLocalPart() + ", detail = " + e.getFaultString() + " - retrying",
                        e);
            throw new ServiceInterruption("Remote procedure exception: " + e.getMessage(), e,
                    currentTime + 300000L, currentTime + 3 * 60 * 60000L, -1, false);
        } catch (RemoteException remoteException) {
            throw new ManifoldCFException("Meridio: An unknown remote exception occurred while "
                    + "connecting: " + remoteException.getMessage(), remoteException);
        }

    }
}

From source file:com.uber.stream.kafka.mirrormaker.manager.ManagerConf.java

public static ManagerConf getManagerConf(CommandLine cmd) {
    ManagerConf managerConf = new ManagerConf();
    if (cmd.hasOption("config")) {
        managerConf.setConfigFile(cmd.getOptionValue("config"));
    } else {//w  w w .  j  a v  a2 s.  com
        managerConf.setConfigFile("");
    }
    if (cmd.hasOption("srcClusters")) {
        managerConf.setSourceClusters(cmd.getOptionValue("srcClusters"));
    } else {
        managerConf.setSourceClusters("");
    }
    if (cmd.hasOption("destClusters")) {
        managerConf.setDestinationClusters(cmd.getOptionValue("destClusters"));
    } else {
        managerConf.setDestinationClusters("");
    }
    if (cmd.hasOption("enableRebalance")) {
        managerConf.setEnableRebalance(cmd.getOptionValue("enableRebalance"));
    } else {
        managerConf.setEnableRebalance(Boolean.toString(DEFAULT_ENABLE_REBALANCE));
    }
    if (cmd.hasOption("zookeeper")) {
        managerConf.setManagerZkStr(cmd.getOptionValue("zookeeper"));
    } else {
        throw new RuntimeException("Missing option: --zookeeper");
    }
    if (cmd.hasOption("managerPort")) {
        managerConf.setManagerPort(cmd.getOptionValue("managerPort"));
    } else {
        throw new RuntimeException("Missing option: --managerPort");
    }
    if (cmd.hasOption("deployment")) {
        managerConf.setManagerDeployment(cmd.getOptionValue("deployment"));
    } else {
        throw new RuntimeException("Missing option: --deployment");
    }
    if (cmd.hasOption("env")) {
        managerConf.setEnvironment(cmd.getOptionValue("env"));
    } else {
        throw new RuntimeException("Missing option: --env");
    }
    if (cmd.hasOption("instanceId")) {
        managerConf.setManagerInstanceId(cmd.getOptionValue("instanceId"));
    } else {
        try {
            managerConf.setManagerInstanceId(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            throw new RuntimeException("Missing option: --instanceId");
        }
    }
    if (cmd.hasOption("controllerPort")) {
        managerConf.setControllerPort(cmd.getOptionValue("controllerPort"));
    } else {
        throw new RuntimeException("Missing option: --controllerPort");
    }
    if (cmd.hasOption("graphiteHost")) {
        managerConf.setGraphiteHost(cmd.getOptionValue("graphiteHost"));
    }
    if (cmd.hasOption("graphitePort")) {
        managerConf.setGraphitePort(cmd.getOptionValue("graphitePort"));
    } else {
        managerConf.setGraphitePort("0");
    }
    if (cmd.hasOption("metricsPrefix")) {
        managerConf.setMetricsPrefix(cmd.getOptionValue("metricsPrefix"));
    } else {
        managerConf.setMetricsPrefix(DEFAULT_METRICS_PREFIX);
    }
    if (cmd.hasOption("c3Host")) {
        managerConf.setC3Host(cmd.getOptionValue("c3Host"));
    } else {
        managerConf.setC3Host(DEFAULT_C3_HOST);
    }
    if (cmd.hasOption("c3Port")) {
        managerConf.setC3Port(cmd.getOptionValue("c3Port"));
    } else {
        managerConf.setC3Port(Integer.toString(DEFAULT_C3_PORT));
    }
    if (cmd.hasOption("clusterPrefixLength")) {
        managerConf.setClusterPrefixLength(cmd.getOptionValue("clusterPrefixLength"));
    } else {
        managerConf.setClusterPrefixLength(Integer.toString(DEFAULT_CLUSTER_PREFIX_LENGTH));
    }
    if (cmd.hasOption("workloadRefreshPeriodInSeconds")) {
        managerConf.setWorkloadRefreshPeriodInSeconds(cmd.getOptionValue("workloadRefreshPeriodInSeconds"));
    } else {
        managerConf.setWorkloadRefreshPeriodInSeconds(
                Integer.toString(DEFAULT_WORKLOAD_REFRESH_PERIOD_IN_SECONDS));
    }
    if (cmd.hasOption("initMaxNumPartitionsPerRoute")) {
        managerConf.setInitMaxNumPartitionsPerRoute(cmd.getOptionValue("initMaxNumPartitionsPerRoute"));
    } else {
        managerConf
                .setInitMaxNumPartitionsPerRoute(Integer.toString(DEFAULT_INIT_MAX_NUM_PARTITIONS_PER_ROUTE));
    }
    if (cmd.hasOption("maxNumPartitionsPerRoute")) {
        managerConf.setMaxNumPartitionsPerRoute(cmd.getOptionValue("maxNumPartitionsPerRoute"));
    } else {
        managerConf.setMaxNumPartitionsPerRoute(Integer.toString(DEFAULT_MAX_NUM_PARTITIONS_PER_ROUTE));
    }
    if (cmd.hasOption("initMaxNumWorkersPerRoute")) {
        managerConf.setInitMaxNumWorkersPerRoute(cmd.getOptionValue("initMaxNumWorkersPerRoute"));
    } else {
        managerConf.setInitMaxNumWorkersPerRoute(Integer.toString(DEFAULT_INIT_MAX_NUM_WORKERS_PER_ROUTE));
    }
    if (cmd.hasOption("maxNumWorkersPerRoute")) {
        managerConf.setMaxNumWorkersPerRoute(cmd.getOptionValue("maxNumWorkersPerRoute"));
    } else {
        managerConf.setMaxNumWorkersPerRoute(Integer.toString(DEFAULT_MAX_NUM_WORKERS_PER_ROUTE));
    }
    if (cmd.hasOption("bytesPerSecondDefault")) {
        managerConf.setBytesPerSecondDefault(cmd.getOptionValue("bytesPerSecondDefault"));
    } else {
        managerConf.setBytesPerSecondDefault(Double.toString(DEFAULT_BYTES_PER_SECOND_DEFAULT));
    }
    if (cmd.hasOption("msgsPerSecondDefault")) {
        managerConf.setMsgsPerSecondDefault(cmd.getOptionValue("msgsPerSecondDefault"));
    } else {
        managerConf.setMsgsPerSecondDefault(Double.toString(DEFAULT_MSGS_PER_SECOND_DEFAULT));
    }
    if (cmd.hasOption("updateStatusCoolDownMs")) {
        managerConf.setUpdateStatusCoolDownMs(cmd.getOptionValue("updateStatusCoolDownMs"));
    } else {
        managerConf.setUpdateStatusCoolDownMs(Integer.toString(DEFAULT_UPDATE_STATUS_COOL_DOWN_MS));
    }

    if (cmd.hasOption("config")) {
        String fileName = cmd.getOptionValue("config");
        managerConf.setConfigFile(fileName);
        // load config from file
        PropertiesConfiguration configFromFile = new PropertiesConfiguration();
        configFromFile.setDelimiterParsingDisabled(true);
        try {
            configFromFile.load(fileName);
        } catch (ConfigurationException e) {
            throw new RuntimeException("Failed to load config from file " + fileName + ": " + e.getMessage());
        }
        // merge the config with command line. Option from command line has higher priority to override config from file
        @SuppressWarnings("unchecked")
        Iterator<String> keyIter = configFromFile.getKeys();
        while (keyIter.hasNext()) {
            String key = keyIter.next();
            if (!managerConf.containsKey(key)) {
                managerConf.addPropertyDirect(key, configFromFile.getProperty(key));
            }
        }
    } else {
        managerConf.setConfigFile("");
    }

    return managerConf;
}

From source file:org.sipfoundry.preflight.TFTP.java

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;//from   ww  w .j  a  va2 s. c  o m
    InetAddress tftpServerAddress = null;
    String testFile = new String("00D01EFFFFFE");
    String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server",
            "[PROVISION]", "decrypt_key" };

    if (networkResources.configServer == null) {
        journalService.println("No TFTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

    journalService.println("Starting TFTP server test.");

    TFTPClient tftp = new TFTPClient();

    tftp.setDefaultTimeout(timeout * 1000);

    if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) {
        try {
            tftpServerAddress = InetAddress.getByName(networkResources.configServer);
        } catch (UnknownHostException e) {
            // Should never get here.
            e.printStackTrace();
        }
        journalService.println("Using TFTP server literal address: " + networkResources.configServer);
    } else {
        // Try to retrieve A RECORD for TFTP server, checking each DNS server.
        SimpleResolver resolver = null;
        try {
            resolver = new SimpleResolver();
            resolver.setTimeout(timeout);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up TFTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String(
                    "  TFTP server address \"" + networkResources.configServer + "\"");
            resolver.setAddress(dnsServer);
            Lookup aLookup = null;
            try {
                aLookup = new Lookup(networkResources.configServer, Type.A);
            } catch (TextParseException e) {
                journalService.println("  is malformed.\n");
                journalService.println(targetMessage);
                return TFTP_ADDRESS_MALFORMED;
            }
            aLookup.setResolver(resolver);
            Record[] aRecords = aLookup.run();
            switch (aLookup.getResult()) {
            case Lookup.SUCCESSFUL:
                if (aRecords != null) {
                    InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress();
                    targetMessage += " resolves to: " + targetAddress.getHostAddress();
                    journalService.println(targetMessage);
                    if (tftpServerAddress == null) {
                        tftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same address.
                        if (!tftpServerAddress.equals(targetAddress)) {
                            journalService.println("  TFTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = TFTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

    if ((tftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) {
        journalService.println("Cannot recover from previous errors, aborting TFTP test.\n");
        return results;
    }

    journalService.println("Beginning TFTP get request of test file: " + testFile);
    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        journalService.println("TFTP client failure. " + e.getMessage() + "\n");
        return TFTP_CLIENT_FAILURE;
    }

    // Try to receive remote file via TFTP
    try {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tftp.open(bindPort, bindAddress);
        tftp.receiveFile(testFile, org.apache.commons.net.tftp.TFTP.ASCII_MODE, output, tftpServerAddress);
        String testFileContents = output.toString();
        boolean verified = true;
        for (String verificationString : verificationStrings) {
            if (!testFileContents.contains(verificationString)) {
                verified = false;
            }
        }
        if (verified) {
            journalService.println("File received successfully.");
        } else {
            journalService.println("File received but contents do not verify.");
            results = TFTP_CONTENTS_FAILED;
        }
    } catch (UnknownHostException e) {
        journalService.println("TFTP client failure. " + e.getMessage());
        results = TFTP_CLIENT_FAILURE;
    } catch (IOException e) {
        journalService.println("TFTP get failed. " + e.getMessage());
        results = TFTP_GET_FAILED;
    } finally {
        // Close local socket and output file
        tftp.close();
    }

    journalService.println("");
    return results;
}

From source file:rems.Global.java

public static void upldImgsFTP(int folderTyp, String locfolderNm, String locfileNm) {
    String subdir = "";
    String[] srvr = Global.getFTPServerDet();
    if (srvr[5].equals("0") || locfileNm.equals("")) {
        return;/*  www. j  a  v a 2 s.  co  m*/
    }
    if (folderTyp == 0) {
        subdir = "/Org";
    } else if (folderTyp == 1) {
        subdir = "/Divs";
    } else if (folderTyp == 2) {
        subdir = "/Person";
    } else if (folderTyp == 3) {
        subdir = "/Inv";
    } else if (folderTyp == 4) {
        subdir = "/PrsnDocs";
    } else if (folderTyp == 5) {
        subdir = "/Accntn";
    } else if (folderTyp == 6) {
        subdir = "/Prchs";
    } else if (folderTyp == 7) {
        subdir = "/Sales";
    } else if (folderTyp == 8) {
        subdir = "/Rcpts";
    } else if (folderTyp == 9) {
        subdir = "/Rpts";
    } else if (folderTyp == 15) {
        subdir = "/Rpts/jrxmls";
    } else if (folderTyp == 10) {
        subdir = "/AttnDocs";
    } else if (folderTyp == 11) {
        subdir = "/AssetDocs";
    } else if (folderTyp == 12) {
        subdir = "/PyblDocs";
    } else if (folderTyp == 13) {
        subdir = "/RcvblDocs";
    } else if (folderTyp == 14) {
        subdir = "/FirmsDocs";
    }

    try {
        //            Global.UploadFile(
        //                    InetAddress.getByName(srvr[0]), srvr[1] + subdir + "/", locfileNm,
        //                    locfolderNm + "/" + locfileNm, srvr[2],
        //                    Global.decrypt(srvr[3], Global.AppKey));
        String srvrIP = srvr[0].replace("ftp://", "");
        srvrIP = srvrIP.replace("/", "");
        Program.thread9 = new Uploadfunc("ThreadNine", InetAddress.getByName(srvrIP), srvr[1] + subdir + "/",
                locfileNm, locfolderNm + "/" + locfileNm, srvr[2], Global.decrypt(srvr[3], Global.AppKey));
        Program.thread9.setDaemon(true);
        Program.thread9.setName("ThreadNine");
        Program.thread9.setPriority(Thread.MIN_PRIORITY);
        Program.thread9.start();
    } catch (UnknownHostException ex) {
        Global.errorLog = ex.getMessage() + "\r\n" + Arrays.toString(ex.getStackTrace()) + "\r\n";
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    }
}

From source file:rems.Global.java

public static void dwnldImgsFTP(int folderTyp, String locfolderNm, String locfileNm) {
    String[] srvr = Global.getFTPServerDet();
    String subdir = "";
    if (srvr[5].equals("0") || locfileNm.equals("")) {
        return;//from   w ww.j  a v  a2  s .com
    }
    if (folderTyp == 0) {
        subdir = "/Org";
    } else if (folderTyp == 1) {
        subdir = "/Divs";
    } else if (folderTyp == 2) {
        subdir = "/Person";
    } else if (folderTyp == 3) {
        subdir = "/Inv";
    } else if (folderTyp == 4) {
        subdir = "/PrsnDocs";
    } else if (folderTyp == 5) {
        subdir = "/Accntn";
    } else if (folderTyp == 6) {
        subdir = "/Prchs";
    } else if (folderTyp == 7) {
        subdir = "/Sales";
    } else if (folderTyp == 8) {
        subdir = "/Rcpts";
    } else if (folderTyp == 9) {
        subdir = "/Rpts";
    } else if (folderTyp == 15) {
        subdir = "/Rpts/jrxmls";
    } else if (folderTyp == 10) {
        subdir = "/AttnDocs";
    } else if (folderTyp == 11) {
        subdir = "/AssetDocs";
    } else if (folderTyp == 12) {
        subdir = "/PyblDocs";
    } else if (folderTyp == 13) {
        subdir = "/RcvblDocs";
    } else if (folderTyp == 14) {
        subdir = "/FirmsDocs";
    }
    try {
        String srvrIP = srvr[0].replace("ftp://", "");
        srvrIP = srvrIP.replace("/", "");
        Program.thread10 = new Downloadfunc("ThreadNine", InetAddress.getByName(srvrIP), srvr[1] + subdir + "/",
                locfileNm, locfolderNm + "/" + locfileNm, srvr[2], Global.decrypt(srvr[3], Global.AppKey));
        Program.thread10.setDaemon(true);
        Program.thread10.setName("ThreadNine");
        Program.thread10.setPriority(Thread.MIN_PRIORITY);
        Program.thread10.start();
    } catch (UnknownHostException ex) {
        Global.errorLog = ex.getMessage() + "\r\n" + Arrays.toString(ex.getStackTrace()) + "\r\n";
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    }
    //        try {
    //            Global.DownloadFile(InetAddress.getByName(srvr[0]), 
    //                    srvr[1] + subdir + "/", 
    //                    locfileNm,
    //                    locfolderNm + "/" + locfileNm, 
    //                    srvr[2],
    //                    Global.decrypt(srvr[3], Global.AppKey));
    //        } catch (UnknownHostException ex) {
    //            Logger.getLogger(Global.class.getName()).log(Level.SEVERE, null, ex);
    //        }
}