Example usage for java.net UnknownHostException printStackTrace

List of usage examples for java.net UnknownHostException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.mule.modules.mymulelogger.MyLogger.java

/**
 * This is EnterpriseLogger constructor which takes logger Name, service
 * name as inputs/*  w ww.j  a  va  2  s  .  co  m*/
 * 
 * @param loggerName
 * @param serviceName
 */

public MyLogger(String loggerName, String serviceName) {
    //EnterpriseServiceConfig serviceConfig = null;
    if (null != loggerName) {
        MDC.put(MyLoggerConstants.LOGGER_NAME, loggerName);
    }
    if (null != serviceName) {
        MDC.put(MyLoggerConstants.SERVICE_NAME, serviceName);
    }

    try {
        MDC.put(MyLoggerConstants.NODE_NAME, InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {

        enterpriseLogger.error("Error while getting the NodeName in EnterpriseLogger.java Class", e);
    }

    try {
        File file = new File("common_logger_module.properties");
        FileInputStream fileInput = new FileInputStream(file);
        properties = new Properties();
        properties.load(fileInput);
        fileInput.close();

        Enumeration<?> enuKeys = properties.keys();
        while (enuKeys.hasMoreElements()) {
            String key = (String) enuKeys.nextElement();
            String value = properties.getProperty(key);
            System.out.println(key + ": " + value);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (null != properties) {
        Logger.getRootLogger().getLoggerRepository().resetConfiguration();
        String IS_CONSOLE_APPENDER_ENABLE = properties.getProperty("es.common.logger.enable.appender.console");
        String IS_FILE_APPENDER_ENABLE = properties.getProperty("es.common.logger.enable.appender.file");
        //String IS_DATABASE_APPENDER_ENABLE = properties.getProperty("es.common.logger.enable.appender.db");
        String SERVICE_LEVEL = properties.getProperty("es.common.logger.log.level." + serviceName);

        // This default logger code will be used for mule log statements.
        // This can be configured from service config properties.
        common_logger_code = properties.getProperty(MyLoggerConstants.ES_DEFAULT_MULE_LOGGING_CODE);
        if (null != common_logger_code) {
            MDC.put(MyLoggerConstants.PROCESS_STATE, common_logger_code);
        }

        if (null != SERVICE_LEVEL) {
            // setting log level for the interface from zuul properties
            serviceLevel = Level.toLevel(properties.getProperty("es.common.logger.log.level." + serviceName));
        }

        // Set log level to specified packages
        // Set All Log level packages
        String allLevelPackages = properties.getProperty(MyLoggerConstants.ALL_LOG_LEVEL_PACKAGES);
        if (null != allLevelPackages) {
            String strKeyArray[] = allLevelPackages.split(",");
            for (int i = 0; i < strKeyArray.length; i++) {
                Logger.getLogger(strKeyArray[i]).setLevel(Level.ALL);
            }
        }

        // Set Trace Log level packages
        String traceLevelPackages = properties.getProperty(MyLoggerConstants.TRACE_LOG_LEVEL_PACKAGES);
        if (null != traceLevelPackages) {
            String strKeyArray[] = traceLevelPackages.split(",");
            for (int i = 0; i < strKeyArray.length; i++) {
                Logger.getLogger(strKeyArray[i]).setLevel(Level.TRACE);
            }
        }

        // Set Debug Log level packages
        String debugLevelPackages = properties.getProperty(MyLoggerConstants.DEBUG_LOG_LEVEL_PACKAGES);
        if (null != debugLevelPackages) {
            String strKeyArray[] = debugLevelPackages.split(",");
            for (int i = 0; i < strKeyArray.length; i++) {
                Logger.getLogger(strKeyArray[i]).setLevel(Level.DEBUG);
            }
        }

        // Set INFO Log level packages
        String infoLevelPackages = properties.getProperty(MyLoggerConstants.INFO_LOG_LEVEL_PACKAGES);
        if (null != infoLevelPackages) {
            String strKeyArray[] = infoLevelPackages.split(",");
            for (int i = 0; i < strKeyArray.length; i++) {
                Logger.getLogger(strKeyArray[i]).setLevel(Level.INFO);
            }
        }

        // Set Warn Log level packages
        String warnLevelPackages = properties.getProperty(MyLoggerConstants.WARN_LOG_LEVEL_PACKAGES);
        if (null != warnLevelPackages) {
            String strKeyArray[] = warnLevelPackages.split(",");
            for (int i = 0; i < strKeyArray.length; i++) {
                Logger.getLogger(strKeyArray[i]).setLevel(Level.WARN);
            }
        }

        // Set Error Log level packages
        String errorLevelPackages = properties.getProperty(MyLoggerConstants.ERROR_LOG_LEVEL_PACKAGES);
        if (null != errorLevelPackages) {
            String strKeyArray[] = errorLevelPackages.split(",");
            for (int i = 0; i < strKeyArray.length; i++) {
                Logger.getLogger(strKeyArray[i]).setLevel(Level.ERROR);
            }
        }

        // Set Fatal Log level packages
        String fatalLevelPackages = properties.getProperty(MyLoggerConstants.FATAL_LOG_LEVEL_PACKAGES);
        if (null != fatalLevelPackages) {
            String strKeyArray[] = fatalLevelPackages.split(",");
            for (int i = 0; i < strKeyArray.length; i++) {
                Logger.getLogger(strKeyArray[i]).setLevel(Level.FATAL);
            }
        }

        // Set Off Log level packages
        String offLevelPackages = properties.getProperty(MyLoggerConstants.OFF_LOG_LEVEL_PACKAGES);
        if (null != offLevelPackages) {
            String strKeyArray[] = offLevelPackages.split(",");
            for (int i = 0; i < strKeyArray.length; i++) {
                Logger.getLogger(strKeyArray[i]).setLevel(Level.OFF);
            }
        }

        if (null != IS_CONSOLE_APPENDER_ENABLE && IS_CONSOLE_APPENDER_ENABLE.equalsIgnoreCase("true")) {

            String setConsoleConversionPattern = properties
                    .getProperty("es.common.logger.enable.appender.console.conversion.pattern");
            if (null != setConsoleConversionPattern) {
                setConsoleAppender(setConsoleConversionPattern, serviceLevel);

            }
        }
        if (null != IS_FILE_APPENDER_ENABLE && IS_FILE_APPENDER_ENABLE.equalsIgnoreCase("true")) {
            String setFileConversionPattern = properties
                    .getProperty("es.common.logger.enable.appender.file.conversion.pattern");
            String setFileDatePattern = properties
                    .getProperty("es.common.logger.enable.appender.file.date.pattern");
            String setMaxLogFileSize = properties.getProperty("es.common.logger.enable.appender.file.max.size");
            String maxBackupIndex = properties.getProperty("es.common.logger.enable.appender.file.max.backup");
            // setting the default number of log file backups to 100, this
            // can be configured from zuul otherwise
            int setMaxBackupIndex = 100;
            if (maxBackupIndex.length() > 0) {
                try {
                    setMaxBackupIndex = Integer.parseInt(maxBackupIndex);
                } catch (NumberFormatException numFormatException) {
                    enterpriseLogger.log(Level.toLevel(MyLoggerConstants.ERROR),
                            numFormatException.getMessage());
                }
            }
            String fileLocation = properties.getProperty("es.common.logger.enable.appender.file.location")
                    + serviceName + ".log";

            if (null != fileLocation && null != setFileDatePattern) {
                setDailyFileAsAppender(fileLocation, setFileConversionPattern, setFileDatePattern,
                        setMaxLogFileSize, setMaxBackupIndex, serviceLevel);
            }
        }

    }
}

From source file:ac.dynam.rundeck.plugin.resources.ovirt.InstanceToNodeMapper.java

/**
 * Convert an oVirt Instance to a RunDeck INodeEntry based on the mapping input
 *///  w  w  w . j a va 2s.  c  om
@SuppressWarnings("unchecked")
static INodeEntry instanceToNode(final VM inst) throws GeneratorException {
    final NodeEntryImpl node = new NodeEntryImpl();

    node.setNodename(inst.getName());
    node.setOsArch(inst.getCpu().getArchitecture());
    node.setOsName(inst.getOs().getType());
    node.setDescription(inst.getDescription());
    node.setUsername("root");
    InetAddress address = null;
    if (inst.getGuestInfo() != null) {
        try {
            address = InetAddress.getByName(inst.getGuestInfo().getFqdn());
            logger.debug("Host " + node.getNodename() + " Guest FQDN " + inst.getGuestInfo().getFqdn()
                    + " Address: " + address.getHostName());
            if (address.getHostName() == "localhost")
                throw new UnknownHostException();
        } catch (UnknownHostException e) {
            /* try the first IP instead then */
            logger.warn("Host " + node.getNodename() + " address " + inst.getGuestInfo().getFqdn()
                    + " does not resolve. Trying IP addresses instead");
            for (int i = 0; i < inst.getGuestInfo().getIps().getIPs().size(); i++) {
                logger.debug("Host " + node.getNodename() + " Trying "
                        + inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                try {
                    address = InetAddress.getByName(inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                    if (address != null) {
                        if (address.isLinkLocalAddress() || address.isMulticastAddress()) {
                            logger.warn("Host " + node.getNodename() + " ip address is not valid: "
                                    + inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                            continue;
                        }
                        logger.debug("Host " + node.getNodename() + " ip address " + address.getHostAddress()
                                + " will be used instead");
                        break;
                    }
                } catch (UnknownHostException e1) {
                    logger.warn("Host " + node.getNodename() + " IP Address "
                            + inst.getGuestInfo().getIps().getIPs().get(i).getAddress() + " is invalid");
                }
            }
        }
    }
    if (address == null) {
        /* try resolving based on name */
        try {
            address = InetAddress.getByName(node.getNodename());
        } catch (UnknownHostException e) {
            logger.warn("Unable to Find IP address for Host " + node.getNodename());
            return null;
        }
    }

    if (address != null)
        node.setHostname(address.getCanonicalHostName());

    if (inst.getTags() != null) {
        VMTags tags = inst.getTags();
        final HashSet<String> tagset = new HashSet<String>();
        try {
            for (int j = 0; j < tags.list().size(); j++) {
                tagset.add(tags.list().get(j).getName());
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (null == node.getTags()) {
            node.setTags(tagset);
        } else {
            final HashSet<String> orig = new HashSet<String>(node.getTags());
            orig.addAll(tagset);
            node.setTags(orig);
        }
    }

    if (inst.getHighAvailability().getEnabled())
        node.setAttribute("HighAvailability", "true");
    if (inst.getType() != null)
        node.setAttribute("Host Type", inst.getType());
    node.setAttribute("oVirt VM", "true");
    node.setAttribute("oVirt Host", inst.getHost().getName());

    return node;
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * The "times" are the inter-packet intervals at which to run the test. Ideally these should be
 * based on the model constructed by the server, a default assumed value is used in their absence.
 * /*ww w  .ja  v  a 2  s .co  m*/
 * <ol>
 * <li>vSend a packet to initiate the RRC state desired.</li>
 * <li>Create a randomly generated host name (to ensure that the host name is not cached). I found
 * on some devices that even when you clear the cache manually, the data remains in the cache.</li>
 * <li>Time how long it took to look it up.</li>
 * <li>Count the total packets sent, globally on the phone. If more packets were sent than</li>
 * expected, abort and try again. </li>
 * <li>Otherwise, save the data for that test and move to the next inter-packet interval.</li>
 * </ol>
 * 
 * Test is similar to the approach taken in DnsLookUpTask.java.
 * 
 * @param times List of inter-packet intervals, in half-second increments, at which to run the
 *        test
 * @param desc Stores parameters for the RRC inference tests in general
 * @throws MeasurementError
 */

public void runDnsTest(final Integer[] times, RRCDesc desc) throws MeasurementError {
    Logger.d("Active inference DNS test: about to begin");
    if (times.length != desc.dnsTest.length) {
        desc.dnsTest = new int[times.length];
    }

    long startTime = 0;
    long endTime = 0;

    // For each inter-packet interval...
    for (int i = 0; i < times.length; i++) {
        // On a failure, try again until a threshold is reached.
        for (int j = 0; j < desc.GIVEUP_THRESHHOLD; j++) {

            // Sometimes the network can change in the middle of a test
            checkIfWifi();
            if (stopFlag) {
                throw new MeasurementError("Cancelled");
            }

            /*
             * We keep track of the packets sent at the beginning and end of the test so we can detect
             * if there is competing traffic anywhere on the phone.
             */

            PacketMonitor packetMonitor = new PacketMonitor();

            // Initiate the desired RRC state by sending a large enough packet
            // to go to DCH and waiting for the specified amount of time
            try {
                InetAddress serverAddr;
                serverAddr = InetAddress.getByName(desc.echoHost);
                sendPacket(serverAddr, desc.MAX, desc);
                waitTime(times[i] * desc.GRANULARITY, true);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                continue;
            } catch (UnknownHostException e) {
                e.printStackTrace();
                continue;
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }

            // Create a random URL, to avoid the caching problem
            UUID uuid = UUID.randomUUID();
            String host = uuid.toString() + ".com";
            // Start measuring the time to complete the task
            startTime = System.currentTimeMillis();
            try {
                @SuppressWarnings("unused")
                InetAddress serverAddr = InetAddress.getByName(host);
            } catch (UnknownHostException e) {
                // we do this on purpose! Since it's a fake URL the lookup will fail
            }
            // When we fail to find the URL, we stop timing
            endTime = System.currentTimeMillis();

            // Check how many packets were sent again. If the expected number
            // of packets were sent, we can finish and go to the next task.
            // Otherwise, we have to try again.
            if (!packetMonitor.isTrafficInterfering(5, 5)) {
                break;
            }

            startTime = 0;
            endTime = 0;
        }

        // If we broke out of the try-again loop, the last set of results are
        // valid and we can save them.
        long rtt = endTime - startTime;
        try {
            desc.setDns(i, (int) rtt);
        } catch (MeasurementError e) {
            e.printStackTrace();
        }
        Logger.d("Time for DNS" + rtt);
    }
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Due to problems with how we detect interfering traffic, this test does not always work and
 * results should be treated with caution. I am keeping this test around, though, as we can still
 * get data on how much HTTP handshakes vary in how long they take.
 * /*from  w w w  .  j  ava  2  s  .co  m*/
 * The "times" are the inter-packet intervals at which to run the test. Ideally these should be
 * based on the model constructed by the server, a default assumed value is used in their absence.
 * 
 * Based on the time it takes to load a response from the page.
 * 
 * This test is not currently as accurate as the other tests, for reasons described below, and has
 * thus been disabled.
 * 
 * @param times List of inter-packet intervals, in half-second increments, at which to run the
 *        tests
 * @param desc Stores parameters for the RRC inference tests in general
 * @throws MeasurementError
 */
private void runHTTPTest(final Integer[] times, RRCDesc desc) throws MeasurementError {
    /*
     * Length of time it takes to request and read in a page.
     */

    Logger.d("Active inference HTTP test: about to begin");
    if (times.length != desc.httpTest.length) {
        desc.httpTest = new int[times.length];
    }
    long startTime = 0;
    long endTime = 0;
    try {
        for (int i = 0; i < times.length; i++) {
            // We try until we reach a threshhold or until there is no
            // competing traffic.
            for (int j = 0; j < desc.GIVEUP_THRESHHOLD; j++) {
                // Sometimes the network can change in the middle of a test
                checkIfWifi();
                if (stopFlag) {
                    throw new MeasurementError("Cancelled");
                }

                /*
                 * We keep track of the packets sent at the beginning and end of the test so we can detect
                 * if there is competing traffic anywhere on the phone.
                 */
                PacketMonitor packetMonitor = new PacketMonitor();

                // Initiate the desired RRC state by sending a large enough packet
                // to go to DCH and waiting for the specified amount of time
                try {
                    InetAddress serverAddr;
                    serverAddr = InetAddress.getByName(desc.echoHost);
                    sendPacket(serverAddr, desc.MAX, desc);

                    waitTime(times[i] * desc.GRANULARITY, true);

                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                    continue;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    continue;
                } catch (IOException e) {
                    e.printStackTrace();
                    continue;
                }
                startTime = System.currentTimeMillis();
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();

                request.setURI(new URI("http://" + desc.target + "?dummy=" + i + "" + j));

                HttpResponse response = client.execute(request);
                endTime = System.currentTimeMillis();

                BufferedReader in = null;
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String line = "";

                while ((line = in.readLine()) != null) {
                    sb.append(line + "\n");
                }
                in.close();

                // not really accurate, just rules out the worst cases of interference
                if (!packetMonitor.isTrafficInterfering(100, 100)) {
                    break;
                }
                startTime = 0;
                endTime = 0;

            }

            long rtt = endTime - startTime;
            try {
                desc.setHttp(i, (int) rtt);
            } catch (MeasurementError e) {
                e.printStackTrace();
            }
            Logger.d("Time for Http" + rtt);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:com.corebase.android.framework.http.client.AsyncHttpRequest.java

private void makeRequestWithRetries() throws IOException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See:/*from   w w w.  jav a  2 s.  com*/
    // https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            makeRequest();
            return;
        } catch (UnknownHostException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(mycontext, e, "can't resolve host");
            }
            Log.i("msg", "1");
            return;
        } catch (SocketException e) {
            // Added to detect host unreachable
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(mycontext, e, "can't resolve host");
            }
            Log.i("msg", "2");
            return;
        } catch (SocketTimeoutException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(mycontext, e, "socket time out");
            }
            Log.i("msg", "3");
            return;
        } catch (IOException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            Log.i("msg", "4");
        } 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());
            Log.i("msg", "4");
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (Exception e) {
            e.printStackTrace();
            cause = new IOException("Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            Log.i("msg", "4");
        }
    }

    // ??
    // ConnectException ex = new ConnectException();
    // ex.initCause(cause);
    throw cause;
}

From source file:org.apache.hadoop.hive.service.HSSessionItem.java

public HSSessionItem(HSAuth auth, String sessionName, TTransport trans) throws FileNotFoundException {

    this.jobid = 0;
    this.auth = auth;
    this.sessionName = sessionName;
    this.home = ".";
    this.runable = null;
    this.jr = null;
    this.config = new SessionConfig(jobType.ONESHOT);
    this.jobStatus = HSSessionItem.JobStatus.INIT;
    this.date = new Date();
    this.opdate = this.date;
    if (SessionState.get() != null) {
        this.to = SessionState.get().getConf().getIntVar(HiveConf.ConfVars.HIVESESSIONTIMEOUT);
        if (this.to > 7200 || this.to < 0) {
            this.to = 60;
        }/*from ww  w .j  a  v a  2  s .co  m*/
    } else {
        this.to = 7200;
    }

    this.transSet = new HashSet();
    if (trans != null)
        transSet.add(trans);
    l4j.debug("HSSessionItem created");
    status = SessionItemStatus.NEW;

    l4j.debug("Wait for NEW->READY transition");
    l4j.debug("NEW->READY transition complete");

    queryInfo = new HashMap<Integer, GregorianCalendar>();
    this.current_query_count = 0;

    InetAddress localhost = null;
    try {
        localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    if (localhost != null)
        hostip = localhost.getHostAddress();

    try {
        TSocket tSocket = (TSocket) trans;
        Socket socket = tSocket.getSocket();
        InetAddress addr = socket.getInetAddress();
        this.clientip = addr.getHostAddress();
        l4j.debug("client address: " + addr.getHostAddress() + " client port: " + socket.getPort());
    } catch (Exception e) {
        l4j.debug("get IP, PORT failed in create session");
    }

    if ((conf_file_loc == null) || conf_file_loc.length() == 0) {
        return;
    }

    File f = new File(conf_file_loc);
    if (!f.exists()) {
        if (!f.mkdir()) {
            return;
        }
    }

    try {
        sessionFileName = conf_file_loc + "/" + sessionName + ".txt";
        File thefile = new File(sessionFileName);
        if (!thefile.exists()) {
            dayLogStream = new PrintWriter(new FileWriter(sessionFileName, true));
        } else {
            dayLogStream = new PrintWriter(new FileWriter(sessionFileName, true));
            dayLogStream.print("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            dayLogStream.print('\n');
            dayLogStream.print("A new session is appended here!  ");
            dayLogStream.print('\n');
            Calendar rightNow = Calendar.getInstance();
            Date time = rightNow.getTime();
            dayLogStream.print(time.toString());
            dayLogStream.print('\n');
            dayLogStream.print("+++++++++++++++++++++++++++++++++++++++++++++++++++");
            dayLogStream.print('\n');
        }
    } catch (Exception ex) {
    }
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public Thread videoUploadToFTPserver(final Activity activity, final Handler handler,
        final String latestVideoFile_filename, final String latestVideoFile_absolutepath,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doVideoFTP starting");

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();

    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // FTP; connect preferences here!
            ////from   ww  w . j  a v  a2 s . co m
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
            String ftpHostName = prefs.getString("defaultFTPhostPreference", null);
            String ftpUsername = prefs.getString("defaultFTPusernamePreference", null);
            String ftpPassword = prefs.getString("defaultFTPpasswordPreference", null);

            // use name of local file.
            String ftpRemoteFtpFilename = latestVideoFile_filename;

            // FTP
            FTPClient ftpClient = new FTPClient();
            InetAddress uploadhost = null;
            try {

                uploadhost = InetAddress.getByName(ftpHostName);
            } catch (UnknownHostException e1) {
                // If DNS resolution fails then abort immediately - show
                // dialog to
                // inform user first.
                e1.printStackTrace();
                Log.e(TAG, " got exception resolving " + ftpHostName + " - video uploading failed.");
                uploadhost = null;
            }

            if (uploadhost == null) {

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_find_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                })

                                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();

                    }
                }, 0);

                return;
            }

            boolean connected = false;

            try {
                ftpClient.connect(uploadhost);
                connected = true;

            } catch (SocketException e) {
                e.printStackTrace();
                connected = false;

            } catch (UnknownHostException e) {
                //
                e.printStackTrace();
                connected = false;
            } catch (IOException e) {
                //
                e.printStackTrace();
                connected = false;
            }

            if (!connected) {

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                })

                                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();

                    }
                }, 0);

                return;
            }

            boolean reply = false;
            try {

                reply = ftpClient.login(ftpUsername, ftpPassword);
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp.login - video uploading failed.");
            }

            // check the reply code here
            // If we cant login, abort after showing user a dialog.
            if (!reply) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    //
                    e.printStackTrace();
                }

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();
                    }
                }, 0);

                return;
            }

            // Set File type to binary
            try {
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            } catch (IOException e) {
                //
                e.printStackTrace();
                // keep going?!
            }

            // BEYOND HERE DONT USE DIALOGS!

            // Construct the input stream to send to Ftp server, from the
            // local
            // video file on the sd card
            BufferedInputStream buffIn = null;
            File file = new File(latestVideoFile_absolutepath);

            try {
                buffIn = new BufferedInputStream(new FileInputStream(file));
            } catch (FileNotFoundException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on local video file - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);

                // This is a bad error, lets abort.
                // user dialog ?! shouldnt happen, but still...
                return;
            }

            ftpClient.enterLocalPassiveMode();

            try {
                // UPLOAD THE LOCAL VIDEO FILE.
                ftpClient.storeFile(ftpRemoteFtpFilename, buffIn);
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on storeFile - video uploading failed.");

                // This is a bad error, lets abort.
                // user dialog ?! shouldnt happen, but still...
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                buffIn.close();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on buff.close - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                ftpClient.logout();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp logout - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp disconnect - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }

            if (emailAddress != null && ftpHostName != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + ftpHostName, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, ftpHostName, ftpHostName, "");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(true);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_ftp_host_succeeded_));

                }
            }, 0);

        }
    });

    t.start();

    return t;
}

From source file:ntpclock.kamalan.com.utility.NTPClient.java

/**
 * Process <code>TimeInfo</code> object and print its details.
 * @param info <code>TimeInfo</code> object.
 *//*  w  ww.  j av a  2s. c  om*/
public static Date processResponse(TimeInfo info) {

    NtpV3Packet message = info.getMessage();
    int stratum = message.getStratum();
    String refType;
    if (stratum <= 0) {
        refType = "(Unspecified or Unavailable)";
    } else if (stratum == 1) {
        refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
    } else {
        refType = "(Secondary Reference; e.g. via NTP or SNTP)";
    }
    // stratum should be 0..15...
    System.out.println(" Stratum: " + stratum + " " + refType);
    int version = message.getVersion();
    int li = message.getLeapIndicator();
    System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision());

    System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");
    int poll = message.getPoll();
    // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
    System.out.println(
            " poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")");
    double disp = message.getRootDispersionInMillisDouble();
    System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
            + ", rootdispersion(ms): " + numberFormat.format(disp));

    int refId = message.getReferenceId();
    String refAddr = NtpUtils.getHostAddress(refId);
    String refName = null;
    if (refId != 0) {
        if (refAddr.equals("127.127.1.0")) {
            refName = "LOCAL"; // This is the ref address for the Local Clock
        } else if (stratum >= 2) {
            // If reference id has 127.127 prefix then it uses its own reference clock
            // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
            // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
            if (!refAddr.startsWith("127.127")) {
                try {
                    InetAddress addr = InetAddress.getByName(refAddr);
                    String name = addr.getHostName();
                    if (name != null && !name.equals(refAddr)) {
                        refName = name;
                    }
                } catch (UnknownHostException e) {
                    // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2)
                    // ref not valid host maybe it's a reference clock name?
                    // otherwise just show the ref IP address.
                    refName = NtpUtils.getReferenceClock(message);
                }
            }
        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
            refName = NtpUtils.getReferenceClock(message);
            // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
        }
        // otherwise give up on naming the beast...
    }
    if (refName != null && refName.length() > 1) {
        refAddr += " (" + refName + ")";
    }
    System.out.println(" Reference Identifier:\t" + refAddr);

    TimeStamp refNtpTime = message.getReferenceTimeStamp();
    System.out.println(" Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();
    System.out.println(" Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString());

    long destTime = info.getReturnTime();
    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
    System.out.println(" Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
    System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString());

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
    System.out.println(" Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString());

    info.computeDetails(); // compute offset/delay if not already done
    Long offsetValue = info.getOffset();
    Long delayValue = info.getDelay();
    String delay = (delayValue == null) ? "N/A" : delayValue.toString();
    String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

    System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset in ms

    // convert date string to java util.date format
    // sample: Wed, Jul 16 2014 05:00:00.070
    Date date = null;
    try {
        //            Log.e("NTPClient", destNtpTime.toDateString());
        date = new SimpleDateFormat("EEE, MMM dd yyyy hh:mm:ss.SSS").parse(destNtpTime.toDateString());
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return date;
}

From source file:com.todoroo.astrid.taskrabbit.TaskRabbitActivity.java

@SuppressWarnings("nls")
protected void submitTaskRabbit() {

    if (!Preferences.isSet(TASK_RABBIT_TOKEN)) {
        loginTaskRabbit();//ww  w. ja  v  a 2  s . c  om
    } else if (!supportsSelectedLocation()) {
        Message successMessage = new Message();
        successMessage.what = MESSAGE_CODE_LOCATION_FAILURE;
        handler.sendMessage(successMessage);
    } else {

        if (progressDialog == null)
            progressDialog = DialogUtilities.progressDialog(this, getString(R.string.DLG_please_wait));
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean success = false;

                String urlCall = "tasks/";
                if (taskRabbitTask.getTaskID() > 0)
                    urlCall += taskRabbitTask.getTaskID();
                urlCall += String.format("?client_id=%s&client_application=%s", TASK_RABBIT_CLIENT_ID,
                        TASK_RABBIT_CLIENT_APPLICATION_ID);
                Header authorization = new BasicHeader("Authorization",
                        "OAuth " + Preferences.getStringValue(TASK_RABBIT_TOKEN));
                Header contentType = new BasicHeader("Content-Type", "application/json");
                HttpEntity taskBody = getTaskBody();
                String response = null;
                try {
                    response = restClient.post(taskRabbitURL(urlCall), taskBody, contentType, authorization);
                    Log.e("The response", "The post response: " + response);
                    JSONObject taskResponse = new JSONObject(response);
                    if (taskResponse.has(TASK_RABBIT_ID)) {
                        taskRabbitTask.setRemoteTaskData(response);
                        taskRabbitTask.setTaskID(taskResponse.optString(TASK_RABBIT_ID));
                        Message successMessage = new Message();
                        successMessage.what = MESSAGE_CODE_SUCCESS;
                        handler.sendMessage(successMessage);
                        success = true;
                    }
                } catch (UnknownHostException e) {
                    Message failureMessage = new Message();
                    failureMessage.what = MESSAGE_CODE_INTERNET_FAILURE;
                    handler.sendMessage(failureMessage);
                } catch (Exception e) {
                    Message failureMessage = new Message();
                    failureMessage.what = MESSAGE_CODE_FAILURE;
                    handler.sendMessage(failureMessage);
                } finally {
                    StatisticsService.reportEvent(StatisticsConstants.TASK_RABBIT_POST, "success",
                            new Boolean(success).toString());
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (progressDialog != null) {
                                DialogUtilities.dismissDialog(TaskRabbitActivity.this, progressDialog);
                            }
                        }
                    });
                }
            }
        }).start();

    }
    try {
        taskRabbitTask.setLocalTaskData(serializeToJSON().toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    //submit!
}