Example usage for java.io IOException toString

List of usage examples for java.io IOException toString

Introduction

In this page you can find the example usage for java.io IOException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:at.jps.sanction.model.queue.file.FileQueue.java

private IBigQueue createQueue() {

    try {/*from ww w  .j a va  2s . com*/
        this.messageQueue = new BigQueueImpl(getBasePath(), getName());

        if (logger.isInfoEnabled()) {
            logger.info("Queue created (BigQueueImpl, " + getBasePath() + "/" + getName() + ")");
        }

        if (isPurgeQueuesOnStartup()) {
            if (logger.isInfoEnabled()) {
                logger.info("CLEANUP Queue !!");
            }
            clear();
        }

    } catch (final IOException e) {
        logger.error("Queue creation failed (BigQueueImpl," + getBasePath() + "/" + getName() + ") :"
                + e.toString());
        logger.debug("Exception: ", e);
    }

    return this.messageQueue;
}

From source file:io.confluent.support.metrics.BaseMetricsReporter.java

void submitMetrics() {
    byte[] encodedMetricsRecord = null;
    GenericContainer metricsRecord = metricsCollector.collectMetrics();
    try {/*from  ww  w.  j  ava2 s . c o m*/
        encodedMetricsRecord = encoder.serialize(metricsRecord);
    } catch (IOException e) {
        log.error("Could not serialize metrics record: {}", e.toString());
    }

    try {
        if (sendToKafkaEnabled() && encodedMetricsRecord != null) {
            // attempt to create the topic. If failures occur, try again in the next round, however
            // the current batch of metrics will be lost.
            if (kafkaUtilities.createAndVerifyTopic(zkClientProvider().zkClient(), supportTopic,
                    SUPPORT_TOPIC_PARTITIONS, SUPPORT_TOPIC_REPLICATION, RETENTION_MS)) {
                kafkaSubmitter.submit(encodedMetricsRecord);
            }
        }
    } catch (RuntimeException e) {
        log.error("Could not submit metrics to Kafka topic {}: {}", supportTopic, e.getMessage());
    }

    try {
        if (sendToConfluentEnabled() && encodedMetricsRecord != null) {
            confluentSubmitter.submit(encodedMetricsRecord);
        }
    } catch (RuntimeException e) {
        log.error("Could not submit metrics to Confluent: {}", e.getMessage());
    }
}

From source file:com.telefonica.iot.perseo.UtilsTest.java

/**
 * Test of DoHTTPPost method, of class Utils.
 *//*from w w w  . j av  a  2 s.  c om*/
@Test
public void testDoHTTPPost() {
    System.out.println("DoHTTPPost");
    InetSocketAddress address = new InetSocketAddress(Help.PORT);
    HttpServer httpServer = null;
    try {
        httpServer = HttpServer.create(address, 0);
        HttpHandler handler = new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                byte[] response = "OK\n".getBytes();
                exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
                exchange.getResponseBody().write(response);
                exchange.close();
            }
        };
        httpServer.createContext("/path", handler);
        httpServer.start();
        boolean result = Utils.DoHTTPPost(String.format("http://localhost:%d/path", Help.PORT), "xxxxx");
        assertEquals(true, result);
        result = Utils.DoHTTPPost(String.format("http://localhost:%d/notexist", Help.PORT), "xxxxx");
        assertEquals(false, result);
        result = Utils.DoHTTPPost("<<this is an invalid URL>>", "xxxxx");
        assertEquals(false, result);

    } catch (IOException ex) {
        Logger.getLogger(UtilsTest.class.getName()).log(Level.SEVERE, null, ex);
        fail(ex.toString());
    } finally {
        if (httpServer != null) {
            httpServer.stop(0);
        }
    }

}

From source file:com.yen.actiondevice.endapplications.VLCControl.java

public void connect() throws IOException {
    staticInstance = this; // used by reader to get input stream

    try {/*from ww  w . jav a  2  s .c  o m*/
        staticInstance.connect("localhost", VLC_PORT);

        Thread thread = new Thread(new VLCControl()); // starts the thread
        // to get the text
        // sent back from
        // VLC
        thread.start();
        staticInstance.registerNotifHandler(this); // notifications call
        // back to logger
        Runtime.getRuntime().addShutdownHook(new Thread() { // shutdown hook
            // here makes
            // sure to
            // disconnect
            // cleanly, as
            // long as we
            // are not
            // terminated

            @Override
            public void run() {
                try {
                    if (isConnected()) {
                        disconnect();
                    }
                } catch (IOException ex) {
                    log.warning(ex.toString());
                }
            }
        });
    } catch (IOException e) {
        log.warning(
                "couldn't connect to VLC - you may need to start VLC with command line \"vlc --rc-host=localhost:4444\"");
        throw new IOException(e);
    }
}

From source file:it.tidalwave.northernwind.core.impl.util.CachedURIResolver.java

/*******************************************************************************************************************
 *
 ******************************************************************************************************************/
private void cacheDocument(final @Nonnull File cachedFile, final @Nonnull String href) throws IOException {
    log.debug(">>>> caching external document to {}", cachedFile);
    final File tempFile = File.createTempFile("temp", ".txt", new File(cacheFolderPath));
    tempFile.deleteOnExit();/*from   w  w  w  .  j  a v a 2 s . c o m*/
    log.debug(">>>> waiting for lock...");

    try (final FileChannel channel = new RandomAccessFile(tempFile, "rw").getChannel();
            final FileLock lock = channel.lock()) {
        log.debug(">>>> got lock: {}", lock);
        FileUtils.copyURLToFile(new URL(href), tempFile, connectionTimeout, readTimeout);
        rename(tempFile, cachedFile);
    } catch (IOException e) {
        if (cachedFile.exists()) {
            log.warn("Error while retrieving document from {}: {} - using previously cached file", href,
                    e.toString());
        } else {
            throw e;
        }
    }

    log.debug(">>>> done");
}

From source file:com.cloudera.sqoop.manager.SQLServerManagerImportManualTest.java

private void runSQLServerTest(String[] expectedResults) throws IOException {

    Path warehousePath = new Path(this.getWarehouseDir());
    Path tablePath = new Path(warehousePath, TABLE_NAME);
    Path filePath = new Path(tablePath, "part-m-00000");

    File tableFile = new File(tablePath.toString());
    if (tableFile.exists() && tableFile.isDirectory()) {
        // remove the directory before running the import.
        FileListing.recursiveDeleteDir(tableFile);
    }//from  w  w  w.j  a v a2 s.c  o m

    String[] argv = getArgv();
    try {
        runImport(argv);
    } catch (IOException ioe) {
        LOG.error("Got IOException during import: " + ioe.toString());
        ioe.printStackTrace();
        fail(ioe.toString());
    }

    File f = new File(filePath.toString());
    assertTrue("Could not find imported data file", f.exists());
    BufferedReader r = null;
    try {
        // Read through the file and make sure it's all there.
        r = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
        for (String expectedLine : expectedResults) {
            assertEquals(expectedLine, r.readLine());
        }
    } catch (IOException ioe) {
        LOG.error("Got IOException verifying results: " + ioe.toString());
        ioe.printStackTrace();
        fail(ioe.toString());
    } finally {
        IOUtils.closeStream(r);
    }
}

From source file:com.cubusmail.server.mail.security.MailboxLoginModule.java

public boolean login() throws LoginException {

    if (this.callbackHandler == null) {
        log.fatal("callbackHandler is null");
        throw new LoginException(IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED);
    }/*from w  w  w.ja  va  2 s.com*/

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username");
    callbacks[1] = new PasswordCallback("Password", false);

    try {
        this.callbackHandler.handle(callbacks);
        String username = ((NameCallback) callbacks[0]).getName();

        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
        if (tmpPassword == null) {
            // treat a NULL password as an empty password
            tmpPassword = new char[0];
        }
        char[] password = new char[tmpPassword.length];
        System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
        ((PasswordCallback) callbacks[1]).clearPassword();

        // start authentication
        // TODO: very dirty, must be replaced by Spring Security stuff
        ApplicationContext context = WebApplicationContextUtils
                .getRequiredWebApplicationContext(SessionManager.getRequest().getSession().getServletContext());
        MailboxFactory factory = context.getBean(MailboxFactory.class);
        IMailbox mailbox = factory.createMailbox(IMailbox.TYPE_IMAP);
        mailbox.init(username, new String(password));

        log.debug("Start login...");
        mailbox.login();
        log.debug("Login successful");

        this.mailboxPrincipal = new MailboxPrincipal(username, mailbox);
        this.succeeded = true;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        log.error(uce.getMessage(), uce);
        throw new LoginException(IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED);
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        mapMessagingException(e);
    }

    return this.succeeded;
}

From source file:com.denimgroup.threadfix.importer.impl.remoteprovider.utils.RemoteProviderHttpUtilsImpl.java

@Override
public HttpResponse getUrlWithConfigurer(String url, RequestConfigurer configurer) {
    assert url != null;
    assert configurer != null;

    GetMethod get = new GetMethod(url);

    get.setRequestHeader("Content-type", "text/xml; charset=UTF-8");

    configurer.configure(get);/*from ww  w  . j  a  v a2 s .c o  m*/

    HttpClient client = getConfiguredHttpClient(classInstance);

    int status = -1;

    try {
        status = client.executeMethod(get);

        if (status != 200) {
            LOG.warn("Status wasn't 200, it was " + status);
            return HttpResponse.failure(status, get.getResponseBodyAsStream());
        } else {
            return HttpResponse.success(status, get.getResponseBodyAsStream());
        }

    } catch (IOException e) {
        LOG.error("Encountered IOException while making request in " + classInstance.getName() + ". "
                + e.toString());
        throw new RestException(e, e.toString());
    }
}

From source file:com.tethrnet.manage.socket.SecureShellWS.java

@OnMessage
public void onMessage(String message) {

    if (session.isOpen()) {

        if (StringUtils.isNotEmpty(message)) {

            Map jsonRoot = new Gson().fromJson(message, Map.class);

            String command = (String) jsonRoot.get("command");

            Integer keyCode = null;
            Double keyCodeDbl = (Double) jsonRoot.get("keyCode");
            if (keyCodeDbl != null) {
                keyCode = keyCodeDbl.intValue();
            }//  w w  w.  j  a  v  a 2 s . c  om

            for (String idStr : (ArrayList<String>) jsonRoot.get("id")) {
                Integer id = Integer.parseInt(idStr);

                //get servletRequest.getSession() for user
                UserSchSessions userSchSessions = SecureShellAction.getUserSchSessionMap().get(sessionId);
                if (userSchSessions != null) {
                    SchSession schSession = userSchSessions.getSchSessionMap().get(id);
                    if (keyCode != null) {
                        if (keyMap.containsKey(keyCode)) {
                            try {
                                schSession.getCommander().write(keyMap.get(keyCode));
                            } catch (IOException ex) {
                                log.error(ex.toString(), ex);
                            }
                        }
                    } else {
                        schSession.getCommander().print(command);
                    }
                }

            }
            //update timeout
            AuthUtil.setTimeout(httpSession);

        }
    }

}

From source file:edu.usf.cutr.opentripplanner.android.pois.GooglePlaces.java

public JSONObject requestPlaces(String paramLocation, String paramRadius, String paramName) {
    StringBuilder builder = new StringBuilder();

    String encodedParamLocation = "";
    String encodedParamRadius = "";
    String encodedParamName;//from   ww  w .  j a v  a2 s . c o  m
    try {
        if ((paramLocation != null) && (paramRadius != null)) {
            encodedParamLocation = URLEncoder.encode(paramLocation, OTPApp.URL_ENCODING);
            encodedParamRadius = URLEncoder.encode(paramRadius, OTPApp.URL_ENCODING);
        }
        encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING);
    } catch (UnsupportedEncodingException e1) {
        Log.e(OTPApp.TAG, "Error encoding Google Places request");
        e1.printStackTrace();
        return null;
    }

    if ((paramLocation != null) && (paramRadius != null)) {
        request += "location=" + encodedParamLocation;
        request += "&radius=" + encodedParamRadius;
        request += "&query=" + encodedParamName;
    } else {
        request += "query=" + encodedParamName;
    }
    request += "&sensor=false";
    request += "&key=" + getApiKey();

    Log.d(OTPApp.TAG, request);

    HttpURLConnection urlConnection = null;

    try {
        URL url = new URL(request);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT);
        urlConnection.connect();
        int status = urlConnection.getResponseCode();

        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e(OTPApp.TAG, "Error obtaining Google Places response, status code: \" + status");
        }
    } catch (IOException e) {
        Log.e(OTPApp.TAG, "Error obtaining Google Places response" + e.toString());
        e.printStackTrace();
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    Log.d(OTPApp.TAG, builder.toString());

    JSONObject json = null;
    try {
        json = new JSONObject(builder.toString());
    } catch (JSONException e) {
        Log.e(OTPApp.TAG, "Error parsing Google Places data " + e.toString());
    }

    return json;
}