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:com.android.yijiang.kzx.http.AsyncHttpRequest.java

private void makeRequestWithRetries() throws IOException {
    boolean retry = true;
    IOException cause = null;/*  w  w  w .  java  2s  .  com*/
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    try {
        while (retry) {
            try {
                makeRequest();
                return;
            } catch (UnknownHostException e) {
                // switching between WI-FI and mobile data networks can cause a retry which then results in an UnknownHostException
                // while the WI-FI is initialising. The retry logic will be invoked here, if this is NOT the first retry
                // (to assist in genuine cases of unknown host) which seems better than outright failure
                cause = new IOException("UnknownHostException exception: " + e.getMessage());
                retry = (executionCount > 0) && retryHandler.retryRequest(cause, ++executionCount, context);
            } catch (NullPointerException e) {
                // 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);
            } catch (IOException e) {
                if (isCancelled()) {
                    // Eating exception, as the request was cancelled
                    return;
                }
                cause = e;
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            }
            if (retry && (responseHandler != null)) {
                responseHandler.sendRetryMessage(executionCount);
            }
        }
    } catch (Exception e) {
        // catch anything else to ensure failure message is propagated
        Log.e("AsyncHttpRequest", "Unhandled exception origin cause", e);
        cause = new IOException("Unhandled exception: " + e.getMessage());
    }

    // cleaned up to throw IOException
    throw (cause);
}

From source file:com.wen.security.http.AsyncHttpRequest.java

private void makeRequestWithRetries() throws IOException {
    boolean retry = true;
    IOException cause = null;//  www.j  a  v a  2 s .c o  m
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    try {
        while (retry) {
            try {
                makeRequest();
                return;
            } catch (UnknownHostException e) {
                // switching between WI-FI and mobile data networks can cause a retry which then results in an UnknownHostException
                // while the WI-FI is initialising. The retry logic will be invoked here, if this is NOT the first retry
                // (to assist in genuine cases of unknown host) which seems better than outright failure
                cause = new IOException("UnknownHostException exception: " + e.getMessage());
                retry = (executionCount > 0) && retryHandler.retryRequest(cause, ++executionCount, context);
            } catch (NullPointerException e) {
                // 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);
            } catch (IOException e) {
                if (isCancelled()) {
                    // Eating exception, as the request was cancelled
                    return;
                }
                cause = e;
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            }
            if (retry && (responseHandler != null)) {
                responseHandler.sendRetryMessage(executionCount);
            }
        }
    } catch (Exception e) {
        // catch anything else to ensure failure message is propagated
        Log.e("AsyncHttpRequest", "Unhandled exception origin cause", e);
        cause = new IOException("Unhandled exception: " + e.getMessage());
    }
    // cleaned up to throw IOException
    throw (cause);
}

From source file:org.squidy.nodes.tracking.CameraConfigComm.java

public void sendParameter(String name, String type, String value) {
    if (!initDone) {
        try {/*from  w w w.  j a v  a 2s  .c  o m*/
            initConnection();
        } catch (UnknownHostException e1) {
            if (LOG.isErrorEnabled()) {
                LOG.error(e1.getMessage(), e1);
            }
            System.out.println("Could not connect to Camera on " + addressOutgoing + " : " + portOutgoing);
            return;
        }
    }
    OSCBundle bundle = new OSCBundle();
    OSCMessage param = new OSCMessage("/config/param");

    param.addArgument(id);
    param.addArgument(1);
    param.addArgument("set");
    param.addArgument(name);
    param.addArgument(type);
    param.addArgument(value);
    bundle.addPacket(param);
    int len = bundle.getByteArray().length;

    if (name.equals("stream_image") && value.equals("true")) {

        //init imageServer
        if (imageServer == null) {
            try {
                imageServer = new ServerSocket(imageServerPort);
            } catch (IOException e) {
                e.printStackTrace();
                imageServer = null;
            }
        }
        if (imageListener == null) {
            imageListener = new ImageListener(imageServer, this);
            imageListener.start();
        }
    }

    //send
    try {
        oscPortOut.send(bundle);
    } catch (IOException e) {
        throw new ProcessException(e.getMessage(), e);
    }

    /*
    if (name.equals("stream_image") && value.equals("true")) {
       try {
    imageServer.close();         
    imageServer = new ServerSocket(imageServerPort);
       } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
       }
       imageListener = new ImageListener(imageServer, this);
       if (!this.isAlive())
    this.start();
       else
    this.resume();
            
    } else if (name.equals("stream_image") && value.equals("false")) {
       try {
    imageServer.close();
    imageServer = new ServerSocket(imageServerPort);
    if (this.isAlive())
       this.suspend();
            
       } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
       }
    } else {
       try {
    oscPortOut.send(bundle);
       } catch (IOException e) {
    throw new ProcessException(e.getMessage(), e);
       }
    }
    */
    id++;

}

From source file:uk.ac.ebi.arrayexpress.jobs.ReloadBiosamplesJob.java

public void doExecute(JobExecutionContext jec) throws Exception {
    logger.info("Reloading all Biosamples data into the Application Server");
    File setupDirectory = null;/* w  ww  . ja  v a2  s.c  o m*/
    File backDir = null;
    //File globalSetupDBDirectory = null;
    File setupTempDirectory = null;
    String hostname = "NA";
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        logger.error("Host not available-> " + e.getMessage());
    }
    try {

        // Thread.currentThread().sleep(30000);//sleep for 1000 ms

        boolean updateActive = Application.getInstance().getPreferences().getBoolean("bs.xmlupdate.active");
        logger.info("Is Reloading Active?->" + updateActive);

        if (!updateActive) {
            logger.error("ReloadBiosamplesJob is trying to execute and the configuration does not allow that");
            this.getApplication().sendEmail(null, null, hostname + "->" + "BIOSAMPLES: WARNING",
                    "ReloadBiosamplesJob is trying to execute and the configuration does not allow that!");
            // throw new
            // Exception("ReloadBiosamplesJob is trying to execute and the configuration does not allow that!");
            return;
        }

        // I will create a backup directory, where I will backup the Actual
        // Setup directory, where I will put the new biosamples.xml and
        // where I will creste a new SetupDirectory based on the new
        // biosamples.xml
        String setupDir = Application.getInstance().getPreferences().getString("bs.setupDirectory");
        logger.info("setupDir->" + setupDir);

        setupDirectory = new File(setupDir);
        String backupDirectory = Application.getInstance().getPreferences().getString("bs.backupDirectory");
        logger.info("backupDirectory->" + backupDirectory);

        String globalSetupDir = Application.getInstance().getPreferences().getString("bs.globalSetupDirectory");
        logger.info("globalSetupDirectory->" + globalSetupDir);
        File globalSetupDirectory = new File(globalSetupDir);

        String globalSetupDBDir = Application.getInstance().getPreferences()
                .getString("bs.globalSetupDBDirectory");
        logger.info("globalSetupDBDirectory->" + globalSetupDBDir);

        String globalSetupLuceneDir = Application.getInstance().getPreferences()
                .getString("bs.globalSetupLuceneDirectory");
        logger.info("globalSetupLuceneDir->" + globalSetupLuceneDir);

        //globalSetupDBDirectory=new File(globalSetupDBDir);

        String dbname = Application.getInstance().getPreferences().getString("bs.xmldatabase.dbname");
        String dbPathDirectory = Application.getInstance().getPreferences().getString("bs.xmldatabase.path");
        File dbDirectory = new File(dbPathDirectory + File.separator + dbname);
        logger.debug("dbPathDirectory->" + dbDirectory);

        // this variable will be used in the creation of the bakup
        // directory anda in the creation od the database backup
        Long tempDir = System.nanoTime();

        String newDir = "backup_" + tempDir;
        backDir = new File(backupDirectory + File.separator + newDir);
        if (backDir.mkdir()) {
            logger.info("Backup directory was created in [{}]", backDir.getAbsolutePath());

        } else {
            // TODO: rpe stop the process
            logger.error("Backup directory was NOT created in [{}]", backDir.getAbsolutePath());
            throw new Exception(
                    hostname + "->" + "Backup directory was NOT created in " + backDir.getAbsolutePath());
        }

        // DownloadBiosamplesXmlFileFromAGE dxml = new
        // DownloadBiosamplesXmlFileFromAGE();
        // I need to know which type of biosample updting process am I using
        String typeBioSampleUpdate = Application.getInstance().getPreferences().getString("bs.xmlupdate.type");
        logger.debug("Type of Biosamples updating process->" + typeBioSampleUpdate);
        IDownloadBiosamplesXmlFile dxml = DownloadBiosamplesXmlFileFactory
                .createDownloadBiosamplesXmlFile(typeBioSampleUpdate);
        File xmlDir = new File(backDir.getAbsolutePath() + "/XmlDownload");
        if (xmlDir.mkdir()) {
            logger.info("XmlDownload  directory was created in [{}]", xmlDir.getAbsolutePath());
        } else {
            logger.error("XmlDownload directory was NOT created in [{}]", xmlDir.getAbsolutePath());
            throw new Exception(
                    hostname + "->" + "XmlDownload  directory was NOT created in " + xmlDir.getAbsolutePath());
        }
        String downloadDirectory = xmlDir.getAbsolutePath();
        boolean downloadOk = dxml.downloadXml(downloadDirectory);

        if (downloadOk) {

            File oldSetupDir = new File(backDir.getAbsolutePath() + "/OldSetup");
            if (oldSetupDir.mkdir()) {
                logger.info("OldSetup Backup directory was created in [{}]", oldSetupDir.getAbsolutePath());
                copyDirectory(setupDirectory, oldSetupDir);
            } else {
                logger.error("OldSetup Backup directory was NOT created in [{}]",
                        oldSetupDir.getAbsolutePath());
                throw new Exception(hostname + "->" + "oldSetupDir Backup directory was NOT created in "
                        + oldSetupDir.getAbsolutePath());
            }

            // update of the xmlDatabase
            logger.info("DatabaseXml Creation");

            // File newSetupDir= new File(backDir.getAbsolutePath() +
            // "/newSetup" );
            // I need to change this because it's not possible to move
            // directories from a local disk (/tomcat/temp to NFS). So my
            // all temporary Setup will be created in the same place where
            // is th Setup Directory)
            // getParentFile() to create at the same level of Setup
            // directory
            File newSetupDir = new File(setupDirectory.getParentFile().getAbsolutePath() + "/newSetup");

            if (newSetupDir.exists()) {
                // I will force the delete of the NewSetupDir (I need this
                // because if for any reason the process fails once (before
                // it renames nesSetup to Setup), the next time the process
                // will always fail because the newSetup already exists
                FileUtils.forceDelete(newSetupDir);
            }
            if (newSetupDir.mkdir()) {
                logger.info("newSetupDir  directory was created in [{}]", newSetupDir.getAbsolutePath());
            } else {
                logger.error("newSetupDir directory was NOT created in [{}]", newSetupDir.getAbsolutePath());
                throw new Exception(hostname + "->" + "newSetupDir  directory was NOT created in "
                        + newSetupDir.getAbsolutePath());
            }

            // update in a temporary database
            // index it in the newSetupDir
            updateXMLDatabase(xmlDir, newSetupDir, tempDir);
            logger.info("End of DatabaseXml Creation");
            // only after update the database I update the Lucenes Indexes
            logger.info("Deleting Setup Directory and renaming - from now on the application is not answering");

            SearchEngine search = ((SearchEngine) getComponent("SearchEngine"));

            // I need to close the IndexReader otherwise it would not be
            // possible dor me to delete the Setup directory (this problem
            // only occurs on NFS);
            search.getController().getEnvironment("biosamplesgroup").closeIndexReader();
            search.getController().getEnvironment("biosamplessample").closeIndexReader();

            // remove the old setupdirectory /tmp/Setup is deleted
            deleteDirectory(setupDirectory);

            // Rename file (or directory) /tmp/newSetup->  /tmp/Setup
            logger.info("Before file renamed!!!");
            boolean success2 = newSetupDir.renameTo(setupDirectory);
            File globalSetupLuceneDirectory = new File(globalSetupDir + File.separator + globalSetupLuceneDir);
            if (success2) {
                logger.info("newSetupDir was successfully renamed to [{}]!!!",
                        setupDirectory.getAbsolutePath());
                // need to remove the globalSetupDirectory e copy the new
                // one to there
                if (globalSetupLuceneDirectory.exists()) {
                    FileUtils.forceDelete(globalSetupLuceneDirectory);
                } else {
                    logger.info("globalSetupLuceneDirectory doesnt exist!! [{}]!!!",
                            globalSetupLuceneDirectory.getAbsolutePath());
                }

            } else {
                logger.error("newSetupDir was not successfully renamed to [{}]!!!",
                        setupDirectory.getAbsolutePath());
                throw new Exception(hostname + "->" + "newSetupDir was not successfully renamed to ->"
                        + setupDirectory.getAbsolutePath());
            }
            logger.info("Deleting Setup Directory and renaming - End");

            // I do this to know the number of elements
            ((BioSamplesGroup) getComponent("BioSamplesGroup")).reloadIndex();
            // TODO: rpe nowaday I need to do this to clean the xmldatabase
            // connection nad to reload the new index
            ((IndexEnvironmentBiosamplesGroup) search.getController().getEnvironment("biosamplesgroup"))
                    .setup();

            ((BioSamplesSample) getComponent("BioSamplesSample")).reloadIndex();
            // TODO: rpe nowadays I need to do this to clean the xmldatabase
            // connection nad to reload the new index
            ((IndexEnvironmentBiosamplesSample) search.getController().getEnvironment("biosamplessample"))
                    .setup();

            //Copy the data to GlobalSETUP (doing this here to reduce the downtime            
            FileUtils.copyDirectory(setupDirectory, globalSetupLuceneDirectory);
            logger.info("XML DB was copied to globalSetupLuceneDirectory !! [{}]!!!",
                    globalSetupLuceneDirectory.getAbsolutePath());
            //I will also copy there the XML DB               
            File newSetupDBDir = new File(
                    dbDirectory.getParentFile().getAbsolutePath() + File.separator + dbname);

            File globalSetupDBDirectory = new File(globalSetupDir + File.separator + globalSetupDBDir);
            if (globalSetupDBDirectory.exists()) {
                FileUtils.forceDelete(globalSetupDBDirectory);
            } else {
                logger.info("globalSetupDBDirectory doesnt exist!! [{}]!!!",
                        globalSetupDBDirectory.getAbsolutePath());
                throw new Exception(hostname + "->" + "globalSetupDBDirectory doesnt exist!! ->"
                        + globalSetupDBDirectory.getAbsolutePath());
            }

            if (newSetupDBDir.exists()) {
                FileUtils.copyDirectory(newSetupDBDir, globalSetupDBDirectory);
                logger.info("XML DB was copied to globalSetupDBDirectory !! [{}]!!!",
                        globalSetupDBDirectory.getAbsolutePath());
            } else {
                logger.error("New Xml DB doesnt exist!! [{}]!!!", newSetupDBDir.getAbsolutePath());
                throw new Exception(
                        hostname + "->" + "New Xml DB doesnt exist!!->" + newSetupDBDir.getAbsolutePath());
            }

            //send an email saying that everything is ok (with some stats)
            this.getApplication().sendEmail(null, null,
                    hostname + "->" + "BIOSAMPLES: RELOAD samplegroups-> + "
                            + ((IndexEnvironmentBiosamplesGroup) search
                                    .getController().getEnvironment("biosamplesgroup")).getCountDocuments()
                            + " samples->"
                            + ((IndexEnvironmentBiosamplesSample) search.getController()
                                    .getEnvironment("biosamplessample")).getCountDocuments(),
                    "ReloadBiosamplesJob is finished!");

        } else {
            logger.debug("Something went wrong on Xml download");
            throw new Exception(hostname + "->" + " Something went wrong on Xml download");

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {

    }
    logger.info("End of Reloading all Biosamples data into the Application Server");

    // I want to start using the new version of the data
    // (/Users/rpslpereira/Apps/apache-tomcat-6.0.33/temp/StagingArea/4)
}

From source file:com.clustercontrol.notify.util.SendSyslog.java

/**
 * ???syslog?????/*www .jav a2 s. c  o  m*/
 * NotifyLogEscalateInfoData ? EscalateFacilityFlg ?ExecFacilityConstant.TYPE_GENERATION??
 * ?????outputInfo?null??????????
 *
 * @param outputInfo 
 * @param logEscalateInfo 
 * @return ??IP
 */
private List<InetAddress> getIpAddresses(OutputBasicInfo outputInfo,
        NotifyLogEscalateInfoData logEscalateInfo) {

    // ?
    ArrayList<InetAddress> ipAddresses = new ArrayList<InetAddress>();
    //?(RepositoryControllerLocal)?
    try {
        String facilityId = null;

        // 
        if (logEscalateInfo.getEscalateFacilityFlg() == ExecFacilityConstant.TYPE_FIX) {
            // ??????ID?????
            facilityId = logEscalateInfo.getEscalateFacility();
        } else {
            // ???
            if (outputInfo == null) {
                // NotifyLogEscalateInfoData ? EscalateFacilityFlg ?ExecFacilityConstant.TYPE_GENERATION??
                // ?????outputInfo?null??????????
                return ipAddresses;
            } else {
                facilityId = outputInfo.getFacilityId();
            }
        }

        ArrayList<String> facilityIdList = new RepositoryControllerBean()
                .getExecTargetFacilityIdList(facilityId, logEscalateInfo.getOwnerRoleId());

        for (String targetFacilityId : facilityIdList) {
            FacilityInfo facility = new RepositoryControllerBean().getFacilityEntityByPK(targetFacilityId);
            try {
                ipAddresses.add(getInetAdress(facility));
            } catch (UnknownHostException e) {
                m_log.info("getIpAddresses() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
                // ?????
            }
        }

        return ipAddresses;
    } catch (Exception e) {
        m_log.warn("getIpAddresses() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
        // ????????
        return null;
    }
}

From source file:org.pentaho.di.trans.steps.http.HTTP.java

private Object[] callHttpService(RowMetaInterface rowMeta, Object[] rowData) throws KettleException {
    String url = determineUrl(rowMeta, rowData);
    try {/*from  w  w w  .j a va2  s. c om*/
        if (isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "HTTP.Log.Connecting", url));
        }

        // Prepare HTTP get
        //
        HttpClient httpclient = SlaveConnectionManager.getInstance().createHttpClient();
        HttpMethod method = new GetMethod(url);

        // Set timeout
        if (data.realConnectionTimeout > -1) {
            httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(data.realConnectionTimeout);
        }
        if (data.realSocketTimeout > -1) {
            httpclient.getHttpConnectionManager().getParams().setSoTimeout(data.realSocketTimeout);
        }

        if (!Const.isEmpty(data.realHttpLogin)) {
            httpclient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(data.realHttpLogin,
                    data.realHttpPassword);
            httpclient.getState().setCredentials(AuthScope.ANY, defaultcreds);
        }

        HostConfiguration hostConfiguration = new HostConfiguration();
        if (!Const.isEmpty(data.realProxyHost)) {
            hostConfiguration.setProxy(data.realProxyHost, data.realProxyPort);
        }

        // Add Custom HTTP headers
        if (data.useHeaderParameters) {
            for (int i = 0; i < data.header_parameters_nrs.length; i++) {
                method.addRequestHeader(data.headerParameters[i].getName(),
                        data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]));
                if (isDebug()) {
                    log.logDebug(BaseMessages.getString(PKG, "HTTPDialog.Log.HeaderValue",
                            data.headerParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])));
                }
            }
        }

        InputStreamReader inputStreamReader = null;
        Object[] newRow = null;
        if (rowData != null) {
            newRow = rowData.clone();
        }
        // Execute request
        //
        try {
            // used for calculating the responseTime
            long startTime = System.currentTimeMillis();

            int statusCode = httpclient.executeMethod(hostConfiguration, method);

            // calculate the responseTime
            long responseTime = System.currentTimeMillis() - startTime;
            if (log.isDetailed()) {
                log.logDetailed(BaseMessages.getString(PKG, "HTTP.Log.ResponseTime", responseTime, url));
            }

            String body = null;
            // The status code
            if (isDebug()) {
                logDebug(BaseMessages.getString(PKG, "HTTP.Log.ResponseStatusCode", "" + statusCode));
            }

            if (statusCode != -1) {
                if (statusCode == 204) {
                    body = "";
                } else {
                    // if the response is not 401: HTTP Authentication required
                    if (statusCode != 401) {
                        // guess encoding
                        //
                        String encoding = meta.getEncoding();

                        // Try to determine the encoding from the Content-Type value
                        //
                        if (Const.isEmpty(encoding)) {
                            String contentType = method.getResponseHeader("Content-Type").getValue();
                            if (contentType != null && contentType.contains("charset")) {
                                encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "")
                                        .replace("\"", "").trim();
                            }
                        }

                        if (isDebug()) {
                            log.logDebug(toString(),
                                    BaseMessages.getString(PKG, "HTTP.Log.ResponseHeaderEncoding", encoding));
                        }

                        // the response
                        if (!Const.isEmpty(encoding)) {
                            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(),
                                    encoding);
                        } else {
                            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream());
                        }
                        StringBuffer bodyBuffer = new StringBuffer();

                        int c;
                        while ((c = inputStreamReader.read()) != -1) {
                            bodyBuffer.append((char) c);
                        }

                        inputStreamReader.close();

                        body = bodyBuffer.toString();
                        if (isDebug()) {
                            logDebug("Response body: " + body);
                        }

                    } else { // the status is a 401
                        throw new KettleStepException(
                                BaseMessages.getString(PKG, "HTTP.Exception.Authentication", data.realUrl));

                    }
                }
            }

            int returnFieldsOffset = rowMeta.size();
            if (!Const.isEmpty(meta.getFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
                returnFieldsOffset++;
            }

            if (!Const.isEmpty(meta.getResultCodeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode));
                returnFieldsOffset++;
            }
            if (!Const.isEmpty(meta.getResponseTimeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
            }

        } finally {
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            // Release current connection to the connection pool once you are done
            method.releaseConnection();
            if (data.realcloseIdleConnectionsTime > -1) {
                httpclient.getHttpConnectionManager().closeIdleConnections(data.realcloseIdleConnectionsTime);
            }
        }
        return newRow;
    } catch (UnknownHostException uhe) {
        throw new KettleException(
                BaseMessages.getString(PKG, "HTTP.Error.UnknownHostException", uhe.getMessage()));
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "HTTP.Log.UnableGetResult", url), e);
    }
}

From source file:org.jboss.tools.discovery.core.internal.connectors.xpl.RemoteExternalBundleDiscoveryStrategy.java

protected Map<File, Entry> loadRegistry(File storageDirectory, IProgressMonitor monitor) throws CoreException {

    // new SubProgressMonitor(monitor, ticksTenPercent * 3);

    final int totalTicks = 100000;
    final int ticksTenPercent = totalTicks / 10;

    monitor.beginTask("Remote discovery", totalTicks);

    Directory directory;//w ww .  j a  v  a 2  s  .c  om

    try {
        final Directory[] temp = new Directory[1];
        final URI uri = new URI(directoryUrl);
        WebUtil.readResource(uri, new TextContentProcessor() {
            public void process(Reader reader) throws IOException {
                DirectoryParser parser = new DirectoryParser();
                parser.setBaseUri(uri);
                temp[0] = parser.parse(reader);
            }
        }, new SubProgressMonitor(monitor, ticksTenPercent));
        directory = temp[0];
        if (directory == null) {
            throw new IllegalStateException();
        }
    } catch (UnknownHostException e) {
        throw new CoreException(new Status(IStatus.ERROR, DiscoveryCore.ID_PLUGIN,
                NLS.bind(
                        "Cannot access {0}: unknown host: please check your Internet connection and try again.",
                        e.getMessage()),
                e));
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, DiscoveryCore.ID_PLUGIN,
                "IO failure: cannot load discovery directory", e));
    } catch (URISyntaxException e) {
        throw new CoreException(new Status(IStatus.ERROR, DiscoveryCore.ID_PLUGIN,
                "IO failure: cannot load discovery directory", e));
    }
    if (monitor.isCanceled()) {
        return null;
    }
    if (directory.getEntries().isEmpty()) {
        throw new CoreException(
                new Status(IStatus.ERROR, DiscoveryCore.ID_PLUGIN, "Discovery directory is empty"));
    }

    Map<File, Directory.Entry> bundleFileToDirectoryEntry = new HashMap<File, Directory.Entry>();

    ExecutorService executorService = createExecutorService(directory.getEntries().size());
    try {
        List<Future<DownloadBundleJob>> futures = new ArrayList<Future<DownloadBundleJob>>();
        // submit jobs
        for (Directory.Entry entry : directory.getEntries()) {
            futures.add(executorService.submit(new DownloadBundleJob(entry, storageDirectory, monitor)));
        }
        int futureSize = ticksTenPercent * 4 / directory.getEntries().size();
        // collect job results
        for (Future<DownloadBundleJob> job : futures) {
            try {
                DownloadBundleJob bundleJob;
                for (;;) {
                    try {
                        bundleJob = job.get(1L, TimeUnit.SECONDS);
                        break;
                    } catch (TimeoutException e) {
                        if (monitor.isCanceled()) {
                            return null;
                        }
                    }
                }
                if (bundleJob.file != null) {
                    bundleFileToDirectoryEntry.put(bundleJob.file, bundleJob.entry);
                }
                monitor.worked(futureSize);
            } catch (ExecutionException e) {
                Throwable cause = e.getCause();
                if (cause instanceof OperationCanceledException) {
                    monitor.setCanceled(true);
                    return null;
                }
                IStatus status;
                if (cause instanceof CoreException) {
                    status = ((CoreException) cause).getStatus();
                } else {
                    status = new Status(IStatus.ERROR, DiscoveryCore.ID_PLUGIN, "Unexpected error", cause);
                }
                // log errors but continue on
                StatusHandler.log(status);
            } catch (InterruptedException e) {
                monitor.setCanceled(true);
                return null;
            }
        }
    } finally {
        executorService.shutdownNow();
    }
    return bundleFileToDirectoryEntry;
}

From source file:com.loopj.android.AsyncHttpRequest.java

private void makeRequestWithRetries() throws IOException {
    boolean retry = true;
    IOException cause = null;/*from ww  w. j a  v  a 2 s.c om*/
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    try {
        while (retry) {
            try {
                makeRequest();
                return;
            } catch (UnknownHostException e) {
                // switching between WI-FI and mobile data networks can cause a retry
                // which then results in an UnknownHostException
                // while the WI-FI is initialising. The retry logic will be invoked
                // here, if this is NOT the first retry
                // (to assist in genuine cases of unknown host) which seems better
                // than outright failure
                cause = new IOException("UnknownHostException exception: " + e.getMessage());
                retry = (executionCount > 0) && retryHandler.retryRequest(cause, ++executionCount, context);
            } catch (NullPointerException e) {
                // 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);
            } catch (IOException e) {
                cause = e;
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            }
            if (retry && (responseHandler != null)) {
                responseHandler.sendRetryMessage();
            }
        }
    } catch (Exception e) {
        // catch anything else to ensure failure message is propagated
        Log.e("AsyncHttpRequest", "Unhandled exception origin cause", e);
        cause = new IOException("Unhandled exception: " + e.getMessage());
    }

    // cleaned up to throw IOException
    throw (cause);
}

From source file:de.unwesen.web.DownloadCache.java

private void processQueue(Thread thread) {
    while (true) {
        // Grab and process next item on the queue
        CacheItem info = mFetcherQueue.poll();
        if (null == info) {
            break;
        }/*ww  w.ja v  a 2  s.c  o  m*/

        // Check whether file exists.
        String filename = getCacheFileName(info.mDownloadUri);
        File cachefile = new File(filename);
        if (cachefile.exists()) {
            // Log.d(LTAG, "Url is already downloaded and cached.");
            info.mFilename = filename;
            info.sendMessage(CACHE_SUCCESS);
            continue;
        }

        // Download file.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(info.mDownloadUri.toString());
        try {
            HttpResponse response = httpClient.execute(request);

            // Log non-200 response codes, return a link failure
            if (200 != response.getStatusLine().getStatusCode()) {
                Log.w(LTAG, "Could not retrieve URI: " + info.mDownloadUri);
                info.sendMessage(CACHE_LINK_FAILURE);
                continue;
            }

            InputStream istream = response.getEntity().getContent();

            // Create path for cache file.
            String pathname = cachefile.getParentFile().getPath();
            File path = new File(pathname);
            if (!path.exists() && !path.mkdirs()) {
                Log.e(LTAG, "Could not create cache directory '" + pathname + "'!");
                info.sendMessage(CACHE_FAILURE);
                continue;
            }

            // Write to temporary file. XXX temp_filename assumes the same download
            // isn't started more than once in the same millisecond - fairly safe,
            // but not foolproof. It's safe insofar as the DownloadCache class
            // itself does not download in parallel.
            String temp_filename = filename + "." + System.currentTimeMillis();
            File tempfile = new File(temp_filename);
            // Log.d(LTAG, "Downloading to temporary location '" + tempfile.getAbsolutePath() + "'...");
            if (!copyFile(temp_filename, istream)) {
                info.sendMessage(CACHE_FAILURE);
                continue;
            }

            // Now move the temp file over to filename.
            if (!tempfile.renameTo(cachefile)) {
                Log.e(LTAG, "Could not finalize download!");
                info.sendMessage(CACHE_FAILURE);
                continue;
            }

            // Final check.
            if (!cachefile.exists()) {
                Log.e(LTAG, "Unknown error when retrieving file from cache.");
                info.sendMessage(CACHE_FAILURE);
                continue;
            }

            // Success!
            info.mFilename = cachefile.getPath();
            info.sendMessage(CACHE_SUCCESS);

        } catch (java.net.UnknownHostException ex) {
            Log.w(LTAG, "Unknown host: " + ex.getMessage());
            info.sendMessage(CACHE_TEMP_LINK_FAILURE);
        } catch (Exception ex) {
            Log.e(LTAG, "Could not download '" + info.mDownloadUri + "': " + ex.getMessage());
            info.sendMessage(CACHE_LINK_FAILURE);
        } catch (OutOfMemoryError ex) {
            Log.e(LTAG, "Out of memory: " + ex.getMessage());
            info.sendMessage(CACHE_LINK_FAILURE);
        }
    }

    // Finally, clear the least recently used items.
    //  mLRUThread.interrupt();
    //clearLRU();
}

From source file:io.logspace.agent.hq.HqAgentController.java

@Override
public void update(Date nextFireTime) {
    try {// w w  w .  j  a va  2  s  .c  o m
        this.uploadCapabilities();
    } catch (UnknownHostException uhex) {
        this.logger.error(
                "Could not upload capabilities because the HQ was not available: {} - Will retry at {}",
                uhex.getMessage(), nextFireTime);
        // no need to try downloading as well
        return;
    } catch (NoRouteToHostException nrthex) {
        this.logger.error(
                "Could not upload capabilities because the HQ was not available: {} - Will retry at {}",
                nrthex.getMessage(), nextFireTime);
        // no need to try downloading as well
        return;
    } catch (ConnectException cex) {
        this.logger.error(
                "Could not upload capabilities because the HQ was not available: {} - Will retry at {}",
                cex.getMessage(), nextFireTime);
        // no need to try downloading as well
        return;
    } catch (IOException ioex) {
        this.logger.error("Failed to upload capabilities. Will retry at " + nextFireTime, ioex);
    }

    try {
        this.downloadOrder();
    } catch (ConnectException cex) {
        this.logger.error("Could not download orders because the HQ was not available: {} - Will retry at {}",
                cex.getMessage(), nextFireTime);
    } catch (HttpResponseException hrex) {
        if (hrex.getStatusCode() == HTTP_NOT_FOUND) {
            this.logger.error("There was no order available: {} - Will retry at {}", hrex.getMessage(),
                    nextFireTime);
        } else if (hrex.getStatusCode() == HTTP_FORBIDDEN) {
            this.logger.error("Not allowed to download order: {} - Will retry at {}", hrex.getMessage(),
                    nextFireTime);
        } else {
            this.logger.error("Failed to download order. Will retry at {}", nextFireTime, hrex);
        }
    } catch (IOException ioex) {
        this.logger.error("Failed to download order. Will retry at {}", nextFireTime, ioex);
    }
}