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:com.nubits.nubot.pricefeeds.ExchangeratelabPriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;// w  w  w  .java2 s .co m
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.severe(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            JSONArray array = (JSONArray) httpAnswerJson.get("rates");

            String lookingfor = pair.getOrderCurrency().getCode().toUpperCase();

            boolean found = false;
            double rate = -1;
            for (int i = 0; i < array.size(); i++) {
                JSONObject temp = (JSONObject) array.get(i);
                String tempCurrency = (String) temp.get("to");
                if (tempCurrency.equalsIgnoreCase(lookingfor)) {
                    found = true;
                    rate = Utils.getDouble((Double) temp.get("rate"));
                    rate = Utils.round(1 / rate, 8);
                }
            }

            lastRequest = System.currentTimeMillis();

            if (found) {

                lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                        new Amount(rate, pair.getPaymentCurrency()));
                return lastPrice;
            } else {
                LOG.warning("Cannot find currency " + lookingfor + " on feed " + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } catch (Exception ex) {
            LOG.severe(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.fine("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}

From source file:com.nubits.nubot.pricefeeds.feedservices.ExchangeratelabPriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;/*from   w w w  . j a v a 2 s .  c om*/
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.error(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            JSONArray array = (JSONArray) httpAnswerJson.get("rates");

            String lookingfor = pair.getOrderCurrency().getCode().toUpperCase();

            boolean found = false;
            double rate = -1;
            for (int i = 0; i < array.size(); i++) {
                JSONObject temp = (JSONObject) array.get(i);
                String tempCurrency = (String) temp.get("to");
                if (tempCurrency.equalsIgnoreCase(lookingfor)) {
                    found = true;
                    rate = Utils.getDouble((Double) temp.get("rate"));
                    rate = Utils.round(1 / rate, 8);
                }
            }

            lastRequest = System.currentTimeMillis();

            if (found) {

                lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                        new Amount(rate, pair.getPaymentCurrency()));
                return lastPrice;
            } else {
                LOG.warn("Cannot find currency " + lookingfor + " on feed " + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } catch (Exception ex) {
            LOG.error(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.warn("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}

From source file:com.streamsets.pipeline.lib.parser.delimited.DelimitedDataParserFactory.java

private DataParser createParser(String id, OverrunReader reader, long offset) throws DataParserException {
    Utils.checkState(reader.getPos() == 0,
            Utils.formatL("reader must be in position '0', it is at '{}'", reader.getPos()));
    CSVFormat csvFormat = getSettings().getMode(CsvMode.class).getFormat();
    if (getSettings().getMode(CsvMode.class) == CsvMode.CUSTOM) {
        csvFormat = CSVFormat.DEFAULT// w w w. ja  va  2 s .  com
                .withDelimiter((char) getSettings().getConfig(DelimitedDataConstants.DELIMITER_CONFIG))
                .withEscape((char) getSettings().getConfig(DelimitedDataConstants.ESCAPE_CONFIG))
                .withQuote((char) getSettings().getConfig(DelimitedDataConstants.QUOTE_CONFIG));
    }
    try {
        return new DelimitedCharDataParser(getSettings().getContext(), id, reader, offset,
                (Integer) getSettings().getConfig(DelimitedDataConstants.SKIP_START_LINES), csvFormat,
                getSettings().getMode(CsvHeader.class), getSettings().getMaxRecordLen(),
                getSettings().getMode(CsvRecordType.class));
    } catch (IOException ex) {
        throw new DataParserException(Errors.DELIMITED_PARSER_00, id, offset, ex.toString(), ex);
    }
}

From source file:eu.morfeoproject.fast.catalogue.recommender.FPGrowth.java

public void rebuild() {
    log.info("Starting Sequential FPGrowth");
    int maxHeapSize = Integer.valueOf(params.get("maxHeapSize", "50"));
    int minSupport = Integer.valueOf(params.get("minSupport", "2"));

    try {/*from w ww. jav  a 2s.  c  o m*/
        String output = params.get("output", "fpgrowth-output.dat");
        Path path = new Path(output);
        FileSystem fs = FileSystem.get(this.conf);

        Charset encoding = Charset.forName(params.get("encoding"));
        String input = params.get("input");

        String pattern = params.get("splitPattern", PFPGrowth.SPLITTER.toString());

        SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, path, Text.class,
                TopKStringPatterns.class);

        org.apache.mahout.fpm.pfpgrowth.fpgrowth.FPGrowth<String> fp = new org.apache.mahout.fpm.pfpgrowth.fpgrowth.FPGrowth<String>();
        Set<String> features = new HashSet<String>();

        fp.generateTopKFrequentPatterns(
                new StringRecordIterator(new FileLineIterable(new File(input), encoding, false), pattern),
                fp.generateFList(new StringRecordIterator(
                        new FileLineIterable(new File(input), encoding, false), pattern), minSupport),
                minSupport, maxHeapSize, features,
                new StringOutputConverter(new SequenceFileOutputCollector<Text, TopKStringPatterns>(writer)),
                new ContextStatusUpdater(null));
        writer.close();

        if (log.isInfoEnabled()) {
            List<Pair<String, TopKStringPatterns>> frequentPatterns = org.apache.mahout.fpm.pfpgrowth.fpgrowth.FPGrowth
                    .readFrequentPattern(fs, conf, path);
            for (Pair<String, TopKStringPatterns> entry : frequentPatterns) {
                log.info("Dumping Patterns for Feature: " + entry.getFirst() + " \n"
                        + entry.getSecond().toString());
            }
        }
    } catch (IOException e) {
        log.error(e.toString(), e);
    }
}

From source file:org.starfishrespect.myconsumption.server.business.notifications.Notifier.java

private void sendNotification(PeriodStat dayStat, PeriodStat weekStat) {

    if (dayStat.getDiffLastTwo() == 0)
        return;//from  w  ww.  j  ava 2s. c om

    String sensorId = dayStat.getSensorId();
    String sensorName = mSensorRepository.getSensor(sensorId).getName();

    // Get the user associated to this sensor id
    List<User> users = mUserRepository.findBySensorId(sensorId);

    String msgNotif;

    // If the day consumption will lead to a week consumption greater/smaller by 15%
    if ((dayStat.getConsumption() * 7) > (weekStat.getConsumption() * threshold))
        msgNotif = "Your daily consumption is increasing for the sensor " + sensorName;
    else if ((dayStat.getConsumption() * 7 * threshold) < weekStat.getConsumption())
        msgNotif = "Your daily consumption is decreasing for the sensor " + sensorName;
    else
        return;

    for (User user : users) {
        if (user.getRegisterId() == null || user.getRegisterId().isEmpty())
            continue;

        NotificationSender sender = new NotificationSender(mApiKey);
        NotificationMessage message = new NotificationMessage.Builder().timeToLive(24 * 60 * 60 * 7) // A week in seconds
                .delayWhileIdle(true).collapseKey(sensorId).addData("message", msgNotif)
                .addData("sensor", sensorId).build();
        try {
            sender.sendNoRetry(message, user.getRegisterId());
        } catch (IOException e) {
            mLogger.error("Notification not sent: " + e.toString());
        }
    }
}

From source file:com.msopentech.ThaliClient.ProxyDesktop.java

public void initialize() throws URISyntaxException, IOException {
    // Initialize the relay - We find the root directory of the install and navigate down to the web directory
    File rootDirectoryOfInstall = new File(
            getClass().getProtectionDomain().getCodeSource().getLocation().getFile());
    String webPath = "web"; // For production
    //String webPath = "install/Java/web"; // For debugging from inside of intelliJ
    File webDirectory = rootDirectoryOfInstall.toPath().getParent().getParent().resolve(webPath).toFile();
    if (webDirectory.exists() == false) {
        throw new RuntimeException(
                "Either the web directory wasn't installed or we have the wrong location or you are debugging AND DIDN'T READ THE README.md!!!!!!!! - "
                        + webDirectory.getAbsolutePath());
    }//  w ww .j  av  a 2s  .  c om

    // Useful for debugging
    // webPath = new File(new File(System.getProperty("user.dir")).getParent(), "web").toPath();

    // This is sleezy, we should really have a function that gets us the httpkeys file and share that
    // function with the Java TDH but I really don't want to put in a cross project dependency to share
    // a few strings.
    File httpKeysFileDirectory = new File(System.getProperty("user.home"), ".thaliTdh");
    File httpKeysFile = new File(httpKeysFileDirectory, "httpkeys");
    if (httpKeysFile.exists() == false) {
        throw new RuntimeException("We can't find the httpkeys file! Someone start up the TDH!!!!");
    }
    ObjectMapper mapper = new ObjectMapper();
    HttpKeyTypes httpKeyTypes = mapper.readValue(httpKeysFile, HttpKeyTypes.class);

    try {
        server = new RelayWebServer(new JavaEktorpCreateClientBuilder(), webDirectory, httpKeyTypes, relayHost,
                relayPort);
    } catch (Exception e) {
        throw new RuntimeException("cannot start relay web server!", e);
    }

    // Initialize the local web server
    System.out.println("Setting web root to: " + webDirectory.getAbsolutePath());
    host = new SimpleWebServer("localhost", localWebserverPort, webDirectory, false);

    // Start both listeners
    try {
        System.out.println("Starting WebServer at http://localhost:" + localWebserverPort);
        host.start();

        System.out.println("Starting Relay on http://" + relayHost + ":" + relayPort);
        server.start();
    } catch (IOException ioe) {
        System.out.println("Exception: " + ioe.toString());
    }
    System.out.println("Started.");
}

From source file:com.streamsets.pipeline.lib.parser.text.TextDataParserFactory.java

private DataParser createParser(String id, OverrunReader reader, long offset) throws DataParserException {
    Utils.checkState(reader.getPos() == 0,
            Utils.formatL("reader must be in position '0', it is at '{}'", reader.getPos()));
    try {/*from ww  w. j a  va  2  s.c  o  m*/

        return new TextCharDataParser(getSettings().getContext(), id,
                getSettings().<Boolean>getConfig(MULTI_LINE_KEY),
                getSettings().<Boolean>getConfig(USE_CUSTOM_DELIMITER_KEY),
                StringEscapeUtils.unescapeJava(getSettings().<String>getConfig(CUSTOM_DELIMITER_KEY)),
                getSettings().<Boolean>getConfig(INCLUDE_CUSTOM_DELIMITER_IN_TEXT_KEY), reader, offset,
                getSettings().getMaxRecordLen(), TEXT_FIELD_NAME, TRUNCATED_FIELD_NAME, stringBuilderPool);
    } catch (IOException ex) {
        throw new DataParserException(Errors.TEXT_PARSER_00, id, offset, ex.toString(), ex);
    }
}

From source file:com.tussle.script.SubactionScriptSystem.java

public void update(float deltaTime) {
    //Fetch input, push it into the stream
    //Using stdin and stdout for now, will probably change later
    try {// ww w.  ja va 2s.c  o m
        stdinInterpreter.write(Utility.readAll(stdIn));
        if (stdinInterpreter.ready()) {
            stdInProcessor.write(stdinInterpreter.read());
        }
    } catch (IOException ex) {
        System.err.println(ex.toString());
    }
    super.update(deltaTime);
    try {
        StringBuilder outBuffer = new StringBuilder();
        while (stdOutProcessor.ready())
            outBuffer.append(stdOutProcessor.read().toString());
        String writeString = outBuffer.toString();

        StringBuilder errBuffer = new StringBuilder();
        while (stdErrProcessor.ready())
            errBuffer.append(stdErrProcessor.read().toString());
        String errorString = errBuffer.toString();
        stdOut.write(writeString);
        System.err.print(errorString);
    } catch (IOException ex) {
        System.err.println(ex.toString());
    }
    //Fetch output, pull it up to the screen
}

From source file:com.athena.meerkat.controller.web.provisioning.log.LogTailerListener.java

protected void stop() {
    this.tailer.stop();

    if (this.session != null && this.lastTailer) {
        try {/* w  w  w  .j av a2  s  .  c o m*/
            this.session.close();
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
    }

    stop = true;
    LOGGER.debug("tailer stop!!");
}

From source file:com.ibm.storlet.common.StorletContainerHandle.java

@SuppressWarnings("unchecked")
public StorletObjectOutputStream getObjectOutputStream(String objectName) throws StorletException {
    StorletObjectOutputStream objectStream = null;
    String key = containerName + objectName + new Date().getTime();
    JSONObject jRequestObj = new JSONObject();
    jRequestObj.put("object_name", objectName);
    jRequestObj.put("container_name", containerName);
    jRequestObj.put("key", key);

    ObjectRequestEntry requestEntry = requestTable.Insert(key);

    try {/*  w w  w  .j  a  v a 2  s  .co  m*/
        stream.write(jRequestObj.toString().getBytes());
    } catch (IOException e) {
        throw new StorletException("Failed to serialize object descriptor request " + e.toString());
    }

    try {
        objectStream = requestEntry.get();
    } catch (InterruptedException e) {
        throw new StorletException("Exception while waiting for request entry" + e.getMessage());
    }
    requestTable.Remove(key);
    return objectStream;
}